PersonWorkService.php 65 KB

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