PersonWorkService.php 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217
  1. <?php
  2. namespace App\Service;
  3. use App\Jobs\ProcessDataJob;
  4. use App\Model\CalendarDetails;
  5. use App\Model\DailyPwOrder;
  6. use App\Model\DailyPwOrderDetails;
  7. use App\Model\Employee;
  8. use App\Model\Item;
  9. use App\Model\MonthlyPwOrder;
  10. use App\Model\MonthlyPwOrderDetails;
  11. use App\Model\RuleSetDetails;
  12. use Illuminate\Support\Facades\DB;
  13. class PersonWorkService extends Service
  14. {
  15. // 人员月工时单-------------------------------------------
  16. public function monthlyPwOrderEdit($data,$user){
  17. list($status,$msg) = $this->monthlyPwOrderRule($data, $user, false);
  18. if(!$status) return [$status,$msg];
  19. try {
  20. DB::beginTransaction();
  21. $model = MonthlyPwOrder::where('id',$data['id'])->first();
  22. // $model->month = $data['month'] ?? 0;
  23. // $model->save();
  24. $time = time();
  25. MonthlyPwOrderDetails::where('del_time',0)
  26. ->where('main_id', $model->id)
  27. ->update(['del_time' => $time]);
  28. $this->saveDetail($model->id, $time, $data);
  29. DB::commit();
  30. }catch (\Exception $exception){
  31. DB::rollBack();
  32. return [false,$exception->getMessage()];
  33. }
  34. return [true, ''];
  35. }
  36. public function monthlyPwOrderAdd($data,$user){
  37. list($status,$msg) = $this->monthlyPwOrderRule($data, $user);
  38. if(!$status) return [$status,$msg];
  39. try {
  40. DB::beginTransaction();
  41. $model = new MonthlyPwOrder();
  42. $model->code = $this->generateBillNo([
  43. 'top_depart_id' => $user['top_depart_id'],
  44. 'type' => MonthlyPwOrder::Order_type,
  45. 'period' => date("Ym", $data['month'])
  46. ]);
  47. $model->month = $data['month'] ?? 0;
  48. $model->crt_id = $user['id'];
  49. $model->top_depart_id = $data['top_depart_id'];
  50. $model->save();
  51. $this->saveDetail($model->id, time(), $data);
  52. DB::commit();
  53. }catch (\Exception $exception){
  54. DB::rollBack();
  55. return [false,$exception->getMessage()];
  56. }
  57. return [true, ''];
  58. }
  59. private function saveDetail($id, $time, $data){
  60. if(! empty($data['details'])){
  61. $unit = [];
  62. foreach ($data['details'] as $value){
  63. $unit[] = [
  64. 'main_id' => $id,
  65. 'employee_id' => $value['employee_id'],
  66. 'total_days' => $value['total_days'],
  67. 'rd_total_days' => $value['rd_total_days'],
  68. 'total_hours' => $value['total_hours'],
  69. 'rd_total_hours' => $value['rd_total_hours'],
  70. 'crt_time' => $time,
  71. 'top_depart_id' => $value['top_depart_id'],
  72. ];
  73. }
  74. if(! empty($unit)) MonthlyPwOrderDetails::insert($unit);
  75. }
  76. }
  77. private function getDetail($id){
  78. $data = MonthlyPwOrderDetails::where('del_time',0)
  79. ->where('main_id', $id)
  80. ->select('employee_id', 'total_days', 'rd_total_days', 'total_hours', 'rd_total_hours')
  81. ->get()->toArray();
  82. $id = array_column($data,'employee_id');
  83. $map = Employee::whereIn('id', $id)->select('title','id','number')->get()->toArray();
  84. $map = array_column($map,null,'id');
  85. foreach ($data as $key => $value){
  86. $tmp = $map[$value['employee_id']] ?? [];
  87. $merge = [];
  88. $merge['employee_title'] = $tmp['title'];
  89. $merge['employee_number'] = $tmp['number'];
  90. $data[$key] = array_merge($value, $merge);
  91. }
  92. $detail = [
  93. 'details' => $data,
  94. ];
  95. //foreach ($detail as $key => $value) {
  96. // if (empty($value)) {
  97. //$detail[$key] = (object)[]; // 转成 stdClass 对象
  98. //}
  99. //}
  100. return $detail;
  101. }
  102. public function monthlyPwOrderDel($data, $user){
  103. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  104. try {
  105. DB::beginTransaction();
  106. $time = time();
  107. $month = MonthlyPwOrder::where('del_time',0)
  108. ->whereIn('id',$data['id'])
  109. ->pluck('month')
  110. ->toArray();
  111. //归档
  112. list($status, $msg) = ArchiveService::isArchive($month, $user);
  113. if(! $status) return [false, $msg];
  114. MonthlyPwOrder::where('del_time',0)
  115. ->whereIn('id',$data['id'])
  116. ->update(['del_time' => $time]);
  117. MonthlyPwOrderDetails::where('del_time',0)
  118. ->whereIn('main_id', $data['id'])
  119. ->update(['del_time' => $time]);
  120. DB::commit();
  121. }catch (\Exception $exception){
  122. DB::rollBack();
  123. return [false,$exception->getMessage()];
  124. }
  125. return [true, ''];
  126. }
  127. public function monthlyPwOrderDetail($data, $user){
  128. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  129. $customer = MonthlyPwOrder::where('del_time',0)
  130. ->where('id',$data['id'])
  131. ->first();
  132. if(empty($customer)) return [false,'人员月度工时单不存在或已被删除'];
  133. $customer = $customer->toArray();
  134. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  135. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  136. $map = ArchiveService::fillIsArchive($customer['month'], $user);
  137. $customer['is_archive'] = $map[$customer['month']] ?? false;
  138. $customer['month'] = $customer['month'] ? date("Y-m",$customer['month']): '';
  139. $details = $this->getDetail($data['id']);
  140. $customer = array_merge($customer, $details);
  141. return [true, $customer];
  142. }
  143. public function monthlyPwOrderCommon($data,$user, $field = []){
  144. if(empty($field)) $field = MonthlyPwOrder::$field;
  145. $model = MonthlyPwOrder::Clear($user,$data);
  146. $model = $model->where('del_time',0)
  147. ->select($field)
  148. ->orderby('id', 'desc');
  149. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  150. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  151. $model->where('month','>=',$return[0]);
  152. $model->where('month','<=',$return[1]);
  153. }
  154. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  155. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  156. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  157. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  158. $model->where('crt_time','>=',$return[0]);
  159. $model->where('crt_time','<=',$return[1]);
  160. }
  161. return $model;
  162. }
  163. public function monthlyPwOrderList($data,$user){
  164. $model = $this->monthlyPwOrderCommon($data, $user);
  165. $list = $this->limit($model,'',$data);
  166. $list = $this->fillData($list, $user);
  167. return [true, $list];
  168. }
  169. public function monthlyPwOrderRule(&$data, $user, $is_add = true)
  170. {
  171. if (empty($data['month'])) return [false, '月份不能为空'];
  172. $data['month'] = $this->changeDateToDate($data['month']);
  173. $data['top_depart_id'] = $user['top_depart_id'];
  174. //归档
  175. list($status, $msg) = ArchiveService::isArchive($data['month'], $user);
  176. if(! $status) return [false, $msg];
  177. if (empty($data['details'])) return [false, '人员月度工时单明细不能为空'];
  178. //获取系统计算的考勤基准数据 ---
  179. $empIds = array_column($data['details'], 'employee_id');
  180. list($status, $systemStats) = (new EmployeeService())->getEmployeesMonthStats($empIds, $data['month'], $user);
  181. if (!$status) return [false, $systemStats]; // 如果日历未设置,直接拦截
  182. // 字段中文映射,用于报错
  183. $fieldNames = [
  184. 'total_days' => '出勤总天数',
  185. 'rd_total_days' => '研发出勤总天数',
  186. 'total_hours' => '出勤总工时',
  187. 'rd_total_hours'=> '研发总工时'
  188. ];
  189. foreach ($data['details'] as $key => $value) {
  190. $lineTitle = "第" . ($key + 1) . "行:";
  191. if (empty($value['employee_id'])) return [false, '人员不能为空'];
  192. $empId = $value['employee_id'];
  193. // 基础数字格式检查
  194. foreach ($fieldNames as $field => $title) {
  195. if(! isset($value[$field])) return [false, $lineTitle . $title . "不存在"];
  196. $precision = 2;
  197. $res = $this->checkNumber($value[$field], $precision, 'non-negative');
  198. if (!$res['valid']) return [false, $lineTitle . $value['employee_title'] . "的" . $title . ":" . $res['error']];
  199. }
  200. // --- 业务逻辑校验:出勤天数与工时合法性 ---
  201. $sysData = $systemStats[$empId] ?? null;
  202. if ($sysData) {
  203. // 1. 研发天数不能大于出勤总天数
  204. if ($value['rd_total_days'] > $value['total_days']) {
  205. return [false, $lineTitle . "研发出勤天数不能大于出勤总天数"];
  206. }
  207. // 2. 研发工时不能大于出勤总工时
  208. if ($value['rd_total_hours'] > $value['total_hours']) {
  209. return [false, $lineTitle . "研发总工时不能大于出勤总工时"];
  210. }
  211. // 4. 校验出勤总天数是否超过了系统计算的上限
  212. if ($value['total_days'] != $sysData['attendance_days']) {
  213. return [false, $lineTitle . "人员[{$empId}]填写的出勤总天数({$value['total_days']})不等于系统核算的天数({$sysData['attendance_days']})"];
  214. }
  215. //校验出勤总工时是否超过了系统计算的上限
  216. if ($value['total_hours'] != $sysData['final_work_hour']) {
  217. return [false, $lineTitle . "人员[{$empId}]填写的出勤总工时({$value['total_hours']})不等于系统核算的工时({$sysData['final_work_hour']})"];
  218. }
  219. }
  220. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  221. }
  222. // --- 查重与唯一性校验 ---
  223. list($status, $msg) = $this->checkArrayRepeat($data['details'], 'employee_id', '人员');
  224. if (!$status) return [false, $msg];
  225. $query = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
  226. ->where('month', $data['month'])
  227. ->where('del_time', 0);
  228. if (!$is_add) {
  229. if (empty($data['id'])) return [false, 'ID不能为空'];
  230. $query->where('id', '<>', $data['id']);
  231. }
  232. if ($query->exists()) {
  233. return [false, date("Y-m", $data['month']) . '已存在人员月度研发工时单'];
  234. }
  235. return [true, ''];
  236. }
  237. public function fillData($data, $user){
  238. if(empty($data['data'])) return $data;
  239. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  240. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'month')), $user);
  241. foreach ($data['data'] as $key => $value){
  242. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  243. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  244. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  245. $data['data'][$key]['is_archive'] = $map[$value['month']] ?? false;
  246. }
  247. return $data;
  248. }
  249. public function fillDataForExport($data, $column, &$return)
  250. {
  251. if(empty($data)) return;
  252. $mainIds = array_column($data, 'id');
  253. // 获取详情映射 [main_id => [details...]]
  254. $detailsMap = $this->getDetailsMap($mainIds);
  255. // 默认空行模板
  256. $defaultRow = array_fill_keys($column, '');
  257. foreach ($data as $main) {
  258. $mainId = $main['id'];
  259. $details = $detailsMap[$mainId] ?? [];
  260. // 提取主表信息
  261. $mainInfo = [
  262. 'code' => $main['code'],
  263. 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
  264. ];
  265. if (empty($details)) {
  266. // 如果没有详情,至少导出一行主表信息(可选)
  267. $return[] = array_merge($defaultRow, $mainInfo);
  268. } else {
  269. // 核心:遍历详情,每一行详情都合并主表信息
  270. foreach ($details as $sub) {
  271. // 合并主表字段 + 详情字段
  272. $fullRow = array_merge($mainInfo, $sub);
  273. // 过滤掉不在导出列里的字段,并补充缺失列
  274. $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
  275. }
  276. }
  277. }
  278. }
  279. public function getDetailsMap($main_ids)
  280. {
  281. // 获取详情
  282. $details = MonthlyPwOrderDetails::where('del_time', 0)
  283. ->whereIn('main_id', $main_ids)
  284. ->get();
  285. // 获取人员信息
  286. $empIds = $details->pluck('employee_id')->unique();
  287. $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id');
  288. $res = [];
  289. foreach ($details as $item) {
  290. $tmpEmp = $empMap[$item->employee_id] ?? null;
  291. // 组装每一行详情需要展示的字段
  292. $res[$item->main_id][] = [
  293. 'employee_number' => $tmpEmp ? $tmpEmp->number : '',
  294. 'employee_title' => $tmpEmp ? $tmpEmp->title : '',
  295. 'total_days' => $item->total_days,
  296. 'rd_total_days' => $item->rd_total_days,
  297. 'total_hours' => $item->total_hours,
  298. 'rd_total_hours' => $item->rd_total_hours,
  299. ];
  300. }
  301. return $res; // 返回 [main_id => [detail_row, detail_row]]
  302. }
  303. // 人员日工时单 ------------------------------------------------
  304. public function dailyPwOrderEdit($data,$user){
  305. list($status,$msg) = $this->dailyPwOrderRule($data, $user, false);
  306. if(!$status) return [$status,$msg];
  307. try {
  308. DB::beginTransaction();
  309. $model = DailyPwOrder::where('id',$data['id'])->first();
  310. $model->item_id = $data['item_id'] ?? 0;
  311. $model->save();
  312. $time = time();
  313. DailyPwOrderDetails::where('del_time',0)
  314. ->where('main_id', $model->id)
  315. ->update(['del_time' => $time]);
  316. $this->saveDetailDaily($model->id, $time, $data, $user);
  317. DB::commit();
  318. }catch (\Exception $exception){
  319. DB::rollBack();
  320. return [false,$exception->getMessage()];
  321. }
  322. return [true, ''];
  323. }
  324. public function dailyPwOrderAdd($data,$user){
  325. list($status,$msg) = $this->dailyPwOrderRule($data, $user);
  326. if(!$status) return [$status,$msg];
  327. try {
  328. DB::beginTransaction();
  329. $model = new DailyPwOrder();
  330. $model->code = $this->generateBillNo([
  331. 'top_depart_id' => $user['top_depart_id'],
  332. 'type' => DailyPwOrder::Order_type,
  333. 'period' => date("Ym", $data['order_time'])
  334. ]);
  335. $model->order_time = $data['order_time'] ?? 0;
  336. $model->item_id = $data['item_id'] ?? 0;
  337. $model->crt_id = $user['id'];
  338. $model->top_depart_id = $data['top_depart_id'];
  339. $model->save();
  340. $this->saveDetailDaily($model->id, time(), $data, $user);
  341. DB::commit();
  342. }catch (\Exception $exception){
  343. DB::rollBack();
  344. return [false,$exception->getMessage()];
  345. }
  346. return [true, ''];
  347. }
  348. private function saveDetailDaily($id, $time, $data, $user){
  349. if(! empty($data['details'])){
  350. $unit = [];
  351. foreach ($data['details'] as $value){
  352. $unit[] = [
  353. 'main_id' => $id,
  354. 'employee_id' => $value['employee_id'],
  355. 'start_time_hour' => $value['start_time_hour'],
  356. 'start_time_min' => $value['start_time_min'],
  357. 'end_time_hour' => $value['end_time_hour'],
  358. 'end_time_min' => $value['end_time_min'],
  359. 'total_work_min' => $value['total_work_min'],
  360. 'crt_time' => $time,
  361. 'top_depart_id' => $value['top_depart_id'],
  362. 'order_time' => $data['order_time'] ?? 0,
  363. 'item_id' => $data['item_id'],
  364. 'crt_id' => $user['id'],
  365. ];
  366. }
  367. if(! empty($unit)) DailyPwOrderDetails::insert($unit);
  368. }
  369. }
  370. private function getDetailDaily($id){
  371. $data = DailyPwOrderDetails::where('del_time',0)
  372. ->where('main_id', $id)
  373. ->select('employee_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_work_min')
  374. ->get()->toArray();
  375. $id = array_column($data,'employee_id');
  376. $map = Employee::whereIn('id', $id)
  377. ->select('title','id','number')
  378. ->get()
  379. ->keyBy('id')
  380. ->toArray();
  381. foreach ($data as $key => $value){
  382. $tmp = $map[$value['employee_id']] ?? [];
  383. $merge = [];
  384. $merge['employee_title'] = $tmp['title'];
  385. $merge['employee_number'] = $tmp['number'];
  386. $data[$key] = array_merge($value, $merge);
  387. }
  388. $detail = [
  389. 'details' => $data,
  390. ];
  391. //foreach ($detail as $key => $value) {
  392. // if (empty($value)) {
  393. //$detail[$key] = (object)[]; // 转成 stdClass 对象
  394. //}
  395. //}
  396. return $detail;
  397. }
  398. public function dailyPwOrderDel($data, $user){
  399. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  400. try {
  401. DB::beginTransaction();
  402. $time = time();
  403. $month = DailyPwOrder::where('del_time',0)
  404. ->whereIn('id',$data['id'])
  405. ->pluck('order_time')
  406. ->toArray();
  407. //归档
  408. list($status, $msg) = ArchiveService::isArchive($month, $user);
  409. if(! $status) return [false, $msg];
  410. DailyPwOrder::where('del_time',0)
  411. ->whereIn('id',$data['id'])
  412. ->update(['del_time' => $time]);
  413. DailyPwOrderDetails::where('del_time',0)
  414. ->whereIn('main_id', $data['id'])
  415. ->update(['del_time' => $time]);
  416. DB::commit();
  417. }catch (\Exception $exception){
  418. DB::rollBack();
  419. return [false,$exception->getMessage()];
  420. }
  421. return [true, ''];
  422. }
  423. public function dailyPwOrderDetail($data, $user){
  424. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  425. $customer = DailyPwOrder::where('del_time',0)
  426. ->where('id',$data['id'])
  427. ->first();
  428. if(empty($customer)) return [false,'人员日工时单不存在或已被删除'];
  429. $customer = $customer->toArray();
  430. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  431. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  432. $item = Item::where('id', $customer['item_id'])->first();
  433. $customer['item_title'] = $item->title ?? '';
  434. $customer['item_code'] = $item->code ?? '';
  435. $map = ArchiveService::fillIsArchive($customer['order_time'], $user);
  436. $customer['is_archive'] = $map[$customer['order_time']] ?? false;
  437. $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
  438. $details = $this->getDetailDaily($data['id']);
  439. $customer = array_merge($customer, $details);
  440. return [true, $customer];
  441. }
  442. public function dailyPwOrderCommon($data,$user, $field = []){
  443. if(empty($field)) $field = DailyPwOrder::$field;
  444. $model = DailyPwOrder::Clear($user,$data);
  445. $model = $model->where('del_time',0)
  446. ->select($field)
  447. ->orderby('id', 'desc');
  448. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  449. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  450. $model->where('order_time','>=',$return[0]);
  451. $model->where('order_time','<=',$return[1]);
  452. }
  453. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  454. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  455. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  456. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  457. $model->where('crt_time','>=',$return[0]);
  458. $model->where('crt_time','<=',$return[1]);
  459. }
  460. if (!empty($data['item_title'])) {
  461. $models = Item::TopClear($user,$data);
  462. $id = $models->where('del_time',0)
  463. ->where('title', 'LIKE', '%'.$data['item_title'].'%')
  464. ->pluck('id')
  465. ->all();
  466. $model->whereIn('item_id', $id);
  467. }
  468. return $model;
  469. }
  470. public function dailyPwOrderList($data,$user){
  471. $model = $this->dailyPwOrderCommon($data, $user);
  472. $list = $this->limit($model,'',$data);
  473. $list = $this->fillDataDaily($list, $user);
  474. return [true, $list];
  475. }
  476. public function dailyPwOrderRule(&$data, $user, $is_add = true){
  477. $data['top_depart_id'] = $user['top_depart_id'];
  478. if(empty($data['order_time'])) return [false, '单据日期不能为空'];
  479. $data['order_time'] = $this->changeDateToDate($data['order_time']);
  480. $orderTime = $data['order_time'];
  481. $itemId = $data['item_id'] ?? 0;
  482. // 使用日期范围限制
  483. list($status, $msg) = MiddleGroundService::checkTimestampInRange($data['order_time'], $data['top_depart_id']);
  484. if(! $status) return [false, $msg];
  485. //归档
  486. list($status, $msg) = ArchiveService::isArchive($data['order_time'], $user);
  487. if(! $status) return [false, $msg];
  488. if(empty($itemId)) return [false, '项目不能为空'];
  489. $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
  490. if(!$bool) return [false, '项目不存在或已被删除'];
  491. if(empty($data['details'])) return [false, '人员日工时单明细不能为空'];
  492. // --- 1. 批量预获取人员信息,用于报错提示 ---
  493. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'employee_id')));
  494. // 如果需要工号+姓名,建议这样获取:
  495. $empDisplayMap = Employee::whereIn('id', $allEmpIds)
  496. ->get(['id', 'number', 'title'])
  497. ->mapWithKeys(function($item){
  498. return [$item->id => "[{$item->number}]{$item->title}"];
  499. })->toArray();
  500. // 2. 本次提交内部重叠记录器
  501. $internalOverlap = [];
  502. foreach ($data['details'] as $key => $value){
  503. $line = $key + 1;
  504. $t = "第" . $line . "行";
  505. $empId = $value['employee_id'] ?? 0;
  506. if(empty($empId)) return [false, '人员不能为空'];
  507. $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
  508. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  509. if(!$res['valid']) return [false, $t . "人员{$empName}开始点:" . $res['error']];
  510. if($value['start_time_hour'] > 23) return [false, false, $t . "人员{$empName}开始点不合法"];
  511. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  512. if(!$res['valid']) return [false, $t . "人员{$empName}开始分:" . $res['error']];
  513. if($value['start_time_min'] > 60) return [false, false, $t . "人员{$empName}开始点不合法"];
  514. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  515. if(!$res['valid']) return [false, $t . "人员{$empName}结束点:" . $res['error']];
  516. if($value['end_time_hour'] > 24) return [false, false, $t . "人员{$empName}结束点不合法"];
  517. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  518. if(!$res['valid']) return [false, $t . "人员{$empName}结束分:" . $res['error']];
  519. if($value['end_time_min'] > 60) return [false, false, $t . "人员{$empName}结束分不合法"];
  520. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  521. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  522. if ($currentStart >= $currentEnd) {
  523. return [false, $t . "人员{$empName}:开始时间必须早于结束时间"];
  524. }
  525. // --- 新增:总分钟数校验 ---
  526. $calculatedTotal = $currentEnd - $currentStart;
  527. if (!isset($value['total_work_min']) || intval($value['total_work_min']) !== $calculatedTotal) {
  528. return [false, $t . "人员{$empName}:总工时计算有误,应为 {$calculatedTotal} 分钟"];
  529. }
  530. // --- 3. 内部重叠校验(防止一次提交多行重复) ---
  531. if (isset($internalOverlap[$empId])) {
  532. foreach ($internalOverlap[$empId] as $period) {
  533. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  534. return [false, "人员{$empName}在本次提交的多行明细中时间段重叠"];
  535. }
  536. }
  537. }
  538. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  539. $query = DB::table('daily_pw_order_details as d')
  540. ->join('daily_pw_order as m', 'd.main_id', '=', 'm.id')
  541. ->where('m.top_depart_id', $data['top_depart_id'])
  542. ->where('m.order_time', $orderTime)
  543. ->where('m.item_id', $itemId)
  544. ->where('d.employee_id', $empId)
  545. ->where('m.del_time', 0)
  546. ->where('d.del_time', 0);
  547. if (!$is_add && !empty($data['id'])) {
  548. $query->where('m.id', '<>', $data['id']);
  549. }
  550. $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
  551. foreach ($existingPeriods as $p) {
  552. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  553. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  554. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  555. return [false, "人员{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
  556. }
  557. }
  558. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  559. }
  560. if(!$is_add){
  561. if(empty($data['id'])) return [false,'ID不能为空'];
  562. $bool = DailyPwOrder::where('top_depart_id', $data['top_depart_id'])
  563. ->where('id',$data['id'])
  564. ->where('del_time',0)
  565. ->exists();
  566. if(!$bool) return [false, '人员日工时单不存在或已被删除'];
  567. }
  568. return [true, ''];
  569. }
  570. public function fillDataDaily($data, $user){
  571. if(empty($data['data'])) return $data;
  572. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  573. $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_id')));
  574. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'order_time')), $user);
  575. foreach ($data['data'] as $key => $value){
  576. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  577. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  578. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  579. $item_tmp = $item[$value['item_id']] ?? [];
  580. $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
  581. $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
  582. $data['data'][$key]['is_archive'] = $map[$value['order_time']] ?? false;
  583. }
  584. return $data;
  585. }
  586. public function fillDataForExportDaily($data, $column, &$return)
  587. {
  588. if (empty($data)) return;
  589. $mainIds = array_column($data, 'id');
  590. // 1. 获取详情及所有关联档案(项目、人员)的映射
  591. $detailsMap = $this->getDailyDetailsMap($mainIds, $data);
  592. foreach ($data as $main) {
  593. $mainId = $main['id'];
  594. $details = $detailsMap[$mainId] ?? [];
  595. // 2. 提取并格式化主表共有信息
  596. $mainInfo = [
  597. 'code' => $main['code'],
  598. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  599. ];
  600. if (empty($details)) {
  601. // 无明细时只导出一行主表信息
  602. $tempRow = [];
  603. foreach ($column as $col) {
  604. $tempRow[] = $mainInfo[$col] ?? '';
  605. }
  606. $return[] = $tempRow;
  607. } else {
  608. // 3. 平铺:将详情里的项目信息、人员信息与主表信息合并
  609. foreach ($details as $sub) {
  610. $fullRowData = array_merge($mainInfo, $sub);
  611. $tempRow = [];
  612. foreach ($column as $col) {
  613. $tempRow[] = $fullRowData[$col] ?? '';
  614. }
  615. $return[] = $tempRow;
  616. }
  617. }
  618. }
  619. }
  620. public function getDailyDetailsMap($mainIds, $mainData)
  621. {
  622. // 1. 获取所有子表记录
  623. $details = DB::table('daily_pw_order_details')
  624. ->where('del_time', 0)
  625. ->whereIn('main_id', $mainIds)
  626. ->get();
  627. // 2. 提取所有关联 ID
  628. $empIds = $details->pluck('employee_id')->unique();
  629. $itemIds = array_unique(array_column($mainData, 'item_id')); // 从主表数组提取项目ID
  630. // 3. 批量获取档案 Map
  631. $empMap = DB::table('employee')
  632. ->whereIn('id', $empIds)
  633. ->get(['id', 'title', 'number'])
  634. ->keyBy('id');
  635. $itemMap = DB::table('item')
  636. ->whereIn('id', $itemIds)
  637. ->get(['id', 'title', 'code'])
  638. ->keyBy('id');
  639. // 4. 将主表的项目信息预先挂载到主表 ID 下,方便后续合并
  640. $mainItemInfo = [];
  641. foreach ($mainData as $m) {
  642. $proj = $itemMap[$m['item_id']] ?? null;
  643. $mainItemInfo[$m['id']] = [
  644. 'item_code' => $proj ? $proj->code : '',
  645. 'item_title' => $proj ? $proj->title : '',
  646. ];
  647. }
  648. $res = [];
  649. if ($details->isEmpty()) {
  650. // 如果没有详情,把项目信息返回去,确保主表能导出行
  651. foreach ($mainItemInfo as $mId => $info) {
  652. $res[$mId] = [];
  653. }
  654. return $res;
  655. }
  656. foreach ($details as $item) {
  657. $emp = $empMap[$item->employee_id] ?? null;
  658. // 组装明细行数据
  659. $detailRow = [
  660. // 人员信息
  661. 'employee_number' => $emp ? $emp->number : '',
  662. 'employee_title' => $emp ? $emp->title : '',
  663. // 时间信息
  664. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  665. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  666. // 将主表的项目信息也塞进每一行详情里实现平铺
  667. 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
  668. 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
  669. 'total_work_min' => $item->total_work_min,
  670. ];
  671. $res[$item->main_id][] = $detailRow;
  672. }
  673. return $res;
  674. }
  675. public function dailyPwOrderCreate($data, $user)
  676. {
  677. $topDepartId = $user['top_depart_id'];
  678. if (empty($data['month'])) return [false, '月份不能为空'];
  679. $monthStart = $this->changeDateToDate($data['month']);
  680. // --- 一开始就做的核心校验 ---
  681. // 1. 检查是否存在月度工时明细(如果没有,队列执行也是徒劳)
  682. $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
  683. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  684. ->where('m.month', $monthStart)
  685. ->where('m.top_depart_id', $topDepartId)
  686. ->where('m.del_time', 0)
  687. ->where('d.del_time', 0)
  688. ->exists();
  689. if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
  690. // 2. 检查是否配置了工作日历
  691. $hasCalendar = DB::table('calendar_details')
  692. ->where('month', $monthStart)
  693. ->where('del_time', 0)
  694. ->exists();
  695. if (!$hasCalendar) return [false, '该月份工作日历未配置'];
  696. // 3. 检查是否配置了项目比例规则
  697. $hasRules = DB::table('rule_set as r')
  698. ->where('r.month', $monthStart)
  699. ->where('r.top_depart_id', $topDepartId)
  700. ->where('r.del_time', 0)
  701. ->exists();
  702. if (!$hasRules) return [false, '未找到该月份的规则配置单'];
  703. $data['type'] = "p_work";
  704. ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
  705. return [true, '生成任务已提交,系统正在后台处理,请稍后查看'];
  706. }
  707. public function dailyPwOrderCreateMain($data, $user)
  708. {
  709. $topDepartId = $user['top_depart_id'];
  710. if (empty($data['month'])) return [false, '月份不能为空'];
  711. $monthStart = $this->changeDateToDate($data['month']);
  712. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  713. $now = time();
  714. DB::beginTransaction();
  715. try {
  716. // --- 0. 清理旧数据 ---
  717. $oldOrderIds = DB::table('daily_pw_order')
  718. ->where('top_depart_id', $topDepartId)
  719. ->where('order_time', '>=', $monthStart)
  720. ->where('order_time', '<=', $monthEnd)
  721. ->where('is_create', 1)
  722. ->where('del_time', 0)
  723. ->pluck('id');
  724. if ($oldOrderIds->isNotEmpty()) {
  725. DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  726. DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  727. }
  728. // --- 1. 基础数据加载 ---
  729. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  730. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  731. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  732. ->where('m.del_time', 0)->where('d.del_time', 0)
  733. ->select('d.*')->get();
  734. if ($monthlyOrder->isEmpty()) return [false, '未找到月度工时明细'];
  735. $empIds = $monthlyOrder->pluck('employee_id')->unique()->toArray();
  736. $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  737. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  738. $ruleSet = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  739. ->where('r.month', $monthStart)->where('rd.type', RuleSetDetails::type_one)
  740. ->where('r.del_time', 0)->where('rd.del_time', 0)
  741. ->select('rd.*')->get()->groupBy('data_id');
  742. $allDays = DB::table('calendar_details')->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
  743. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  744. ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('m.del_time', 0)
  745. ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
  746. // --- 2. 核心分配逻辑:计算每天、每个项目、每个人的分钟数 ---
  747. $finalAlloc = [];
  748. foreach ($monthlyOrder as $mDetail) {
  749. $empId = $mDetail->employee_id;
  750. $empRules = $ruleSet->get($empId);
  751. if (!$empRules) continue;
  752. $empRemainingMin = (float)$mDetail->rd_total_hours * 60;
  753. if ($empRemainingMin <= 0) continue;
  754. foreach ($allDays as $dayInfo) {
  755. if ($empRemainingMin <= 0) break;
  756. $dayTs = $dayInfo->time;
  757. $isWorkDay = ($dayInfo->is_work == CalendarDetails::TYPE_ONE);
  758. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  759. $todayOvertimes = $todaySpecials->where('main_type', 2);
  760. if (!$isWorkDay && $todayOvertimes->isEmpty()) continue;
  761. // 计算当天可用总时长
  762. $dayAvailableMin = 0;
  763. if ($isWorkDay) {
  764. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  765. foreach ($baseRanges as $br) {
  766. $brS = $br->start_time_hour * 60 + $br->start_time_min;
  767. $brE = $br->end_time_hour * 60 + $br->end_time_min;
  768. $avail = (float)$br->total_work_min;
  769. foreach ($todaySpecials->where('main_type', 1) as $lv) {
  770. $overlap = min($brE, ($lv->end_time_hour * 60 + $lv->end_time_min)) - max($brS, ($lv->start_time_hour * 60 + $lv->start_time_min));
  771. if ($overlap > 0) $avail -= $overlap;
  772. }
  773. $dayAvailableMin += max(0, $avail);
  774. }
  775. }
  776. foreach ($todayOvertimes as $ot) $dayAvailableMin += (float)$ot->total_min;
  777. $canAllocToday = min($empRemainingMin, $dayAvailableMin);
  778. if ($canAllocToday <= 0) continue;
  779. foreach ($empRules as $rule) {
  780. $rate = (float)$rule->rate / 100;
  781. $projectMin = $canAllocToday * $rate;
  782. if ($projectMin > 0) {
  783. // 结果存入:[日期][项目][人员]
  784. $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
  785. }
  786. }
  787. $empRemainingMin -= $canAllocToday;
  788. }
  789. }
  790. // --- 3. 生成单据:解决时间重叠的核心逻辑 ---
  791. $newOrderIds = [];
  792. // 为了解决重叠,我们需要按 [日期][人员] 来追踪时间池的消耗进度
  793. $dailyEmpTimePools = [];
  794. foreach ($finalAlloc as $dayTs => $projects) {
  795. foreach ($projects as $itemId => $employees) {
  796. $mainId = DB::table('daily_pw_order')->insertGetId([
  797. 'code' => '', 'item_id' => $itemId, 'order_time' => $dayTs, 'top_depart_id' => $topDepartId,
  798. 'is_create' => 1, 'crt_id' => $user['id'], 'crt_time' => $now, 'upd_time' => $now,
  799. ]);
  800. $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
  801. foreach ($employees as $empId => $toAllocMin) {
  802. // 如果该员工当天的池子还没构建,先构建一次
  803. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  804. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  805. }
  806. $tempRem = $toAllocMin;
  807. // 指向该员工当天的可用池引用,这样处理完项目A,池子里的时间会自动被“消耗”
  808. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  809. if ($tempRem <= 0) break;
  810. $pMax = $p['e'] - $p['s'];
  811. if ($pMax <= 0) continue;
  812. $take = min($tempRem, $pMax);
  813. $realStart = $p['s'];
  814. $realEnd = $p['s'] + $take;
  815. DB::table('daily_pw_order_details')->insert([
  816. 'main_id' => $mainId, 'employee_id' => $empId, 'top_depart_id' => $topDepartId,
  817. 'start_time_hour' => floor($realStart / 60), 'start_time_min' => $realStart % 60,
  818. 'end_time_hour' => floor($realEnd / 60), 'end_time_min' => $realEnd % 60,
  819. 'total_work_min' => $take, 'crt_time' => $now, 'upd_time' => $now,
  820. ]);
  821. $tempRem -= $take;
  822. // 重要:消耗掉这个时段的起始位置,确保下一个项目从这里开始
  823. $p['s'] = $realEnd;
  824. }
  825. }
  826. }
  827. }
  828. // --- 4. 回填单号 ---
  829. if (empty($newOrderIds)) return [false, '未生成数据'];
  830. foreach ($newOrderIds as $item) {
  831. $code = $this->generateBillNo(['top_depart_id' => $topDepartId, 'type' => DailyPwOrder::Order_type, 'period' => date("Ym", $item['time'])]);
  832. DB::table('daily_pw_order')->where('id', $item['id'])->update(['code' => $code]);
  833. }
  834. DB::commit();
  835. } catch (\Exception $e) {
  836. DB::rollBack();
  837. return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
  838. }
  839. return [true, ''];
  840. }
  841. /**
  842. * 辅助函数:构建某人某天的初始可用时段池
  843. */
  844. private function buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData)
  845. {
  846. $dayInfo = $allDays->where('time', $dayTs)->first();
  847. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  848. $pool = [];
  849. if ($dayInfo && $dayInfo->is_work == CalendarDetails::TYPE_ONE) {
  850. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  851. foreach ($baseRanges as $br) {
  852. $currentS = $br->start_time_hour * 60 + $br->start_time_min;
  853. $eMin = $br->end_time_hour * 60 + $br->end_time_min;
  854. $sortedLeaves = $todaySpecials->where('main_type', 1)->sortBy('start_time_hour');
  855. foreach ($sortedLeaves as $lv) {
  856. $lvS = $lv->start_time_hour * 60 + $lv->start_time_min;
  857. $lvE = $lv->end_time_hour * 60 + $lv->end_time_min;
  858. if ($lvS < $eMin && $lvE > $currentS) {
  859. if ($lvS > $currentS) $pool[] = ['s' => $currentS, 'e' => $lvS];
  860. $currentS = max($currentS, $lvE);
  861. }
  862. }
  863. if ($currentS < $eMin) $pool[] = ['s' => $currentS, 'e' => $eMin];
  864. }
  865. }
  866. foreach ($todaySpecials->where('main_type', 2) as $ot) {
  867. $otS = $ot->start_time_hour * 60 + $ot->start_time_min;
  868. $pool[] = ['s' => $otS, 'e' => $otS + (float)$ot->total_min];
  869. }
  870. return $pool;
  871. }
  872. public function dailyPwOrderPreview($data, $user)
  873. {
  874. $topDepartId = $user['top_depart_id'];
  875. if (empty($data['month'])) return [false, '月份不能为空'];
  876. // 1. 前置校验 (保留你之前的校验逻辑)
  877. $monthStart = $this->changeDateToDate($data['month']);
  878. //归档
  879. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  880. if(! $status) return [false, $msg];
  881. // 1. 检查是否存在月度工时明细
  882. $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
  883. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  884. ->where('m.month', $monthStart)
  885. ->where('m.top_depart_id', $topDepartId)
  886. ->where('m.del_time', 0)
  887. ->where('d.del_time', 0)
  888. ->exists();
  889. if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
  890. // 2. 检查是否配置了工作日历
  891. $hasCalendar = DB::table('calendar_details')
  892. ->where('month', $monthStart)
  893. ->where('del_time', 0)
  894. ->exists();
  895. if (!$hasCalendar) return [false, '该月份工作日历未配置'];
  896. // 3. 检查是否配置了项目比例规则
  897. $hasRules = DB::table('rule_set as r')
  898. ->where('r.month', $monthStart)
  899. ->where('r.top_depart_id', $topDepartId)
  900. ->where('r.del_time', 0)
  901. ->exists();
  902. if (!$hasRules) return [false, '未找到该月份的规则配置单'];
  903. // 2. 调用核心计算逻辑 (抽取出的私有方法)
  904. $result = $this->calculateDailyAllocation($monthStart, $topDepartId, $user);
  905. if (!$result['status']) return [false, $result['msg']];
  906. // 3. 将结果存入临时表或直接返回
  907. // 建议增加一个 batch_id,防止多人操作冲突
  908. $batchId = uniqid('batch_');
  909. $previewData = $result['data'];
  910. // $total = 0;
  911. // foreach ($previewData as $value){
  912. // if($value['employee_id'] == 142 && $value['item_id'] == 122) $total += $value['total_work_min'];
  913. // }dd($total);
  914. return [true, [
  915. 'batch_id' => $batchId,
  916. 'list' => $previewData // 返回给前端展示
  917. ]];
  918. }
  919. /**
  920. * 核心分配逻辑:计算预览数据(确保全整数分钟)
  921. * @param int $monthStart 月初时间戳
  922. * @param int $topDepartId 顶级部门ID
  923. * @param array $user 用户信息
  924. * @return array
  925. */
  926. private function calculateDailyAllocation1($monthStart, $topDepartId, $user)
  927. {
  928. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  929. $now = time();
  930. // --- 1. 基础数据加载 ---
  931. // 加载月度工时明细,并关联人员姓名
  932. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  933. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  934. ->leftJoin('employee as e', 'e.id', '=', 'd.employee_id') // 关联人员表
  935. ->where('m.month', $monthStart)
  936. ->where('m.top_depart_id', $topDepartId)
  937. ->where('m.del_time', 0)
  938. ->where('d.del_time', 0)
  939. ->select('d.*', 'e.title as employee_title') // 获取人员姓名
  940. ->get();
  941. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到该月份的月度工时明细'];
  942. // 建立人员 ID -> 姓名的映射,方便后续取用
  943. $empNameMap = $monthlyOrder->pluck('employee_title', 'employee_id')->toArray();
  944. $empIds = array_keys($empNameMap);
  945. // 加载项目信息,用于获取项目名称
  946. // 假设项目表名为 items,请根据你实际的表名修改
  947. $itemIds = DB::table('rule_set_details as rd')
  948. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  949. ->where('r.month', $monthStart)
  950. ->where('r.top_depart_id', $topDepartId)
  951. ->pluck('rd.item_id')->unique()->toArray();
  952. $itemMap = DB::table('item')
  953. ->whereIn('id', $itemIds)
  954. ->pluck('title', 'id')
  955. ->toArray();
  956. // 加载分配规则
  957. $ruleSet = DB::table('rule_set_details as rd')
  958. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  959. ->where('r.month', $monthStart)
  960. ->where('rd.type', 1)
  961. ->where('r.del_time', 0)
  962. ->where('rd.del_time', 0)
  963. ->select('rd.*')
  964. ->get()
  965. ->groupBy('data_id');
  966. // 加载员工/标准班次、日历、请假加班数据 (逻辑同前)
  967. $empWorkRanges = DB::table('employee_work_range')
  968. ->whereIn('employee_id', $empIds)
  969. ->where('top_depart_id', $topDepartId)
  970. ->get()->groupBy('employee_id');
  971. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)
  972. ->where('del_time', 0)->get();
  973. $allDays = DB::table('calendar_details')->where('top_depart_id', $topDepartId)
  974. ->where('month', $monthStart)
  975. ->where('del_time', 0)
  976. ->orderBy('time', 'asc')
  977. ->get();
  978. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  979. ->whereBetween('m.order_time', [$monthStart, $monthEnd])
  980. ->where('d.top_depart_id', $topDepartId)
  981. ->where('m.del_time', 0)
  982. ->select('d.*', 'm.order_time', 'm.type as main_type')
  983. ->get()->groupBy(['employee_id', 'order_time']);
  984. // --- 2. 阶段一:计算每个人每天在每个项目上应分配的整数分钟数 ---
  985. $finalAlloc = [];
  986. foreach ($monthlyOrder as $mDetail) {
  987. $empId = $mDetail->employee_id;
  988. $empRules = $ruleSet->get($empId);
  989. if (!$empRules) continue;
  990. $empRemainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  991. if ($empRemainingMin <= 0) continue;
  992. foreach ($allDays as $dayInfo) {
  993. if ($empRemainingMin <= 0) break;
  994. $dayTs = $dayInfo->time;
  995. $tempPool = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  996. $dayAvailableMin = 0;
  997. foreach ($tempPool as $p) { $dayAvailableMin += (int)($p['e'] - $p['s']); }
  998. if ($dayAvailableMin <= 0) continue;
  999. $canAllocToday = min($empRemainingMin, $dayAvailableMin);
  1000. $allocatedInDay = 0;
  1001. $ruleCount = count($empRules);
  1002. foreach ($empRules as $index => $rule) {
  1003. $rate = (float)$rule->rate / 100;
  1004. if ($index === $ruleCount - 1) {
  1005. $projectMin = $canAllocToday - $allocatedInDay;
  1006. } else {
  1007. $projectMin = (int)round($canAllocToday * $rate);
  1008. }
  1009. if ($projectMin > 0) {
  1010. $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
  1011. $allocatedInDay += $projectMin;
  1012. }
  1013. }
  1014. $empRemainingMin -= $canAllocToday;
  1015. }
  1016. }
  1017. // --- 3. 阶段二:打散到具体时间点并生成预览行 ---
  1018. $previewList = [];
  1019. $dailyEmpTimePools = [];
  1020. $tempMainIdCounter = 1;
  1021. foreach ($finalAlloc as $dayTs => $projects) {
  1022. foreach ($projects as $itemId => $employees) {
  1023. $currentTempMainId = $tempMainIdCounter++;
  1024. // 获取项目名称
  1025. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  1026. foreach ($employees as $empId => $toAllocMin) {
  1027. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  1028. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  1029. }
  1030. $tempRem = (int)$toAllocMin;
  1031. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  1032. if ($tempRem <= 0) break;
  1033. $pMax = (int)($p['e'] - $p['s']);
  1034. if ($pMax <= 0) continue;
  1035. $take = min($tempRem, $pMax);
  1036. $realStart = (int)$p['s'];
  1037. $realEnd = $realStart + $take;
  1038. // 写入带 Title 的结果
  1039. $previewList[] = [
  1040. 'temp_main_id' => $currentTempMainId,
  1041. 'order_time' => date('Y-m-d', $dayTs),
  1042. 'order_timestamp' => $dayTs,
  1043. 'item_id' => $itemId,
  1044. 'item_title' => $itemTitle, // 项目名称
  1045. 'employee_id' => $empId,
  1046. 'employee_title' => $empNameMap[$empId] ?? '未知人员', // 人员姓名
  1047. 'start_time' => sprintf('%02d:%02d', floor($realStart / 60), $realStart % 60),
  1048. 'end_time' => sprintf('%02d:%02d', floor($realEnd / 60), $realEnd % 60),
  1049. 'start_hour' => (int)floor($realStart / 60),
  1050. 'start_min' => (int)($realStart % 60),
  1051. 'end_hour' => (int)floor($realEnd / 60),
  1052. 'end_min' => (int)($realEnd % 60),
  1053. 'total_work_min' => $take,
  1054. ];
  1055. $tempRem -= $take;
  1056. $p['s'] = $realEnd;
  1057. }
  1058. }
  1059. }
  1060. }
  1061. return ['status' => true, 'data' => $previewList];
  1062. }
  1063. private function calculateDailyAllocation($monthStart, $topDepartId, $user)
  1064. {
  1065. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  1066. $step = 5; // 尽量 5 分钟对齐;明细允许个别非整 5
  1067. // --- 1. 基础数据加载 ---
  1068. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  1069. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  1070. ->leftJoin('employee as e', 'e.id', '=', 'd.employee_id')
  1071. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  1072. ->where('m.del_time', 0)->where('d.del_time', 0)
  1073. ->select('d.*', 'e.title as employee_title')->get();
  1074. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到明细'];
  1075. $empNameMap = $monthlyOrder->pluck('employee_title', 'employee_id')->toArray();
  1076. $empIds = array_keys($empNameMap);
  1077. $itemIds = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  1078. ->where('r.month', $monthStart)->where('r.top_depart_id', $topDepartId)->pluck('rd.item_id')->unique()->toArray();
  1079. $itemMap = DB::table('item')->whereIn('id', $itemIds)->pluck('title', 'id')->toArray();
  1080. $ruleSet = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  1081. ->where('r.month', $monthStart)->where('rd.type', 1)->where('r.del_time', 0)->where('rd.del_time', 0)
  1082. ->select('rd.*')->get()->groupBy('data_id');
  1083. $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  1084. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  1085. $allDays = DB::table('calendar_details')->where('top_depart_id', $topDepartId)->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
  1086. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  1087. ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('d.top_depart_id', $topDepartId)->where('m.del_time', 0)
  1088. ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
  1089. // --- 2. 阶段一:先锁定「每人每项目月目标」= 最大余数法(月总×比例),再往工作日摊 ---
  1090. // 5 分钟对齐产生的零头,只加回「同一个人 + 同一个项目」的明细,不甩给别的项目
  1091. $finalAlloc = [];
  1092. $empProjectTargets = []; // [empId][itemId] => 月目标分钟
  1093. $dayBalance = [];
  1094. foreach ($monthlyOrder as $mDetail) {
  1095. $empId = $mDetail->employee_id;
  1096. $empRules = $ruleSet->get($empId);
  1097. if (!$empRules || $empRules->isEmpty()) continue;
  1098. $empTotalMin = (int)round((float)$mDetail->rd_total_hours * 60);
  1099. if ($empTotalMin <= 0) continue;
  1100. // 2.1 按比例拆月目标(最大余数法,保证加总=月总,且最接近「月总×比例」)
  1101. $projTarget = $this->buildProjectMonthTargetsByRate($empRules, $empTotalMin);
  1102. if (empty($projTarget)) continue;
  1103. $empProjectTargets[$empId] = $projTarget;
  1104. $projRem = $projTarget;
  1105. $empRemainingMin = $empTotalMin;
  1106. // 2.2 预计算有容量的工作日
  1107. $dayCaps = [];
  1108. foreach ($allDays as $dayInfo) {
  1109. $dayTs = $dayInfo->time;
  1110. $tempPool = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  1111. $dayCapacity = 0;
  1112. foreach ($tempPool as $p) {
  1113. $dayCapacity += (int)($p['e'] - $p['s']);
  1114. }
  1115. if ($dayCapacity > 0) {
  1116. $dayCaps[$dayTs] = $dayCapacity;
  1117. }
  1118. }
  1119. if (empty($dayCaps)) continue;
  1120. $dayTsList = array_keys($dayCaps);
  1121. $dayIndex = 0;
  1122. $dayCount = count($dayTsList);
  1123. foreach ($dayTsList as $dayTs) {
  1124. if ($empRemainingMin <= 0) break;
  1125. if (array_sum($projRem) <= 0) break;
  1126. $dayCapacity = $dayCaps[$dayTs];
  1127. $theoryAlloc = min($empRemainingMin, $dayCapacity);
  1128. $isLastDay = ($dayIndex === $dayCount - 1) || ($theoryAlloc >= $empRemainingMin);
  1129. if (!$isLastDay) {
  1130. $currentWithBalance = $theoryAlloc + ($dayBalance[$empId] ?? 0);
  1131. $roundedAlloc = (int)round($currentWithBalance / $step) * $step;
  1132. $canAllocToday = min($roundedAlloc, $dayCapacity, $empRemainingMin);
  1133. if ($canAllocToday <= 0 && $theoryAlloc > 0) {
  1134. $canAllocToday = min($theoryAlloc, $empRemainingMin);
  1135. }
  1136. $dayBalance[$empId] = $currentWithBalance - $canAllocToday;
  1137. } else {
  1138. $canAllocToday = min($empRemainingMin, $dayCapacity);
  1139. $dayBalance[$empId] = 0;
  1140. }
  1141. if ($canAllocToday <= 0) {
  1142. $dayIndex++;
  1143. continue;
  1144. }
  1145. $dayParts = $this->splitMinutesByRemaining($canAllocToday, $projRem, $step, $isLastDay);
  1146. foreach ($dayParts as $itemId => $projectMin) {
  1147. if ($projectMin <= 0) continue;
  1148. $finalAlloc[$dayTs][$itemId][$empId] = ($finalAlloc[$dayTs][$itemId][$empId] ?? 0) + $projectMin;
  1149. $projRem[$itemId] = max(0, ($projRem[$itemId] ?? 0) - $projectMin);
  1150. }
  1151. $empRemainingMin -= $canAllocToday;
  1152. $dayIndex++;
  1153. }
  1154. // 2.3 仍有项目剩余则塞进尚有空闲的天(仍归原项目)
  1155. $stuck = array_sum($projRem);
  1156. if ($stuck > 0) {
  1157. foreach ($dayCaps as $dayTs => $dayCapacity) {
  1158. if ($stuck <= 0) break;
  1159. $used = 0;
  1160. if (!empty($finalAlloc[$dayTs])) {
  1161. foreach ($finalAlloc[$dayTs] as $emps) {
  1162. $used += (int)($emps[$empId] ?? 0);
  1163. }
  1164. }
  1165. $free = $dayCapacity - $used;
  1166. if ($free <= 0) continue;
  1167. foreach ($projRem as $itemId => $rem) {
  1168. if ($rem <= 0 || $free <= 0) continue;
  1169. $take = min($rem, $free);
  1170. $finalAlloc[$dayTs][$itemId][$empId] = ($finalAlloc[$dayTs][$itemId][$empId] ?? 0) + $take;
  1171. $projRem[$itemId] -= $take;
  1172. $free -= $take;
  1173. $stuck -= $take;
  1174. }
  1175. }
  1176. }
  1177. }
  1178. // --- 3. 阶段二:打散到时间点;尽量 5 对齐,零头加回同一人同一项目的某条明细 ---
  1179. $previewList = [];
  1180. $dailyEmpTimePools = [];
  1181. $tempMainIdCounter = 1;
  1182. foreach ($finalAlloc as $dayTs => $projects) {
  1183. foreach ($projects as $itemId => $employees) {
  1184. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  1185. foreach ($employees as $empId => $toAllocMin) {
  1186. $currentTempMainId = $tempMainIdCounter++;
  1187. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  1188. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool(
  1189. $empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData
  1190. );
  1191. }
  1192. $tempRem = (int)$toAllocMin;
  1193. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  1194. if ($tempRem <= 0) break;
  1195. $rawStart = (int)$p['s'];
  1196. $alignedStart = (int)ceil($rawStart / $step) * $step;
  1197. if ($alignedStart < $p['e'] && ($p['e'] - $alignedStart) >= min($tempRem, 1)) {
  1198. $realStart = $alignedStart;
  1199. } else {
  1200. $realStart = $rawStart;
  1201. }
  1202. if ($realStart >= $p['e']) continue;
  1203. $pMax = (int)($p['e'] - $realStart);
  1204. $take = min($tempRem, $pMax);
  1205. // 先尽量按 5 切开;零头必须加到「后面有空档」的同人同项目明细上,避免保存时时间冲突
  1206. if ($take >= $step && $tempRem > $step) {
  1207. $alignedTake = (int)floor($take / $step) * $step;
  1208. if ($take >= $tempRem) {
  1209. $blocks = (int)floor($tempRem / $step) * $step;
  1210. $odd = $tempRem - $blocks;
  1211. $take = $blocks > 0 ? $blocks : $tempRem;
  1212. if ($blocks > 0 && $odd > 0) {
  1213. $realEnd = $realStart + $take;
  1214. // 零头只能加在当前池子剩余空间内,且不与已有明细冲突
  1215. $roomInPool = (int)$p['e'] - $realEnd;
  1216. $oddToAdd = min($odd, max(0, $roomInPool));
  1217. $previewList[] = $this->makePreviewRow(
  1218. $currentTempMainId, $dayTs, $itemId, $itemTitle, $empId,
  1219. $empNameMap[$empId] ?? '未知人员', $realStart, $realEnd, $take
  1220. );
  1221. $rowIdx = count($previewList) - 1;
  1222. $tempRem -= $take;
  1223. $p['s'] = $realEnd;
  1224. if ($oddToAdd > 0 && $this->safeBumpPreviewRowMinutes($previewList, $rowIdx, $oddToAdd)) {
  1225. $tempRem -= $oddToAdd;
  1226. $p['s'] = $realEnd + $oddToAdd;
  1227. }
  1228. // 加不进去的 odd 留给后面 safe 回填
  1229. continue;
  1230. }
  1231. } elseif ($alignedTake > 0) {
  1232. $take = $alignedTake;
  1233. }
  1234. }
  1235. $realEnd = $realStart + $take;
  1236. $previewList[] = $this->makePreviewRow(
  1237. $currentTempMainId, $dayTs, $itemId, $itemTitle, $empId,
  1238. $empNameMap[$empId] ?? '未知人员', $realStart, $realEnd, $take
  1239. );
  1240. $tempRem -= $take;
  1241. $p['s'] = $realEnd;
  1242. }
  1243. unset($p);
  1244. // 剩余分钟:找同人同项目、延长后不冲突的明细往后加
  1245. if ($tempRem > 0) {
  1246. $left = $this->safeBumpMinutesOntoEmpItem(
  1247. $previewList,
  1248. (int)$empId,
  1249. (int)$itemId,
  1250. $tempRem,
  1251. date('Y-m-d', $dayTs)
  1252. );
  1253. if ($left > 0) {
  1254. // 当天加不下,再在其它日期的同人同项目明细上找空档
  1255. $left = $this->safeBumpMinutesOntoEmpItem(
  1256. $previewList,
  1257. (int)$empId,
  1258. (int)$itemId,
  1259. $left,
  1260. null
  1261. );
  1262. }
  1263. // 仍剩:在当天找同人空档新开一条短明细(仍属本项目)
  1264. if ($left > 0) {
  1265. $placed = $this->insertRemainderRowInFreeGap(
  1266. $previewList,
  1267. $currentTempMainId,
  1268. $dayTs,
  1269. $itemId,
  1270. $itemTitle,
  1271. $empId,
  1272. $empNameMap[$empId] ?? '未知人员',
  1273. $left
  1274. );
  1275. if ($placed) {
  1276. $left = 0;
  1277. }
  1278. }
  1279. $tempRem = $left;
  1280. }
  1281. }
  1282. }
  1283. }
  1284. // 3.1 最终校验:每人每项目合计必须等于月目标;差额安全加回(不制造重叠)
  1285. $previewList = $this->reconcilePreviewToProjectTargets($previewList, $empProjectTargets);
  1286. return ['status' => true, 'data' => $previewList];
  1287. }
  1288. /**
  1289. * 按分摊比例生成每人各项目月目标分钟(最大余数法)
  1290. * 保证:sum(项目) = 月总;各项目尽可能等于 round/最接近 月总×比例
  1291. */
  1292. private function buildProjectMonthTargetsByRate($empRules, $empTotalMin)
  1293. {
  1294. $rateByItem = [];
  1295. foreach ($empRules as $rule) {
  1296. $itemId = (int)$rule->item_id;
  1297. $rateByItem[$itemId] = ($rateByItem[$itemId] ?? 0) + (float)$rule->rate;
  1298. }
  1299. if (empty($rateByItem) || $empTotalMin <= 0) {
  1300. return [];
  1301. }
  1302. $rateSum = array_sum($rateByItem);
  1303. if ($rateSum <= 0) {
  1304. return [];
  1305. }
  1306. $targets = [];
  1307. $parts = [];
  1308. $used = 0;
  1309. foreach ($rateByItem as $itemId => $rate) {
  1310. $ideal = $empTotalMin * ($rate / $rateSum);
  1311. $floor = (int)floor($ideal + 1e-8);
  1312. $targets[$itemId] = $floor;
  1313. $used += $floor;
  1314. $parts[] = [
  1315. 'item_id' => $itemId,
  1316. 'frac' => $ideal - $floor,
  1317. 'rate' => $rate,
  1318. ];
  1319. }
  1320. $left = $empTotalMin - $used;
  1321. usort($parts, function ($a, $b) {
  1322. if ($a['frac'] == $b['frac']) {
  1323. return $b['rate'] <=> $a['rate'];
  1324. }
  1325. return $b['frac'] <=> $a['frac'];
  1326. });
  1327. foreach ($parts as $row) {
  1328. if ($left <= 0) break;
  1329. $targets[$row['item_id']]++;
  1330. $left--;
  1331. }
  1332. return $targets;
  1333. }
  1334. private function makePreviewRow($tempMainId, $dayTs, $itemId, $itemTitle, $empId, $empTitle, $realStart, $realEnd, $take)
  1335. {
  1336. return [
  1337. 'temp_main_id' => $tempMainId,
  1338. 'order_time' => date('Y-m-d', $dayTs),
  1339. 'order_timestamp' => $dayTs,
  1340. 'item_id' => $itemId,
  1341. 'item_title' => $itemTitle,
  1342. 'employee_id' => $empId,
  1343. 'employee_title' => $empTitle,
  1344. 'start_time' => sprintf('%02d:%02d', floor($realStart / 60), $realStart % 60),
  1345. 'end_time' => sprintf('%02d:%02d', floor($realEnd / 60), $realEnd % 60),
  1346. 'start_hour' => (int)floor($realStart / 60),
  1347. 'start_min' => (int)($realStart % 60),
  1348. 'end_hour' => (int)floor($realEnd / 60),
  1349. 'end_min' => (int)($realEnd % 60),
  1350. 'total_work_min' => $take,
  1351. ];
  1352. }
  1353. private function rowStartMin(array $row)
  1354. {
  1355. return ((int)$row['start_hour']) * 60 + (int)$row['start_min'];
  1356. }
  1357. private function rowEndMin(array $row)
  1358. {
  1359. return ((int)$row['end_hour']) * 60 + (int)$row['end_min'];
  1360. }
  1361. /**
  1362. * 指定下标延长 end,不校验冲突(调用方需先确保安全)
  1363. */
  1364. private function bumpPreviewRowMinutes(array &$previewList, $index, $addMin)
  1365. {
  1366. if ($addMin == 0 || !isset($previewList[$index])) {
  1367. return;
  1368. }
  1369. $row = &$previewList[$index];
  1370. $end = $this->rowEndMin($row) + (int)$addMin;
  1371. if ($end < $this->rowStartMin($row)) {
  1372. $end = $this->rowStartMin($row);
  1373. }
  1374. $row['end_hour'] = (int)floor($end / 60);
  1375. $row['end_min'] = (int)($end % 60);
  1376. $row['end_time'] = sprintf('%02d:%02d', $row['end_hour'], $row['end_min']);
  1377. $row['total_work_min'] = max(0, $end - $this->rowStartMin($row));
  1378. unset($row);
  1379. }
  1380. /**
  1381. * 判断把 index 行结束时间延长 addMin 后,是否与同人同日其它明细冲突
  1382. */
  1383. private function canBumpRowWithoutOverlap(array $previewList, $index, $addMin)
  1384. {
  1385. if ($addMin <= 0 || !isset($previewList[$index])) {
  1386. return false;
  1387. }
  1388. $row = $previewList[$index];
  1389. $empId = (int)$row['employee_id'];
  1390. $dateStr = $row['order_time'];
  1391. $newS = $this->rowStartMin($row);
  1392. $newE = $this->rowEndMin($row) + (int)$addMin;
  1393. if ($newE <= $newS) {
  1394. return false;
  1395. }
  1396. foreach ($previewList as $i => $other) {
  1397. if ($i === $index) {
  1398. continue;
  1399. }
  1400. if ((int)$other['employee_id'] !== $empId) {
  1401. continue;
  1402. }
  1403. if ($other['order_time'] !== $dateStr) {
  1404. continue;
  1405. }
  1406. $os = $this->rowStartMin($other);
  1407. $oe = $this->rowEndMin($other);
  1408. if ($newS < $oe && $newE > $os) {
  1409. return false;
  1410. }
  1411. }
  1412. return true;
  1413. }
  1414. /**
  1415. * 安全延长指定行(通过冲突检查才改)
  1416. */
  1417. private function safeBumpPreviewRowMinutes(array &$previewList, $index, $addMin)
  1418. {
  1419. if (!$this->canBumpRowWithoutOverlap($previewList, $index, $addMin)) {
  1420. return false;
  1421. }
  1422. $this->bumpPreviewRowMinutes($previewList, $index, $addMin);
  1423. return true;
  1424. }
  1425. /**
  1426. * 把分钟安全加到「同人 + 同项目」某条明细后面(优先指定日期)
  1427. * @return int 未能加上的剩余分钟
  1428. */
  1429. private function safeBumpMinutesOntoEmpItem(array &$previewList, $empId, $itemId, $addMin, $preferDate = null)
  1430. {
  1431. $addMin = (int)$addMin;
  1432. if ($addMin <= 0) {
  1433. return 0;
  1434. }
  1435. // 候选:同人同项目,按「结束后空档大小」优先;同日优先
  1436. $candidates = [];
  1437. foreach ($previewList as $i => $row) {
  1438. if ((int)$row['employee_id'] !== (int)$empId) {
  1439. continue;
  1440. }
  1441. if ((int)$row['item_id'] !== (int)$itemId) {
  1442. continue;
  1443. }
  1444. if ($preferDate !== null && $row['order_time'] !== $preferDate) {
  1445. continue;
  1446. }
  1447. $gap = $this->gapAfterRow($previewList, $i);
  1448. if ($gap <= 0) {
  1449. continue;
  1450. }
  1451. $candidates[] = [
  1452. 'index' => $i,
  1453. 'gap' => $gap,
  1454. 'end' => $this->rowEndMin($row),
  1455. 'same_day' => 1,
  1456. ];
  1457. }
  1458. // 指定日没有空档时,扩大到其它日期
  1459. if (empty($candidates) && $preferDate !== null) {
  1460. return $this->safeBumpMinutesOntoEmpItem($previewList, $empId, $itemId, $addMin, null);
  1461. }
  1462. usort($candidates, function ($a, $b) {
  1463. if ($a['gap'] == $b['gap']) {
  1464. return $b['end'] <=> $a['end'];
  1465. }
  1466. return $b['gap'] <=> $a['gap'];
  1467. });
  1468. $left = $addMin;
  1469. foreach ($candidates as $c) {
  1470. if ($left <= 0) {
  1471. break;
  1472. }
  1473. $give = min($left, $c['gap']);
  1474. // 再确认一次(可能前面已经 bump 过改变了空隙)
  1475. $gapNow = $this->gapAfterRow($previewList, $c['index']);
  1476. $give = min($give, $gapNow);
  1477. if ($give <= 0) {
  1478. continue;
  1479. }
  1480. if ($this->safeBumpPreviewRowMinutes($previewList, $c['index'], $give)) {
  1481. $left -= $give;
  1482. }
  1483. }
  1484. return max(0, $left);
  1485. }
  1486. /**
  1487. * 某条明细结束后,到同人同日下一段开始之间的空档分钟数
  1488. */
  1489. private function gapAfterRow(array $previewList, $index)
  1490. {
  1491. if (!isset($previewList[$index])) {
  1492. return 0;
  1493. }
  1494. $row = $previewList[$index];
  1495. $empId = (int)$row['employee_id'];
  1496. $dateStr = $row['order_time'];
  1497. $end = $this->rowEndMin($row);
  1498. $nextStart = null;
  1499. foreach ($previewList as $i => $other) {
  1500. if ($i === $index) {
  1501. continue;
  1502. }
  1503. if ((int)$other['employee_id'] !== $empId) {
  1504. continue;
  1505. }
  1506. if ($other['order_time'] !== $dateStr) {
  1507. continue;
  1508. }
  1509. $os = $this->rowStartMin($other);
  1510. if ($os >= $end) {
  1511. if ($nextStart === null || $os < $nextStart) {
  1512. $nextStart = $os;
  1513. }
  1514. }
  1515. }
  1516. // 没有下一段:最多延到当天 24:00,避免无限延长
  1517. if ($nextStart === null) {
  1518. $nextStart = 24 * 60;
  1519. }
  1520. return max(0, $nextStart - $end);
  1521. }
  1522. /**
  1523. * 在同人当天已有时间线的空隙中,插入一条余数明细(仍属本项目)
  1524. */
  1525. private function insertRemainderRowInFreeGap(
  1526. array &$previewList,
  1527. $tempMainId,
  1528. $dayTs,
  1529. $itemId,
  1530. $itemTitle,
  1531. $empId,
  1532. $empTitle,
  1533. $needMin
  1534. ) {
  1535. $needMin = (int)$needMin;
  1536. if ($needMin <= 0) {
  1537. return false;
  1538. }
  1539. $dateStr = date('Y-m-d', $dayTs);
  1540. // 收集当天该人所有区间
  1541. $intervals = [];
  1542. foreach ($previewList as $row) {
  1543. if ((int)$row['employee_id'] !== (int)$empId) {
  1544. continue;
  1545. }
  1546. if ($row['order_time'] !== $dateStr) {
  1547. continue;
  1548. }
  1549. $intervals[] = ['s' => $this->rowStartMin($row), 'e' => $this->rowEndMin($row)];
  1550. }
  1551. usort($intervals, function ($a, $b) {
  1552. return $a['s'] <=> $b['s'];
  1553. });
  1554. // 合并后找空隙
  1555. $cursor = 0;
  1556. $dayEnd = 24 * 60;
  1557. foreach ($intervals as $iv) {
  1558. if ($iv['s'] > $cursor) {
  1559. $gap = $iv['s'] - $cursor;
  1560. if ($gap >= $needMin) {
  1561. $previewList[] = $this->makePreviewRow(
  1562. $tempMainId, $dayTs, $itemId, $itemTitle, $empId, $empTitle,
  1563. $cursor, $cursor + $needMin, $needMin
  1564. );
  1565. return true;
  1566. }
  1567. }
  1568. $cursor = max($cursor, $iv['e']);
  1569. }
  1570. if ($dayEnd - $cursor >= $needMin) {
  1571. $previewList[] = $this->makePreviewRow(
  1572. $tempMainId, $dayTs, $itemId, $itemTitle, $empId, $empTitle,
  1573. $cursor, $cursor + $needMin, $needMin
  1574. );
  1575. return true;
  1576. }
  1577. return false;
  1578. }
  1579. /**
  1580. * 最终对齐:每人每项目明细合计必须等于月目标;差额安全加回(不制造重叠)
  1581. */
  1582. private function reconcilePreviewToProjectTargets(array $previewList, array $empProjectTargets)
  1583. {
  1584. if (empty($empProjectTargets) || empty($previewList)) {
  1585. return $previewList;
  1586. }
  1587. $actual = [];
  1588. foreach ($previewList as $row) {
  1589. $empId = (int)$row['employee_id'];
  1590. $itemId = (int)$row['item_id'];
  1591. $actual[$empId][$itemId] = ($actual[$empId][$itemId] ?? 0) + (int)$row['total_work_min'];
  1592. }
  1593. foreach ($empProjectTargets as $empId => $items) {
  1594. foreach ($items as $itemId => $target) {
  1595. $got = (int)($actual[$empId][$itemId] ?? 0);
  1596. $diff = (int)$target - $got;
  1597. if ($diff === 0) {
  1598. continue;
  1599. }
  1600. if ($diff > 0) {
  1601. $left = $this->safeBumpMinutesOntoEmpItem($previewList, $empId, $itemId, $diff, null);
  1602. // 仍缺:按天找空档插入
  1603. if ($left > 0) {
  1604. $dates = [];
  1605. foreach ($previewList as $row) {
  1606. if ((int)$row['employee_id'] === (int)$empId) {
  1607. $dates[$row['order_time']] = $row['order_timestamp'] ?? strtotime($row['order_time']);
  1608. }
  1609. }
  1610. foreach ($dates as $dateStr => $ts) {
  1611. if ($left <= 0) {
  1612. break;
  1613. }
  1614. $itemTitle = '';
  1615. foreach ($previewList as $row) {
  1616. if ((int)$row['employee_id'] === (int)$empId && (int)$row['item_id'] === (int)$itemId) {
  1617. $itemTitle = $row['item_title'];
  1618. break;
  1619. }
  1620. }
  1621. $empTitle = '';
  1622. foreach ($previewList as $row) {
  1623. if ((int)$row['employee_id'] === (int)$empId) {
  1624. $empTitle = $row['employee_title'];
  1625. break;
  1626. }
  1627. }
  1628. $before = $left;
  1629. if ($this->insertRemainderRowInFreeGap(
  1630. $previewList,
  1631. 'reconcile_' . $empId . '_' . $itemId,
  1632. (int)$ts,
  1633. $itemId,
  1634. $itemTitle ?: '未知项目',
  1635. $empId,
  1636. $empTitle ?: '未知人员',
  1637. $left
  1638. )) {
  1639. $left = 0;
  1640. }
  1641. // 插不进整天 needMin,尝试拆小:逐分钟插太慢;改为能插多少插多少
  1642. if ($left > 0) {
  1643. for ($n = $left; $n >= 1; $n--) {
  1644. if ($this->insertRemainderRowInFreeGap(
  1645. $previewList,
  1646. 'reconcile_' . $empId . '_' . $itemId,
  1647. (int)$ts,
  1648. $itemId,
  1649. $itemTitle ?: '未知项目',
  1650. $empId,
  1651. $empTitle ?: '未知人员',
  1652. $n
  1653. )) {
  1654. $left -= $n;
  1655. break;
  1656. }
  1657. }
  1658. }
  1659. unset($before);
  1660. }
  1661. }
  1662. } elseif ($diff < 0) {
  1663. // 多了:从有空可缩的明细尾部扣(不制造 start>=end)
  1664. $needCut = -$diff;
  1665. for ($i = count($previewList) - 1; $i >= 0 && $needCut > 0; $i--) {
  1666. $row = $previewList[$i];
  1667. if ((int)$row['employee_id'] !== (int)$empId) {
  1668. continue;
  1669. }
  1670. if ((int)$row['item_id'] !== (int)$itemId) {
  1671. continue;
  1672. }
  1673. $len = (int)$row['total_work_min'];
  1674. if ($len <= 1) {
  1675. continue;
  1676. }
  1677. $cut = min($needCut, $len - 1);
  1678. $this->bumpPreviewRowMinutes($previewList, $i, -$cut);
  1679. $needCut -= $cut;
  1680. }
  1681. }
  1682. }
  1683. }
  1684. return $previewList;
  1685. }
  1686. /**
  1687. * 按各项目剩余月目标,把当天额度拆开(最大余数法)
  1688. * - 非最后一天:尽量按 5 分钟块分配
  1689. * - 当天 1~4 分钟零头:补给「仍有剩余目标」的项目自身
  1690. *
  1691. * @param int $dayBudget 当天可分配总分钟
  1692. * @param array $projRem [item_id => 剩余目标分钟]
  1693. * @param int $step
  1694. * @param bool $forceExact 是否强制精确分完(最后一天)
  1695. * @return array [item_id => 当天分配分钟]
  1696. */
  1697. private function splitMinutesByRemaining($dayBudget, array $projRem, $step = 5, $forceExact = false)
  1698. {
  1699. $active = [];
  1700. foreach ($projRem as $itemId => $rem) {
  1701. if ($rem > 0) {
  1702. $active[(int)$itemId] = (int)$rem;
  1703. }
  1704. }
  1705. if (empty($active) || $dayBudget <= 0) {
  1706. return [];
  1707. }
  1708. $totalRem = array_sum($active);
  1709. $dayBudget = min($dayBudget, $totalRem);
  1710. $result = array_fill_keys(array_keys($active), 0);
  1711. if ($forceExact || $dayBudget < $step) {
  1712. $order = [];
  1713. $used = 0;
  1714. foreach ($active as $itemId => $rem) {
  1715. $ideal = $dayBudget * $rem / $totalRem;
  1716. $base = (int)floor($ideal);
  1717. $base = min($base, $rem);
  1718. $result[$itemId] = $base;
  1719. $used += $base;
  1720. $order[] = [
  1721. 'item_id' => $itemId,
  1722. 'frac' => $ideal - $base,
  1723. 'rem' => $rem - $base,
  1724. ];
  1725. }
  1726. usort($order, function ($a, $b) {
  1727. if ($a['frac'] == $b['frac']) {
  1728. return $b['rem'] <=> $a['rem'];
  1729. }
  1730. return $b['frac'] <=> $a['frac'];
  1731. });
  1732. $left = $dayBudget - $used;
  1733. foreach ($order as $row) {
  1734. if ($left <= 0) break;
  1735. if ($row['rem'] <= 0) continue;
  1736. $give = min($left, $row['rem']);
  1737. $result[$row['item_id']] += $give;
  1738. $left -= $give;
  1739. }
  1740. return array_filter($result);
  1741. }
  1742. $blockBudget = (int)floor($dayBudget / $step) * $step;
  1743. if ($blockBudget <= 0) {
  1744. return $this->splitMinutesByRemaining($dayBudget, $active, $step, true);
  1745. }
  1746. $blocks = (int)($blockBudget / $step);
  1747. $order = [];
  1748. $usedBlocks = 0;
  1749. foreach ($active as $itemId => $rem) {
  1750. $maxBlocks = (int)floor($rem / $step);
  1751. $idealBlocks = $blocks * $rem / $totalRem;
  1752. $base = (int)floor($idealBlocks);
  1753. $base = min($base, $maxBlocks);
  1754. $result[$itemId] = $base * $step;
  1755. $usedBlocks += $base;
  1756. $order[] = [
  1757. 'item_id' => $itemId,
  1758. 'frac' => $idealBlocks - $base,
  1759. 'rem_blocks' => $maxBlocks - $base,
  1760. 'rem' => $rem,
  1761. ];
  1762. }
  1763. usort($order, function ($a, $b) {
  1764. if ($a['frac'] == $b['frac']) {
  1765. return $b['rem_blocks'] <=> $a['rem_blocks'];
  1766. }
  1767. return $b['frac'] <=> $a['frac'];
  1768. });
  1769. $leftBlocks = $blocks - $usedBlocks;
  1770. foreach ($order as $row) {
  1771. if ($leftBlocks <= 0) break;
  1772. if ($row['rem_blocks'] <= 0) continue;
  1773. $result[$row['item_id']] += $step;
  1774. $leftBlocks--;
  1775. }
  1776. // 当天 1~4 分钟零头:按剩余目标最大余数补给对应项目(该人该项目自己的零头)
  1777. $odd = $dayBudget - $blockBudget;
  1778. if ($odd > 0) {
  1779. $oddParts = $this->splitMinutesByRemaining($odd, $active, $step, true);
  1780. foreach ($oddParts as $itemId => $mins) {
  1781. $already = $result[$itemId] ?? 0;
  1782. $cap = $active[$itemId] - $already;
  1783. if ($cap <= 0) continue;
  1784. $result[$itemId] = $already + min($mins, $cap);
  1785. }
  1786. }
  1787. return array_filter($result);
  1788. }
  1789. public function dailyPwOrderSave($data, $user)
  1790. {
  1791. $list = $data['list'] ?? [];
  1792. if (empty($list)) return [false, '没有可保存的数据'];
  1793. $topDepartId = $user['top_depart_id'];
  1794. $month = $data['month'];
  1795. $monthStart = $this->changeDateToDate($month);
  1796. //归档
  1797. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  1798. if(! $status) return [false, $msg];
  1799. $now = time();
  1800. // 1. 预加载员工名称映射 (使用 title 字段)
  1801. $empIds = collect($list)->pluck('employee_id')->unique()->toArray();
  1802. $empMap = DB::table('employee')->whereIn('id', $empIds)->pluck('title', 'id')->toArray();
  1803. // --- 2. 重新分组并记录行号 ---
  1804. $groupedByOrder = [];
  1805. foreach ($list as $index => $item) {
  1806. $item['_line'] = $index + 1; // 记录原始行号(从1开始)
  1807. // 以日期字符串和项目ID作为分组 Key
  1808. $groupKey = $item['order_time'] . '_' . $item['item_id'];
  1809. $groupedByOrder[$groupKey][] = $item;
  1810. }
  1811. // 冲突校验器容器:记录 [员工ID][日期字符串] 下已占用的时间段
  1812. $empTimeline = [];
  1813. DB::beginTransaction();
  1814. try {
  1815. // A. 清理该月份旧数据
  1816. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  1817. $oldOrderIds = DB::table('daily_pw_order')
  1818. ->where('top_depart_id', $topDepartId)
  1819. ->whereBetween('order_time', [$monthStart, $monthEnd])
  1820. ->where('del_time', 0)
  1821. ->pluck('id');
  1822. if ($oldOrderIds->isNotEmpty()) {
  1823. DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  1824. DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  1825. }
  1826. // B. 遍历重组后的分组写入
  1827. foreach ($groupedByOrder as $details) {
  1828. $first = $details[0];
  1829. // 【修正】统一将前端日期字符串转为时间戳入库
  1830. $orderTimestamp = strtotime($first['order_time']);
  1831. $itemId = $first['item_id'];
  1832. // 写入主表
  1833. $mainId = DB::table('daily_pw_order')->insertGetId([
  1834. 'code' => '',
  1835. 'item_id' => $itemId,
  1836. 'order_time' => $orderTimestamp,
  1837. 'top_depart_id' => $topDepartId,
  1838. 'is_create' => 1,
  1839. 'crt_id' => $user['id'],
  1840. 'crt_time' => $now,
  1841. ]);
  1842. $insertDetails = [];
  1843. foreach ($details as $d) {
  1844. $rowNum = $d['_line'];
  1845. $empId = $d['employee_id'];
  1846. $empName = $empMap[$empId] ?? "人员(ID:{$empId})";
  1847. // --- 新增:月份一致性校验 ---
  1848. // 校验这行数据的日期是否属于当前保存的月份
  1849. if (date("Y-m", strtotime($d['order_time'])) !== $month) {
  1850. return [false, "第 {$rowNum} 行:人员[{$empName}]的日期[{$d['order_time']}]不属于保存月份[{$month}]"];
  1851. }
  1852. // 【修正】强制由后端计算分钟数
  1853. $s = (int)$d['start_hour'] * 60 + (int)$d['start_min'];
  1854. $e = (int)$d['end_hour'] * 60 + (int)$d['end_min'];
  1855. $calcTotalMin = $e - $s;
  1856. // 校验1:逻辑合法性
  1857. if ($calcTotalMin <= 0) {
  1858. return [false, "第 {$rowNum} 行:人员[{$empName}]在[{$d['order_time']}]的时间段无效:结束时间必须晚于开始时间"];
  1859. }
  1860. // 校验2:跨单据时间重叠校验
  1861. $dateStr = $d['order_time'];
  1862. if (isset($empTimeline[$empId][$dateStr])) {
  1863. foreach ($empTimeline[$empId][$dateStr] as $exist) {
  1864. if ($s < $exist['e'] && $e > $exist['s']) {
  1865. return [false, "第 {$rowNum} 行:人员[{$empName}]在[{$dateStr}]存在时间冲突({$d['start_time']}-{$d['end_time']}),请检查!"];
  1866. }
  1867. }
  1868. }
  1869. $empTimeline[$empId][$dateStr][] = ['s' => $s, 'e' => $e];
  1870. $insertDetails[] = [
  1871. 'main_id' => $mainId,
  1872. 'employee_id' => $empId,
  1873. 'top_depart_id' => $topDepartId,
  1874. 'start_time_hour' => $d['start_hour'],
  1875. 'start_time_min' => $d['start_min'],
  1876. 'end_time_hour' => $d['end_hour'],
  1877. 'end_time_min' => $d['end_min'],
  1878. 'total_work_min' => $calcTotalMin,
  1879. 'crt_time' => $now,
  1880. 'item_id' => $itemId,
  1881. 'order_time' => $orderTimestamp,
  1882. 'crt_id' => $user['id'],
  1883. ];
  1884. }
  1885. // 批量写入明细
  1886. DB::table('daily_pw_order_details')->insert($insertDetails);
  1887. // C. 回填单号
  1888. $code = $this->generateBillNo([
  1889. 'top_depart_id' => $topDepartId,
  1890. 'type' => DailyPwOrder::Order_type,
  1891. 'period' => date("Ym", $orderTimestamp)
  1892. ]);
  1893. DB::table('daily_pw_order')->where('id', $mainId)->update(['code' => $code]);
  1894. }
  1895. DB::commit();
  1896. return [true, ''];
  1897. } catch (\Exception $e) {
  1898. DB::rollBack();
  1899. return [false, "保存失败:" . $e->getMessage()];
  1900. }
  1901. }
  1902. }