DeviceWorkService.php 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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, $user);
  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, $user);
  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, $user){
  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. 'crt_id' => $user['id'],
  392. ];
  393. }
  394. if(! empty($unit)) DailyDwOrderDetails::insert($unit);
  395. }
  396. }
  397. private function getDetailDaily($id){
  398. $data = DailyDwOrderDetails::where('del_time',0)
  399. ->where('main_id', $id)
  400. ->select('device_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_work_min')
  401. ->get()->toArray();
  402. $id = array_column($data,'device_id');
  403. $map = Device::whereIn('id',$id)
  404. ->select('title','id','code')
  405. ->get()
  406. ->keyBy('id')
  407. ->toArray();
  408. foreach ($data as $key => $value){
  409. $tmp = $map[$value['device_id']] ?? [];
  410. $merge = [];
  411. $merge['device_title'] = $tmp['title'];
  412. $merge['device_code'] = $tmp['code'];
  413. $data[$key] = array_merge($value, $merge);
  414. }
  415. $detail = [
  416. 'details' => $data,
  417. ];
  418. foreach ($detail as $key => $value) {
  419. if (empty($value)) {
  420. $detail[$key] = (object)[]; // 转成 stdClass 对象
  421. }
  422. }
  423. return $detail;
  424. }
  425. public function dailyDwOrderDel($data){
  426. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  427. try {
  428. DB::beginTransaction();
  429. $time = time();
  430. DailyDwOrder::where('del_time',0)
  431. ->whereIn('id',$data['id'])
  432. ->update(['del_time' => $time]);
  433. DailyDwOrderDetails::where('del_time',0)
  434. ->whereIn('main_id', $data['id'])
  435. ->update(['del_time' => $time]);
  436. DB::commit();
  437. }catch (\Exception $exception){
  438. DB::rollBack();
  439. return [false,$exception->getMessage()];
  440. }
  441. return [true, ''];
  442. }
  443. public function dailyDwOrderDetail($data, $user){
  444. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  445. $customer = DailyDwOrder::where('del_time',0)
  446. ->where('id',$data['id'])
  447. ->first();
  448. if(empty($customer)) return [false,'设备日工时单不存在或已被删除'];
  449. $customer = $customer->toArray();
  450. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  451. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  452. $item = Item::where('id', $customer['item_id'])->first();
  453. $customer['item_title'] = $item->title;
  454. $customer['item_code'] = $item->code;
  455. $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
  456. $details = $this->getDetailDaily($data['id']);
  457. $customer = array_merge($customer, $details);
  458. return [true, $customer];
  459. }
  460. public function dailyDwOrderCommon($data,$user, $field = []){
  461. if(empty($field)) $field = DailyDwOrder::$field;
  462. $model = DailyDwOrder::Clear($user,$data);
  463. $model = $model->where('del_time',0)
  464. ->select($field)
  465. ->orderby('id', 'desc');
  466. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  467. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  468. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  469. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  470. $model->where('crt_time','>=',$return[0]);
  471. $model->where('crt_time','<=',$return[1]);
  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. if(empty($data['order_time'])) return [false, '单据日期不能为空'];
  483. $data['order_time'] = $this->changeDateToDate($data['order_time']);
  484. $orderTime = $data['order_time'];
  485. $itemId = $data['item_id'] ?? 0;
  486. if(empty($itemId)) return [false, '项目不能为空'];
  487. $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
  488. if(!$bool) return [false, '项目不存在或已被删除'];
  489. $data['top_depart_id'] = $user['top_depart_id'];
  490. if(empty($data['details'])) return [false, '设备日工时单明细不能为空'];
  491. // --- 1. 批量预获取人员信息,用于报错提示 ---
  492. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'device_id')));
  493. $empDisplayMap = Device::whereIn('id', $allEmpIds)
  494. ->get(['id', 'code', 'title'])
  495. ->mapWithKeys(function($item){
  496. return [$item->id => "[{$item->code}]{$item->title}"];
  497. })->toArray();
  498. // 2. 本次提交内部重叠记录
  499. $internalOverlap = [];
  500. foreach ($data['details'] as $key => $value){
  501. $empId = $value['device_id'] ?? 0;
  502. if(empty($empId)) return [false, '设备不能为空'];
  503. $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
  504. // 校验数字有效性
  505. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  506. if(!$res['valid']) return [false, "设备{$empName}开始点:" . $res['error']];
  507. if($value['start_time_hour'] > 23) return [false, false, "设备{$empName}开始点不合法"];
  508. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  509. if(!$res['valid']) return [false, "设备{$empName}开始分:" . $res['error']];
  510. if($value['start_time_min'] > 60) return [false, false, "设备{$empName}开始点不合法"];
  511. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  512. if(!$res['valid']) return [false, "设备{$empName}结束点:" . $res['error']];
  513. if($value['end_time_hour'] > 24) return [false, false, "设备{$empName}结束点不合法"];
  514. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  515. if(!$res['valid']) return [false, "设备{$empName}结束分:" . $res['error']];
  516. if($value['end_time_min'] > 60) return [false, false, "设备{$empName}结束分不合法"];
  517. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  518. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  519. if ($currentStart >= $currentEnd) {
  520. return [false, "设备{$empName}:开始时间必须早于结束时间"];
  521. }
  522. // --- 3. 内部重叠校验(防止一次提交多行重复) ---
  523. if (isset($internalOverlap[$empId])) {
  524. foreach ($internalOverlap[$empId] as $period) {
  525. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  526. return [false, "设备{$empName}在本次提交的多行明细中时间段重叠"];
  527. }
  528. }
  529. }
  530. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  531. $query = DB::table('daily_dw_order_details as d')
  532. ->join('daily_dw_order as m', 'd.main_id', '=', 'm.id')
  533. ->where('m.top_depart_id', $data['top_depart_id'])
  534. ->where('m.order_time', $orderTime)
  535. ->where('m.item_id', $itemId)
  536. ->where('d.device_id', $empId)
  537. ->where('m.del_time', 0)
  538. ->where('d.del_time', 0);
  539. if (!$is_add && !empty($data['id'])) {
  540. $query->where('m.id', '<>', $data['id']);
  541. }
  542. $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
  543. foreach ($existingPeriods as $p) {
  544. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  545. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  546. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  547. return [false, "设备{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
  548. }
  549. }
  550. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  551. }
  552. if(!$is_add){
  553. if(empty($data['id'])) return [false,'ID不能为空'];
  554. $bool = DailyDwOrder::where('top_depart_id', $data['top_depart_id'])
  555. ->where('id',$data['id'])
  556. ->where('del_time',0)
  557. ->exists();
  558. if(!$bool) return [false, '设备日工时单不存在或已被删除'];
  559. }
  560. return [true, ''];
  561. }
  562. public function fillDataDaily($data){
  563. if(empty($data['data'])) return $data;
  564. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  565. $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_id')));
  566. foreach ($data['data'] as $key => $value){
  567. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  568. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  569. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  570. $item_tmp = $item[$value['item_id']] ?? [];
  571. $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
  572. $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
  573. }
  574. return $data;
  575. }
  576. public function fillDataForExportDaily($data, $column, &$return)
  577. {
  578. if (empty($data)) return;
  579. $mainIds = array_column($data, 'id');
  580. // 1. 获取详情及所有关联档案(项目、设备)的映射
  581. $detailsMap = $this->getDwDailyDetailsMap($mainIds, $data);
  582. foreach ($data as $main) {
  583. $mainId = $main['id'];
  584. $details = $detailsMap[$mainId] ?? [];
  585. // 2. 提取并格式化主表共有信息
  586. $mainInfo = [
  587. 'code' => $main['code'],
  588. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  589. ];
  590. if (empty($details)) {
  591. // 无明细时只导出一行主表信息
  592. $tempRow = [];
  593. foreach ($column as $col) {
  594. $tempRow[] = $mainInfo[$col] ?? '';
  595. }
  596. $return[] = $tempRow;
  597. } else {
  598. // 3. 平铺:将设备明细信息、项目信息与主表信息合并
  599. foreach ($details as $sub) {
  600. $fullRowData = array_merge($mainInfo, $sub);
  601. $tempRow = [];
  602. foreach ($column as $col) {
  603. $tempRow[] = $fullRowData[$col] ?? '';
  604. }
  605. $return[] = $tempRow;
  606. }
  607. }
  608. }
  609. }
  610. public function getDwDailyDetailsMap($mainIds, $mainData)
  611. {
  612. // 1. 获取设备工时子表记录
  613. $details = DB::table('daily_dw_order_details')
  614. ->where('del_time', 0)
  615. ->whereIn('main_id', $mainIds)
  616. ->get();
  617. // 2. 提取关联 ID(设备 ID 和 项目 ID)
  618. $deviceIds = $details->pluck('device_id')->unique();
  619. $itemIds = array_unique(array_column($mainData, 'item_id'));
  620. // 3. 批量获取设备档案和项目档案
  621. $deviceMap = DB::table('device')
  622. ->whereIn('id', $deviceIds)
  623. ->get(['id', 'title', 'code'])
  624. ->keyBy('id');
  625. $itemMap = DB::table('item')
  626. ->whereIn('id', $itemIds)
  627. ->get(['id', 'title', 'code'])
  628. ->keyBy('id');
  629. // 4. 预挂载主表的项目信息(item_code, item_title)
  630. $mainItemInfo = [];
  631. foreach ($mainData as $m) {
  632. $proj = $itemMap[$m['item_id']] ?? null;
  633. $mainItemInfo[$m['id']] = [
  634. 'item_code' => $proj ? $proj->code : '',
  635. 'item_title' => $proj ? $proj->title : '',
  636. ];
  637. }
  638. $res = [];
  639. // 如果没有详情,初始化空结构
  640. if ($details->isEmpty()) {
  641. foreach ($mainItemInfo as $mId => $info) {
  642. $res[$mId] = [];
  643. }
  644. return $res;
  645. }
  646. // 5. 循环子表,合并设备档案信息
  647. foreach ($details as $item) {
  648. $device = $deviceMap[$item->device_id] ?? null;
  649. $detailRow = [
  650. // 设备信息(对应 Excel 配置中的 key)
  651. 'device_code' => $device ? $device->code : '',
  652. 'device_title' => $device ? $device->title : '',
  653. // 时间信息
  654. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  655. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  656. // 项目信息(由主表平铺而来)
  657. 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
  658. 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
  659. ];
  660. $res[$item->main_id][] = $detailRow;
  661. }
  662. return $res;
  663. }
  664. public function dailyDwOrderCreate($data, $user)
  665. {
  666. $topDepartId = $user['top_depart_id'];
  667. if (empty($data['month'])) return [false, '月份不能为空'];
  668. $monthStart = $this->changeDateToDate($data['month']);
  669. // --- 前置核心校验 ---
  670. // 1. 校验设备月度明细是否存在
  671. $hasMonthly = DB::table('monthly_dw_order_details as d')
  672. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  673. ->where('m.month', $monthStart)
  674. ->where('m.top_depart_id', $topDepartId)
  675. ->where('m.del_time', 0)
  676. ->exists();
  677. if (!$hasMonthly) return [false, '未找到该月份的设备月度工时明细'];
  678. // 2. 校验设备项目分配规则
  679. $hasRules = DB::table('rule_set as r')
  680. ->where('r.month', $monthStart)
  681. ->where('r.top_depart_id', $topDepartId)
  682. ->where('r.del_time', 0)
  683. ->exists();
  684. if (!$hasRules) return [false, '未找到该月份的项目比例规则设置'];
  685. // 3. 校验工作日历
  686. $hasCalendar = DB::table('calendar_details')
  687. ->where('month', $monthStart)
  688. ->where('is_work', 1)
  689. ->where('del_time', 0)
  690. ->exists();
  691. if (!$hasCalendar) return [false, '该月份未配置工作日历'];
  692. $data['type'] = 'd_work';
  693. ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
  694. return [true, '设备工时生成任务已提交,请稍后查看结果'];
  695. }
  696. public function dailyDwOrderCreateMain($data, $user)
  697. {
  698. $topDepartId = $user['top_depart_id'];
  699. if (empty($data['month'])) return [false, '月份不能为空'];
  700. $monthStart = $this->changeDateToDate($data['month']);
  701. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  702. $now = time();
  703. DB::beginTransaction();
  704. try {
  705. // --- 0. 清理旧数据 ---
  706. $oldOrderIds = DB::table('daily_dw_order')
  707. ->where('top_depart_id', $topDepartId)
  708. ->where('order_time', '>=', $monthStart)
  709. ->where('order_time', '<=', $monthEnd)
  710. ->where('is_create', 1)
  711. ->where('del_time', 0)
  712. ->pluck('id');
  713. if ($oldOrderIds->isNotEmpty()) {
  714. DB::table('daily_dw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  715. DB::table('daily_dw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  716. }
  717. // --- 1. 基础数据预加载 ---
  718. // 月度设备工时明细
  719. $monthlyOrder = DB::table('monthly_dw_order_details as d')
  720. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  721. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  722. ->where('m.del_time', 0)->where('d.del_time', 0)
  723. ->select('d.*')->get();
  724. if ($monthlyOrder->isEmpty()) return [false, '未找到设备月度工时明细'];
  725. // 设备项目分配比例 (与人员类似,但通常关联 device_id)
  726. $ruleSet = DB::table('rule_set_details as rd')
  727. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  728. ->where('r.month', $monthStart)
  729. ->where('rd.type', RuleSetDetails::type_two) // 假设 type_two 是设备类型
  730. ->where('r.del_time', 0)->where('rd.del_time', 0)
  731. ->select('rd.*')->get()->groupBy('data_id');
  732. // 标准工作时段 (设备通常只走公司标准时段)
  733. $standardWorkRanges = DB::table('work_range_details')
  734. ->where('top_depart_id', $topDepartId)
  735. ->where('del_time', 0)
  736. ->get();
  737. // 工作日历
  738. $workDays = DB::table('calendar_details')
  739. ->where('month', $monthStart)
  740. ->where('is_work', CalendarDetails::TYPE_ONE)
  741. ->where('del_time', 0)
  742. ->orderBy('time', 'asc')
  743. ->get();
  744. if ($workDays->isEmpty()) return [false, '未配置工作日历,无法分配设备工时'];
  745. // --- 2. 核心分配逻辑 ---
  746. $finalAlloc = [];
  747. foreach ($monthlyOrder as $mDetail) {
  748. $deviceId = $mDetail->device_id;
  749. $deviceRules = $ruleSet->get($deviceId);
  750. if (!$deviceRules) continue;
  751. $remainingMin = (float)$mDetail->rd_total_hours * 60;
  752. if ($remainingMin <= 0) continue;
  753. foreach ($workDays as $dayInfo) {
  754. if ($remainingMin <= 0) break;
  755. // 计算当天设备最大可用分钟 (标准时段总和)
  756. $dayMaxAvail = $standardWorkRanges->sum('total_work_min');
  757. $canAllocToday = min($remainingMin, $dayMaxAvail);
  758. foreach ($deviceRules as $rule) {
  759. $rate = (float)$rule->rate / 100;
  760. $projectMin = $canAllocToday * $rate;
  761. if ($projectMin > 0) {
  762. $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = ($finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] ?? 0) + $projectMin;
  763. }
  764. }
  765. $remainingMin -= $canAllocToday;
  766. }
  767. }
  768. // --- 3. 生成单据并填充时段 (防重叠) ---
  769. $newOrderIds = [];
  770. $dailyDevicePools = []; // 追踪每台设备每天的时间消耗情况
  771. foreach ($finalAlloc as $dayTs => $projects) {
  772. foreach ($projects as $itemId => $devices) {
  773. $mainId = DB::table('daily_dw_order')->insertGetId([
  774. 'code' => '',
  775. 'item_id' => $itemId,
  776. 'order_time' => $dayTs,
  777. 'top_depart_id' => $topDepartId,
  778. 'is_create' => 1,
  779. 'crt_id' => $user['id'],
  780. 'crt_time' => $now,
  781. 'upd_time' => $now,
  782. ]);
  783. $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
  784. foreach ($devices as $deviceId => $toAllocMin) {
  785. // 初始化该设备当天的时段池 (仅由标准时段构成)
  786. if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
  787. $pool = [];
  788. foreach ($standardWorkRanges as $swr) {
  789. $pool[] = [
  790. 's' => $swr->start_time_hour * 60 + $swr->start_time_min,
  791. 'e' => $swr->end_time_hour * 60 + $swr->end_time_min
  792. ];
  793. }
  794. $dailyDevicePools[$dayTs][$deviceId] = $pool;
  795. }
  796. $tempRem = $toAllocMin;
  797. foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
  798. if ($tempRem <= 0) break;
  799. $pMax = $p['e'] - $p['s'];
  800. if ($pMax <= 0) continue;
  801. $take = min($tempRem, $pMax);
  802. $start = $p['s'];
  803. $end = $p['s'] + $take;
  804. DB::table('daily_dw_order_details')->insert([
  805. 'main_id' => $mainId,
  806. 'device_id' => $deviceId,
  807. 'top_depart_id' => $topDepartId,
  808. 'start_time_hour' => floor($start / 60),
  809. 'start_time_min' => $start % 60,
  810. 'end_time_hour' => floor($end / 60),
  811. 'end_time_min' => $end % 60,
  812. 'total_work_min' => $take,
  813. 'crt_time' => $now,
  814. 'upd_time' => $now,
  815. ]);
  816. $tempRem -= $take;
  817. $p['s'] = $end; // 指针后移,防重叠
  818. }
  819. }
  820. }
  821. }
  822. // --- 4. 回填单号 ---
  823. if (empty($newOrderIds)) return [false, '未生成任何设备日工时单'];
  824. foreach ($newOrderIds as $item) {
  825. $code = $this->generateBillNo([
  826. 'top_depart_id' => $topDepartId,
  827. 'type' => DailyDwOrder::Order_type, // 确保模型中定义了此常量
  828. 'period' => date("Ym", $item['time'])
  829. ]);
  830. DB::table('daily_dw_order')->where('id', $item['id'])->update(['code' => $code]);
  831. }
  832. DB::commit();
  833. } catch (\Exception $e) {
  834. DB::rollBack();
  835. return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
  836. }
  837. return [true, ''];
  838. }
  839. public function dailyDwOrderPreview($data, $user)
  840. {
  841. $topDepartId = $user['top_depart_id'];
  842. if (empty($data['month'])) return [false, '月份不能为空'];
  843. $monthStart = $this->changeDateToDate($data['month']);
  844. // 调用核心计算逻辑
  845. $result = $this->calculateDailyDeviceAllocation($monthStart, $topDepartId, $user);
  846. if (!$result['status']) return [false, $result['msg']];
  847. return [true, [
  848. 'list' => $result['data'] // 返回给前端预览
  849. ]];
  850. }
  851. private function calculateDailyDeviceAllocation($monthStart, $topDepartId, $user)
  852. {
  853. // 加载月度设备明细
  854. $monthlyOrder = DB::table('monthly_dw_order_details as d')
  855. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  856. ->where('m.month', $monthStart)
  857. ->where('m.top_depart_id', $topDepartId)
  858. ->where('m.del_time', 0)
  859. ->where('d.del_time', 0)
  860. ->select('d.*')
  861. ->get();
  862. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到设备月度工时明细'];
  863. $usedDeviceIds = $monthlyOrder->pluck('device_id')->unique()->toArray();
  864. // 【优化点】按需查询设备名称
  865. $deviceMap = DB::table('device')
  866. ->whereIn('id', $usedDeviceIds)
  867. ->pluck('title', 'id')
  868. ->toArray();
  869. // 加载分配规则
  870. $ruleSet = DB::table('rule_set_details as rd')
  871. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  872. ->where('r.month', $monthStart)
  873. ->where('rd.type', RuleSetDetails::type_two) // 设备类型
  874. ->where('r.del_time', 0)
  875. ->where('rd.del_time', 0)
  876. ->select('rd.*')
  877. ->get();
  878. // 【优化点】按需查询项目名称
  879. $usedItemIds = $ruleSet->pluck('item_id')->unique()->toArray();
  880. $itemMap = DB::table('item')
  881. ->whereIn('id', $usedItemIds)
  882. ->pluck('title', 'id')
  883. ->toArray();
  884. $ruleSetGrouped = $ruleSet->groupBy('data_id'); // 按 device_id 分组
  885. // 标准班次 & 日历 (逻辑同前)
  886. $standardWorkRanges = DB::table('work_range_details')
  887. ->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  888. $dayMaxAvail = (int)$standardWorkRanges->sum('total_work_min');
  889. $workDays = DB::table('calendar_details')
  890. ->where('month', $monthStart)->where('is_work', 1)->where('del_time', 0)
  891. ->orderBy('time', 'asc')->get();
  892. if ($workDays->isEmpty()) return ['status' => false, 'msg' => '未配置工作日历'];
  893. // --- 2. 阶段一:计算每天每台设备分配的项目分钟数 ---
  894. $finalAlloc = [];
  895. foreach ($monthlyOrder as $mDetail) {
  896. $deviceId = $mDetail->device_id;
  897. $deviceRules = $ruleSetGrouped->get($deviceId);
  898. if (!$deviceRules) continue;
  899. $remainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  900. if ($remainingMin <= 0) continue;
  901. foreach ($workDays as $dayInfo) {
  902. if ($remainingMin <= 0) break;
  903. $canAllocToday = min($remainingMin, $dayMaxAvail);
  904. $allocatedInDay = 0;
  905. $ruleCount = count($deviceRules);
  906. foreach ($deviceRules as $index => $rule) {
  907. $rate = (float)$rule->rate / 100;
  908. if ($index === $ruleCount - 1) {
  909. $projectMin = $canAllocToday - $allocatedInDay;
  910. } else {
  911. $projectMin = (int)round($canAllocToday * $rate);
  912. }
  913. if ($projectMin > 0) {
  914. $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = $projectMin;
  915. $allocatedInDay += $projectMin;
  916. }
  917. }
  918. $remainingMin -= $canAllocToday;
  919. }
  920. }
  921. // --- 3. 阶段二:生成预览行 ---
  922. $previewList = [];
  923. $dailyDevicePools = [];
  924. $tempMainIdCounter = 1;
  925. foreach ($finalAlloc as $dayTs => $projects) {
  926. foreach ($projects as $itemId => $devices) {
  927. $currentTempMainId = $tempMainIdCounter++;
  928. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  929. foreach ($devices as $deviceId => $toAllocMin) {
  930. if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
  931. $pool = [];
  932. foreach ($standardWorkRanges as $swr) {
  933. $pool[] = [
  934. 's' => (int)($swr->start_time_hour * 60 + $swr->start_time_min),
  935. 'e' => (int)($swr->end_time_hour * 60 + $swr->end_time_min)
  936. ];
  937. }
  938. $dailyDevicePools[$dayTs][$deviceId] = $pool;
  939. }
  940. $tempRem = (int)$toAllocMin;
  941. foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
  942. if ($tempRem <= 0) break;
  943. $pMax = $p['e'] - $p['s'];
  944. if ($pMax <= 0) continue;
  945. $take = min($tempRem, $pMax);
  946. $start = (int)$p['s'];
  947. $end = $start + $take;
  948. $previewList[] = [
  949. 'temp_main_id' => $currentTempMainId,
  950. 'order_time' => date('Y-m-d', $dayTs),
  951. 'order_timestamp' => $dayTs,
  952. 'item_id' => $itemId,
  953. 'item_title' => $itemTitle,
  954. 'device_id' => $deviceId,
  955. 'device_title' => $deviceMap[$deviceId] ?? '未知设备',
  956. 'start_time' => sprintf('%02d:%02d', floor($start / 60), $start % 60),
  957. 'end_time' => sprintf('%02d:%02d', floor($end / 60), $end % 60),
  958. 'start_hour' => (int)floor($start / 60),
  959. 'start_min' => (int)($start % 60),
  960. 'end_hour' => (int)floor($end / 60),
  961. 'end_min' => (int)($end % 60),
  962. 'total_work_min' => $take,
  963. ];
  964. $tempRem -= $take;
  965. $p['s'] = $end;
  966. }
  967. }
  968. }
  969. }
  970. return ['status' => true, 'data' => $previewList];
  971. }
  972. public function dailyDwOrderSave($data, $user)
  973. {
  974. $list = $data['list'] ?? [];
  975. if (empty($list)) return [false, '提交数据不能为空'];
  976. $topDepartId = $user['top_depart_id'];
  977. $month = $data['month']; // 格式如: "2026-03"
  978. $now = time();
  979. // 1. 预加载映射
  980. $deviceIds = collect($list)->pluck('device_id')->unique()->toArray();
  981. $deviceMap = DB::table('device')->whereIn('id', $deviceIds)->pluck('title', 'id')->toArray();
  982. // 2. 重新分组并记录行号
  983. $groupedByOrder = [];
  984. foreach ($list as $index => $item) {
  985. $item['_line'] = $index + 1;
  986. $groupKey = $item['order_time'] . '_' . $item['item_id'];
  987. $groupedByOrder[$groupKey][] = $item;
  988. }
  989. $deviceTimeline = [];
  990. DB::beginTransaction();
  991. try {
  992. // A. 清理旧数据
  993. $monthStart = $this->changeDateToDate($month);
  994. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  995. $oldOrderIds = DB::table('daily_dw_order')
  996. ->where('top_depart_id', $topDepartId)
  997. ->whereBetween('order_time', [$monthStart, $monthEnd])
  998. ->where('del_time', 0)
  999. ->pluck('id');
  1000. if ($oldOrderIds->isNotEmpty()) {
  1001. DB::table('daily_dw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  1002. DB::table('daily_dw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  1003. }
  1004. // B. 遍历重组后的分组
  1005. foreach ($groupedByOrder as $details) {
  1006. $first = $details[0];
  1007. $orderTimestamp = strtotime($first['order_time']);
  1008. $itemId = $first['item_id'];
  1009. $mainId = DB::table('daily_dw_order')->insertGetId([
  1010. 'code' => '',
  1011. 'item_id' => $itemId,
  1012. 'order_time' => $orderTimestamp,
  1013. 'top_depart_id' => $topDepartId,
  1014. 'is_create' => 1,
  1015. 'crt_id' => $user['id'],
  1016. 'crt_time' => $now,
  1017. ]);
  1018. $insertDetails = [];
  1019. foreach ($details as $d) {
  1020. $rowNum = $d['_line'];
  1021. $devId = $d['device_id'];
  1022. $devName = $deviceMap[$devId] ?? "设备(ID:{$devId})";
  1023. // --- 新增:校验 order_time 是否属于当前选择的 month ---
  1024. if (date("Y-m", strtotime($d['order_time'])) !== $month) {
  1025. return [false, "第 {$rowNum} 行:日期[{$d['order_time']}]不属于保存月份[{$month}],请修正!"];
  1026. }
  1027. $s = (int)$d['start_hour'] * 60 + (int)$d['start_min'];
  1028. $e = (int)$d['end_hour'] * 60 + (int)$d['end_min'];
  1029. $calcTotalMin = $e - $s;
  1030. if ($calcTotalMin <= 0) {
  1031. return [false, "第 {$rowNum} 行:设备[{$devName}]在[{$d['order_time']}]的结束时间必须晚于开始时间"];
  1032. }
  1033. // 冲突校验
  1034. $dateStr = $d['order_time'];
  1035. if (isset($deviceTimeline[$devId][$dateStr])) {
  1036. foreach ($deviceTimeline[$devId][$dateStr] as $exist) {
  1037. if ($s < $exist['e'] && $e > $exist['s']) {
  1038. return [false, "第 {$rowNum} 行:设备[{$devName}]在[{$dateStr}]存在时间冲突({$d['start_time']}-{$d['end_time']})"];
  1039. }
  1040. }
  1041. }
  1042. $deviceTimeline[$devId][$dateStr][] = ['s' => $s, 'e' => $e];
  1043. $insertDetails[] = [
  1044. 'main_id' => $mainId,
  1045. 'device_id' => $devId,
  1046. 'top_depart_id' => $topDepartId,
  1047. 'start_time_hour' => $d['start_hour'],
  1048. 'start_time_min' => $d['start_min'],
  1049. 'end_time_hour' => $d['end_hour'],
  1050. 'end_time_min' => $d['end_min'],
  1051. 'total_work_min' => $calcTotalMin,
  1052. 'crt_time' => $now,
  1053. 'order_time' => $orderTimestamp,
  1054. 'item_id' => $itemId,
  1055. 'crt_id' => $user['id'],
  1056. ];
  1057. }
  1058. DB::table('daily_dw_order_details')->insert($insertDetails);
  1059. $code = $this->generateBillNo([
  1060. 'top_depart_id' => $topDepartId,
  1061. 'type' => DailyDwOrder::Order_type,
  1062. 'period' => date("Ym", $orderTimestamp)
  1063. ]);
  1064. DB::table('daily_dw_order')->where('id', $mainId)->update(['code' => $code]);
  1065. }
  1066. DB::commit();
  1067. return [true, ''];
  1068. } catch (\Exception $e) {
  1069. DB::rollBack();
  1070. return [false, "保存失败:" . $e->getMessage()];
  1071. }
  1072. }
  1073. }