PersonWorkService.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. <?php
  2. namespace App\Service;
  3. use App\Jobs\ProcessDataJob;
  4. use App\Model\CalendarDetails;
  5. use App\Model\DailyPwOrder;
  6. use App\Model\DailyPwOrderDetails;
  7. use App\Model\Employee;
  8. use App\Model\Item;
  9. use App\Model\MonthlyPwOrder;
  10. use App\Model\MonthlyPwOrderDetails;
  11. use App\Model\RuleSetDetails;
  12. use Illuminate\Support\Facades\DB;
  13. class PersonWorkService extends Service
  14. {
  15. // 人员月工时单-------------------------------------------
  16. public function monthlyPwOrderEdit($data,$user){
  17. list($status,$msg) = $this->monthlyPwOrderRule($data, $user, false);
  18. if(!$status) return [$status,$msg];
  19. try {
  20. DB::beginTransaction();
  21. $model = MonthlyPwOrder::where('id',$data['id'])->first();
  22. // $model->month = $data['month'] ?? 0;
  23. // $model->save();
  24. $time = time();
  25. MonthlyPwOrderDetails::where('del_time',0)
  26. ->where('main_id', $model->id)
  27. ->update(['del_time' => $time]);
  28. $this->saveDetail($model->id, $time, $data);
  29. DB::commit();
  30. }catch (\Exception $exception){
  31. DB::rollBack();
  32. return [false,$exception->getMessage()];
  33. }
  34. return [true, ''];
  35. }
  36. public function monthlyPwOrderAdd($data,$user){
  37. list($status,$msg) = $this->monthlyPwOrderRule($data, $user);
  38. if(!$status) return [$status,$msg];
  39. try {
  40. DB::beginTransaction();
  41. $model = new MonthlyPwOrder();
  42. $model->code = $this->generateBillNo([
  43. 'top_depart_id' => $user['top_depart_id'],
  44. 'type' => MonthlyPwOrder::Order_type,
  45. 'period' => date("Ym", $data['month'])
  46. ]);
  47. $model->month = $data['month'] ?? 0;
  48. $model->crt_id = $user['id'];
  49. $model->top_depart_id = $data['top_depart_id'];
  50. $model->save();
  51. $this->saveDetail($model->id, time(), $data);
  52. DB::commit();
  53. }catch (\Exception $exception){
  54. DB::rollBack();
  55. return [false,$exception->getMessage()];
  56. }
  57. return [true, ''];
  58. }
  59. private function saveDetail($id, $time, $data){
  60. if(! empty($data['details'])){
  61. $unit = [];
  62. foreach ($data['details'] as $value){
  63. $unit[] = [
  64. 'main_id' => $id,
  65. 'employee_id' => $value['employee_id'],
  66. 'total_days' => $value['total_days'],
  67. 'rd_total_days' => $value['rd_total_days'],
  68. 'total_hours' => $value['total_hours'],
  69. 'rd_total_hours' => $value['rd_total_hours'],
  70. 'crt_time' => $time,
  71. 'top_depart_id' => $value['top_depart_id'],
  72. ];
  73. }
  74. if(! empty($unit)) MonthlyPwOrderDetails::insert($unit);
  75. }
  76. }
  77. private function getDetail($id){
  78. $data = MonthlyPwOrderDetails::where('del_time',0)
  79. ->where('main_id', $id)
  80. ->select('employee_id', 'total_days', 'rd_total_days', 'total_hours', 'rd_total_hours')
  81. ->get()->toArray();
  82. $id = array_column($data,'employee_id');
  83. $map = Employee::whereIn('id', $id)->select('title','id','number')->get()->toArray();
  84. $map = array_column($map,null,'id');
  85. foreach ($data as $key => $value){
  86. $tmp = $map[$value['employee_id']] ?? [];
  87. $merge = [];
  88. $merge['employee_title'] = $tmp['title'];
  89. $merge['employee_number'] = $tmp['number'];
  90. $data[$key] = array_merge($value, $merge);
  91. }
  92. $detail = [
  93. 'details' => $data,
  94. ];
  95. foreach ($detail as $key => $value) {
  96. if (empty($value)) {
  97. $detail[$key] = (object)[]; // 转成 stdClass 对象
  98. }
  99. }
  100. return $detail;
  101. }
  102. public function monthlyPwOrderDel($data){
  103. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  104. try {
  105. DB::beginTransaction();
  106. $time = time();
  107. MonthlyPwOrder::where('del_time',0)
  108. ->whereIn('id',$data['id'])
  109. ->update(['del_time' => $time]);
  110. MonthlyPwOrderDetails::where('del_time',0)
  111. ->whereIn('main_id', $data['id'])
  112. ->update(['del_time' => $time]);
  113. DB::commit();
  114. }catch (\Exception $exception){
  115. DB::rollBack();
  116. return [false,$exception->getMessage()];
  117. }
  118. return [true, ''];
  119. }
  120. public function monthlyPwOrderDetail($data, $user){
  121. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  122. $customer = MonthlyPwOrder::where('del_time',0)
  123. ->where('id',$data['id'])
  124. ->first();
  125. if(empty($customer)) return [false,'人员月度工时单不存在或已被删除'];
  126. $customer = $customer->toArray();
  127. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  128. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  129. $customer['month'] = $customer['month'] ? date("Y-m",$customer['month']): '';
  130. $details = $this->getDetail($data['id']);
  131. $customer = array_merge($customer, $details);
  132. return [true, $customer];
  133. }
  134. public function monthlyPwOrderCommon($data,$user, $field = []){
  135. if(empty($field)) $field = MonthlyPwOrder::$field;
  136. $model = MonthlyPwOrder::Clear($user,$data);
  137. $model = $model->where('del_time',0)
  138. ->select($field)
  139. ->orderby('id', 'desc');
  140. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  141. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  142. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  143. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  144. $model->where('crt_time','>=',$return[0]);
  145. $model->where('crt_time','<=',$return[1]);
  146. }
  147. return $model;
  148. }
  149. public function monthlyPwOrderList($data,$user){
  150. $model = $this->monthlyPwOrderCommon($data, $user);
  151. $list = $this->limit($model,'',$data);
  152. $list = $this->fillData($list);
  153. return [true, $list];
  154. }
  155. public function monthlyPwOrderRule(&$data, $user, $is_add = true)
  156. {
  157. if (empty($data['month'])) return [false, '月份不能为空'];
  158. $data['month'] = $this->changeDateToDate($data['month']);
  159. $data['top_depart_id'] = $user['top_depart_id'];
  160. if (empty($data['details'])) return [false, '人员月度工时单明细不能为空'];
  161. //获取系统计算的考勤基准数据 ---
  162. $empIds = array_column($data['details'], 'employee_id');
  163. list($status, $systemStats) = (new EmployeeService())->getEmployeesMonthStats($empIds, $data['month'], $user);
  164. if (!$status) return [false, $systemStats]; // 如果日历未设置,直接拦截
  165. foreach ($data['details'] as $key => $value) {
  166. if (empty($value['employee_id'])) return [false, '人员不能为空'];
  167. $empId = $value['employee_id'];
  168. // 基础数字格式检查
  169. foreach (['total_days', 'rd_total_days', 'total_hours', 'rd_total_hours'] as $field) {
  170. $precision = 2;
  171. $res = $this->checkNumber($value[$field], $precision, 'non-negative');
  172. if (!$res['valid']) return [false, $value['employee_title'] . "的" . $field . ":" . $res['error']];
  173. }
  174. // --- 业务逻辑校验:出勤天数与工时合法性 ---
  175. $sysData = $systemStats[$empId] ?? null;
  176. if ($sysData) {
  177. // 1. 研发天数不能大于出勤总天数
  178. if ($value['rd_total_days'] > $value['total_days']) {
  179. return [false, "第" . ($key + 1) . "行:研发出勤天数不能大于出勤总天数"];
  180. }
  181. // 2. 研发工时不能大于出勤总工时
  182. if ($value['rd_total_hours'] > $value['total_hours']) {
  183. return [false, "第" . ($key + 1) . "行:研发总工时不能大于出勤总工时"];
  184. }
  185. // 4. 校验出勤总天数是否超过了系统计算的上限
  186. if ($value['total_days'] != $sysData['attendance_days']) {
  187. return [false, "人员[{$empId}]填写的出勤总天数({$value['total_days']})不等于系统核算的天数({$sysData['attendance_days']})"];
  188. }
  189. //校验出勤总工时是否超过了系统计算的上限
  190. if ($value['total_hours'] != $sysData['final_work_hour']) {
  191. return [false, "人员[{$empId}]填写的出勤总工时({$value['total_hours']})不等于系统核算的工时({$sysData['final_work_hour']})"];
  192. }
  193. }
  194. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  195. }
  196. // --- 查重与唯一性校验 ---
  197. list($status, $msg) = $this->checkArrayRepeat($data['details'], 'employee_id', '人员');
  198. if (!$status) return [false, $msg];
  199. $query = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
  200. ->where('month', $data['month'])
  201. ->where('del_time', 0);
  202. if (!$is_add) {
  203. if (empty($data['id'])) return [false, 'ID不能为空'];
  204. $query->where('id', '<>', $data['id']);
  205. }
  206. if ($query->exists()) {
  207. return [false, date("Y-m", $data['month']) . '已存在人员月度研发工时单'];
  208. }
  209. return [true, ''];
  210. }
  211. public function monthlyPwOrderRule1(&$data, $user, $is_add = true){
  212. if(empty($data['month'])) return [false, '月份不能为空'];
  213. $data['month'] = $this->changeDateToDate($data['month']);
  214. $data['top_depart_id'] = $user['top_depart_id'];
  215. if(empty($data['details'])) return [false, '人员月度工时单明细不能为空'];
  216. foreach ($data['details'] as $key => $value){
  217. if(empty($value['employee_id'])) return [false, '人员不能为空'];
  218. $res = $this->checkNumber($value['total_days'],0,'non-negative');
  219. if(! $res['valid']) return [false,'出勤总天数:' . $res['error']];
  220. $res = $this->checkNumber($value['rd_total_days'],0,'non-negative');
  221. if(! $res['valid']) return [false,'研发出勤总天数:' . $res['error']];
  222. $res = $this->checkNumber($value['total_hours'],2,'non-negative');
  223. if(! $res['valid']) return [false,'出勤总工时:' . $res['error']];
  224. $res = $this->checkNumber($value['rd_total_hours'],2,'non-negative');
  225. if(! $res['valid']) return [false,'研发总工时:' . $res['error']];
  226. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  227. }
  228. list($status, $msg) = $this->checkArrayRepeat($data['details'],'employee_id','人员');
  229. if(! $status) return [false, $msg];
  230. if($is_add){
  231. $bool = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
  232. ->where('month', $data['month'])
  233. ->where('del_time',0)
  234. ->exists();
  235. }else{
  236. if(empty($data['id'])) return [false,'ID不能为空'];
  237. $bool = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
  238. ->where('month', $data['month'])
  239. ->where('id','<>',$data['id'])
  240. ->where('del_time',0)
  241. ->exists();
  242. }
  243. if($bool) return [false, date("Y-m", $data['month']) . '已存在人员月度研发工时单'];
  244. return [true, ''];
  245. }
  246. public function fillData($data){
  247. if(empty($data['data'])) return $data;
  248. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  249. foreach ($data['data'] as $key => $value){
  250. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  251. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  252. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  253. }
  254. return $data;
  255. }
  256. public function fillDataForExport($data, $column, &$return)
  257. {
  258. if(empty($data)) return;
  259. $mainIds = array_column($data, 'id');
  260. // 获取详情映射 [main_id => [details...]]
  261. $detailsMap = $this->getDetailsMap($mainIds);
  262. // 默认空行模板
  263. $defaultRow = array_fill_keys($column, '');
  264. foreach ($data as $main) {
  265. $mainId = $main['id'];
  266. $details = $detailsMap[$mainId] ?? [];
  267. // 提取主表信息
  268. $mainInfo = [
  269. 'code' => $main['code'],
  270. 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
  271. ];
  272. if (empty($details)) {
  273. // 如果没有详情,至少导出一行主表信息(可选)
  274. $return[] = array_merge($defaultRow, $mainInfo);
  275. } else {
  276. // 核心:遍历详情,每一行详情都合并主表信息
  277. foreach ($details as $sub) {
  278. // 合并主表字段 + 详情字段
  279. $fullRow = array_merge($mainInfo, $sub);
  280. // 过滤掉不在导出列里的字段,并补充缺失列
  281. $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
  282. }
  283. }
  284. }
  285. }
  286. public function getDetailsMap($main_ids)
  287. {
  288. // 获取详情
  289. $details = MonthlyPwOrderDetails::where('del_time', 0)
  290. ->whereIn('main_id', $main_ids)
  291. ->get();
  292. // 获取人员信息
  293. $empIds = $details->pluck('employee_id')->unique();
  294. $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id');
  295. $res = [];
  296. foreach ($details as $item) {
  297. $tmpEmp = $empMap[$item->employee_id] ?? null;
  298. // 组装每一行详情需要展示的字段
  299. $res[$item->main_id][] = [
  300. 'employee_number' => $tmpEmp ? $tmpEmp->number : '',
  301. 'employee_title' => $tmpEmp ? $tmpEmp->title : '',
  302. 'total_days' => $item->total_days,
  303. 'rd_total_days' => $item->rd_total_days,
  304. 'total_hours' => $item->total_hours,
  305. 'rd_total_hours' => $item->rd_total_hours,
  306. ];
  307. }
  308. return $res; // 返回 [main_id => [detail_row, detail_row]]
  309. }
  310. // 人员日工时单 ------------------------------------------------
  311. public function dailyPwOrderEdit($data,$user){
  312. list($status,$msg) = $this->dailyPwOrderRule($data, $user, false);
  313. if(!$status) return [$status,$msg];
  314. try {
  315. DB::beginTransaction();
  316. $model = DailyPwOrder::where('id',$data['id'])->first();
  317. $model->item_id = $data['item_id'] ?? 0;
  318. $model->save();
  319. $time = time();
  320. DailyPwOrderDetails::where('del_time',0)
  321. ->where('main_id', $model->id)
  322. ->update(['del_time' => $time]);
  323. $this->saveDetailDaily($model->id, $time, $data);
  324. DB::commit();
  325. }catch (\Exception $exception){
  326. DB::rollBack();
  327. return [false,$exception->getMessage()];
  328. }
  329. return [true, ''];
  330. }
  331. public function dailyPwOrderAdd($data,$user){
  332. list($status,$msg) = $this->dailyPwOrderRule($data, $user);
  333. if(!$status) return [$status,$msg];
  334. try {
  335. DB::beginTransaction();
  336. $model = new DailyPwOrder();
  337. $model->code = $this->generateBillNo([
  338. 'top_depart_id' => $user['top_depart_id'],
  339. 'type' => DailyPwOrder::Order_type,
  340. 'period' => date("Ym", $data['order_time'])
  341. ]);
  342. $model->order_time = $data['order_time'] ?? 0;
  343. $model->item_id = $data['item_id'] ?? 0;
  344. $model->crt_id = $user['id'];
  345. $model->top_depart_id = $data['top_depart_id'];
  346. $model->save();
  347. $this->saveDetailDaily($model->id, time(), $data);
  348. DB::commit();
  349. }catch (\Exception $exception){
  350. DB::rollBack();
  351. return [false,$exception->getMessage()];
  352. }
  353. return [true, ''];
  354. }
  355. private function saveDetailDaily($id, $time, $data){
  356. if(! empty($data['details'])){
  357. $unit = [];
  358. foreach ($data['details'] as $value){
  359. $unit[] = [
  360. 'main_id' => $id,
  361. 'employee_id' => $value['employee_id'],
  362. 'start_time_hour' => $value['start_time_hour'],
  363. 'start_time_min' => $value['start_time_min'],
  364. 'end_time_hour' => $value['end_time_hour'],
  365. 'end_time_min' => $value['end_time_min'],
  366. 'total_work_min' => $value['total_work_min'],
  367. 'crt_time' => $time,
  368. 'top_depart_id' => $value['top_depart_id'],
  369. 'order_time' => $data['order_time'] ?? 0,
  370. ];
  371. }
  372. if(! empty($unit)) DailyPwOrderDetails::insert($unit);
  373. }
  374. }
  375. private function getDetailDaily($id){
  376. $data = DailyPwOrderDetails::where('del_time',0)
  377. ->where('main_id', $id)
  378. ->select('employee_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_work_min')
  379. ->get()->toArray();
  380. $id = array_column($data,'employee_id');
  381. $map = Employee::whereIn('id', $id)
  382. ->select('title','id','number')
  383. ->get()
  384. ->keyBy('id')
  385. ->toArray();
  386. foreach ($data as $key => $value){
  387. $tmp = $map[$value['employee_id']] ?? [];
  388. $merge = [];
  389. $merge['employee_title'] = $tmp['title'];
  390. $merge['employee_number'] = $tmp['number'];
  391. $data[$key] = array_merge($value, $merge);
  392. }
  393. $detail = [
  394. 'details' => $data,
  395. ];
  396. foreach ($detail as $key => $value) {
  397. if (empty($value)) {
  398. $detail[$key] = (object)[]; // 转成 stdClass 对象
  399. }
  400. }
  401. return $detail;
  402. }
  403. public function dailyPwOrderDel($data){
  404. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  405. try {
  406. DB::beginTransaction();
  407. $time = time();
  408. DailyPwOrder::where('del_time',0)
  409. ->whereIn('id',$data['id'])
  410. ->update(['del_time' => $time]);
  411. DailyPwOrderDetails::where('del_time',0)
  412. ->whereIn('main_id', $data['id'])
  413. ->update(['del_time' => $time]);
  414. DB::commit();
  415. }catch (\Exception $exception){
  416. DB::rollBack();
  417. return [false,$exception->getMessage()];
  418. }
  419. return [true, ''];
  420. }
  421. public function dailyPwOrderDetail($data, $user){
  422. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  423. $customer = DailyPwOrder::where('del_time',0)
  424. ->where('id',$data['id'])
  425. ->first();
  426. if(empty($customer)) return [false,'人员日工时单不存在或已被删除'];
  427. $customer = $customer->toArray();
  428. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  429. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  430. $item = Item::where('id', $customer['item_id'])->first();
  431. $customer['item_title'] = $item->title;
  432. $customer['item_code'] = $item->code;
  433. $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
  434. $details = $this->getDetailDaily($data['id']);
  435. $customer = array_merge($customer, $details);
  436. return [true, $customer];
  437. }
  438. public function dailyPwOrderCommon($data,$user, $field = []){
  439. if(empty($field)) $field = DailyPwOrder::$field;
  440. $model = DailyPwOrder::Clear($user,$data);
  441. $model = $model->where('del_time',0)
  442. ->select($field)
  443. ->orderby('id', 'desc');
  444. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  445. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  446. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  447. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  448. $model->where('crt_time','>=',$return[0]);
  449. $model->where('crt_time','<=',$return[1]);
  450. }
  451. return $model;
  452. }
  453. public function dailyPwOrderList($data,$user){
  454. $model = $this->dailyPwOrderCommon($data, $user);
  455. $list = $this->limit($model,'',$data);
  456. $list = $this->fillDataDaily($list);
  457. return [true, $list];
  458. }
  459. public function dailyPwOrderRule(&$data, $user, $is_add = true){
  460. if(empty($data['order_time'])) return [false, '单据日期不能为空'];
  461. $data['order_time'] = $this->changeDateToDate($data['order_time']);
  462. $orderTime = $data['order_time'];
  463. $itemId = $data['item_id'] ?? 0;
  464. if(empty($itemId)) return [false, '项目不能为空'];
  465. $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
  466. if(!$bool) return [false, '项目不存在或已被删除'];
  467. $data['top_depart_id'] = $user['top_depart_id'];
  468. if(empty($data['details'])) return [false, '人员日工时单明细不能为空'];
  469. // --- 1. 批量预获取人员信息,用于报错提示 ---
  470. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'employee_id')));
  471. // 如果需要工号+姓名,建议这样获取:
  472. $empDisplayMap = Employee::whereIn('id', $allEmpIds)
  473. ->get(['id', 'number', 'title'])
  474. ->mapWithKeys(function($item){
  475. return [$item->id => "[{$item->number}]{$item->title}"];
  476. })->toArray();
  477. // 2. 本次提交内部重叠记录器
  478. $internalOverlap = [];
  479. foreach ($data['details'] as $key => $value){
  480. $empId = $value['employee_id'] ?? 0;
  481. if(empty($empId)) return [false, '人员不能为空'];
  482. $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
  483. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  484. if(!$res['valid']) return [false, "人员{$empName}开始点:" . $res['error']];
  485. if($value['start_time_hour'] > 23) return [false, false, "人员{$empName}开始点不合法"];
  486. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  487. if(!$res['valid']) return [false, "人员{$empName}开始分:" . $res['error']];
  488. if($value['start_time_min'] > 60) return [false, false, "人员{$empName}开始点不合法"];
  489. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  490. if(!$res['valid']) return [false, "人员{$empName}结束点:" . $res['error']];
  491. if($value['end_time_hour'] > 24) return [false, false, "人员{$empName}结束点不合法"];
  492. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  493. if(!$res['valid']) return [false, "人员{$empName}结束分:" . $res['error']];
  494. if($value['end_time_min'] > 60) return [false, false, "人员{$empName}结束分不合法"];
  495. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  496. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  497. if ($currentStart >= $currentEnd) {
  498. return [false, "人员{$empName}:开始时间必须早于结束时间"];
  499. }
  500. // --- 3. 内部重叠校验(防止一次提交多行重复) ---
  501. if (isset($internalOverlap[$empId])) {
  502. foreach ($internalOverlap[$empId] as $period) {
  503. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  504. return [false, "人员{$empName}在本次提交的多行明细中时间段重叠"];
  505. }
  506. }
  507. }
  508. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  509. $query = DB::table('daily_pw_order_details as d')
  510. ->join('daily_pw_order as m', 'd.main_id', '=', 'm.id')
  511. ->where('m.top_depart_id', $data['top_depart_id'])
  512. ->where('m.order_time', $orderTime)
  513. ->where('m.item_id', $itemId)
  514. ->where('d.employee_id', $empId)
  515. ->where('m.del_time', 0)
  516. ->where('d.del_time', 0);
  517. if (!$is_add && !empty($data['id'])) {
  518. $query->where('m.id', '<>', $data['id']);
  519. }
  520. $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
  521. foreach ($existingPeriods as $p) {
  522. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  523. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  524. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  525. return [false, "人员{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
  526. }
  527. }
  528. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  529. }
  530. if(!$is_add){
  531. if(empty($data['id'])) return [false,'ID不能为空'];
  532. $bool = DailyPwOrder::where('top_depart_id', $data['top_depart_id'])
  533. ->where('id',$data['id'])
  534. ->where('del_time',0)
  535. ->exists();
  536. if(!$bool) return [false, '人员日工时单不存在或已被删除'];
  537. }
  538. return [true, ''];
  539. }
  540. public function fillDataDaily($data){
  541. if(empty($data['data'])) return $data;
  542. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  543. $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_id')));
  544. foreach ($data['data'] as $key => $value){
  545. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  546. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  547. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  548. $item_tmp = $item[$value['item_id']] ?? [];
  549. $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
  550. $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
  551. }
  552. return $data;
  553. }
  554. public function fillDataForExportDaily($data, $column, &$return)
  555. {
  556. if (empty($data)) return;
  557. $mainIds = array_column($data, 'id');
  558. // 1. 获取详情及所有关联档案(项目、人员)的映射
  559. $detailsMap = $this->getDailyDetailsMap($mainIds, $data);
  560. foreach ($data as $main) {
  561. $mainId = $main['id'];
  562. $details = $detailsMap[$mainId] ?? [];
  563. // 2. 提取并格式化主表共有信息
  564. $mainInfo = [
  565. 'code' => $main['code'],
  566. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  567. ];
  568. if (empty($details)) {
  569. // 无明细时只导出一行主表信息
  570. $tempRow = [];
  571. foreach ($column as $col) {
  572. $tempRow[] = $mainInfo[$col] ?? '';
  573. }
  574. $return[] = $tempRow;
  575. } else {
  576. // 3. 平铺:将详情里的项目信息、人员信息与主表信息合并
  577. foreach ($details as $sub) {
  578. $fullRowData = array_merge($mainInfo, $sub);
  579. $tempRow = [];
  580. foreach ($column as $col) {
  581. $tempRow[] = $fullRowData[$col] ?? '';
  582. }
  583. $return[] = $tempRow;
  584. }
  585. }
  586. }
  587. }
  588. public function getDailyDetailsMap($mainIds, $mainData)
  589. {
  590. // 1. 获取所有子表记录
  591. $details = DB::table('daily_pw_order_details')
  592. ->where('del_time', 0)
  593. ->whereIn('main_id', $mainIds)
  594. ->get();
  595. // 2. 提取所有关联 ID
  596. $empIds = $details->pluck('employee_id')->unique();
  597. $itemIds = array_unique(array_column($mainData, 'item_id')); // 从主表数组提取项目ID
  598. // 3. 批量获取档案 Map
  599. $empMap = DB::table('employee')
  600. ->whereIn('id', $empIds)
  601. ->get(['id', 'title', 'number'])
  602. ->keyBy('id');
  603. $itemMap = DB::table('item')
  604. ->whereIn('id', $itemIds)
  605. ->get(['id', 'title', 'code'])
  606. ->keyBy('id');
  607. // 4. 将主表的项目信息预先挂载到主表 ID 下,方便后续合并
  608. $mainItemInfo = [];
  609. foreach ($mainData as $m) {
  610. $proj = $itemMap[$m['item_id']] ?? null;
  611. $mainItemInfo[$m['id']] = [
  612. 'item_code' => $proj ? $proj->code : '',
  613. 'item_title' => $proj ? $proj->title : '',
  614. ];
  615. }
  616. $res = [];
  617. if ($details->isEmpty()) {
  618. // 如果没有详情,把项目信息返回去,确保主表能导出行
  619. foreach ($mainItemInfo as $mId => $info) {
  620. $res[$mId] = [];
  621. }
  622. return $res;
  623. }
  624. foreach ($details as $item) {
  625. $emp = $empMap[$item->employee_id] ?? null;
  626. // 组装明细行数据
  627. $detailRow = [
  628. // 人员信息
  629. 'employee_number' => $emp ? $emp->number : '',
  630. 'employee_title' => $emp ? $emp->title : '',
  631. // 时间信息
  632. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  633. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  634. // 将主表的项目信息也塞进每一行详情里实现平铺
  635. 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
  636. 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
  637. ];
  638. $res[$item->main_id][] = $detailRow;
  639. }
  640. return $res;
  641. }
  642. public function dailyPwOrderCreate($data, $user)
  643. {
  644. $topDepartId = $user['top_depart_id'];
  645. if (empty($data['month'])) return [false, '月份不能为空'];
  646. $monthStart = $this->changeDateToDate($data['month']);
  647. // --- 一开始就做的核心校验 ---
  648. // 1. 检查是否存在月度工时明细(如果没有,队列执行也是徒劳)
  649. $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
  650. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  651. ->where('m.month', $monthStart)
  652. ->where('m.top_depart_id', $topDepartId)
  653. ->where('m.del_time', 0)
  654. ->where('d.del_time', 0)
  655. ->exists();
  656. if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
  657. // 2. 检查是否配置了工作日历
  658. $hasCalendar = DB::table('calendar_details')
  659. ->where('month', $monthStart)
  660. ->where('del_time', 0)
  661. ->exists();
  662. if (!$hasCalendar) return [false, '该月份工作日历未配置'];
  663. // 3. 检查是否配置了项目比例规则
  664. $hasRules = DB::table('rule_set as r')
  665. ->where('r.month', $monthStart)
  666. ->where('r.top_depart_id', $topDepartId)
  667. ->where('r.del_time', 0)
  668. ->exists();
  669. if (!$hasRules) return [false, '未找到该月份的规则配置单'];
  670. $data['type'] = "p_work";
  671. ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
  672. return [true, '生成任务已提交,系统正在后台处理,请稍后查看'];
  673. }
  674. public function dailyPwOrderCreateMain($data, $user)
  675. {
  676. $topDepartId = $user['top_depart_id'];
  677. if (empty($data['month'])) return [false, '月份不能为空'];
  678. $monthStart = $this->changeDateToDate($data['month']);
  679. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  680. $now = time();
  681. DB::beginTransaction();
  682. try {
  683. // --- 0. 清理旧数据 ---
  684. $oldOrderIds = DB::table('daily_pw_order')
  685. ->where('top_depart_id', $topDepartId)
  686. ->where('order_time', '>=', $monthStart)
  687. ->where('order_time', '<=', $monthEnd)
  688. ->where('is_create', 1)
  689. ->where('del_time', 0)
  690. ->pluck('id');
  691. if ($oldOrderIds->isNotEmpty()) {
  692. DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  693. DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  694. }
  695. // --- 1. 基础数据加载 ---
  696. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  697. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  698. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  699. ->where('m.del_time', 0)->where('d.del_time', 0)
  700. ->select('d.*')->get();
  701. if ($monthlyOrder->isEmpty()) return [false, '未找到月度工时明细'];
  702. $empIds = $monthlyOrder->pluck('employee_id')->unique()->toArray();
  703. $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  704. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  705. $ruleSet = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  706. ->where('r.month', $monthStart)->where('rd.type', RuleSetDetails::type_one)
  707. ->where('r.del_time', 0)->where('rd.del_time', 0)
  708. ->select('rd.*')->get()->groupBy('data_id');
  709. $allDays = DB::table('calendar_details')->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
  710. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  711. ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('m.del_time', 0)
  712. ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
  713. // --- 2. 核心分配逻辑:计算每天、每个项目、每个人的分钟数 ---
  714. $finalAlloc = [];
  715. foreach ($monthlyOrder as $mDetail) {
  716. $empId = $mDetail->employee_id;
  717. $empRules = $ruleSet->get($empId);
  718. if (!$empRules) continue;
  719. $empRemainingMin = (float)$mDetail->rd_total_hours * 60;
  720. if ($empRemainingMin <= 0) continue;
  721. foreach ($allDays as $dayInfo) {
  722. if ($empRemainingMin <= 0) break;
  723. $dayTs = $dayInfo->time;
  724. $isWorkDay = ($dayInfo->is_work == CalendarDetails::TYPE_ONE);
  725. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  726. $todayOvertimes = $todaySpecials->where('main_type', 2);
  727. if (!$isWorkDay && $todayOvertimes->isEmpty()) continue;
  728. // 计算当天可用总时长
  729. $dayAvailableMin = 0;
  730. if ($isWorkDay) {
  731. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  732. foreach ($baseRanges as $br) {
  733. $brS = $br->start_time_hour * 60 + $br->start_time_min;
  734. $brE = $br->end_time_hour * 60 + $br->end_time_min;
  735. $avail = (float)$br->total_work_min;
  736. foreach ($todaySpecials->where('main_type', 1) as $lv) {
  737. $overlap = min($brE, ($lv->end_time_hour * 60 + $lv->end_time_min)) - max($brS, ($lv->start_time_hour * 60 + $lv->start_time_min));
  738. if ($overlap > 0) $avail -= $overlap;
  739. }
  740. $dayAvailableMin += max(0, $avail);
  741. }
  742. }
  743. foreach ($todayOvertimes as $ot) $dayAvailableMin += (float)$ot->total_min;
  744. $canAllocToday = min($empRemainingMin, $dayAvailableMin);
  745. if ($canAllocToday <= 0) continue;
  746. foreach ($empRules as $rule) {
  747. $rate = (float)$rule->rate / 100;
  748. $projectMin = $canAllocToday * $rate;
  749. if ($projectMin > 0) {
  750. // 结果存入:[日期][项目][人员]
  751. $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
  752. }
  753. }
  754. $empRemainingMin -= $canAllocToday;
  755. }
  756. }
  757. // --- 3. 生成单据:解决时间重叠的核心逻辑 ---
  758. $newOrderIds = [];
  759. // 为了解决重叠,我们需要按 [日期][人员] 来追踪时间池的消耗进度
  760. $dailyEmpTimePools = [];
  761. foreach ($finalAlloc as $dayTs => $projects) {
  762. foreach ($projects as $itemId => $employees) {
  763. $mainId = DB::table('daily_pw_order')->insertGetId([
  764. 'code' => '', 'item_id' => $itemId, 'order_time' => $dayTs, 'top_depart_id' => $topDepartId,
  765. 'is_create' => 1, 'crt_id' => $user['id'], 'crt_time' => $now, 'upd_time' => $now,
  766. ]);
  767. $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
  768. foreach ($employees as $empId => $toAllocMin) {
  769. // 如果该员工当天的池子还没构建,先构建一次
  770. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  771. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  772. }
  773. $tempRem = $toAllocMin;
  774. // 指向该员工当天的可用池引用,这样处理完项目A,池子里的时间会自动被“消耗”
  775. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  776. if ($tempRem <= 0) break;
  777. $pMax = $p['e'] - $p['s'];
  778. if ($pMax <= 0) continue;
  779. $take = min($tempRem, $pMax);
  780. $realStart = $p['s'];
  781. $realEnd = $p['s'] + $take;
  782. DB::table('daily_pw_order_details')->insert([
  783. 'main_id' => $mainId, 'employee_id' => $empId, 'top_depart_id' => $topDepartId,
  784. 'start_time_hour' => floor($realStart / 60), 'start_time_min' => $realStart % 60,
  785. 'end_time_hour' => floor($realEnd / 60), 'end_time_min' => $realEnd % 60,
  786. 'total_work_min' => $take, 'crt_time' => $now, 'upd_time' => $now,
  787. ]);
  788. $tempRem -= $take;
  789. // 重要:消耗掉这个时段的起始位置,确保下一个项目从这里开始
  790. $p['s'] = $realEnd;
  791. }
  792. }
  793. }
  794. }
  795. // --- 4. 回填单号 ---
  796. if (empty($newOrderIds)) return [false, '未生成数据'];
  797. foreach ($newOrderIds as $item) {
  798. $code = $this->generateBillNo(['top_depart_id' => $topDepartId, 'type' => DailyPwOrder::Order_type, 'period' => date("Ym", $item['time'])]);
  799. DB::table('daily_pw_order')->where('id', $item['id'])->update(['code' => $code]);
  800. }
  801. DB::commit();
  802. } catch (\Exception $e) {
  803. DB::rollBack();
  804. return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
  805. }
  806. return [true, ''];
  807. }
  808. /**
  809. * 辅助函数:构建某人某天的初始可用时段池
  810. */
  811. private function buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData)
  812. {
  813. $dayInfo = $allDays->where('time', $dayTs)->first();
  814. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  815. $pool = [];
  816. if ($dayInfo && $dayInfo->is_work == CalendarDetails::TYPE_ONE) {
  817. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  818. foreach ($baseRanges as $br) {
  819. $currentS = $br->start_time_hour * 60 + $br->start_time_min;
  820. $eMin = $br->end_time_hour * 60 + $br->end_time_min;
  821. $sortedLeaves = $todaySpecials->where('main_type', 1)->sortBy('start_time_hour');
  822. foreach ($sortedLeaves as $lv) {
  823. $lvS = $lv->start_time_hour * 60 + $lv->start_time_min;
  824. $lvE = $lv->end_time_hour * 60 + $lv->end_time_min;
  825. if ($lvS < $eMin && $lvE > $currentS) {
  826. if ($lvS > $currentS) $pool[] = ['s' => $currentS, 'e' => $lvS];
  827. $currentS = max($currentS, $lvE);
  828. }
  829. }
  830. if ($currentS < $eMin) $pool[] = ['s' => $currentS, 'e' => $eMin];
  831. }
  832. }
  833. foreach ($todaySpecials->where('main_type', 2) as $ot) {
  834. $otS = $ot->start_time_hour * 60 + $ot->start_time_min;
  835. $pool[] = ['s' => $otS, 'e' => $otS + (float)$ot->total_min];
  836. }
  837. return $pool;
  838. }
  839. }