PersonWorkService.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  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) = ArchiveService::isArchive($data['order_time'], $user);
  484. if(! $status) return [false, $msg];
  485. if(empty($itemId)) return [false, '项目不能为空'];
  486. $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
  487. if(!$bool) return [false, '项目不存在或已被删除'];
  488. if(empty($data['details'])) return [false, '人员日工时单明细不能为空'];
  489. // --- 1. 批量预获取人员信息,用于报错提示 ---
  490. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'employee_id')));
  491. // 如果需要工号+姓名,建议这样获取:
  492. $empDisplayMap = Employee::whereIn('id', $allEmpIds)
  493. ->get(['id', 'number', 'title'])
  494. ->mapWithKeys(function($item){
  495. return [$item->id => "[{$item->number}]{$item->title}"];
  496. })->toArray();
  497. // 2. 本次提交内部重叠记录器
  498. $internalOverlap = [];
  499. foreach ($data['details'] as $key => $value){
  500. $line = $key + 1;
  501. $t = "第" . $line . "行";
  502. $empId = $value['employee_id'] ?? 0;
  503. if(empty($empId)) return [false, '人员不能为空'];
  504. $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
  505. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  506. if(!$res['valid']) return [false, $t . "人员{$empName}开始点:" . $res['error']];
  507. if($value['start_time_hour'] > 23) return [false, false, $t . "人员{$empName}开始点不合法"];
  508. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  509. if(!$res['valid']) return [false, $t . "人员{$empName}开始分:" . $res['error']];
  510. if($value['start_time_min'] > 60) return [false, false, $t . "人员{$empName}开始点不合法"];
  511. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  512. if(!$res['valid']) return [false, $t . "人员{$empName}结束点:" . $res['error']];
  513. if($value['end_time_hour'] > 24) return [false, false, $t . "人员{$empName}结束点不合法"];
  514. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  515. if(!$res['valid']) return [false, $t . "人员{$empName}结束分:" . $res['error']];
  516. if($value['end_time_min'] > 60) return [false, false, $t . "人员{$empName}结束分不合法"];
  517. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  518. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  519. if ($currentStart >= $currentEnd) {
  520. return [false, $t . "人员{$empName}:开始时间必须早于结束时间"];
  521. }
  522. // --- 新增:总分钟数校验 ---
  523. $calculatedTotal = $currentEnd - $currentStart;
  524. if (!isset($value['total_work_min']) || intval($value['total_work_min']) !== $calculatedTotal) {
  525. return [false, $t . "人员{$empName}:总工时计算有误,应为 {$calculatedTotal} 分钟"];
  526. }
  527. // --- 3. 内部重叠校验(防止一次提交多行重复) ---
  528. if (isset($internalOverlap[$empId])) {
  529. foreach ($internalOverlap[$empId] as $period) {
  530. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  531. return [false, "人员{$empName}在本次提交的多行明细中时间段重叠"];
  532. }
  533. }
  534. }
  535. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  536. $query = DB::table('daily_pw_order_details as d')
  537. ->join('daily_pw_order as m', 'd.main_id', '=', 'm.id')
  538. ->where('m.top_depart_id', $data['top_depart_id'])
  539. ->where('m.order_time', $orderTime)
  540. ->where('m.item_id', $itemId)
  541. ->where('d.employee_id', $empId)
  542. ->where('m.del_time', 0)
  543. ->where('d.del_time', 0);
  544. if (!$is_add && !empty($data['id'])) {
  545. $query->where('m.id', '<>', $data['id']);
  546. }
  547. $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
  548. foreach ($existingPeriods as $p) {
  549. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  550. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  551. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  552. return [false, "人员{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
  553. }
  554. }
  555. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  556. }
  557. if(!$is_add){
  558. if(empty($data['id'])) return [false,'ID不能为空'];
  559. $bool = DailyPwOrder::where('top_depart_id', $data['top_depart_id'])
  560. ->where('id',$data['id'])
  561. ->where('del_time',0)
  562. ->exists();
  563. if(!$bool) return [false, '人员日工时单不存在或已被删除'];
  564. }
  565. return [true, ''];
  566. }
  567. public function fillDataDaily($data, $user){
  568. if(empty($data['data'])) return $data;
  569. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  570. $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_id')));
  571. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'order_time')), $user);
  572. foreach ($data['data'] as $key => $value){
  573. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  574. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  575. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  576. $item_tmp = $item[$value['item_id']] ?? [];
  577. $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
  578. $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
  579. $data['data'][$key]['is_archive'] = $map[$value['order_time']] ?? false;
  580. }
  581. return $data;
  582. }
  583. public function fillDataForExportDaily($data, $column, &$return)
  584. {
  585. if (empty($data)) return;
  586. $mainIds = array_column($data, 'id');
  587. // 1. 获取详情及所有关联档案(项目、人员)的映射
  588. $detailsMap = $this->getDailyDetailsMap($mainIds, $data);
  589. foreach ($data as $main) {
  590. $mainId = $main['id'];
  591. $details = $detailsMap[$mainId] ?? [];
  592. // 2. 提取并格式化主表共有信息
  593. $mainInfo = [
  594. 'code' => $main['code'],
  595. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  596. ];
  597. if (empty($details)) {
  598. // 无明细时只导出一行主表信息
  599. $tempRow = [];
  600. foreach ($column as $col) {
  601. $tempRow[] = $mainInfo[$col] ?? '';
  602. }
  603. $return[] = $tempRow;
  604. } else {
  605. // 3. 平铺:将详情里的项目信息、人员信息与主表信息合并
  606. foreach ($details as $sub) {
  607. $fullRowData = array_merge($mainInfo, $sub);
  608. $tempRow = [];
  609. foreach ($column as $col) {
  610. $tempRow[] = $fullRowData[$col] ?? '';
  611. }
  612. $return[] = $tempRow;
  613. }
  614. }
  615. }
  616. }
  617. public function getDailyDetailsMap($mainIds, $mainData)
  618. {
  619. // 1. 获取所有子表记录
  620. $details = DB::table('daily_pw_order_details')
  621. ->where('del_time', 0)
  622. ->whereIn('main_id', $mainIds)
  623. ->get();
  624. // 2. 提取所有关联 ID
  625. $empIds = $details->pluck('employee_id')->unique();
  626. $itemIds = array_unique(array_column($mainData, 'item_id')); // 从主表数组提取项目ID
  627. // 3. 批量获取档案 Map
  628. $empMap = DB::table('employee')
  629. ->whereIn('id', $empIds)
  630. ->get(['id', 'title', 'number'])
  631. ->keyBy('id');
  632. $itemMap = DB::table('item')
  633. ->whereIn('id', $itemIds)
  634. ->get(['id', 'title', 'code'])
  635. ->keyBy('id');
  636. // 4. 将主表的项目信息预先挂载到主表 ID 下,方便后续合并
  637. $mainItemInfo = [];
  638. foreach ($mainData as $m) {
  639. $proj = $itemMap[$m['item_id']] ?? null;
  640. $mainItemInfo[$m['id']] = [
  641. 'item_code' => $proj ? $proj->code : '',
  642. 'item_title' => $proj ? $proj->title : '',
  643. ];
  644. }
  645. $res = [];
  646. if ($details->isEmpty()) {
  647. // 如果没有详情,把项目信息返回去,确保主表能导出行
  648. foreach ($mainItemInfo as $mId => $info) {
  649. $res[$mId] = [];
  650. }
  651. return $res;
  652. }
  653. foreach ($details as $item) {
  654. $emp = $empMap[$item->employee_id] ?? null;
  655. // 组装明细行数据
  656. $detailRow = [
  657. // 人员信息
  658. 'employee_number' => $emp ? $emp->number : '',
  659. 'employee_title' => $emp ? $emp->title : '',
  660. // 时间信息
  661. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  662. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  663. // 将主表的项目信息也塞进每一行详情里实现平铺
  664. 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
  665. 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
  666. ];
  667. $res[$item->main_id][] = $detailRow;
  668. }
  669. return $res;
  670. }
  671. public function dailyPwOrderCreate($data, $user)
  672. {
  673. $topDepartId = $user['top_depart_id'];
  674. if (empty($data['month'])) return [false, '月份不能为空'];
  675. $monthStart = $this->changeDateToDate($data['month']);
  676. // --- 一开始就做的核心校验 ---
  677. // 1. 检查是否存在月度工时明细(如果没有,队列执行也是徒劳)
  678. $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
  679. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  680. ->where('m.month', $monthStart)
  681. ->where('m.top_depart_id', $topDepartId)
  682. ->where('m.del_time', 0)
  683. ->where('d.del_time', 0)
  684. ->exists();
  685. if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
  686. // 2. 检查是否配置了工作日历
  687. $hasCalendar = DB::table('calendar_details')
  688. ->where('month', $monthStart)
  689. ->where('del_time', 0)
  690. ->exists();
  691. if (!$hasCalendar) return [false, '该月份工作日历未配置'];
  692. // 3. 检查是否配置了项目比例规则
  693. $hasRules = DB::table('rule_set as r')
  694. ->where('r.month', $monthStart)
  695. ->where('r.top_depart_id', $topDepartId)
  696. ->where('r.del_time', 0)
  697. ->exists();
  698. if (!$hasRules) return [false, '未找到该月份的规则配置单'];
  699. $data['type'] = "p_work";
  700. ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
  701. return [true, '生成任务已提交,系统正在后台处理,请稍后查看'];
  702. }
  703. public function dailyPwOrderCreateMain($data, $user)
  704. {
  705. $topDepartId = $user['top_depart_id'];
  706. if (empty($data['month'])) return [false, '月份不能为空'];
  707. $monthStart = $this->changeDateToDate($data['month']);
  708. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  709. $now = time();
  710. DB::beginTransaction();
  711. try {
  712. // --- 0. 清理旧数据 ---
  713. $oldOrderIds = DB::table('daily_pw_order')
  714. ->where('top_depart_id', $topDepartId)
  715. ->where('order_time', '>=', $monthStart)
  716. ->where('order_time', '<=', $monthEnd)
  717. ->where('is_create', 1)
  718. ->where('del_time', 0)
  719. ->pluck('id');
  720. if ($oldOrderIds->isNotEmpty()) {
  721. DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  722. DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  723. }
  724. // --- 1. 基础数据加载 ---
  725. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  726. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  727. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  728. ->where('m.del_time', 0)->where('d.del_time', 0)
  729. ->select('d.*')->get();
  730. if ($monthlyOrder->isEmpty()) return [false, '未找到月度工时明细'];
  731. $empIds = $monthlyOrder->pluck('employee_id')->unique()->toArray();
  732. $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  733. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  734. $ruleSet = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  735. ->where('r.month', $monthStart)->where('rd.type', RuleSetDetails::type_one)
  736. ->where('r.del_time', 0)->where('rd.del_time', 0)
  737. ->select('rd.*')->get()->groupBy('data_id');
  738. $allDays = DB::table('calendar_details')->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
  739. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  740. ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('m.del_time', 0)
  741. ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
  742. // --- 2. 核心分配逻辑:计算每天、每个项目、每个人的分钟数 ---
  743. $finalAlloc = [];
  744. foreach ($monthlyOrder as $mDetail) {
  745. $empId = $mDetail->employee_id;
  746. $empRules = $ruleSet->get($empId);
  747. if (!$empRules) continue;
  748. $empRemainingMin = (float)$mDetail->rd_total_hours * 60;
  749. if ($empRemainingMin <= 0) continue;
  750. foreach ($allDays as $dayInfo) {
  751. if ($empRemainingMin <= 0) break;
  752. $dayTs = $dayInfo->time;
  753. $isWorkDay = ($dayInfo->is_work == CalendarDetails::TYPE_ONE);
  754. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  755. $todayOvertimes = $todaySpecials->where('main_type', 2);
  756. if (!$isWorkDay && $todayOvertimes->isEmpty()) continue;
  757. // 计算当天可用总时长
  758. $dayAvailableMin = 0;
  759. if ($isWorkDay) {
  760. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  761. foreach ($baseRanges as $br) {
  762. $brS = $br->start_time_hour * 60 + $br->start_time_min;
  763. $brE = $br->end_time_hour * 60 + $br->end_time_min;
  764. $avail = (float)$br->total_work_min;
  765. foreach ($todaySpecials->where('main_type', 1) as $lv) {
  766. $overlap = min($brE, ($lv->end_time_hour * 60 + $lv->end_time_min)) - max($brS, ($lv->start_time_hour * 60 + $lv->start_time_min));
  767. if ($overlap > 0) $avail -= $overlap;
  768. }
  769. $dayAvailableMin += max(0, $avail);
  770. }
  771. }
  772. foreach ($todayOvertimes as $ot) $dayAvailableMin += (float)$ot->total_min;
  773. $canAllocToday = min($empRemainingMin, $dayAvailableMin);
  774. if ($canAllocToday <= 0) continue;
  775. foreach ($empRules as $rule) {
  776. $rate = (float)$rule->rate / 100;
  777. $projectMin = $canAllocToday * $rate;
  778. if ($projectMin > 0) {
  779. // 结果存入:[日期][项目][人员]
  780. $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
  781. }
  782. }
  783. $empRemainingMin -= $canAllocToday;
  784. }
  785. }
  786. // --- 3. 生成单据:解决时间重叠的核心逻辑 ---
  787. $newOrderIds = [];
  788. // 为了解决重叠,我们需要按 [日期][人员] 来追踪时间池的消耗进度
  789. $dailyEmpTimePools = [];
  790. foreach ($finalAlloc as $dayTs => $projects) {
  791. foreach ($projects as $itemId => $employees) {
  792. $mainId = DB::table('daily_pw_order')->insertGetId([
  793. 'code' => '', 'item_id' => $itemId, 'order_time' => $dayTs, 'top_depart_id' => $topDepartId,
  794. 'is_create' => 1, 'crt_id' => $user['id'], 'crt_time' => $now, 'upd_time' => $now,
  795. ]);
  796. $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
  797. foreach ($employees as $empId => $toAllocMin) {
  798. // 如果该员工当天的池子还没构建,先构建一次
  799. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  800. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  801. }
  802. $tempRem = $toAllocMin;
  803. // 指向该员工当天的可用池引用,这样处理完项目A,池子里的时间会自动被“消耗”
  804. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  805. if ($tempRem <= 0) break;
  806. $pMax = $p['e'] - $p['s'];
  807. if ($pMax <= 0) continue;
  808. $take = min($tempRem, $pMax);
  809. $realStart = $p['s'];
  810. $realEnd = $p['s'] + $take;
  811. DB::table('daily_pw_order_details')->insert([
  812. 'main_id' => $mainId, 'employee_id' => $empId, 'top_depart_id' => $topDepartId,
  813. 'start_time_hour' => floor($realStart / 60), 'start_time_min' => $realStart % 60,
  814. 'end_time_hour' => floor($realEnd / 60), 'end_time_min' => $realEnd % 60,
  815. 'total_work_min' => $take, 'crt_time' => $now, 'upd_time' => $now,
  816. ]);
  817. $tempRem -= $take;
  818. // 重要:消耗掉这个时段的起始位置,确保下一个项目从这里开始
  819. $p['s'] = $realEnd;
  820. }
  821. }
  822. }
  823. }
  824. // --- 4. 回填单号 ---
  825. if (empty($newOrderIds)) return [false, '未生成数据'];
  826. foreach ($newOrderIds as $item) {
  827. $code = $this->generateBillNo(['top_depart_id' => $topDepartId, 'type' => DailyPwOrder::Order_type, 'period' => date("Ym", $item['time'])]);
  828. DB::table('daily_pw_order')->where('id', $item['id'])->update(['code' => $code]);
  829. }
  830. DB::commit();
  831. } catch (\Exception $e) {
  832. DB::rollBack();
  833. return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
  834. }
  835. return [true, ''];
  836. }
  837. /**
  838. * 辅助函数:构建某人某天的初始可用时段池
  839. */
  840. private function buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData)
  841. {
  842. $dayInfo = $allDays->where('time', $dayTs)->first();
  843. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  844. $pool = [];
  845. if ($dayInfo && $dayInfo->is_work == CalendarDetails::TYPE_ONE) {
  846. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  847. foreach ($baseRanges as $br) {
  848. $currentS = $br->start_time_hour * 60 + $br->start_time_min;
  849. $eMin = $br->end_time_hour * 60 + $br->end_time_min;
  850. $sortedLeaves = $todaySpecials->where('main_type', 1)->sortBy('start_time_hour');
  851. foreach ($sortedLeaves as $lv) {
  852. $lvS = $lv->start_time_hour * 60 + $lv->start_time_min;
  853. $lvE = $lv->end_time_hour * 60 + $lv->end_time_min;
  854. if ($lvS < $eMin && $lvE > $currentS) {
  855. if ($lvS > $currentS) $pool[] = ['s' => $currentS, 'e' => $lvS];
  856. $currentS = max($currentS, $lvE);
  857. }
  858. }
  859. if ($currentS < $eMin) $pool[] = ['s' => $currentS, 'e' => $eMin];
  860. }
  861. }
  862. foreach ($todaySpecials->where('main_type', 2) as $ot) {
  863. $otS = $ot->start_time_hour * 60 + $ot->start_time_min;
  864. $pool[] = ['s' => $otS, 'e' => $otS + (float)$ot->total_min];
  865. }
  866. return $pool;
  867. }
  868. public function dailyPwOrderPreview($data, $user)
  869. {
  870. $topDepartId = $user['top_depart_id'];
  871. if (empty($data['month'])) return [false, '月份不能为空'];
  872. // 1. 前置校验 (保留你之前的校验逻辑)
  873. $monthStart = $this->changeDateToDate($data['month']);
  874. //归档
  875. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  876. if(! $status) return [false, $msg];
  877. // 1. 检查是否存在月度工时明细
  878. $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
  879. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  880. ->where('m.month', $monthStart)
  881. ->where('m.top_depart_id', $topDepartId)
  882. ->where('m.del_time', 0)
  883. ->where('d.del_time', 0)
  884. ->exists();
  885. if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
  886. // 2. 检查是否配置了工作日历
  887. $hasCalendar = DB::table('calendar_details')
  888. ->where('month', $monthStart)
  889. ->where('del_time', 0)
  890. ->exists();
  891. if (!$hasCalendar) return [false, '该月份工作日历未配置'];
  892. // 3. 检查是否配置了项目比例规则
  893. $hasRules = DB::table('rule_set as r')
  894. ->where('r.month', $monthStart)
  895. ->where('r.top_depart_id', $topDepartId)
  896. ->where('r.del_time', 0)
  897. ->exists();
  898. if (!$hasRules) return [false, '未找到该月份的规则配置单'];
  899. // 2. 调用核心计算逻辑 (抽取出的私有方法)
  900. $result = $this->calculateDailyAllocation($monthStart, $topDepartId, $user);
  901. if (!$result['status']) return [false, $result['msg']];
  902. // 3. 将结果存入临时表或直接返回
  903. // 建议增加一个 batch_id,防止多人操作冲突
  904. $batchId = uniqid('batch_');
  905. $previewData = $result['data'];
  906. return [true, [
  907. 'batch_id' => $batchId,
  908. 'list' => $previewData // 返回给前端展示
  909. ]];
  910. }
  911. /**
  912. * 核心分配逻辑:计算预览数据(确保全整数分钟)
  913. * @param int $monthStart 月初时间戳
  914. * @param int $topDepartId 顶级部门ID
  915. * @param array $user 用户信息
  916. * @return array
  917. */
  918. private function calculateDailyAllocation($monthStart, $topDepartId, $user)
  919. {
  920. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  921. $now = time();
  922. // --- 1. 基础数据加载 ---
  923. // 加载月度工时明细,并关联人员姓名
  924. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  925. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  926. ->leftJoin('employee as e', 'e.id', '=', 'd.employee_id') // 关联人员表
  927. ->where('m.month', $monthStart)
  928. ->where('m.top_depart_id', $topDepartId)
  929. ->where('m.del_time', 0)
  930. ->where('d.del_time', 0)
  931. ->select('d.*', 'e.title as employee_title') // 获取人员姓名
  932. ->get();
  933. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到该月份的月度工时明细'];
  934. // 建立人员 ID -> 姓名的映射,方便后续取用
  935. $empNameMap = $monthlyOrder->pluck('employee_title', 'employee_id')->toArray();
  936. $empIds = array_keys($empNameMap);
  937. // 加载项目信息,用于获取项目名称
  938. // 假设项目表名为 items,请根据你实际的表名修改
  939. $itemIds = DB::table('rule_set_details as rd')
  940. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  941. ->where('r.month', $monthStart)
  942. ->where('r.top_depart_id', $topDepartId)
  943. ->pluck('rd.item_id')->unique()->toArray();
  944. $itemMap = DB::table('item')
  945. ->whereIn('id', $itemIds)
  946. ->pluck('title', 'id')
  947. ->toArray();
  948. // 加载分配规则
  949. $ruleSet = DB::table('rule_set_details as rd')
  950. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  951. ->where('r.month', $monthStart)
  952. ->where('rd.type', 1)
  953. ->where('r.del_time', 0)
  954. ->where('rd.del_time', 0)
  955. ->select('rd.*')
  956. ->get()
  957. ->groupBy('data_id');
  958. // 加载员工/标准班次、日历、请假加班数据 (逻辑同前)
  959. $empWorkRanges = DB::table('employee_work_range')
  960. ->whereIn('employee_id', $empIds)
  961. ->where('top_depart_id', $topDepartId)
  962. ->get()->groupBy('employee_id');
  963. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)
  964. ->where('del_time', 0)->get();
  965. $allDays = DB::table('calendar_details')->where('top_depart_id', $topDepartId)
  966. ->where('month', $monthStart)
  967. ->where('del_time', 0)
  968. ->orderBy('time', 'asc')
  969. ->get();
  970. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  971. ->whereBetween('m.order_time', [$monthStart, $monthEnd])
  972. ->where('d.top_depart_id', $topDepartId)
  973. ->where('m.del_time', 0)
  974. ->select('d.*', 'm.order_time', 'm.type as main_type')
  975. ->get()->groupBy(['employee_id', 'order_time']);
  976. // --- 2. 阶段一:计算每个人每天在每个项目上应分配的整数分钟数 ---
  977. $finalAlloc = [];
  978. foreach ($monthlyOrder as $mDetail) {
  979. $empId = $mDetail->employee_id;
  980. $empRules = $ruleSet->get($empId);
  981. if (!$empRules) continue;
  982. $empRemainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  983. if ($empRemainingMin <= 0) continue;
  984. foreach ($allDays as $dayInfo) {
  985. if ($empRemainingMin <= 0) break;
  986. $dayTs = $dayInfo->time;
  987. $tempPool = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  988. $dayAvailableMin = 0;
  989. foreach ($tempPool as $p) { $dayAvailableMin += (int)($p['e'] - $p['s']); }
  990. if ($dayAvailableMin <= 0) continue;
  991. $canAllocToday = min($empRemainingMin, $dayAvailableMin);
  992. $allocatedInDay = 0;
  993. $ruleCount = count($empRules);
  994. foreach ($empRules as $index => $rule) {
  995. $rate = (float)$rule->rate / 100;
  996. if ($index === $ruleCount - 1) {
  997. $projectMin = $canAllocToday - $allocatedInDay;
  998. } else {
  999. $projectMin = (int)round($canAllocToday * $rate);
  1000. }
  1001. if ($projectMin > 0) {
  1002. $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
  1003. $allocatedInDay += $projectMin;
  1004. }
  1005. }
  1006. $empRemainingMin -= $canAllocToday;
  1007. }
  1008. }
  1009. // --- 3. 阶段二:打散到具体时间点并生成预览行 ---
  1010. $previewList = [];
  1011. $dailyEmpTimePools = [];
  1012. $tempMainIdCounter = 1;
  1013. foreach ($finalAlloc as $dayTs => $projects) {
  1014. foreach ($projects as $itemId => $employees) {
  1015. $currentTempMainId = $tempMainIdCounter++;
  1016. // 获取项目名称
  1017. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  1018. foreach ($employees as $empId => $toAllocMin) {
  1019. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  1020. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  1021. }
  1022. $tempRem = (int)$toAllocMin;
  1023. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  1024. if ($tempRem <= 0) break;
  1025. $pMax = (int)($p['e'] - $p['s']);
  1026. if ($pMax <= 0) continue;
  1027. $take = min($tempRem, $pMax);
  1028. $realStart = (int)$p['s'];
  1029. $realEnd = $realStart + $take;
  1030. // 写入带 Title 的结果
  1031. $previewList[] = [
  1032. 'temp_main_id' => $currentTempMainId,
  1033. 'order_time' => date('Y-m-d', $dayTs),
  1034. 'order_timestamp' => $dayTs,
  1035. 'item_id' => $itemId,
  1036. 'item_title' => $itemTitle, // 项目名称
  1037. 'employee_id' => $empId,
  1038. 'employee_title' => $empNameMap[$empId] ?? '未知人员', // 人员姓名
  1039. 'start_time' => sprintf('%02d:%02d', floor($realStart / 60), $realStart % 60),
  1040. 'end_time' => sprintf('%02d:%02d', floor($realEnd / 60), $realEnd % 60),
  1041. 'start_hour' => (int)floor($realStart / 60),
  1042. 'start_min' => (int)($realStart % 60),
  1043. 'end_hour' => (int)floor($realEnd / 60),
  1044. 'end_min' => (int)($realEnd % 60),
  1045. 'total_work_min' => $take,
  1046. ];
  1047. $tempRem -= $take;
  1048. $p['s'] = $realEnd;
  1049. }
  1050. }
  1051. }
  1052. }
  1053. return ['status' => true, 'data' => $previewList];
  1054. }
  1055. public function dailyPwOrderSave($data, $user)
  1056. {
  1057. $list = $data['list'] ?? [];
  1058. if (empty($list)) return [false, '没有可保存的数据'];
  1059. $topDepartId = $user['top_depart_id'];
  1060. $month = $data['month'];
  1061. $monthStart = $this->changeDateToDate($month);
  1062. //归档
  1063. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  1064. if(! $status) return [false, $msg];
  1065. $now = time();
  1066. // 1. 预加载员工名称映射 (使用 title 字段)
  1067. $empIds = collect($list)->pluck('employee_id')->unique()->toArray();
  1068. $empMap = DB::table('employee')->whereIn('id', $empIds)->pluck('title', 'id')->toArray();
  1069. // --- 2. 重新分组并记录行号 ---
  1070. $groupedByOrder = [];
  1071. foreach ($list as $index => $item) {
  1072. $item['_line'] = $index + 1; // 记录原始行号(从1开始)
  1073. // 以日期字符串和项目ID作为分组 Key
  1074. $groupKey = $item['order_time'] . '_' . $item['item_id'];
  1075. $groupedByOrder[$groupKey][] = $item;
  1076. }
  1077. // 冲突校验器容器:记录 [员工ID][日期字符串] 下已占用的时间段
  1078. $empTimeline = [];
  1079. DB::beginTransaction();
  1080. try {
  1081. // A. 清理该月份旧数据
  1082. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  1083. $oldOrderIds = DB::table('daily_pw_order')
  1084. ->where('top_depart_id', $topDepartId)
  1085. ->whereBetween('order_time', [$monthStart, $monthEnd])
  1086. ->where('del_time', 0)
  1087. ->pluck('id');
  1088. if ($oldOrderIds->isNotEmpty()) {
  1089. DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  1090. DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  1091. }
  1092. // B. 遍历重组后的分组写入
  1093. foreach ($groupedByOrder as $details) {
  1094. $first = $details[0];
  1095. // 【修正】统一将前端日期字符串转为时间戳入库
  1096. $orderTimestamp = strtotime($first['order_time']);
  1097. $itemId = $first['item_id'];
  1098. // 写入主表
  1099. $mainId = DB::table('daily_pw_order')->insertGetId([
  1100. 'code' => '',
  1101. 'item_id' => $itemId,
  1102. 'order_time' => $orderTimestamp,
  1103. 'top_depart_id' => $topDepartId,
  1104. 'is_create' => 1,
  1105. 'crt_id' => $user['id'],
  1106. 'crt_time' => $now,
  1107. ]);
  1108. $insertDetails = [];
  1109. foreach ($details as $d) {
  1110. $rowNum = $d['_line'];
  1111. $empId = $d['employee_id'];
  1112. $empName = $empMap[$empId] ?? "人员(ID:{$empId})";
  1113. // --- 新增:月份一致性校验 ---
  1114. // 校验这行数据的日期是否属于当前保存的月份
  1115. if (date("Y-m", strtotime($d['order_time'])) !== $month) {
  1116. return [false, "第 {$rowNum} 行:人员[{$empName}]的日期[{$d['order_time']}]不属于保存月份[{$month}]"];
  1117. }
  1118. // 【修正】强制由后端计算分钟数
  1119. $s = (int)$d['start_hour'] * 60 + (int)$d['start_min'];
  1120. $e = (int)$d['end_hour'] * 60 + (int)$d['end_min'];
  1121. $calcTotalMin = $e - $s;
  1122. // 校验1:逻辑合法性
  1123. if ($calcTotalMin <= 0) {
  1124. return [false, "第 {$rowNum} 行:人员[{$empName}]在[{$d['order_time']}]的时间段无效:结束时间必须晚于开始时间"];
  1125. }
  1126. // 校验2:跨单据时间重叠校验
  1127. $dateStr = $d['order_time'];
  1128. if (isset($empTimeline[$empId][$dateStr])) {
  1129. foreach ($empTimeline[$empId][$dateStr] as $exist) {
  1130. if ($s < $exist['e'] && $e > $exist['s']) {
  1131. return [false, "第 {$rowNum} 行:人员[{$empName}]在[{$dateStr}]存在时间冲突({$d['start_time']}-{$d['end_time']}),请检查!"];
  1132. }
  1133. }
  1134. }
  1135. $empTimeline[$empId][$dateStr][] = ['s' => $s, 'e' => $e];
  1136. $insertDetails[] = [
  1137. 'main_id' => $mainId,
  1138. 'employee_id' => $empId,
  1139. 'top_depart_id' => $topDepartId,
  1140. 'start_time_hour' => $d['start_hour'],
  1141. 'start_time_min' => $d['start_min'],
  1142. 'end_time_hour' => $d['end_hour'],
  1143. 'end_time_min' => $d['end_min'],
  1144. 'total_work_min' => $calcTotalMin,
  1145. 'crt_time' => $now,
  1146. 'item_id' => $itemId,
  1147. 'order_time' => $orderTimestamp,
  1148. 'crt_id' => $user['id'],
  1149. ];
  1150. }
  1151. // 批量写入明细
  1152. DB::table('daily_pw_order_details')->insert($insertDetails);
  1153. // C. 回填单号
  1154. $code = $this->generateBillNo([
  1155. 'top_depart_id' => $topDepartId,
  1156. 'type' => DailyPwOrder::Order_type,
  1157. 'period' => date("Ym", $orderTimestamp)
  1158. ]);
  1159. DB::table('daily_pw_order')->where('id', $mainId)->update(['code' => $code]);
  1160. }
  1161. DB::commit();
  1162. return [true, ''];
  1163. } catch (\Exception $e) {
  1164. DB::rollBack();
  1165. return [false, "保存失败:" . $e->getMessage()];
  1166. }
  1167. }
  1168. }