DeviceWorkService.php 52 KB

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