DeviceWorkService.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. <?php
  2. namespace App\Service;
  3. use App\Jobs\ProcessDataJob;
  4. use App\Model\CalendarDetails;
  5. use App\Model\DailyDwOrder;
  6. use App\Model\DailyDwOrderDetails;
  7. use App\Model\DailyPwOrder;
  8. use App\Model\Device;
  9. use App\Model\Employee;
  10. use App\Model\Item;
  11. use App\Model\MonthlyDwOrder;
  12. use App\Model\MonthlyDwOrderDetails;
  13. use App\Model\RuleSetDetails;
  14. use Illuminate\Support\Facades\DB;
  15. class DeviceWorkService extends Service
  16. {
  17. //设备月工时单--------------------------------------------
  18. public function monthlyDwOrderEdit($data,$user){
  19. list($status,$msg) = $this->monthlyDwOrderRule($data, $user, false);
  20. if(!$status) return [$status,$msg];
  21. try {
  22. DB::beginTransaction();
  23. $model = MonthlyDwOrder::where('id',$data['id'])->first();
  24. // $model->month = $data['month'] ?? 0;
  25. // $model->save();
  26. $time = time();
  27. MonthlyDwOrderDetails::where('del_time',0)
  28. ->where('main_id', $model->id)
  29. ->update(['del_time' => $time]);
  30. $this->saveDetail($model->id, $time, $data);
  31. DB::commit();
  32. }catch (\Exception $exception){
  33. DB::rollBack();
  34. return [false,$exception->getMessage()];
  35. }
  36. return [true, ''];
  37. }
  38. public function monthlyDwOrderAdd($data,$user){
  39. list($status,$msg) = $this->monthlyDwOrderRule($data, $user);
  40. if(!$status) return [$status,$msg];
  41. try {
  42. DB::beginTransaction();
  43. $model = new MonthlyDwOrder();
  44. $model->code = $this->generateBillNo([
  45. 'top_depart_id' => $user['top_depart_id'],
  46. 'type' => MonthlyDwOrder::Order_type,
  47. 'period' => date("Ym", $data['month'])
  48. ]);
  49. $model->month = $data['month'] ?? 0;
  50. $model->crt_id = $user['id'];
  51. $model->top_depart_id = $data['top_depart_id'];
  52. $model->save();
  53. $this->saveDetail($model->id, time(), $data);
  54. DB::commit();
  55. }catch (\Exception $exception){
  56. DB::rollBack();
  57. return [false,$exception->getMessage()];
  58. }
  59. return [true, ''];
  60. }
  61. private function saveDetail($id, $time, $data){
  62. if(! empty($data['details'])){
  63. $unit = [];
  64. foreach ($data['details'] as $value){
  65. $unit[] = [
  66. 'main_id' => $id,
  67. 'device_id' => $value['device_id'],
  68. 'total_days' => $value['total_days'],
  69. 'rd_total_days' => $value['rd_total_days'],
  70. 'total_hours' => $value['total_hours'],
  71. 'rd_total_hours' => $value['rd_total_hours'],
  72. 'crt_time' => $time,
  73. 'top_depart_id' => $value['top_depart_id'],
  74. ];
  75. }
  76. if(! empty($unit)) MonthlyDwOrderDetails::insert($unit);
  77. }
  78. }
  79. private function getDetail($id){
  80. $data = MonthlyDwOrderDetails::where('del_time',0)
  81. ->where('main_id', $id)
  82. ->select('device_id', 'total_days', 'rd_total_days', 'total_hours', 'rd_total_hours')
  83. ->get()->toArray();
  84. $id = array_column($data,'device_id');
  85. $map = Device::whereIn('id', $id)->select('title','id','code')->get()->toArray();
  86. $map = array_column($map,null,'id');
  87. foreach ($data as $key => $value){
  88. $tmp = $map[$value['device_id']] ?? [];
  89. $merge = [];
  90. $merge['device_title'] = $tmp['title'];
  91. $merge['device_code'] = $tmp['code'];
  92. $data[$key] = array_merge($value, $merge);
  93. }
  94. $detail = [
  95. 'details' => $data,
  96. ];
  97. foreach ($detail as $key => $value) {
  98. if (empty($value)) {
  99. $detail[$key] = (object)[]; // 转成 stdClass 对象
  100. }
  101. }
  102. return $detail;
  103. }
  104. public function monthlyDwOrderDel($data){
  105. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  106. try {
  107. DB::beginTransaction();
  108. $time = time();
  109. MonthlyDwOrder::where('del_time',0)
  110. ->whereIn('id',$data['id'])
  111. ->update(['del_time' => $time]);
  112. MonthlyDwOrderDetails::where('del_time',0)
  113. ->whereIn('main_id', $data['id'])
  114. ->update(['del_time' => $time]);
  115. DB::commit();
  116. }catch (\Exception $exception){
  117. DB::rollBack();
  118. return [false,$exception->getMessage()];
  119. }
  120. return [true, ''];
  121. }
  122. public function monthlyDwOrderDetail($data, $user){
  123. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  124. $customer = MonthlyDwOrder::where('del_time',0)
  125. ->where('id',$data['id'])
  126. ->first();
  127. if(empty($customer)) return [false,'设备月度工时单不存在或已被删除'];
  128. $customer = $customer->toArray();
  129. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  130. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  131. $customer['month'] = $customer['month'] ? date("Y-m",$customer['month']): '';
  132. $details = $this->getDetail($data['id']);
  133. $customer = array_merge($customer, $details);
  134. return [true, $customer];
  135. }
  136. public function monthlyDwOrderCommon($data,$user, $field = []){
  137. if(empty($field)) $field = MonthlyDwOrder::$field;
  138. $model = MonthlyDwOrder::Clear($user,$data);
  139. $model = $model->where('del_time',0)
  140. ->select($field)
  141. ->orderby('id', 'desc');
  142. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  143. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  144. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  145. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  146. $model->where('crt_time','>=',$return[0]);
  147. $model->where('crt_time','<=',$return[1]);
  148. }
  149. return $model;
  150. }
  151. public function monthlyDwOrderList($data,$user){
  152. $model = $this->monthlyDwOrderCommon($data, $user);
  153. $list = $this->limit($model,'',$data);
  154. $list = $this->fillData($list);
  155. return [true, $list];
  156. }
  157. public function monthlyDwOrderRule(&$data, $user, $is_add = true)
  158. {
  159. if (empty($data['month'])) return [false, '月份不能为空'];
  160. $data['month'] = $this->changeDateToDate($data['month']);
  161. $data['top_depart_id'] = $user['top_depart_id'];
  162. if (empty($data['details'])) return [false, '设备月度工时单明细不能为空'];
  163. // --- 1. 批量获取设备档案信息 (用于展示 [编码]名称) ---
  164. $deviceIds = array_column($data['details'], 'device_id');
  165. $deviceMap = DB::table('device')
  166. ->whereIn('id', $deviceIds)
  167. ->where('top_depart_id', $data['top_depart_id'])
  168. ->get(['id', 'code', 'title'])
  169. ->mapWithKeys(fn($item) => [$item->id => "[{$item->code}]{$item->title}"])
  170. ->toArray();
  171. // --- 2. 获取设备考勤基准 ---
  172. list($status, $deviceStats) = (new DeviceService())->getDevicesMonthStats($deviceIds, $data['month'], $user);
  173. if (!$status) return [false, $deviceStats];
  174. // 字段中文映射,用于报错
  175. $fieldNames = [
  176. 'total_days' => '出勤总天数',
  177. 'rd_total_days' => '研发出勤天数',
  178. 'total_hours' => '出勤总工时',
  179. 'rd_total_hours'=> '研发总工时'
  180. ];
  181. // --- 3. 循环校验明细 ---
  182. foreach ($data['details'] as $key => $value) {
  183. $line = $key + 1; // 行号
  184. if (empty($value['device_id'])) return [false, "第{$line}行:设备ID不能为空"];
  185. $deviceId = $value['device_id'];
  186. $deviceDisplayName = $deviceMap[$deviceId] ?? "";
  187. if(empty($deviceDisplayName)) return [false, "第{$line}行:设备不存在或已被删除"];
  188. // 基础数字格式检查
  189. foreach ($fieldNames as $field => $cnName) {
  190. $precision = 2;
  191. $res = $this->checkNumber($value[$field], $precision, 'non-negative');
  192. if (!$res['valid']) {
  193. return [false, "第{$line}行:设备{$deviceDisplayName}的{$cnName}填写不规范({$res['error']})"];
  194. }
  195. }
  196. // --- 4. 业务逻辑校验 ---
  197. $sysData = $deviceStats[$deviceId] ?? null;
  198. if ($sysData) {
  199. // A. 内部逻辑:研发不能大于总额
  200. if ($value['rd_total_days'] > $value['total_days']) {
  201. return [false, "第{$line}行:设备{$deviceDisplayName}的研发出勤天数不能大于出勤总天数"];
  202. }
  203. if ($value['rd_total_hours'] > $value['total_hours']) {
  204. return [false, "第{$line}行:设备{$deviceDisplayName}的研发总工时不能大于出勤总工时"];
  205. }
  206. // B. 外部逻辑:不能超过系统根据日历算出的上限
  207. if ($value['total_days'] != $sysData['attendance_days']) {
  208. return [false, "第{$line}行:设备{$deviceDisplayName}的出勤总天数({$value['total_days']})不等于当月标准天数({$sysData['attendance_days']})"];
  209. }
  210. if ($value['total_hours'] != $sysData['final_work_hour']) {
  211. return [false, "第{$line}行:设备{$deviceDisplayName}的出勤总工时({$value['total_hours']})不等于当月标准工时({$sysData['final_work_hour']})"];
  212. }
  213. }
  214. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  215. }
  216. // --- 5. 查重与唯一性校验 ---
  217. list($status, $msg) = $this->checkArrayRepeat($data['details'], 'device_id', '设备');
  218. if (!$status) return [false, $msg];
  219. $query = MonthlyDwOrder::where('top_depart_id', $data['top_depart_id'])
  220. ->where('month', $data['month'])
  221. ->where('del_time', 0);
  222. if (!$is_add) {
  223. if (empty($data['id'])) return [false, 'ID不能为空'];
  224. $query->where('id', '<>', $data['id']);
  225. }
  226. if ($query->exists()) {
  227. return [false, date("Y-m", $data['month']) . '已存在设备月度研发工时单'];
  228. }
  229. return [true, ''];
  230. }
  231. public function monthlyDwOrderRule1(&$data, $user, $is_add = true){
  232. if(empty($data['month'])) return [false, '月份不能为空'];
  233. $data['month'] = $this->changeDateToDate($data['month']);
  234. $data['top_depart_id'] = $user['top_depart_id'];
  235. if(empty($data['details'])) return [false, '设备月度工时单明细不能为空'];
  236. foreach ($data['details'] as $key => $value){
  237. if(empty($value['device_id'])) return [false, '设备不能为空'];
  238. $res = $this->checkNumber($value['total_days'],0,'non-negative');
  239. if(! $res['valid']) return [false,'出勤总天数:' . $res['error']];
  240. $res = $this->checkNumber($value['rd_total_days'],0,'non-negative');
  241. if(! $res['valid']) return [false,'研发出勤总天数:' . $res['error']];
  242. $res = $this->checkNumber($value['total_hours'],2,'non-negative');
  243. if(! $res['valid']) return [false,'出勤总工时:' . $res['error']];
  244. $res = $this->checkNumber($value['rd_total_hours'],2,'non-negative');
  245. if(! $res['valid']) return [false,'研发总工时:' . $res['error']];
  246. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  247. }
  248. list($status, $msg) = $this->checkArrayRepeat($data['details'],'device_id','设备');
  249. if(! $status) return [false, $msg];
  250. if($is_add){
  251. $bool = MonthlyDwOrder::where('top_depart_id', $data['top_depart_id'])
  252. ->where('month', $data['month'])
  253. ->where('del_time',0)
  254. ->exists();
  255. }else{
  256. if(empty($data['id'])) return [false,'ID不能为空'];
  257. $bool = MonthlyDwOrder::where('top_depart_id', $data['top_depart_id'])
  258. ->where('month', $data['month'])
  259. ->where('id','<>',$data['id'])
  260. ->where('del_time',0)
  261. ->exists();
  262. }
  263. if($bool) return [false, date("Y-m", $data['month']) . '已存在设备月度研发工时单'];
  264. return [true, ''];
  265. }
  266. public function fillData($data){
  267. if(empty($data['data'])) return $data;
  268. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  269. foreach ($data['data'] as $key => $value){
  270. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  271. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  272. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  273. }
  274. return $data;
  275. }
  276. public function fillDataForExport($data, $column, &$return)
  277. {
  278. if(empty($data)) return;
  279. $mainIds = array_column($data, 'id');
  280. // 获取详情映射 [main_id => [details...]]
  281. $detailsMap = $this->getDetailsMap($mainIds);
  282. // 默认空行模板
  283. $defaultRow = array_fill_keys($column, '');
  284. foreach ($data as $main) {
  285. $mainId = $main['id'];
  286. $details = $detailsMap[$mainId] ?? [];
  287. // 提取主表信息
  288. $mainInfo = [
  289. 'code' => $main['code'],
  290. 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
  291. ];
  292. if (empty($details)) {
  293. // 如果没有详情,至少导出一行主表信息(可选)
  294. $return[] = array_merge($defaultRow, $mainInfo);
  295. } else {
  296. // 核心:遍历详情,每一行详情都合并主表信息
  297. foreach ($details as $sub) {
  298. // 合并主表字段 + 详情字段
  299. $fullRow = array_merge($mainInfo, $sub);
  300. // 过滤掉不在导出列里的字段,并补充缺失列
  301. $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
  302. }
  303. }
  304. }
  305. }
  306. public function getDetailsMap($main_ids)
  307. {
  308. // 获取详情
  309. $details = MonthlyDwOrderDetails::where('del_time', 0)
  310. ->whereIn('main_id', $main_ids)
  311. ->get();
  312. // 获取设备信息
  313. $empIds = $details->pluck('device_id')->unique();
  314. $empMap = Device::whereIn('id', $empIds)->get()->keyBy('id');
  315. $res = [];
  316. foreach ($details as $item) {
  317. $tmpEmp = $empMap[$item->device_id] ?? null;
  318. // 组装每一行详情需要展示的字段
  319. $res[$item->main_id][] = [
  320. 'device_code' => $tmpEmp ? $tmpEmp->code : '',
  321. 'device_title' => $tmpEmp ? $tmpEmp->title : '',
  322. 'total_days' => $item->total_days,
  323. 'rd_total_days' => $item->rd_total_days,
  324. 'total_hours' => $item->total_hours,
  325. 'rd_total_hours' => $item->rd_total_hours,
  326. ];
  327. }
  328. return $res; // 返回 [main_id => [detail_row, detail_row]]
  329. }
  330. //设备日工时单----------------------------------------------
  331. public function dailyDwOrderEdit($data,$user){
  332. list($status,$msg) = $this->dailyDwOrderRule($data, $user, false);
  333. if(!$status) return [$status,$msg];
  334. try {
  335. DB::beginTransaction();
  336. $model = DailyDwOrder::where('id',$data['id'])->first();
  337. $model->item_id = $data['item_id'] ?? 0;
  338. $model->save();
  339. $time = time();
  340. DailyDwOrderDetails::where('del_time',0)
  341. ->where('main_id', $model->id)
  342. ->update(['del_time' => $time]);
  343. $this->saveDetailDaily($model->id, $time, $data);
  344. DB::commit();
  345. }catch (\Exception $exception){
  346. DB::rollBack();
  347. return [false,$exception->getMessage()];
  348. }
  349. return [true, ''];
  350. }
  351. public function dailyDwOrderAdd($data,$user){
  352. list($status,$msg) = $this->dailyDwOrderRule($data, $user);
  353. if(!$status) return [$status,$msg];
  354. try {
  355. DB::beginTransaction();
  356. $model = new DailyDwOrder();
  357. $model->code = $this->generateBillNo([
  358. 'top_depart_id' => $user['top_depart_id'],
  359. 'type' => DailyDwOrder::Order_type,
  360. 'period' => date("Ym", $data['order_time'])
  361. ]);
  362. $model->order_time = $data['order_time'] ?? 0;
  363. $model->item_id = $data['item_id'] ?? 0;
  364. $model->crt_id = $user['id'];
  365. $model->top_depart_id = $data['top_depart_id'];
  366. $model->save();
  367. $this->saveDetailDaily($model->id, time(), $data);
  368. DB::commit();
  369. }catch (\Exception $exception){
  370. DB::rollBack();
  371. return [false,$exception->getMessage()];
  372. }
  373. return [true, ''];
  374. }
  375. private function saveDetailDaily($id, $time, $data){
  376. if(! empty($data['details'])){
  377. $unit = [];
  378. foreach ($data['details'] as $value){
  379. $unit[] = [
  380. 'main_id' => $id,
  381. 'device_id' => $value['device_id'],
  382. 'start_time_hour' => $value['start_time_hour'],
  383. 'start_time_min' => $value['start_time_min'],
  384. 'end_time_hour' => $value['end_time_hour'],
  385. 'end_time_min' => $value['end_time_min'],
  386. 'total_work_min' => $value['total_work_min'],
  387. 'crt_time' => $time,
  388. 'top_depart_id' => $value['top_depart_id'],
  389. 'order_time' => $data['order_time'] ?? 0,
  390. 'item_id' => $data['item_id']
  391. ];
  392. }
  393. if(! empty($unit)) DailyDwOrderDetails::insert($unit);
  394. }
  395. }
  396. private function getDetailDaily($id){
  397. $data = DailyDwOrderDetails::where('del_time',0)
  398. ->where('main_id', $id)
  399. ->select('device_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_work_min')
  400. ->get()->toArray();
  401. $id = array_column($data,'device_id');
  402. $map = Device::whereIn('id',$id)
  403. ->select('title','id','code')
  404. ->get()
  405. ->keyBy('id')
  406. ->toArray();
  407. foreach ($data as $key => $value){
  408. $tmp = $map[$value['device_id']] ?? [];
  409. $merge = [];
  410. $merge['device_title'] = $tmp['title'];
  411. $merge['device_code'] = $tmp['code'];
  412. $data[$key] = array_merge($value, $merge);
  413. }
  414. $detail = [
  415. 'details' => $data,
  416. ];
  417. foreach ($detail as $key => $value) {
  418. if (empty($value)) {
  419. $detail[$key] = (object)[]; // 转成 stdClass 对象
  420. }
  421. }
  422. return $detail;
  423. }
  424. public function dailyDwOrderDel($data){
  425. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  426. try {
  427. DB::beginTransaction();
  428. $time = time();
  429. DailyDwOrder::where('del_time',0)
  430. ->whereIn('id',$data['id'])
  431. ->update(['del_time' => $time]);
  432. DailyDwOrderDetails::where('del_time',0)
  433. ->whereIn('main_id', $data['id'])
  434. ->update(['del_time' => $time]);
  435. DB::commit();
  436. }catch (\Exception $exception){
  437. DB::rollBack();
  438. return [false,$exception->getMessage()];
  439. }
  440. return [true, ''];
  441. }
  442. public function dailyDwOrderDetail($data, $user){
  443. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  444. $customer = DailyDwOrder::where('del_time',0)
  445. ->where('id',$data['id'])
  446. ->first();
  447. if(empty($customer)) return [false,'设备日工时单不存在或已被删除'];
  448. $customer = $customer->toArray();
  449. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  450. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  451. $item = Item::where('id', $customer['item_id'])->first();
  452. $customer['item_title'] = $item->title;
  453. $customer['item_code'] = $item->code;
  454. $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
  455. $details = $this->getDetailDaily($data['id']);
  456. $customer = array_merge($customer, $details);
  457. return [true, $customer];
  458. }
  459. public function dailyDwOrderCommon($data,$user, $field = []){
  460. if(empty($field)) $field = DailyDwOrder::$field;
  461. $model = DailyDwOrder::Clear($user,$data);
  462. $model = $model->where('del_time',0)
  463. ->select($field)
  464. ->orderby('id', 'desc');
  465. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  466. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  467. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  468. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  469. $model->where('crt_time','>=',$return[0]);
  470. $model->where('crt_time','<=',$return[1]);
  471. }
  472. return $model;
  473. }
  474. public function dailyDwOrderList($data,$user){
  475. $model = $this->dailyDwOrderCommon($data, $user);
  476. $list = $this->limit($model,'',$data);
  477. $list = $this->fillDataDaily($list);
  478. return [true, $list];
  479. }
  480. public function dailyDwOrderRule(&$data, $user, $is_add = true){
  481. if(empty($data['order_time'])) return [false, '单据日期不能为空'];
  482. $data['order_time'] = $this->changeDateToDate($data['order_time']);
  483. $orderTime = $data['order_time'];
  484. $itemId = $data['item_id'] ?? 0;
  485. if(empty($itemId)) return [false, '项目不能为空'];
  486. $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
  487. if(!$bool) return [false, '项目不存在或已被删除'];
  488. $data['top_depart_id'] = $user['top_depart_id'];
  489. if(empty($data['details'])) return [false, '设备日工时单明细不能为空'];
  490. // --- 1. 批量预获取人员信息,用于报错提示 ---
  491. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'device_id')));
  492. $empDisplayMap = Device::whereIn('id', $allEmpIds)
  493. ->get(['id', 'code', 'title'])
  494. ->mapWithKeys(function($item){
  495. return [$item->id => "[{$item->code}]{$item->title}"];
  496. })->toArray();
  497. // 2. 本次提交内部重叠记录
  498. $internalOverlap = [];
  499. foreach ($data['details'] as $key => $value){
  500. $empId = $value['device_id'] ?? 0;
  501. if(empty($empId)) return [false, '设备不能为空'];
  502. $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
  503. // 校验数字有效性
  504. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  505. if(!$res['valid']) return [false, "设备{$empName}开始点:" . $res['error']];
  506. if($value['start_time_hour'] > 23) return [false, false, "设备{$empName}开始点不合法"];
  507. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  508. if(!$res['valid']) return [false, "设备{$empName}开始分:" . $res['error']];
  509. if($value['start_time_min'] > 60) return [false, false, "设备{$empName}开始点不合法"];
  510. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  511. if(!$res['valid']) return [false, "设备{$empName}结束点:" . $res['error']];
  512. if($value['end_time_hour'] > 24) return [false, false, "设备{$empName}结束点不合法"];
  513. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  514. if(!$res['valid']) return [false, "设备{$empName}结束分:" . $res['error']];
  515. if($value['end_time_min'] > 60) return [false, false, "设备{$empName}结束分不合法"];
  516. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  517. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  518. if ($currentStart >= $currentEnd) {
  519. return [false, "设备{$empName}:开始时间必须早于结束时间"];
  520. }
  521. // --- 3. 内部重叠校验(防止一次提交多行重复) ---
  522. if (isset($internalOverlap[$empId])) {
  523. foreach ($internalOverlap[$empId] as $period) {
  524. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  525. return [false, "设备{$empName}在本次提交的多行明细中时间段重叠"];
  526. }
  527. }
  528. }
  529. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  530. $query = DB::table('daily_dw_order_details as d')
  531. ->join('daily_dw_order as m', 'd.main_id', '=', 'm.id')
  532. ->where('m.top_depart_id', $data['top_depart_id'])
  533. ->where('m.order_time', $orderTime)
  534. ->where('m.item_id', $itemId)
  535. ->where('d.device_id', $empId)
  536. ->where('m.del_time', 0)
  537. ->where('d.del_time', 0);
  538. if (!$is_add && !empty($data['id'])) {
  539. $query->where('m.id', '<>', $data['id']);
  540. }
  541. $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
  542. foreach ($existingPeriods as $p) {
  543. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  544. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  545. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  546. return [false, "设备{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
  547. }
  548. }
  549. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  550. }
  551. if(!$is_add){
  552. if(empty($data['id'])) return [false,'ID不能为空'];
  553. $bool = DailyDwOrder::where('top_depart_id', $data['top_depart_id'])
  554. ->where('id',$data['id'])
  555. ->where('del_time',0)
  556. ->exists();
  557. if(!$bool) return [false, '设备日工时单不存在或已被删除'];
  558. }
  559. return [true, ''];
  560. }
  561. public function fillDataDaily($data){
  562. if(empty($data['data'])) return $data;
  563. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  564. $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_id')));
  565. foreach ($data['data'] as $key => $value){
  566. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  567. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  568. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  569. $item_tmp = $item[$value['item_id']] ?? [];
  570. $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
  571. $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
  572. }
  573. return $data;
  574. }
  575. public function fillDataForExportDaily($data, $column, &$return)
  576. {
  577. if (empty($data)) return;
  578. $mainIds = array_column($data, 'id');
  579. // 1. 获取详情及所有关联档案(项目、设备)的映射
  580. $detailsMap = $this->getDwDailyDetailsMap($mainIds, $data);
  581. foreach ($data as $main) {
  582. $mainId = $main['id'];
  583. $details = $detailsMap[$mainId] ?? [];
  584. // 2. 提取并格式化主表共有信息
  585. $mainInfo = [
  586. 'code' => $main['code'],
  587. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  588. ];
  589. if (empty($details)) {
  590. // 无明细时只导出一行主表信息
  591. $tempRow = [];
  592. foreach ($column as $col) {
  593. $tempRow[] = $mainInfo[$col] ?? '';
  594. }
  595. $return[] = $tempRow;
  596. } else {
  597. // 3. 平铺:将设备明细信息、项目信息与主表信息合并
  598. foreach ($details as $sub) {
  599. $fullRowData = array_merge($mainInfo, $sub);
  600. $tempRow = [];
  601. foreach ($column as $col) {
  602. $tempRow[] = $fullRowData[$col] ?? '';
  603. }
  604. $return[] = $tempRow;
  605. }
  606. }
  607. }
  608. }
  609. public function getDwDailyDetailsMap($mainIds, $mainData)
  610. {
  611. // 1. 获取设备工时子表记录
  612. $details = DB::table('daily_dw_order_details')
  613. ->where('del_time', 0)
  614. ->whereIn('main_id', $mainIds)
  615. ->get();
  616. // 2. 提取关联 ID(设备 ID 和 项目 ID)
  617. $deviceIds = $details->pluck('device_id')->unique();
  618. $itemIds = array_unique(array_column($mainData, 'item_id'));
  619. // 3. 批量获取设备档案和项目档案
  620. $deviceMap = DB::table('device')
  621. ->whereIn('id', $deviceIds)
  622. ->get(['id', 'title', 'code'])
  623. ->keyBy('id');
  624. $itemMap = DB::table('item')
  625. ->whereIn('id', $itemIds)
  626. ->get(['id', 'title', 'code'])
  627. ->keyBy('id');
  628. // 4. 预挂载主表的项目信息(item_code, item_title)
  629. $mainItemInfo = [];
  630. foreach ($mainData as $m) {
  631. $proj = $itemMap[$m['item_id']] ?? null;
  632. $mainItemInfo[$m['id']] = [
  633. 'item_code' => $proj ? $proj->code : '',
  634. 'item_title' => $proj ? $proj->title : '',
  635. ];
  636. }
  637. $res = [];
  638. // 如果没有详情,初始化空结构
  639. if ($details->isEmpty()) {
  640. foreach ($mainItemInfo as $mId => $info) {
  641. $res[$mId] = [];
  642. }
  643. return $res;
  644. }
  645. // 5. 循环子表,合并设备档案信息
  646. foreach ($details as $item) {
  647. $device = $deviceMap[$item->device_id] ?? null;
  648. $detailRow = [
  649. // 设备信息(对应 Excel 配置中的 key)
  650. 'device_code' => $device ? $device->code : '',
  651. 'device_title' => $device ? $device->title : '',
  652. // 时间信息
  653. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  654. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  655. // 项目信息(由主表平铺而来)
  656. 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
  657. 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
  658. ];
  659. $res[$item->main_id][] = $detailRow;
  660. }
  661. return $res;
  662. }
  663. public function dailyDwOrderCreate($data, $user)
  664. {
  665. $topDepartId = $user['top_depart_id'];
  666. if (empty($data['month'])) return [false, '月份不能为空'];
  667. $monthStart = $this->changeDateToDate($data['month']);
  668. // --- 前置核心校验 ---
  669. // 1. 校验设备月度明细是否存在
  670. $hasMonthly = DB::table('monthly_dw_order_details as d')
  671. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  672. ->where('m.month', $monthStart)
  673. ->where('m.top_depart_id', $topDepartId)
  674. ->where('m.del_time', 0)
  675. ->exists();
  676. if (!$hasMonthly) return [false, '未找到该月份的设备月度工时明细'];
  677. // 2. 校验设备项目分配规则
  678. $hasRules = DB::table('rule_set as r')
  679. ->where('r.month', $monthStart)
  680. ->where('r.top_depart_id', $topDepartId)
  681. ->where('r.del_time', 0)
  682. ->exists();
  683. if (!$hasRules) return [false, '未找到该月份的项目比例规则设置'];
  684. // 3. 校验工作日历
  685. $hasCalendar = DB::table('calendar_details')
  686. ->where('month', $monthStart)
  687. ->where('is_work', 1)
  688. ->where('del_time', 0)
  689. ->exists();
  690. if (!$hasCalendar) return [false, '该月份未配置工作日历'];
  691. $data['type'] = 'd_work';
  692. ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
  693. return [true, '设备工时生成任务已提交,请稍后查看结果'];
  694. }
  695. public function dailyDwOrderCreateMain($data, $user)
  696. {
  697. $topDepartId = $user['top_depart_id'];
  698. if (empty($data['month'])) return [false, '月份不能为空'];
  699. $monthStart = $this->changeDateToDate($data['month']);
  700. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  701. $now = time();
  702. DB::beginTransaction();
  703. try {
  704. // --- 0. 清理旧数据 ---
  705. $oldOrderIds = DB::table('daily_dw_order')
  706. ->where('top_depart_id', $topDepartId)
  707. ->where('order_time', '>=', $monthStart)
  708. ->where('order_time', '<=', $monthEnd)
  709. ->where('is_create', 1)
  710. ->where('del_time', 0)
  711. ->pluck('id');
  712. if ($oldOrderIds->isNotEmpty()) {
  713. DB::table('daily_dw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  714. DB::table('daily_dw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  715. }
  716. // --- 1. 基础数据预加载 ---
  717. // 月度设备工时明细
  718. $monthlyOrder = DB::table('monthly_dw_order_details as d')
  719. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  720. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  721. ->where('m.del_time', 0)->where('d.del_time', 0)
  722. ->select('d.*')->get();
  723. if ($monthlyOrder->isEmpty()) return [false, '未找到设备月度工时明细'];
  724. // 设备项目分配比例 (与人员类似,但通常关联 device_id)
  725. $ruleSet = DB::table('rule_set_details as rd')
  726. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  727. ->where('r.month', $monthStart)
  728. ->where('rd.type', RuleSetDetails::type_two) // 假设 type_two 是设备类型
  729. ->where('r.del_time', 0)->where('rd.del_time', 0)
  730. ->select('rd.*')->get()->groupBy('data_id');
  731. // 标准工作时段 (设备通常只走公司标准时段)
  732. $standardWorkRanges = DB::table('work_range_details')
  733. ->where('top_depart_id', $topDepartId)
  734. ->where('del_time', 0)
  735. ->get();
  736. // 工作日历
  737. $workDays = DB::table('calendar_details')
  738. ->where('month', $monthStart)
  739. ->where('is_work', CalendarDetails::TYPE_ONE)
  740. ->where('del_time', 0)
  741. ->orderBy('time', 'asc')
  742. ->get();
  743. if ($workDays->isEmpty()) return [false, '未配置工作日历,无法分配设备工时'];
  744. // --- 2. 核心分配逻辑 ---
  745. $finalAlloc = [];
  746. foreach ($monthlyOrder as $mDetail) {
  747. $deviceId = $mDetail->device_id;
  748. $deviceRules = $ruleSet->get($deviceId);
  749. if (!$deviceRules) continue;
  750. $remainingMin = (float)$mDetail->rd_total_hours * 60;
  751. if ($remainingMin <= 0) continue;
  752. foreach ($workDays as $dayInfo) {
  753. if ($remainingMin <= 0) break;
  754. // 计算当天设备最大可用分钟 (标准时段总和)
  755. $dayMaxAvail = $standardWorkRanges->sum('total_work_min');
  756. $canAllocToday = min($remainingMin, $dayMaxAvail);
  757. foreach ($deviceRules as $rule) {
  758. $rate = (float)$rule->rate / 100;
  759. $projectMin = $canAllocToday * $rate;
  760. if ($projectMin > 0) {
  761. $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = ($finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] ?? 0) + $projectMin;
  762. }
  763. }
  764. $remainingMin -= $canAllocToday;
  765. }
  766. }
  767. // --- 3. 生成单据并填充时段 (防重叠) ---
  768. $newOrderIds = [];
  769. $dailyDevicePools = []; // 追踪每台设备每天的时间消耗情况
  770. foreach ($finalAlloc as $dayTs => $projects) {
  771. foreach ($projects as $itemId => $devices) {
  772. $mainId = DB::table('daily_dw_order')->insertGetId([
  773. 'code' => '',
  774. 'item_id' => $itemId,
  775. 'order_time' => $dayTs,
  776. 'top_depart_id' => $topDepartId,
  777. 'is_create' => 1,
  778. 'crt_id' => $user['id'],
  779. 'crt_time' => $now,
  780. 'upd_time' => $now,
  781. ]);
  782. $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
  783. foreach ($devices as $deviceId => $toAllocMin) {
  784. // 初始化该设备当天的时段池 (仅由标准时段构成)
  785. if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
  786. $pool = [];
  787. foreach ($standardWorkRanges as $swr) {
  788. $pool[] = [
  789. 's' => $swr->start_time_hour * 60 + $swr->start_time_min,
  790. 'e' => $swr->end_time_hour * 60 + $swr->end_time_min
  791. ];
  792. }
  793. $dailyDevicePools[$dayTs][$deviceId] = $pool;
  794. }
  795. $tempRem = $toAllocMin;
  796. foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
  797. if ($tempRem <= 0) break;
  798. $pMax = $p['e'] - $p['s'];
  799. if ($pMax <= 0) continue;
  800. $take = min($tempRem, $pMax);
  801. $start = $p['s'];
  802. $end = $p['s'] + $take;
  803. DB::table('daily_dw_order_details')->insert([
  804. 'main_id' => $mainId,
  805. 'device_id' => $deviceId,
  806. 'top_depart_id' => $topDepartId,
  807. 'start_time_hour' => floor($start / 60),
  808. 'start_time_min' => $start % 60,
  809. 'end_time_hour' => floor($end / 60),
  810. 'end_time_min' => $end % 60,
  811. 'total_work_min' => $take,
  812. 'crt_time' => $now,
  813. 'upd_time' => $now,
  814. ]);
  815. $tempRem -= $take;
  816. $p['s'] = $end; // 指针后移,防重叠
  817. }
  818. }
  819. }
  820. }
  821. // --- 4. 回填单号 ---
  822. if (empty($newOrderIds)) return [false, '未生成任何设备日工时单'];
  823. foreach ($newOrderIds as $item) {
  824. $code = $this->generateBillNo([
  825. 'top_depart_id' => $topDepartId,
  826. 'type' => DailyDwOrder::Order_type, // 确保模型中定义了此常量
  827. 'period' => date("Ym", $item['time'])
  828. ]);
  829. DB::table('daily_dw_order')->where('id', $item['id'])->update(['code' => $code]);
  830. }
  831. DB::commit();
  832. } catch (\Exception $e) {
  833. DB::rollBack();
  834. return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
  835. }
  836. return [true, ''];
  837. }
  838. public function dailyDwOrderPreview($data, $user)
  839. {
  840. $topDepartId = $user['top_depart_id'];
  841. if (empty($data['month'])) return [false, '月份不能为空'];
  842. $monthStart = $this->changeDateToDate($data['month']);
  843. // 调用核心计算逻辑
  844. $result = $this->calculateDailyDeviceAllocation($monthStart, $topDepartId, $user);
  845. if (!$result['status']) return [false, $result['msg']];
  846. return [true, [
  847. 'list' => $result['data'] // 返回给前端预览
  848. ]];
  849. }
  850. private function calculateDailyDeviceAllocation($monthStart, $topDepartId, $user)
  851. {
  852. // 加载月度设备明细
  853. $monthlyOrder = DB::table('monthly_dw_order_details as d')
  854. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  855. ->where('m.month', $monthStart)
  856. ->where('m.top_depart_id', $topDepartId)
  857. ->where('m.del_time', 0)
  858. ->where('d.del_time', 0)
  859. ->select('d.*')
  860. ->get();
  861. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到设备月度工时明细'];
  862. $usedDeviceIds = $monthlyOrder->pluck('device_id')->unique()->toArray();
  863. // 【优化点】按需查询设备名称
  864. $deviceMap = DB::table('device')
  865. ->whereIn('id', $usedDeviceIds)
  866. ->pluck('title', 'id')
  867. ->toArray();
  868. // 加载分配规则
  869. $ruleSet = DB::table('rule_set_details as rd')
  870. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  871. ->where('r.month', $monthStart)
  872. ->where('rd.type', RuleSetDetails::type_two) // 设备类型
  873. ->where('r.del_time', 0)
  874. ->where('rd.del_time', 0)
  875. ->select('rd.*')
  876. ->get();
  877. // 【优化点】按需查询项目名称
  878. $usedItemIds = $ruleSet->pluck('item_id')->unique()->toArray();
  879. $itemMap = DB::table('item')
  880. ->whereIn('id', $usedItemIds)
  881. ->pluck('title', 'id')
  882. ->toArray();
  883. $ruleSetGrouped = $ruleSet->groupBy('data_id'); // 按 device_id 分组
  884. // 标准班次 & 日历 (逻辑同前)
  885. $standardWorkRanges = DB::table('work_range_details')
  886. ->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  887. $dayMaxAvail = (int)$standardWorkRanges->sum('total_work_min');
  888. $workDays = DB::table('calendar_details')
  889. ->where('month', $monthStart)->where('is_work', 1)->where('del_time', 0)
  890. ->orderBy('time', 'asc')->get();
  891. if ($workDays->isEmpty()) return ['status' => false, 'msg' => '未配置工作日历'];
  892. // --- 2. 阶段一:计算每天每台设备分配的项目分钟数 ---
  893. $finalAlloc = [];
  894. foreach ($monthlyOrder as $mDetail) {
  895. $deviceId = $mDetail->device_id;
  896. $deviceRules = $ruleSetGrouped->get($deviceId);
  897. if (!$deviceRules) continue;
  898. $remainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  899. if ($remainingMin <= 0) continue;
  900. foreach ($workDays as $dayInfo) {
  901. if ($remainingMin <= 0) break;
  902. $canAllocToday = min($remainingMin, $dayMaxAvail);
  903. $allocatedInDay = 0;
  904. $ruleCount = count($deviceRules);
  905. foreach ($deviceRules as $index => $rule) {
  906. $rate = (float)$rule->rate / 100;
  907. if ($index === $ruleCount - 1) {
  908. $projectMin = $canAllocToday - $allocatedInDay;
  909. } else {
  910. $projectMin = (int)round($canAllocToday * $rate);
  911. }
  912. if ($projectMin > 0) {
  913. $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = $projectMin;
  914. $allocatedInDay += $projectMin;
  915. }
  916. }
  917. $remainingMin -= $canAllocToday;
  918. }
  919. }
  920. // --- 3. 阶段二:生成预览行 ---
  921. $previewList = [];
  922. $dailyDevicePools = [];
  923. $tempMainIdCounter = 1;
  924. foreach ($finalAlloc as $dayTs => $projects) {
  925. foreach ($projects as $itemId => $devices) {
  926. $currentTempMainId = $tempMainIdCounter++;
  927. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  928. foreach ($devices as $deviceId => $toAllocMin) {
  929. if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
  930. $pool = [];
  931. foreach ($standardWorkRanges as $swr) {
  932. $pool[] = [
  933. 's' => (int)($swr->start_time_hour * 60 + $swr->start_time_min),
  934. 'e' => (int)($swr->end_time_hour * 60 + $swr->end_time_min)
  935. ];
  936. }
  937. $dailyDevicePools[$dayTs][$deviceId] = $pool;
  938. }
  939. $tempRem = (int)$toAllocMin;
  940. foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
  941. if ($tempRem <= 0) break;
  942. $pMax = $p['e'] - $p['s'];
  943. if ($pMax <= 0) continue;
  944. $take = min($tempRem, $pMax);
  945. $start = (int)$p['s'];
  946. $end = $start + $take;
  947. $previewList[] = [
  948. 'temp_main_id' => $currentTempMainId,
  949. 'order_time' => date('Y-m-d', $dayTs),
  950. 'order_timestamp' => $dayTs,
  951. 'item_id' => $itemId,
  952. 'item_title' => $itemTitle,
  953. 'device_id' => $deviceId,
  954. 'device_title' => $deviceMap[$deviceId] ?? '未知设备',
  955. 'start_time' => sprintf('%02d:%02d', floor($start / 60), $start % 60),
  956. 'end_time' => sprintf('%02d:%02d', floor($end / 60), $end % 60),
  957. 'start_hour' => (int)floor($start / 60),
  958. 'start_min' => (int)($start % 60),
  959. 'end_hour' => (int)floor($end / 60),
  960. 'end_min' => (int)($end % 60),
  961. 'total_work_min' => $take,
  962. ];
  963. $tempRem -= $take;
  964. $p['s'] = $end;
  965. }
  966. }
  967. }
  968. }
  969. return ['status' => true, 'data' => $previewList];
  970. }
  971. public function dailyDwOrderSave($data, $user)
  972. {
  973. $list = $data['list'] ?? [];
  974. if (empty($list)) return [false, '提交数据不能为空'];
  975. $topDepartId = $user['top_depart_id'];
  976. $month = $data['month']; // 格式如: "2026-03"
  977. $now = time();
  978. // 1. 预加载映射
  979. $deviceIds = collect($list)->pluck('device_id')->unique()->toArray();
  980. $deviceMap = DB::table('device')->whereIn('id', $deviceIds)->pluck('title', 'id')->toArray();
  981. // 2. 重新分组并记录行号
  982. $groupedByOrder = [];
  983. foreach ($list as $index => $item) {
  984. $item['_line'] = $index + 1;
  985. $groupKey = $item['order_time'] . '_' . $item['item_id'];
  986. $groupedByOrder[$groupKey][] = $item;
  987. }
  988. $deviceTimeline = [];
  989. DB::beginTransaction();
  990. try {
  991. // A. 清理旧数据
  992. $monthStart = $this->changeDateToDate($month);
  993. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  994. $oldOrderIds = DB::table('daily_dw_order')
  995. ->where('top_depart_id', $topDepartId)
  996. ->whereBetween('order_time', [$monthStart, $monthEnd])
  997. ->where('del_time', 0)
  998. ->pluck('id');
  999. if ($oldOrderIds->isNotEmpty()) {
  1000. DB::table('daily_dw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  1001. DB::table('daily_dw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  1002. }
  1003. // B. 遍历重组后的分组
  1004. foreach ($groupedByOrder as $details) {
  1005. $first = $details[0];
  1006. $orderTimestamp = strtotime($first['order_time']);
  1007. $itemId = $first['item_id'];
  1008. $mainId = DB::table('daily_dw_order')->insertGetId([
  1009. 'code' => '',
  1010. 'item_id' => $itemId,
  1011. 'order_time' => $orderTimestamp,
  1012. 'top_depart_id' => $topDepartId,
  1013. 'is_create' => 1,
  1014. 'crt_id' => $user['id'],
  1015. 'crt_time' => $now,
  1016. ]);
  1017. $insertDetails = [];
  1018. foreach ($details as $d) {
  1019. $rowNum = $d['_line'];
  1020. $devId = $d['device_id'];
  1021. $devName = $deviceMap[$devId] ?? "设备(ID:{$devId})";
  1022. // --- 新增:校验 order_time 是否属于当前选择的 month ---
  1023. if (date("Y-m", strtotime($d['order_time'])) !== $month) {
  1024. return [false, "第 {$rowNum} 行:日期[{$d['order_time']}]不属于保存月份[{$month}],请修正!"];
  1025. }
  1026. $s = (int)$d['start_hour'] * 60 + (int)$d['start_min'];
  1027. $e = (int)$d['end_hour'] * 60 + (int)$d['end_min'];
  1028. $calcTotalMin = $e - $s;
  1029. if ($calcTotalMin <= 0) {
  1030. return [false, "第 {$rowNum} 行:设备[{$devName}]在[{$d['order_time']}]的结束时间必须晚于开始时间"];
  1031. }
  1032. // 冲突校验
  1033. $dateStr = $d['order_time'];
  1034. if (isset($deviceTimeline[$devId][$dateStr])) {
  1035. foreach ($deviceTimeline[$devId][$dateStr] as $exist) {
  1036. if ($s < $exist['e'] && $e > $exist['s']) {
  1037. return [false, "第 {$rowNum} 行:设备[{$devName}]在[{$dateStr}]存在时间冲突({$d['start_time']}-{$d['end_time']})"];
  1038. }
  1039. }
  1040. }
  1041. $deviceTimeline[$devId][$dateStr][] = ['s' => $s, 'e' => $e];
  1042. $insertDetails[] = [
  1043. 'main_id' => $mainId,
  1044. 'device_id' => $devId,
  1045. 'top_depart_id' => $topDepartId,
  1046. 'start_time_hour' => $d['start_hour'],
  1047. 'start_time_min' => $d['start_min'],
  1048. 'end_time_hour' => $d['end_hour'],
  1049. 'end_time_min' => $d['end_min'],
  1050. 'total_work_min' => $calcTotalMin,
  1051. 'crt_time' => $now,
  1052. 'order_time' => $orderTimestamp,
  1053. 'item_id' => $itemId,
  1054. ];
  1055. }
  1056. DB::table('daily_dw_order_details')->insert($insertDetails);
  1057. $code = $this->generateBillNo([
  1058. 'top_depart_id' => $topDepartId,
  1059. 'type' => DailyDwOrder::Order_type,
  1060. 'period' => date("Ym", $orderTimestamp)
  1061. ]);
  1062. DB::table('daily_dw_order')->where('id', $mainId)->update(['code' => $code]);
  1063. }
  1064. DB::commit();
  1065. return [true, ''];
  1066. } catch (\Exception $e) {
  1067. DB::rollBack();
  1068. return [false, "保存失败:" . $e->getMessage()];
  1069. }
  1070. }
  1071. }