PersonWorkService.php 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  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, $user){
  103. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  104. try {
  105. DB::beginTransaction();
  106. $time = time();
  107. $month = MonthlyPwOrder::where('del_time',0)
  108. ->whereIn('id',$data['id'])
  109. ->pluck('month')
  110. ->toArray();
  111. //归档
  112. list($status, $msg) = ArchiveService::isArchive($month, $user);
  113. if(! $status) return [false, $msg];
  114. MonthlyPwOrder::where('del_time',0)
  115. ->whereIn('id',$data['id'])
  116. ->update(['del_time' => $time]);
  117. MonthlyPwOrderDetails::where('del_time',0)
  118. ->whereIn('main_id', $data['id'])
  119. ->update(['del_time' => $time]);
  120. DB::commit();
  121. }catch (\Exception $exception){
  122. DB::rollBack();
  123. return [false,$exception->getMessage()];
  124. }
  125. return [true, ''];
  126. }
  127. public function monthlyPwOrderDetail($data, $user){
  128. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  129. $customer = MonthlyPwOrder::where('del_time',0)
  130. ->where('id',$data['id'])
  131. ->first();
  132. if(empty($customer)) return [false,'人员月度工时单不存在或已被删除'];
  133. $customer = $customer->toArray();
  134. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  135. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  136. $map = ArchiveService::fillIsArchive($customer['month'], $user);
  137. $customer['is_archive'] = $map[$customer['month']] ?? false;
  138. $customer['month'] = $customer['month'] ? date("Y-m",$customer['month']): '';
  139. $details = $this->getDetail($data['id']);
  140. $customer = array_merge($customer, $details);
  141. return [true, $customer];
  142. }
  143. public function monthlyPwOrderCommon($data,$user, $field = []){
  144. if(empty($field)) $field = MonthlyPwOrder::$field;
  145. $model = MonthlyPwOrder::Clear($user,$data);
  146. $model = $model->where('del_time',0)
  147. ->select($field)
  148. ->orderby('id', 'desc');
  149. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  150. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  151. $model->where('month','>=',$return[0]);
  152. $model->where('month','<=',$return[1]);
  153. }
  154. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  155. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  156. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  157. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  158. $model->where('crt_time','>=',$return[0]);
  159. $model->where('crt_time','<=',$return[1]);
  160. }
  161. return $model;
  162. }
  163. public function monthlyPwOrderList($data,$user){
  164. $model = $this->monthlyPwOrderCommon($data, $user);
  165. $list = $this->limit($model,'',$data);
  166. $list = $this->fillData($list, $user);
  167. return [true, $list];
  168. }
  169. public function monthlyPwOrderRule(&$data, $user, $is_add = true)
  170. {
  171. if (empty($data['month'])) return [false, '月份不能为空'];
  172. $data['month'] = $this->changeDateToDate($data['month']);
  173. $data['top_depart_id'] = $user['top_depart_id'];
  174. //归档
  175. list($status, $msg) = ArchiveService::isArchive($data['month'], $user);
  176. if(! $status) return [false, $msg];
  177. if (empty($data['details'])) return [false, '人员月度工时单明细不能为空'];
  178. //获取系统计算的考勤基准数据 ---
  179. $empIds = array_column($data['details'], 'employee_id');
  180. list($status, $systemStats) = (new EmployeeService())->getEmployeesMonthStats($empIds, $data['month'], $user);
  181. if (!$status) return [false, $systemStats]; // 如果日历未设置,直接拦截
  182. // 字段中文映射,用于报错
  183. $fieldNames = [
  184. 'total_days' => '出勤总天数',
  185. 'rd_total_days' => '研发出勤总天数',
  186. 'total_hours' => '出勤总工时',
  187. 'rd_total_hours'=> '研发总工时'
  188. ];
  189. foreach ($data['details'] as $key => $value) {
  190. $lineTitle = "第" . ($key + 1) . "行:";
  191. if (empty($value['employee_id'])) return [false, '人员不能为空'];
  192. $empId = $value['employee_id'];
  193. // 基础数字格式检查
  194. foreach ($fieldNames as $field => $title) {
  195. if(! isset($value[$field])) return [false, $lineTitle . $title . "不存在"];
  196. $precision = 2;
  197. $res = $this->checkNumber($value[$field], $precision, 'non-negative');
  198. if (!$res['valid']) return [false, $lineTitle . $value['employee_title'] . "的" . $title . ":" . $res['error']];
  199. }
  200. // --- 业务逻辑校验:出勤天数与工时合法性 ---
  201. $sysData = $systemStats[$empId] ?? null;
  202. if ($sysData) {
  203. // 1. 研发天数不能大于出勤总天数
  204. if ($value['rd_total_days'] > $value['total_days']) {
  205. return [false, $lineTitle . "研发出勤天数不能大于出勤总天数"];
  206. }
  207. // 2. 研发工时不能大于出勤总工时
  208. if ($value['rd_total_hours'] > $value['total_hours']) {
  209. return [false, $lineTitle . "研发总工时不能大于出勤总工时"];
  210. }
  211. // 4. 校验出勤总天数是否超过了系统计算的上限
  212. if ($value['total_days'] != $sysData['attendance_days']) {
  213. return [false, $lineTitle . "人员[{$empId}]填写的出勤总天数({$value['total_days']})不等于系统核算的天数({$sysData['attendance_days']})"];
  214. }
  215. //校验出勤总工时是否超过了系统计算的上限
  216. if ($value['total_hours'] != $sysData['final_work_hour']) {
  217. return [false, $lineTitle . "人员[{$empId}]填写的出勤总工时({$value['total_hours']})不等于系统核算的工时({$sysData['final_work_hour']})"];
  218. }
  219. }
  220. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  221. }
  222. // --- 查重与唯一性校验 ---
  223. list($status, $msg) = $this->checkArrayRepeat($data['details'], 'employee_id', '人员');
  224. if (!$status) return [false, $msg];
  225. $query = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
  226. ->where('month', $data['month'])
  227. ->where('del_time', 0);
  228. if (!$is_add) {
  229. if (empty($data['id'])) return [false, 'ID不能为空'];
  230. $query->where('id', '<>', $data['id']);
  231. }
  232. if ($query->exists()) {
  233. return [false, date("Y-m", $data['month']) . '已存在人员月度研发工时单'];
  234. }
  235. return [true, ''];
  236. }
  237. public function fillData($data, $user){
  238. if(empty($data['data'])) return $data;
  239. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  240. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'month')), $user);
  241. foreach ($data['data'] as $key => $value){
  242. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  243. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  244. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  245. $data['data'][$key]['is_archive'] = $map[$value['month']] ?? false;
  246. }
  247. return $data;
  248. }
  249. public function fillDataForExport($data, $column, &$return)
  250. {
  251. if(empty($data)) return;
  252. $mainIds = array_column($data, 'id');
  253. // 获取详情映射 [main_id => [details...]]
  254. $detailsMap = $this->getDetailsMap($mainIds);
  255. // 默认空行模板
  256. $defaultRow = array_fill_keys($column, '');
  257. foreach ($data as $main) {
  258. $mainId = $main['id'];
  259. $details = $detailsMap[$mainId] ?? [];
  260. // 提取主表信息
  261. $mainInfo = [
  262. 'code' => $main['code'],
  263. 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
  264. ];
  265. if (empty($details)) {
  266. // 如果没有详情,至少导出一行主表信息(可选)
  267. $return[] = array_merge($defaultRow, $mainInfo);
  268. } else {
  269. // 核心:遍历详情,每一行详情都合并主表信息
  270. foreach ($details as $sub) {
  271. // 合并主表字段 + 详情字段
  272. $fullRow = array_merge($mainInfo, $sub);
  273. // 过滤掉不在导出列里的字段,并补充缺失列
  274. $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
  275. }
  276. }
  277. }
  278. }
  279. public function getDetailsMap($main_ids)
  280. {
  281. // 获取详情
  282. $details = MonthlyPwOrderDetails::where('del_time', 0)
  283. ->whereIn('main_id', $main_ids)
  284. ->get();
  285. // 获取人员信息
  286. $empIds = $details->pluck('employee_id')->unique();
  287. $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id');
  288. $res = [];
  289. foreach ($details as $item) {
  290. $tmpEmp = $empMap[$item->employee_id] ?? null;
  291. // 组装每一行详情需要展示的字段
  292. $res[$item->main_id][] = [
  293. 'employee_number' => $tmpEmp ? $tmpEmp->number : '',
  294. 'employee_title' => $tmpEmp ? $tmpEmp->title : '',
  295. 'total_days' => $item->total_days,
  296. 'rd_total_days' => $item->rd_total_days,
  297. 'total_hours' => $item->total_hours,
  298. 'rd_total_hours' => $item->rd_total_hours,
  299. ];
  300. }
  301. return $res; // 返回 [main_id => [detail_row, detail_row]]
  302. }
  303. // 人员日工时单 ------------------------------------------------
  304. public function dailyPwOrderEdit($data,$user){
  305. list($status,$msg) = $this->dailyPwOrderRule($data, $user, false);
  306. if(!$status) return [$status,$msg];
  307. try {
  308. DB::beginTransaction();
  309. $model = DailyPwOrder::where('id',$data['id'])->first();
  310. $model->item_id = $data['item_id'] ?? 0;
  311. $model->save();
  312. $time = time();
  313. DailyPwOrderDetails::where('del_time',0)
  314. ->where('main_id', $model->id)
  315. ->update(['del_time' => $time]);
  316. $this->saveDetailDaily($model->id, $time, $data, $user);
  317. DB::commit();
  318. }catch (\Exception $exception){
  319. DB::rollBack();
  320. return [false,$exception->getMessage()];
  321. }
  322. return [true, ''];
  323. }
  324. public function dailyPwOrderAdd($data,$user){
  325. list($status,$msg) = $this->dailyPwOrderRule($data, $user);
  326. if(!$status) return [$status,$msg];
  327. try {
  328. DB::beginTransaction();
  329. $model = new DailyPwOrder();
  330. $model->code = $this->generateBillNo([
  331. 'top_depart_id' => $user['top_depart_id'],
  332. 'type' => DailyPwOrder::Order_type,
  333. 'period' => date("Ym", $data['order_time'])
  334. ]);
  335. $model->order_time = $data['order_time'] ?? 0;
  336. $model->item_id = $data['item_id'] ?? 0;
  337. $model->crt_id = $user['id'];
  338. $model->top_depart_id = $data['top_depart_id'];
  339. $model->save();
  340. $this->saveDetailDaily($model->id, time(), $data, $user);
  341. DB::commit();
  342. }catch (\Exception $exception){
  343. DB::rollBack();
  344. return [false,$exception->getMessage()];
  345. }
  346. return [true, ''];
  347. }
  348. private function saveDetailDaily($id, $time, $data, $user){
  349. if(! empty($data['details'])){
  350. $unit = [];
  351. foreach ($data['details'] as $value){
  352. $unit[] = [
  353. 'main_id' => $id,
  354. 'employee_id' => $value['employee_id'],
  355. 'start_time_hour' => $value['start_time_hour'],
  356. 'start_time_min' => $value['start_time_min'],
  357. 'end_time_hour' => $value['end_time_hour'],
  358. 'end_time_min' => $value['end_time_min'],
  359. 'total_work_min' => $value['total_work_min'],
  360. 'crt_time' => $time,
  361. 'top_depart_id' => $value['top_depart_id'],
  362. 'order_time' => $data['order_time'] ?? 0,
  363. 'item_id' => $data['item_id'],
  364. 'crt_id' => $user['id'],
  365. ];
  366. }
  367. if(! empty($unit)) DailyPwOrderDetails::insert($unit);
  368. }
  369. }
  370. private function getDetailDaily($id){
  371. $data = DailyPwOrderDetails::where('del_time',0)
  372. ->where('main_id', $id)
  373. ->select('employee_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_work_min')
  374. ->get()->toArray();
  375. $id = array_column($data,'employee_id');
  376. $map = Employee::whereIn('id', $id)
  377. ->select('title','id','number')
  378. ->get()
  379. ->keyBy('id')
  380. ->toArray();
  381. foreach ($data as $key => $value){
  382. $tmp = $map[$value['employee_id']] ?? [];
  383. $merge = [];
  384. $merge['employee_title'] = $tmp['title'];
  385. $merge['employee_number'] = $tmp['number'];
  386. $data[$key] = array_merge($value, $merge);
  387. }
  388. $detail = [
  389. 'details' => $data,
  390. ];
  391. //foreach ($detail as $key => $value) {
  392. // if (empty($value)) {
  393. //$detail[$key] = (object)[]; // 转成 stdClass 对象
  394. //}
  395. //}
  396. return $detail;
  397. }
  398. public function dailyPwOrderDel($data, $user){
  399. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  400. try {
  401. DB::beginTransaction();
  402. $time = time();
  403. $month = DailyPwOrder::where('del_time',0)
  404. ->whereIn('id',$data['id'])
  405. ->pluck('order_time')
  406. ->toArray();
  407. //归档
  408. list($status, $msg) = ArchiveService::isArchive($month, $user);
  409. if(! $status) return [false, $msg];
  410. DailyPwOrder::where('del_time',0)
  411. ->whereIn('id',$data['id'])
  412. ->update(['del_time' => $time]);
  413. DailyPwOrderDetails::where('del_time',0)
  414. ->whereIn('main_id', $data['id'])
  415. ->update(['del_time' => $time]);
  416. DB::commit();
  417. }catch (\Exception $exception){
  418. DB::rollBack();
  419. return [false,$exception->getMessage()];
  420. }
  421. return [true, ''];
  422. }
  423. public function dailyPwOrderDetail($data, $user){
  424. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  425. $customer = DailyPwOrder::where('del_time',0)
  426. ->where('id',$data['id'])
  427. ->first();
  428. if(empty($customer)) return [false,'人员日工时单不存在或已被删除'];
  429. $customer = $customer->toArray();
  430. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  431. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  432. $item = Item::where('id', $customer['item_id'])->first();
  433. $customer['item_title'] = $item->title ?? '';
  434. $customer['item_code'] = $item->code ?? '';
  435. $map = ArchiveService::fillIsArchive($customer['order_time'], $user);
  436. $customer['is_archive'] = $map[$customer['order_time']] ?? false;
  437. $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
  438. $details = $this->getDetailDaily($data['id']);
  439. $customer = array_merge($customer, $details);
  440. return [true, $customer];
  441. }
  442. public function dailyPwOrderCommon($data,$user, $field = []){
  443. if(empty($field)) $field = DailyPwOrder::$field;
  444. $model = DailyPwOrder::Clear($user,$data);
  445. $model = $model->where('del_time',0)
  446. ->select($field)
  447. ->orderby('id', 'desc');
  448. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  449. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  450. $model->where('order_time','>=',$return[0]);
  451. $model->where('order_time','<=',$return[1]);
  452. }
  453. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  454. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  455. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  456. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  457. $model->where('crt_time','>=',$return[0]);
  458. $model->where('crt_time','<=',$return[1]);
  459. }
  460. if (!empty($data['item_title'])) {
  461. $models = Item::TopClear($user,$data);
  462. $id = $models->where('del_time',0)
  463. ->where('title', 'LIKE', '%'.$data['item_title'].'%')
  464. ->pluck('id')
  465. ->all();
  466. $model->whereIn('item_id', $id);
  467. }
  468. return $model;
  469. }
  470. public function dailyPwOrderList($data,$user){
  471. $model = $this->dailyPwOrderCommon($data, $user);
  472. $list = $this->limit($model,'',$data);
  473. $list = $this->fillDataDaily($list, $user);
  474. return [true, $list];
  475. }
  476. public function dailyPwOrderRule(&$data, $user, $is_add = true){
  477. $data['top_depart_id'] = $user['top_depart_id'];
  478. if(empty($data['order_time'])) return [false, '单据日期不能为空'];
  479. $data['order_time'] = $this->changeDateToDate($data['order_time']);
  480. $orderTime = $data['order_time'];
  481. $itemId = $data['item_id'] ?? 0;
  482. // 使用日期范围限制
  483. list($status, $msg) = MiddleGroundService::checkTimestampInRange($data['order_time'], $data['top_depart_id']);
  484. if(! $status) return [false, $msg];
  485. //归档
  486. list($status, $msg) = ArchiveService::isArchive($data['order_time'], $user);
  487. if(! $status) return [false, $msg];
  488. if(empty($itemId)) return [false, '项目不能为空'];
  489. $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
  490. if(!$bool) return [false, '项目不存在或已被删除'];
  491. if(empty($data['details'])) return [false, '人员日工时单明细不能为空'];
  492. // --- 1. 批量预获取人员信息,用于报错提示 ---
  493. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'employee_id')));
  494. // 如果需要工号+姓名,建议这样获取:
  495. $empDisplayMap = Employee::whereIn('id', $allEmpIds)
  496. ->get(['id', 'number', 'title'])
  497. ->mapWithKeys(function($item){
  498. return [$item->id => "[{$item->number}]{$item->title}"];
  499. })->toArray();
  500. // 2. 本次提交内部重叠记录器
  501. $internalOverlap = [];
  502. foreach ($data['details'] as $key => $value){
  503. $line = $key + 1;
  504. $t = "第" . $line . "行";
  505. $empId = $value['employee_id'] ?? 0;
  506. if(empty($empId)) return [false, '人员不能为空'];
  507. $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
  508. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  509. if(!$res['valid']) return [false, $t . "人员{$empName}开始点:" . $res['error']];
  510. if($value['start_time_hour'] > 23) return [false, false, $t . "人员{$empName}开始点不合法"];
  511. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  512. if(!$res['valid']) return [false, $t . "人员{$empName}开始分:" . $res['error']];
  513. if($value['start_time_min'] > 60) return [false, false, $t . "人员{$empName}开始点不合法"];
  514. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  515. if(!$res['valid']) return [false, $t . "人员{$empName}结束点:" . $res['error']];
  516. if($value['end_time_hour'] > 24) return [false, false, $t . "人员{$empName}结束点不合法"];
  517. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  518. if(!$res['valid']) return [false, $t . "人员{$empName}结束分:" . $res['error']];
  519. if($value['end_time_min'] > 60) return [false, false, $t . "人员{$empName}结束分不合法"];
  520. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  521. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  522. if ($currentStart >= $currentEnd) {
  523. return [false, $t . "人员{$empName}:开始时间必须早于结束时间"];
  524. }
  525. // --- 新增:总分钟数校验 ---
  526. $calculatedTotal = $currentEnd - $currentStart;
  527. if (!isset($value['total_work_min']) || intval($value['total_work_min']) !== $calculatedTotal) {
  528. return [false, $t . "人员{$empName}:总工时计算有误,应为 {$calculatedTotal} 分钟"];
  529. }
  530. // --- 3. 内部重叠校验(防止一次提交多行重复) ---
  531. if (isset($internalOverlap[$empId])) {
  532. foreach ($internalOverlap[$empId] as $period) {
  533. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  534. return [false, "人员{$empName}在本次提交的多行明细中时间段重叠"];
  535. }
  536. }
  537. }
  538. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  539. $query = DB::table('daily_pw_order_details as d')
  540. ->join('daily_pw_order as m', 'd.main_id', '=', 'm.id')
  541. ->where('m.top_depart_id', $data['top_depart_id'])
  542. ->where('m.order_time', $orderTime)
  543. ->where('m.item_id', $itemId)
  544. ->where('d.employee_id', $empId)
  545. ->where('m.del_time', 0)
  546. ->where('d.del_time', 0);
  547. if (!$is_add && !empty($data['id'])) {
  548. $query->where('m.id', '<>', $data['id']);
  549. }
  550. $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
  551. foreach ($existingPeriods as $p) {
  552. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  553. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  554. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  555. return [false, "人员{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
  556. }
  557. }
  558. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  559. }
  560. if(!$is_add){
  561. if(empty($data['id'])) return [false,'ID不能为空'];
  562. $bool = DailyPwOrder::where('top_depart_id', $data['top_depart_id'])
  563. ->where('id',$data['id'])
  564. ->where('del_time',0)
  565. ->exists();
  566. if(!$bool) return [false, '人员日工时单不存在或已被删除'];
  567. }
  568. return [true, ''];
  569. }
  570. public function fillDataDaily($data, $user){
  571. if(empty($data['data'])) return $data;
  572. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  573. $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_id')));
  574. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'order_time')), $user);
  575. foreach ($data['data'] as $key => $value){
  576. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  577. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  578. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  579. $item_tmp = $item[$value['item_id']] ?? [];
  580. $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
  581. $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
  582. $data['data'][$key]['is_archive'] = $map[$value['order_time']] ?? false;
  583. }
  584. return $data;
  585. }
  586. public function fillDataForExportDaily($data, $column, &$return)
  587. {
  588. if (empty($data)) return;
  589. $mainIds = array_column($data, 'id');
  590. // 1. 获取详情及所有关联档案(项目、人员)的映射
  591. $detailsMap = $this->getDailyDetailsMap($mainIds, $data);
  592. foreach ($data as $main) {
  593. $mainId = $main['id'];
  594. $details = $detailsMap[$mainId] ?? [];
  595. // 2. 提取并格式化主表共有信息
  596. $mainInfo = [
  597. 'code' => $main['code'],
  598. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  599. ];
  600. if (empty($details)) {
  601. // 无明细时只导出一行主表信息
  602. $tempRow = [];
  603. foreach ($column as $col) {
  604. $tempRow[] = $mainInfo[$col] ?? '';
  605. }
  606. $return[] = $tempRow;
  607. } else {
  608. // 3. 平铺:将详情里的项目信息、人员信息与主表信息合并
  609. foreach ($details as $sub) {
  610. $fullRowData = array_merge($mainInfo, $sub);
  611. $tempRow = [];
  612. foreach ($column as $col) {
  613. $tempRow[] = $fullRowData[$col] ?? '';
  614. }
  615. $return[] = $tempRow;
  616. }
  617. }
  618. }
  619. }
  620. public function getDailyDetailsMap($mainIds, $mainData)
  621. {
  622. // 1. 获取所有子表记录
  623. $details = DB::table('daily_pw_order_details')
  624. ->where('del_time', 0)
  625. ->whereIn('main_id', $mainIds)
  626. ->get();
  627. // 2. 提取所有关联 ID
  628. $empIds = $details->pluck('employee_id')->unique();
  629. $itemIds = array_unique(array_column($mainData, 'item_id')); // 从主表数组提取项目ID
  630. // 3. 批量获取档案 Map
  631. $empMap = DB::table('employee')
  632. ->whereIn('id', $empIds)
  633. ->get(['id', 'title', 'number'])
  634. ->keyBy('id');
  635. $itemMap = DB::table('item')
  636. ->whereIn('id', $itemIds)
  637. ->get(['id', 'title', 'code'])
  638. ->keyBy('id');
  639. // 4. 将主表的项目信息预先挂载到主表 ID 下,方便后续合并
  640. $mainItemInfo = [];
  641. foreach ($mainData as $m) {
  642. $proj = $itemMap[$m['item_id']] ?? null;
  643. $mainItemInfo[$m['id']] = [
  644. 'item_code' => $proj ? $proj->code : '',
  645. 'item_title' => $proj ? $proj->title : '',
  646. ];
  647. }
  648. $res = [];
  649. if ($details->isEmpty()) {
  650. // 如果没有详情,把项目信息返回去,确保主表能导出行
  651. foreach ($mainItemInfo as $mId => $info) {
  652. $res[$mId] = [];
  653. }
  654. return $res;
  655. }
  656. foreach ($details as $item) {
  657. $emp = $empMap[$item->employee_id] ?? null;
  658. // 组装明细行数据
  659. $detailRow = [
  660. // 人员信息
  661. 'employee_number' => $emp ? $emp->number : '',
  662. 'employee_title' => $emp ? $emp->title : '',
  663. // 时间信息
  664. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  665. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  666. // 将主表的项目信息也塞进每一行详情里实现平铺
  667. 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
  668. 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
  669. 'total_work_min' => $item->total_work_min,
  670. ];
  671. $res[$item->main_id][] = $detailRow;
  672. }
  673. return $res;
  674. }
  675. public function dailyPwOrderCreate($data, $user)
  676. {
  677. $topDepartId = $user['top_depart_id'];
  678. if (empty($data['month'])) return [false, '月份不能为空'];
  679. $monthStart = $this->changeDateToDate($data['month']);
  680. // --- 一开始就做的核心校验 ---
  681. // 1. 检查是否存在月度工时明细(如果没有,队列执行也是徒劳)
  682. $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
  683. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  684. ->where('m.month', $monthStart)
  685. ->where('m.top_depart_id', $topDepartId)
  686. ->where('m.del_time', 0)
  687. ->where('d.del_time', 0)
  688. ->exists();
  689. if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
  690. // 2. 检查是否配置了工作日历
  691. $hasCalendar = DB::table('calendar_details')
  692. ->where('month', $monthStart)
  693. ->where('del_time', 0)
  694. ->exists();
  695. if (!$hasCalendar) return [false, '该月份工作日历未配置'];
  696. // 3. 检查是否配置了项目比例规则
  697. $hasRules = DB::table('rule_set as r')
  698. ->where('r.month', $monthStart)
  699. ->where('r.top_depart_id', $topDepartId)
  700. ->where('r.del_time', 0)
  701. ->exists();
  702. if (!$hasRules) return [false, '未找到该月份的规则配置单'];
  703. $data['type'] = "p_work";
  704. ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
  705. return [true, '生成任务已提交,系统正在后台处理,请稍后查看'];
  706. }
  707. public function dailyPwOrderCreateMain($data, $user)
  708. {
  709. $topDepartId = $user['top_depart_id'];
  710. if (empty($data['month'])) return [false, '月份不能为空'];
  711. $monthStart = $this->changeDateToDate($data['month']);
  712. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  713. $now = time();
  714. DB::beginTransaction();
  715. try {
  716. // --- 0. 清理旧数据 ---
  717. $oldOrderIds = DB::table('daily_pw_order')
  718. ->where('top_depart_id', $topDepartId)
  719. ->where('order_time', '>=', $monthStart)
  720. ->where('order_time', '<=', $monthEnd)
  721. ->where('is_create', 1)
  722. ->where('del_time', 0)
  723. ->pluck('id');
  724. if ($oldOrderIds->isNotEmpty()) {
  725. DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  726. DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  727. }
  728. // --- 1. 基础数据加载 ---
  729. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  730. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  731. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  732. ->where('m.del_time', 0)->where('d.del_time', 0)
  733. ->select('d.*')->get();
  734. if ($monthlyOrder->isEmpty()) return [false, '未找到月度工时明细'];
  735. $empIds = $monthlyOrder->pluck('employee_id')->unique()->toArray();
  736. $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  737. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  738. $ruleSet = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  739. ->where('r.month', $monthStart)->where('rd.type', RuleSetDetails::type_one)
  740. ->where('r.del_time', 0)->where('rd.del_time', 0)
  741. ->select('rd.*')->get()->groupBy('data_id');
  742. $allDays = DB::table('calendar_details')->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
  743. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  744. ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('m.del_time', 0)
  745. ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
  746. // --- 2. 核心分配逻辑:计算每天、每个项目、每个人的分钟数 ---
  747. $finalAlloc = [];
  748. foreach ($monthlyOrder as $mDetail) {
  749. $empId = $mDetail->employee_id;
  750. $empRules = $ruleSet->get($empId);
  751. if (!$empRules) continue;
  752. $empRemainingMin = (float)$mDetail->rd_total_hours * 60;
  753. if ($empRemainingMin <= 0) continue;
  754. foreach ($allDays as $dayInfo) {
  755. if ($empRemainingMin <= 0) break;
  756. $dayTs = $dayInfo->time;
  757. $isWorkDay = ($dayInfo->is_work == CalendarDetails::TYPE_ONE);
  758. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  759. $todayOvertimes = $todaySpecials->where('main_type', 2);
  760. if (!$isWorkDay && $todayOvertimes->isEmpty()) continue;
  761. // 计算当天可用总时长
  762. $dayAvailableMin = 0;
  763. if ($isWorkDay) {
  764. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  765. foreach ($baseRanges as $br) {
  766. $brS = $br->start_time_hour * 60 + $br->start_time_min;
  767. $brE = $br->end_time_hour * 60 + $br->end_time_min;
  768. $avail = (float)$br->total_work_min;
  769. foreach ($todaySpecials->where('main_type', 1) as $lv) {
  770. $overlap = min($brE, ($lv->end_time_hour * 60 + $lv->end_time_min)) - max($brS, ($lv->start_time_hour * 60 + $lv->start_time_min));
  771. if ($overlap > 0) $avail -= $overlap;
  772. }
  773. $dayAvailableMin += max(0, $avail);
  774. }
  775. }
  776. foreach ($todayOvertimes as $ot) $dayAvailableMin += (float)$ot->total_min;
  777. $canAllocToday = min($empRemainingMin, $dayAvailableMin);
  778. if ($canAllocToday <= 0) continue;
  779. foreach ($empRules as $rule) {
  780. $rate = (float)$rule->rate / 100;
  781. $projectMin = $canAllocToday * $rate;
  782. if ($projectMin > 0) {
  783. // 结果存入:[日期][项目][人员]
  784. $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
  785. }
  786. }
  787. $empRemainingMin -= $canAllocToday;
  788. }
  789. }
  790. // --- 3. 生成单据:解决时间重叠的核心逻辑 ---
  791. $newOrderIds = [];
  792. // 为了解决重叠,我们需要按 [日期][人员] 来追踪时间池的消耗进度
  793. $dailyEmpTimePools = [];
  794. foreach ($finalAlloc as $dayTs => $projects) {
  795. foreach ($projects as $itemId => $employees) {
  796. $mainId = DB::table('daily_pw_order')->insertGetId([
  797. 'code' => '', 'item_id' => $itemId, 'order_time' => $dayTs, 'top_depart_id' => $topDepartId,
  798. 'is_create' => 1, 'crt_id' => $user['id'], 'crt_time' => $now, 'upd_time' => $now,
  799. ]);
  800. $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
  801. foreach ($employees as $empId => $toAllocMin) {
  802. // 如果该员工当天的池子还没构建,先构建一次
  803. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  804. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  805. }
  806. $tempRem = $toAllocMin;
  807. // 指向该员工当天的可用池引用,这样处理完项目A,池子里的时间会自动被“消耗”
  808. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  809. if ($tempRem <= 0) break;
  810. $pMax = $p['e'] - $p['s'];
  811. if ($pMax <= 0) continue;
  812. $take = min($tempRem, $pMax);
  813. $realStart = $p['s'];
  814. $realEnd = $p['s'] + $take;
  815. DB::table('daily_pw_order_details')->insert([
  816. 'main_id' => $mainId, 'employee_id' => $empId, 'top_depart_id' => $topDepartId,
  817. 'start_time_hour' => floor($realStart / 60), 'start_time_min' => $realStart % 60,
  818. 'end_time_hour' => floor($realEnd / 60), 'end_time_min' => $realEnd % 60,
  819. 'total_work_min' => $take, 'crt_time' => $now, 'upd_time' => $now,
  820. ]);
  821. $tempRem -= $take;
  822. // 重要:消耗掉这个时段的起始位置,确保下一个项目从这里开始
  823. $p['s'] = $realEnd;
  824. }
  825. }
  826. }
  827. }
  828. // --- 4. 回填单号 ---
  829. if (empty($newOrderIds)) return [false, '未生成数据'];
  830. foreach ($newOrderIds as $item) {
  831. $code = $this->generateBillNo(['top_depart_id' => $topDepartId, 'type' => DailyPwOrder::Order_type, 'period' => date("Ym", $item['time'])]);
  832. DB::table('daily_pw_order')->where('id', $item['id'])->update(['code' => $code]);
  833. }
  834. DB::commit();
  835. } catch (\Exception $e) {
  836. DB::rollBack();
  837. return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
  838. }
  839. return [true, ''];
  840. }
  841. /**
  842. * 辅助函数:构建某人某天的初始可用时段池
  843. */
  844. private function buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData)
  845. {
  846. $dayInfo = $allDays->where('time', $dayTs)->first();
  847. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  848. $pool = [];
  849. if ($dayInfo && $dayInfo->is_work == CalendarDetails::TYPE_ONE) {
  850. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  851. foreach ($baseRanges as $br) {
  852. $currentS = $br->start_time_hour * 60 + $br->start_time_min;
  853. $eMin = $br->end_time_hour * 60 + $br->end_time_min;
  854. $sortedLeaves = $todaySpecials->where('main_type', 1)->sortBy('start_time_hour');
  855. foreach ($sortedLeaves as $lv) {
  856. $lvS = $lv->start_time_hour * 60 + $lv->start_time_min;
  857. $lvE = $lv->end_time_hour * 60 + $lv->end_time_min;
  858. if ($lvS < $eMin && $lvE > $currentS) {
  859. if ($lvS > $currentS) $pool[] = ['s' => $currentS, 'e' => $lvS];
  860. $currentS = max($currentS, $lvE);
  861. }
  862. }
  863. if ($currentS < $eMin) $pool[] = ['s' => $currentS, 'e' => $eMin];
  864. }
  865. }
  866. foreach ($todaySpecials->where('main_type', 2) as $ot) {
  867. $otS = $ot->start_time_hour * 60 + $ot->start_time_min;
  868. $pool[] = ['s' => $otS, 'e' => $otS + (float)$ot->total_min];
  869. }
  870. return $pool;
  871. }
  872. public function dailyPwOrderPreview($data, $user)
  873. {
  874. $topDepartId = $user['top_depart_id'];
  875. if (empty($data['month'])) return [false, '月份不能为空'];
  876. // 1. 前置校验 (保留你之前的校验逻辑)
  877. $monthStart = $this->changeDateToDate($data['month']);
  878. //归档
  879. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  880. if(! $status) return [false, $msg];
  881. // 1. 检查是否存在月度工时明细
  882. $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
  883. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  884. ->where('m.month', $monthStart)
  885. ->where('m.top_depart_id', $topDepartId)
  886. ->where('m.del_time', 0)
  887. ->where('d.del_time', 0)
  888. ->exists();
  889. if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
  890. // 2. 检查是否配置了工作日历
  891. $hasCalendar = DB::table('calendar_details')
  892. ->where('month', $monthStart)
  893. ->where('del_time', 0)
  894. ->exists();
  895. if (!$hasCalendar) return [false, '该月份工作日历未配置'];
  896. // 3. 检查是否配置了项目比例规则
  897. $hasRules = DB::table('rule_set as r')
  898. ->where('r.month', $monthStart)
  899. ->where('r.top_depart_id', $topDepartId)
  900. ->where('r.del_time', 0)
  901. ->exists();
  902. if (!$hasRules) return [false, '未找到该月份的规则配置单'];
  903. // 2. 调用核心计算逻辑 (抽取出的私有方法)
  904. $result = $this->calculateDailyAllocation($monthStart, $topDepartId, $user);
  905. if (!$result['status']) return [false, $result['msg']];
  906. // 3. 将结果存入临时表或直接返回
  907. // 建议增加一个 batch_id,防止多人操作冲突
  908. $batchId = uniqid('batch_');
  909. $previewData = $result['data'];
  910. return [true, [
  911. 'batch_id' => $batchId,
  912. 'list' => $previewData // 返回给前端展示
  913. ]];
  914. // $total = 0;
  915. // foreach ($previewData as $value){
  916. // if($value['employee_id'] == 142 && $value['item_id'] == 122) $total += $value['total_work_min'];
  917. // }dd($total);
  918. }
  919. /**
  920. * 核心分配逻辑:计算预览数据(确保全整数分钟)
  921. * @param int $monthStart 月初时间戳
  922. * @param int $topDepartId 顶级部门ID
  923. * @param array $user 用户信息
  924. * @return array
  925. */
  926. private function calculateDailyAllocation1($monthStart, $topDepartId, $user)
  927. {
  928. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  929. $now = time();
  930. // --- 1. 基础数据加载 ---
  931. // 加载月度工时明细,并关联人员姓名
  932. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  933. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  934. ->leftJoin('employee as e', 'e.id', '=', 'd.employee_id') // 关联人员表
  935. ->where('m.month', $monthStart)
  936. ->where('m.top_depart_id', $topDepartId)
  937. ->where('m.del_time', 0)
  938. ->where('d.del_time', 0)
  939. ->select('d.*', 'e.title as employee_title') // 获取人员姓名
  940. ->get();
  941. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到该月份的月度工时明细'];
  942. // 建立人员 ID -> 姓名的映射,方便后续取用
  943. $empNameMap = $monthlyOrder->pluck('employee_title', 'employee_id')->toArray();
  944. $empIds = array_keys($empNameMap);
  945. // 加载项目信息,用于获取项目名称
  946. // 假设项目表名为 items,请根据你实际的表名修改
  947. $itemIds = DB::table('rule_set_details as rd')
  948. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  949. ->where('r.month', $monthStart)
  950. ->where('r.top_depart_id', $topDepartId)
  951. ->pluck('rd.item_id')->unique()->toArray();
  952. $itemMap = DB::table('item')
  953. ->whereIn('id', $itemIds)
  954. ->pluck('title', 'id')
  955. ->toArray();
  956. // 加载分配规则
  957. $ruleSet = DB::table('rule_set_details as rd')
  958. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  959. ->where('r.month', $monthStart)
  960. ->where('rd.type', 1)
  961. ->where('r.del_time', 0)
  962. ->where('rd.del_time', 0)
  963. ->select('rd.*')
  964. ->get()
  965. ->groupBy('data_id');
  966. // 加载员工/标准班次、日历、请假加班数据 (逻辑同前)
  967. $empWorkRanges = DB::table('employee_work_range')
  968. ->whereIn('employee_id', $empIds)
  969. ->where('top_depart_id', $topDepartId)
  970. ->get()->groupBy('employee_id');
  971. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)
  972. ->where('del_time', 0)->get();
  973. $allDays = DB::table('calendar_details')->where('top_depart_id', $topDepartId)
  974. ->where('month', $monthStart)
  975. ->where('del_time', 0)
  976. ->orderBy('time', 'asc')
  977. ->get();
  978. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  979. ->whereBetween('m.order_time', [$monthStart, $monthEnd])
  980. ->where('d.top_depart_id', $topDepartId)
  981. ->where('m.del_time', 0)
  982. ->select('d.*', 'm.order_time', 'm.type as main_type')
  983. ->get()->groupBy(['employee_id', 'order_time']);
  984. // --- 2. 阶段一:计算每个人每天在每个项目上应分配的整数分钟数 ---
  985. $finalAlloc = [];
  986. foreach ($monthlyOrder as $mDetail) {
  987. $empId = $mDetail->employee_id;
  988. $empRules = $ruleSet->get($empId);
  989. if (!$empRules) continue;
  990. $empRemainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  991. if ($empRemainingMin <= 0) continue;
  992. foreach ($allDays as $dayInfo) {
  993. if ($empRemainingMin <= 0) break;
  994. $dayTs = $dayInfo->time;
  995. $tempPool = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  996. $dayAvailableMin = 0;
  997. foreach ($tempPool as $p) { $dayAvailableMin += (int)($p['e'] - $p['s']); }
  998. if ($dayAvailableMin <= 0) continue;
  999. $canAllocToday = min($empRemainingMin, $dayAvailableMin);
  1000. $allocatedInDay = 0;
  1001. $ruleCount = count($empRules);
  1002. foreach ($empRules as $index => $rule) {
  1003. $rate = (float)$rule->rate / 100;
  1004. if ($index === $ruleCount - 1) {
  1005. $projectMin = $canAllocToday - $allocatedInDay;
  1006. } else {
  1007. $projectMin = (int)round($canAllocToday * $rate);
  1008. }
  1009. if ($projectMin > 0) {
  1010. $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
  1011. $allocatedInDay += $projectMin;
  1012. }
  1013. }
  1014. $empRemainingMin -= $canAllocToday;
  1015. }
  1016. }
  1017. // --- 3. 阶段二:打散到具体时间点并生成预览行 ---
  1018. $previewList = [];
  1019. $dailyEmpTimePools = [];
  1020. $tempMainIdCounter = 1;
  1021. foreach ($finalAlloc as $dayTs => $projects) {
  1022. foreach ($projects as $itemId => $employees) {
  1023. $currentTempMainId = $tempMainIdCounter++;
  1024. // 获取项目名称
  1025. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  1026. foreach ($employees as $empId => $toAllocMin) {
  1027. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  1028. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  1029. }
  1030. $tempRem = (int)$toAllocMin;
  1031. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  1032. if ($tempRem <= 0) break;
  1033. $pMax = (int)($p['e'] - $p['s']);
  1034. if ($pMax <= 0) continue;
  1035. $take = min($tempRem, $pMax);
  1036. $realStart = (int)$p['s'];
  1037. $realEnd = $realStart + $take;
  1038. // 写入带 Title 的结果
  1039. $previewList[] = [
  1040. 'temp_main_id' => $currentTempMainId,
  1041. 'order_time' => date('Y-m-d', $dayTs),
  1042. 'order_timestamp' => $dayTs,
  1043. 'item_id' => $itemId,
  1044. 'item_title' => $itemTitle, // 项目名称
  1045. 'employee_id' => $empId,
  1046. 'employee_title' => $empNameMap[$empId] ?? '未知人员', // 人员姓名
  1047. 'start_time' => sprintf('%02d:%02d', floor($realStart / 60), $realStart % 60),
  1048. 'end_time' => sprintf('%02d:%02d', floor($realEnd / 60), $realEnd % 60),
  1049. 'start_hour' => (int)floor($realStart / 60),
  1050. 'start_min' => (int)($realStart % 60),
  1051. 'end_hour' => (int)floor($realEnd / 60),
  1052. 'end_min' => (int)($realEnd % 60),
  1053. 'total_work_min' => $take,
  1054. ];
  1055. $tempRem -= $take;
  1056. $p['s'] = $realEnd;
  1057. }
  1058. }
  1059. }
  1060. }
  1061. return ['status' => true, 'data' => $previewList];
  1062. }
  1063. private function calculateDailyAllocation($monthStart, $topDepartId, $user)
  1064. {
  1065. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  1066. $step = 5; // 尽量 5 分钟对齐;明细允许个别非整 5
  1067. // --- 1. 基础数据加载 ---
  1068. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  1069. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  1070. ->leftJoin('employee as e', 'e.id', '=', 'd.employee_id')
  1071. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  1072. ->where('m.del_time', 0)->where('d.del_time', 0)
  1073. ->select('d.*', 'e.title as employee_title')->get();
  1074. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到明细'];
  1075. $empNameMap = $monthlyOrder->pluck('employee_title', 'employee_id')->toArray();
  1076. $empIds = array_keys($empNameMap);
  1077. $itemIds = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  1078. ->where('r.month', $monthStart)->where('r.top_depart_id', $topDepartId)->pluck('rd.item_id')->unique()->toArray();
  1079. $itemMap = DB::table('item')->whereIn('id', $itemIds)->pluck('title', 'id')->toArray();
  1080. $ruleSet = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  1081. ->where('r.month', $monthStart)->where('rd.type', 1)->where('r.del_time', 0)->where('rd.del_time', 0)
  1082. ->select('rd.*')->get()->groupBy('data_id');
  1083. $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  1084. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  1085. $allDays = DB::table('calendar_details')->where('top_depart_id', $topDepartId)->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
  1086. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  1087. ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('d.top_depart_id', $topDepartId)->where('m.del_time', 0)
  1088. ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
  1089. // --- 2. 阶段一:先锁定「项目月目标分钟」,再按剩余目标往工作日摊 ---
  1090. // 保证:各项目月合计 = 月总 × 比例(末项吃余数);人员月总不变
  1091. $finalAlloc = [];
  1092. $dayBalance = []; // 按天 5 分钟取整时的滚动余额
  1093. foreach ($monthlyOrder as $mDetail) {
  1094. $empId = $mDetail->employee_id;
  1095. $empRules = $ruleSet->get($empId);
  1096. if (!$empRules || $empRules->isEmpty()) continue;
  1097. $empTotalMin = (int)round((float)$mDetail->rd_total_hours * 60);
  1098. if ($empTotalMin <= 0) continue;
  1099. // 2.1 各项目月目标(非末项按比例取整,末项保证加总 = 月总)
  1100. $rules = $empRules->values();
  1101. $ruleCount = $rules->count();
  1102. $projTarget = [];
  1103. $assigned = 0;
  1104. foreach ($rules as $index => $rule) {
  1105. $itemId = (int)$rule->item_id;
  1106. if ($index === $ruleCount - 1) {
  1107. $projTarget[$itemId] = ($projTarget[$itemId] ?? 0) + max(0, $empTotalMin - $assigned);
  1108. } else {
  1109. $part = (int)round($empTotalMin * ((float)$rule->rate / 100));
  1110. $projTarget[$itemId] = ($projTarget[$itemId] ?? 0) + $part;
  1111. $assigned += $part;
  1112. }
  1113. }
  1114. // 极端情况:非末项 round 累加超过月总,压回末项
  1115. $sumTarget = array_sum($projTarget);
  1116. if ($sumTarget > $empTotalMin) {
  1117. $lastItemId = (int)$rules[$ruleCount - 1]->item_id;
  1118. $projTarget[$lastItemId] = max(0, $projTarget[$lastItemId] - ($sumTarget - $empTotalMin));
  1119. }
  1120. $projRem = $projTarget;
  1121. $empRemainingMin = $empTotalMin;
  1122. // 2.2 预计算有容量的工作日
  1123. $dayCaps = [];
  1124. foreach ($allDays as $dayInfo) {
  1125. $dayTs = $dayInfo->time;
  1126. $tempPool = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  1127. $dayCapacity = 0;
  1128. foreach ($tempPool as $p) {
  1129. $dayCapacity += (int)($p['e'] - $p['s']);
  1130. }
  1131. if ($dayCapacity > 0) {
  1132. $dayCaps[$dayTs] = $dayCapacity;
  1133. }
  1134. }
  1135. if (empty($dayCaps)) continue;
  1136. $dayTsList = array_keys($dayCaps);
  1137. $dayIndex = 0;
  1138. $dayCount = count($dayTsList);
  1139. foreach ($dayTsList as $dayTs) {
  1140. if ($empRemainingMin <= 0) break;
  1141. if (array_sum($projRem) <= 0) break;
  1142. $dayCapacity = $dayCaps[$dayTs];
  1143. $theoryAlloc = min($empRemainingMin, $dayCapacity);
  1144. $isLastDay = ($dayIndex === $dayCount - 1) || ($theoryAlloc >= $empRemainingMin);
  1145. // 当天总量尽量 5 对齐;最后一天(或最后一批)吃干净,允许非整 5
  1146. if (!$isLastDay) {
  1147. $currentWithBalance = $theoryAlloc + ($dayBalance[$empId] ?? 0);
  1148. $roundedAlloc = (int)round($currentWithBalance / $step) * $step;
  1149. $canAllocToday = min($roundedAlloc, $dayCapacity, $empRemainingMin);
  1150. // 不能把某天抽成 0 导致后面更难摊完
  1151. if ($canAllocToday <= 0 && $theoryAlloc > 0) {
  1152. $canAllocToday = min($theoryAlloc, $empRemainingMin);
  1153. }
  1154. $dayBalance[$empId] = $currentWithBalance - $canAllocToday;
  1155. } else {
  1156. $canAllocToday = min($empRemainingMin, $dayCapacity);
  1157. $dayBalance[$empId] = 0;
  1158. }
  1159. if ($canAllocToday <= 0) {
  1160. $dayIndex++;
  1161. continue;
  1162. }
  1163. // 按「项目剩余月目标」比例拆当天额度(最大余数法),保证月末项目合计贴近目标
  1164. $dayParts = $this->splitMinutesByRemaining($canAllocToday, $projRem, $step, $isLastDay);
  1165. foreach ($dayParts as $itemId => $projectMin) {
  1166. if ($projectMin <= 0) continue;
  1167. $finalAlloc[$dayTs][$itemId][$empId] = ($finalAlloc[$dayTs][$itemId][$empId] ?? 0) + $projectMin;
  1168. $projRem[$itemId] = max(0, ($projRem[$itemId] ?? 0) - $projectMin);
  1169. }
  1170. $empRemainingMin -= $canAllocToday;
  1171. $dayIndex++;
  1172. }
  1173. // 2.3 若因取整/容量仍有项目剩余,尽量塞进后续仍有空闲的天
  1174. $stuck = array_sum($projRem);
  1175. if ($stuck > 0) {
  1176. foreach ($dayCaps as $dayTs => $dayCapacity) {
  1177. if ($stuck <= 0) break;
  1178. $used = 0;
  1179. if (!empty($finalAlloc[$dayTs])) {
  1180. foreach ($finalAlloc[$dayTs] as $emps) {
  1181. $used += (int)($emps[$empId] ?? 0);
  1182. }
  1183. }
  1184. $free = $dayCapacity - $used;
  1185. if ($free <= 0) continue;
  1186. foreach ($projRem as $itemId => $rem) {
  1187. if ($rem <= 0 || $free <= 0) continue;
  1188. $take = min($rem, $free);
  1189. $finalAlloc[$dayTs][$itemId][$empId] = ($finalAlloc[$dayTs][$itemId][$empId] ?? 0) + $take;
  1190. $projRem[$itemId] -= $take;
  1191. $free -= $take;
  1192. $stuck -= $take;
  1193. }
  1194. }
  1195. }
  1196. }
  1197. // --- 3. 阶段二:打散到具体时间点(起点尽量 5 对齐;单条时长允许非整 5) ---
  1198. $previewList = [];
  1199. $dailyEmpTimePools = [];
  1200. $tempMainIdCounter = 1;
  1201. foreach ($finalAlloc as $dayTs => $projects) {
  1202. foreach ($projects as $itemId => $employees) {
  1203. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  1204. foreach ($employees as $empId => $toAllocMin) {
  1205. $currentTempMainId = $tempMainIdCounter++;
  1206. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  1207. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool(
  1208. $empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData
  1209. );
  1210. }
  1211. $tempRem = (int)$toAllocMin;
  1212. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  1213. if ($tempRem <= 0) break;
  1214. $rawStart = (int)$p['s'];
  1215. $alignedStart = (int)ceil($rawStart / $step) * $step;
  1216. // 对齐后仍够放下剩余(或至少还能放下一段)则对齐;否则用原始起点(允许个别不对齐)
  1217. if ($alignedStart < $p['e'] && ($p['e'] - $alignedStart) >= min($tempRem, 1)) {
  1218. $realStart = $alignedStart;
  1219. } else {
  1220. $realStart = $rawStart;
  1221. }
  1222. if ($realStart >= $p['e']) continue;
  1223. $pMax = (int)($p['e'] - $realStart);
  1224. $take = min($tempRem, $pMax);
  1225. // 本段还放不完时,优先按 5 截取,余数留给后续时段;最后一段(take==tempRem)保持精确
  1226. if ($take < $tempRem && $take >= $step) {
  1227. $alignedTake = (int)floor($take / $step) * $step;
  1228. if ($alignedTake > 0) {
  1229. $take = $alignedTake;
  1230. }
  1231. }
  1232. $realEnd = $realStart + $take;
  1233. $previewList[] = [
  1234. 'temp_main_id' => $currentTempMainId,
  1235. 'order_time' => date('Y-m-d', $dayTs),
  1236. 'order_timestamp' => $dayTs,
  1237. 'item_id' => $itemId,
  1238. 'item_title' => $itemTitle,
  1239. 'employee_id' => $empId,
  1240. 'employee_title' => $empNameMap[$empId] ?? '未知人员',
  1241. 'start_time' => sprintf('%02d:%02d', floor($realStart / 60), $realStart % 60),
  1242. 'end_time' => sprintf('%02d:%02d', floor($realEnd / 60), $realEnd % 60),
  1243. 'start_hour' => (int)floor($realStart / 60),
  1244. 'start_min' => (int)($realStart % 60),
  1245. 'end_hour' => (int)floor($realEnd / 60),
  1246. 'end_min' => (int)($realEnd % 60),
  1247. 'total_work_min' => $take,
  1248. ];
  1249. $tempRem -= $take;
  1250. $p['s'] = $realEnd;
  1251. }
  1252. unset($p);
  1253. }
  1254. }
  1255. }
  1256. return ['status' => true, 'data' => $previewList];
  1257. }
  1258. /**
  1259. * 按各项目剩余月目标,把当天额度拆开(最大余数法)
  1260. * - 非最后一天:尽量按 5 分钟块分配
  1261. * - 最后一天:允许 1 分钟精度,保证项目目标吃干净
  1262. *
  1263. * @param int $dayBudget 当天可分配总分钟
  1264. * @param array $projRem [item_id => 剩余目标分钟]
  1265. * @param int $step
  1266. * @param bool $forceExact 是否强制精确分完(最后一天)
  1267. * @return array [item_id => 当天分配分钟]
  1268. */
  1269. private function splitMinutesByRemaining($dayBudget, array $projRem, $step = 5, $forceExact = false)
  1270. {
  1271. $active = [];
  1272. foreach ($projRem as $itemId => $rem) {
  1273. if ($rem > 0) {
  1274. $active[(int)$itemId] = (int)$rem;
  1275. }
  1276. }
  1277. if (empty($active) || $dayBudget <= 0) {
  1278. return [];
  1279. }
  1280. $totalRem = array_sum($active);
  1281. $dayBudget = min($dayBudget, $totalRem);
  1282. $result = array_fill_keys(array_keys($active), 0);
  1283. if ($forceExact || $dayBudget < $step) {
  1284. // 精确拆:按比例 floor + 最大余数补齐
  1285. $order = [];
  1286. $used = 0;
  1287. foreach ($active as $itemId => $rem) {
  1288. $ideal = $dayBudget * $rem / $totalRem;
  1289. $base = (int)floor($ideal);
  1290. $base = min($base, $rem);
  1291. $result[$itemId] = $base;
  1292. $used += $base;
  1293. $order[] = [
  1294. 'item_id' => $itemId,
  1295. 'frac' => $ideal - $base,
  1296. 'rem' => $rem - $base,
  1297. ];
  1298. }
  1299. usort($order, function ($a, $b) {
  1300. if ($a['frac'] == $b['frac']) {
  1301. return $b['rem'] <=> $a['rem'];
  1302. }
  1303. return $b['frac'] <=> $a['frac'];
  1304. });
  1305. $left = $dayBudget - $used;
  1306. foreach ($order as $row) {
  1307. if ($left <= 0) break;
  1308. if ($row['rem'] <= 0) continue;
  1309. $give = min($left, $row['rem']);
  1310. $result[$row['item_id']] += $give;
  1311. $left -= $give;
  1312. }
  1313. return array_filter($result);
  1314. }
  1315. // 非最后:先按 5 分钟块分配,余数分钟先留在余额逻辑里由后续天消化
  1316. $blockBudget = (int)floor($dayBudget / $step) * $step;
  1317. if ($blockBudget <= 0) {
  1318. // 当天不足 5 分钟,直接精确分掉
  1319. return $this->splitMinutesByRemaining($dayBudget, $active, $step, true);
  1320. }
  1321. $blocks = (int)($blockBudget / $step);
  1322. $blockRem = [];
  1323. foreach ($active as $itemId => $rem) {
  1324. $blockRem[$itemId] = (int)floor($rem / $step); // 项目剩余可占的整块数上限
  1325. }
  1326. // 权重仍用剩余分钟
  1327. $order = [];
  1328. $usedBlocks = 0;
  1329. foreach ($active as $itemId => $rem) {
  1330. $idealBlocks = $blocks * $rem / $totalRem;
  1331. $base = (int)floor($idealBlocks);
  1332. $maxBlocks = $blockRem[$itemId];
  1333. $base = min($base, $maxBlocks);
  1334. $result[$itemId] = $base * $step;
  1335. $usedBlocks += $base;
  1336. $order[] = [
  1337. 'item_id' => $itemId,
  1338. 'frac' => $idealBlocks - $base,
  1339. 'rem_blocks' => $maxBlocks - $base,
  1340. ];
  1341. }
  1342. usort($order, function ($a, $b) {
  1343. if ($a['frac'] == $b['frac']) {
  1344. return $b['rem_blocks'] <=> $a['rem_blocks'];
  1345. }
  1346. return $b['frac'] <=> $a['frac'];
  1347. });
  1348. $leftBlocks = $blocks - $usedBlocks;
  1349. foreach ($order as $row) {
  1350. if ($leftBlocks <= 0) break;
  1351. if ($row['rem_blocks'] <= 0) continue;
  1352. $result[$row['item_id']] += $step;
  1353. $leftBlocks--;
  1354. }
  1355. // 当天 dayBudget 里不足一块的零头(1~4 分钟):补给剩余目标最大的项目(允许个别非整 5)
  1356. $odd = $dayBudget - $blockBudget;
  1357. if ($odd > 0) {
  1358. arsort($active);
  1359. foreach ($active as $itemId => $rem) {
  1360. $already = $result[$itemId] ?? 0;
  1361. if ($already >= $rem) continue;
  1362. $give = min($odd, $rem - $already);
  1363. $result[$itemId] = $already + $give;
  1364. break;
  1365. }
  1366. }
  1367. return array_filter($result);
  1368. }
  1369. public function dailyPwOrderSave($data, $user)
  1370. {
  1371. $list = $data['list'] ?? [];
  1372. if (empty($list)) return [false, '没有可保存的数据'];
  1373. $topDepartId = $user['top_depart_id'];
  1374. $month = $data['month'];
  1375. $monthStart = $this->changeDateToDate($month);
  1376. //归档
  1377. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  1378. if(! $status) return [false, $msg];
  1379. $now = time();
  1380. // 1. 预加载员工名称映射 (使用 title 字段)
  1381. $empIds = collect($list)->pluck('employee_id')->unique()->toArray();
  1382. $empMap = DB::table('employee')->whereIn('id', $empIds)->pluck('title', 'id')->toArray();
  1383. // --- 2. 重新分组并记录行号 ---
  1384. $groupedByOrder = [];
  1385. foreach ($list as $index => $item) {
  1386. $item['_line'] = $index + 1; // 记录原始行号(从1开始)
  1387. // 以日期字符串和项目ID作为分组 Key
  1388. $groupKey = $item['order_time'] . '_' . $item['item_id'];
  1389. $groupedByOrder[$groupKey][] = $item;
  1390. }
  1391. // 冲突校验器容器:记录 [员工ID][日期字符串] 下已占用的时间段
  1392. $empTimeline = [];
  1393. DB::beginTransaction();
  1394. try {
  1395. // A. 清理该月份旧数据
  1396. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  1397. $oldOrderIds = DB::table('daily_pw_order')
  1398. ->where('top_depart_id', $topDepartId)
  1399. ->whereBetween('order_time', [$monthStart, $monthEnd])
  1400. ->where('del_time', 0)
  1401. ->pluck('id');
  1402. if ($oldOrderIds->isNotEmpty()) {
  1403. DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  1404. DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  1405. }
  1406. // B. 遍历重组后的分组写入
  1407. foreach ($groupedByOrder as $details) {
  1408. $first = $details[0];
  1409. // 【修正】统一将前端日期字符串转为时间戳入库
  1410. $orderTimestamp = strtotime($first['order_time']);
  1411. $itemId = $first['item_id'];
  1412. // 写入主表
  1413. $mainId = DB::table('daily_pw_order')->insertGetId([
  1414. 'code' => '',
  1415. 'item_id' => $itemId,
  1416. 'order_time' => $orderTimestamp,
  1417. 'top_depart_id' => $topDepartId,
  1418. 'is_create' => 1,
  1419. 'crt_id' => $user['id'],
  1420. 'crt_time' => $now,
  1421. ]);
  1422. $insertDetails = [];
  1423. foreach ($details as $d) {
  1424. $rowNum = $d['_line'];
  1425. $empId = $d['employee_id'];
  1426. $empName = $empMap[$empId] ?? "人员(ID:{$empId})";
  1427. // --- 新增:月份一致性校验 ---
  1428. // 校验这行数据的日期是否属于当前保存的月份
  1429. if (date("Y-m", strtotime($d['order_time'])) !== $month) {
  1430. return [false, "第 {$rowNum} 行:人员[{$empName}]的日期[{$d['order_time']}]不属于保存月份[{$month}]"];
  1431. }
  1432. // 【修正】强制由后端计算分钟数
  1433. $s = (int)$d['start_hour'] * 60 + (int)$d['start_min'];
  1434. $e = (int)$d['end_hour'] * 60 + (int)$d['end_min'];
  1435. $calcTotalMin = $e - $s;
  1436. // 校验1:逻辑合法性
  1437. if ($calcTotalMin <= 0) {
  1438. return [false, "第 {$rowNum} 行:人员[{$empName}]在[{$d['order_time']}]的时间段无效:结束时间必须晚于开始时间"];
  1439. }
  1440. // 校验2:跨单据时间重叠校验
  1441. $dateStr = $d['order_time'];
  1442. if (isset($empTimeline[$empId][$dateStr])) {
  1443. foreach ($empTimeline[$empId][$dateStr] as $exist) {
  1444. if ($s < $exist['e'] && $e > $exist['s']) {
  1445. return [false, "第 {$rowNum} 行:人员[{$empName}]在[{$dateStr}]存在时间冲突({$d['start_time']}-{$d['end_time']}),请检查!"];
  1446. }
  1447. }
  1448. }
  1449. $empTimeline[$empId][$dateStr][] = ['s' => $s, 'e' => $e];
  1450. $insertDetails[] = [
  1451. 'main_id' => $mainId,
  1452. 'employee_id' => $empId,
  1453. 'top_depart_id' => $topDepartId,
  1454. 'start_time_hour' => $d['start_hour'],
  1455. 'start_time_min' => $d['start_min'],
  1456. 'end_time_hour' => $d['end_hour'],
  1457. 'end_time_min' => $d['end_min'],
  1458. 'total_work_min' => $calcTotalMin,
  1459. 'crt_time' => $now,
  1460. 'item_id' => $itemId,
  1461. 'order_time' => $orderTimestamp,
  1462. 'crt_id' => $user['id'],
  1463. ];
  1464. }
  1465. // 批量写入明细
  1466. DB::table('daily_pw_order_details')->insert($insertDetails);
  1467. // C. 回填单号
  1468. $code = $this->generateBillNo([
  1469. 'top_depart_id' => $topDepartId,
  1470. 'type' => DailyPwOrder::Order_type,
  1471. 'period' => date("Ym", $orderTimestamp)
  1472. ]);
  1473. DB::table('daily_pw_order')->where('id', $mainId)->update(['code' => $code]);
  1474. }
  1475. DB::commit();
  1476. return [true, ''];
  1477. } catch (\Exception $e) {
  1478. DB::rollBack();
  1479. return [false, "保存失败:" . $e->getMessage()];
  1480. }
  1481. }
  1482. }