DeviceWorkService.php 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  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. $map = ArchiveService::fillIsArchive($customer['month'], $user);
  139. $customer['is_archive'] = $map[$customer['month']] ?? false;
  140. $customer['month'] = $customer['month'] ? date("Y-m",$customer['month']): '';
  141. $details = $this->getDetail($data['id']);
  142. $customer = array_merge($customer, $details);
  143. return [true, $customer];
  144. }
  145. public function monthlyDwOrderCommon($data,$user, $field = []){
  146. if(empty($field)) $field = MonthlyDwOrder::$field;
  147. $model = MonthlyDwOrder::Clear($user,$data);
  148. $model = $model->where('del_time',0)
  149. ->select($field)
  150. ->orderby('id', 'desc');
  151. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  152. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  153. $model->where('month','>=',$return[0]);
  154. $model->where('month','<=',$return[1]);
  155. }
  156. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  157. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  158. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  159. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  160. $model->where('crt_time','>=',$return[0]);
  161. $model->where('crt_time','<=',$return[1]);
  162. }
  163. return $model;
  164. }
  165. public function monthlyDwOrderList($data,$user){
  166. $model = $this->monthlyDwOrderCommon($data, $user);
  167. $list = $this->limit($model,'',$data);
  168. $list = $this->fillData($list, $user);
  169. return [true, $list];
  170. }
  171. public function monthlyDwOrderRule(&$data, $user, $is_add = true)
  172. {
  173. if (empty($data['month'])) return [false, '月份不能为空'];
  174. $data['month'] = $this->changeDateToDate($data['month']);
  175. $data['top_depart_id'] = $user['top_depart_id'];
  176. //归档
  177. list($status, $msg) = ArchiveService::isArchive($data['month'], $user);
  178. if(! $status) return [false, $msg];
  179. if (empty($data['details'])) return [false, '设备月度工时单明细不能为空'];
  180. // --- 1. 批量获取设备档案信息 (用于展示 [编码]名称) ---
  181. $deviceIds = array_column($data['details'], 'device_id');
  182. $deviceMap = DB::table('device')
  183. ->whereIn('id', $deviceIds)
  184. ->where('top_depart_id', $data['top_depart_id'])
  185. ->get(['id', 'code', 'title'])
  186. ->mapWithKeys(fn($item) => [$item->id => "[{$item->code}]{$item->title}"])
  187. ->toArray();
  188. // --- 2. 获取设备考勤基准 ---
  189. list($status, $deviceStats) = (new DeviceService())->getDevicesMonthStats($deviceIds, $data['month'], $user);
  190. if (!$status) return [false, $deviceStats];
  191. // 字段中文映射,用于报错
  192. $fieldNames = [
  193. 'total_days' => '使用总天数',
  194. 'rd_total_days' => '研发使用天数',
  195. 'total_hours' => '使用总工时',
  196. 'rd_total_hours'=> '研发总工时'
  197. ];
  198. // --- 3. 循环校验明细 ---
  199. foreach ($data['details'] as $key => $value) {
  200. $line = $key + 1; // 行号
  201. if (empty($value['device_id'])) return [false, "第{$line}行:设备ID不能为空"];
  202. $deviceId = $value['device_id'];
  203. $deviceDisplayName = $deviceMap[$deviceId] ?? "";
  204. if(empty($deviceDisplayName)) return [false, "第{$line}行:设备不存在或已被删除"];
  205. // 基础数字格式检查
  206. foreach ($fieldNames as $field => $cnName) {
  207. $precision = 2;
  208. $res = $this->checkNumber($value[$field], $precision, 'non-negative');
  209. if (!$res['valid']) {
  210. return [false, "第{$line}行:设备{$deviceDisplayName}的{$cnName}填写不规范({$res['error']})"];
  211. }
  212. }
  213. // --- 4. 业务逻辑校验 ---
  214. $sysData = $deviceStats[$deviceId] ?? null;
  215. if ($sysData) {
  216. // A. 内部逻辑:研发不能大于总额
  217. if ($value['rd_total_days'] > $value['total_days']) {
  218. return [false, "第{$line}行:设备{$deviceDisplayName}的研发使用天数不能大于使用总天数"];
  219. }
  220. if ($value['rd_total_hours'] > $value['total_hours']) {
  221. return [false, "第{$line}行:设备{$deviceDisplayName}的研发总工时不能大于使用总工时"];
  222. }
  223. // B. 外部逻辑:不能超过系统根据日历算出的上限
  224. if ($value['total_days'] != $sysData['attendance_days']) {
  225. return [false, "第{$line}行:设备{$deviceDisplayName}的使用总天数({$value['total_days']})不等于系统核算天数({$sysData['attendance_days']})"];
  226. }
  227. if ($value['total_hours'] != $sysData['final_work_hour']) {
  228. return [false, "第{$line}行:设备{$deviceDisplayName}的使用总工时({$value['total_hours']})不等于系统核算工时({$sysData['final_work_hour']})"];
  229. }
  230. }
  231. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  232. }
  233. // --- 5. 查重与唯一性校验 ---
  234. list($status, $msg) = $this->checkArrayRepeat($data['details'], 'device_id', '设备');
  235. if (!$status) return [false, $msg];
  236. $query = MonthlyDwOrder::where('top_depart_id', $data['top_depart_id'])
  237. ->where('month', $data['month'])
  238. ->where('del_time', 0);
  239. if (!$is_add) {
  240. if (empty($data['id'])) return [false, 'ID不能为空'];
  241. $query->where('id', '<>', $data['id']);
  242. }
  243. if ($query->exists()) {
  244. return [false, date("Y-m", $data['month']) . '已存在设备月度研发工时单'];
  245. }
  246. return [true, ''];
  247. }
  248. public function fillData($data, $user){
  249. if(empty($data['data'])) return $data;
  250. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  251. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'month')), $user);
  252. foreach ($data['data'] as $key => $value){
  253. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  254. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  255. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  256. $data['data'][$key]['is_archive'] = $map[$value['month']] ?? false;
  257. }
  258. return $data;
  259. }
  260. public function fillDataForExport($data, $column, &$return)
  261. {
  262. if(empty($data)) return;
  263. $mainIds = array_column($data, 'id');
  264. // 获取详情映射 [main_id => [details...]]
  265. $detailsMap = $this->getDetailsMap($mainIds);
  266. // 默认空行模板
  267. $defaultRow = array_fill_keys($column, '');
  268. foreach ($data as $main) {
  269. $mainId = $main['id'];
  270. $details = $detailsMap[$mainId] ?? [];
  271. // 提取主表信息
  272. $mainInfo = [
  273. 'code' => $main['code'],
  274. 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
  275. ];
  276. if (empty($details)) {
  277. // 如果没有详情,至少导出一行主表信息(可选)
  278. $return[] = array_merge($defaultRow, $mainInfo);
  279. } else {
  280. // 核心:遍历详情,每一行详情都合并主表信息
  281. foreach ($details as $sub) {
  282. // 合并主表字段 + 详情字段
  283. $fullRow = array_merge($mainInfo, $sub);
  284. // 过滤掉不在导出列里的字段,并补充缺失列
  285. $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
  286. }
  287. }
  288. }
  289. }
  290. public function getDetailsMap($main_ids)
  291. {
  292. // 获取详情
  293. $details = MonthlyDwOrderDetails::where('del_time', 0)
  294. ->whereIn('main_id', $main_ids)
  295. ->get();
  296. // 获取设备信息
  297. $empIds = $details->pluck('device_id')->unique();
  298. $empMap = Device::whereIn('id', $empIds)->get()->keyBy('id');
  299. $res = [];
  300. foreach ($details as $item) {
  301. $tmpEmp = $empMap[$item->device_id] ?? null;
  302. // 组装每一行详情需要展示的字段
  303. $res[$item->main_id][] = [
  304. 'device_code' => $tmpEmp ? $tmpEmp->code : '',
  305. 'device_title' => $tmpEmp ? $tmpEmp->title : '',
  306. 'total_days' => $item->total_days,
  307. 'rd_total_days' => $item->rd_total_days,
  308. 'total_hours' => $item->total_hours,
  309. 'rd_total_hours' => $item->rd_total_hours,
  310. ];
  311. }
  312. return $res; // 返回 [main_id => [detail_row, detail_row]]
  313. }
  314. //设备日工时单----------------------------------------------
  315. public function dailyDwOrderEdit($data,$user){
  316. list($status,$msg) = $this->dailyDwOrderRule($data, $user, false);
  317. if(!$status) return [$status,$msg];
  318. try {
  319. DB::beginTransaction();
  320. $model = DailyDwOrder::where('id',$data['id'])->first();
  321. $model->item_id = $data['item_id'] ?? 0;
  322. $model->save();
  323. $time = time();
  324. DailyDwOrderDetails::where('del_time',0)
  325. ->where('main_id', $model->id)
  326. ->update(['del_time' => $time]);
  327. $this->saveDetailDaily($model->id, $time, $data, $user);
  328. DB::commit();
  329. }catch (\Exception $exception){
  330. DB::rollBack();
  331. return [false,$exception->getMessage()];
  332. }
  333. return [true, ''];
  334. }
  335. public function dailyDwOrderAdd($data,$user){
  336. list($status,$msg) = $this->dailyDwOrderRule($data, $user);
  337. if(!$status) return [$status,$msg];
  338. try {
  339. DB::beginTransaction();
  340. $model = new DailyDwOrder();
  341. $model->code = $this->generateBillNo([
  342. 'top_depart_id' => $user['top_depart_id'],
  343. 'type' => DailyDwOrder::Order_type,
  344. 'period' => date("Ym", $data['order_time'])
  345. ]);
  346. $model->order_time = $data['order_time'] ?? 0;
  347. $model->item_id = $data['item_id'] ?? 0;
  348. $model->crt_id = $user['id'];
  349. $model->top_depart_id = $data['top_depart_id'];
  350. $model->save();
  351. $this->saveDetailDaily($model->id, time(), $data, $user);
  352. DB::commit();
  353. }catch (\Exception $exception){
  354. DB::rollBack();
  355. return [false,$exception->getMessage()];
  356. }
  357. return [true, ''];
  358. }
  359. private function saveDetailDaily($id, $time, $data, $user){
  360. if(! empty($data['details'])){
  361. $unit = [];
  362. foreach ($data['details'] as $value){
  363. $unit[] = [
  364. 'main_id' => $id,
  365. 'device_id' => $value['device_id'],
  366. 'start_time_hour' => $value['start_time_hour'],
  367. 'start_time_min' => $value['start_time_min'],
  368. 'end_time_hour' => $value['end_time_hour'],
  369. 'end_time_min' => $value['end_time_min'],
  370. 'total_work_min' => $value['total_work_min'],
  371. 'crt_time' => $time,
  372. 'top_depart_id' => $value['top_depart_id'],
  373. 'order_time' => $data['order_time'] ?? 0,
  374. 'item_id' => $data['item_id'],
  375. 'crt_id' => $user['id'],
  376. ];
  377. }
  378. if(! empty($unit)) DailyDwOrderDetails::insert($unit);
  379. }
  380. }
  381. private function getDetailDaily($id){
  382. $data = DailyDwOrderDetails::where('del_time',0)
  383. ->where('main_id', $id)
  384. ->select('device_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_work_min')
  385. ->get()->toArray();
  386. $id = array_column($data,'device_id');
  387. $map = Device::whereIn('id',$id)
  388. ->select('title','id','code')
  389. ->get()
  390. ->keyBy('id')
  391. ->toArray();
  392. foreach ($data as $key => $value){
  393. $tmp = $map[$value['device_id']] ?? [];
  394. $merge = [];
  395. $merge['device_title'] = $tmp['title'];
  396. $merge['device_code'] = $tmp['code'];
  397. $data[$key] = array_merge($value, $merge);
  398. }
  399. $detail = [
  400. 'details' => $data,
  401. ];
  402. //foreach ($detail as $key => $value) {
  403. // if (empty($value)) {
  404. //$detail[$key] = (object)[]; // 转成 stdClass 对象
  405. //}
  406. //}
  407. return $detail;
  408. }
  409. public function dailyDwOrderDel($data, $user){
  410. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  411. try {
  412. DB::beginTransaction();
  413. $time = time();
  414. $month = DailyDwOrder::where('del_time',0)
  415. ->whereIn('id',$data['id'])
  416. ->pluck('order_time')
  417. ->toArray();
  418. //归档
  419. list($status, $msg) = ArchiveService::isArchive($month, $user);
  420. if(! $status) return [false, $msg];
  421. DailyDwOrder::where('del_time',0)
  422. ->whereIn('id',$data['id'])
  423. ->update(['del_time' => $time]);
  424. DailyDwOrderDetails::where('del_time',0)
  425. ->whereIn('main_id', $data['id'])
  426. ->update(['del_time' => $time]);
  427. DB::commit();
  428. }catch (\Exception $exception){
  429. DB::rollBack();
  430. return [false,$exception->getMessage()];
  431. }
  432. return [true, ''];
  433. }
  434. public function dailyDwOrderDetail($data, $user){
  435. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  436. $customer = DailyDwOrder::where('del_time',0)
  437. ->where('id',$data['id'])
  438. ->first();
  439. if(empty($customer)) return [false,'设备日工时单不存在或已被删除'];
  440. $customer = $customer->toArray();
  441. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  442. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  443. $item = Item::where('id', $customer['item_id'])->first();
  444. $customer['item_title'] = $item->title;
  445. $customer['item_code'] = $item->code;
  446. $map = ArchiveService::fillIsArchive($customer['order_time'], $user);
  447. $customer['is_archive'] = $map[$customer['order_time']] ?? false;
  448. $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
  449. $details = $this->getDetailDaily($data['id']);
  450. $customer = array_merge($customer, $details);
  451. return [true, $customer];
  452. }
  453. public function dailyDwOrderCommon($data,$user, $field = []){
  454. if(empty($field)) $field = DailyDwOrder::$field;
  455. $model = DailyDwOrder::Clear($user,$data);
  456. $model = $model->where('del_time',0)
  457. ->select($field)
  458. ->orderby('id', 'desc');
  459. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  460. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  461. $model->where('order_time','>=',$return[0]);
  462. $model->where('order_time','<=',$return[1]);
  463. }
  464. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  465. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  466. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  467. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  468. $model->where('crt_time','>=',$return[0]);
  469. $model->where('crt_time','<=',$return[1]);
  470. }
  471. if (!empty($data['item_title'])) {
  472. $models = Item::TopClear($user,$data);
  473. $id = $models->where('del_time',0)
  474. ->where('title', 'LIKE', '%'.$data['item_title'].'%')
  475. ->pluck('id')
  476. ->all();
  477. $model->whereIn('item_id', $id);
  478. }
  479. return $model;
  480. }
  481. public function dailyDwOrderList($data,$user){
  482. $model = $this->dailyDwOrderCommon($data, $user);
  483. $list = $this->limit($model,'',$data);
  484. $list = $this->fillDataDaily($list, $user);
  485. return [true, $list];
  486. }
  487. public function dailyDwOrderRule(&$data, $user, $is_add = true){
  488. $data['top_depart_id'] = $user['top_depart_id'];
  489. if(empty($data['order_time'])) return [false, '单据日期不能为空'];
  490. $data['order_time'] = $this->changeDateToDate($data['order_time']);
  491. $orderTime = $data['order_time'];
  492. $itemId = $data['item_id'] ?? 0;
  493. //归档
  494. list($status, $msg) = ArchiveService::isArchive($data['order_time'], $user);
  495. if(! $status) return [false, $msg];
  496. if(empty($itemId)) return [false, '项目不能为空'];
  497. $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
  498. if(!$bool) return [false, '项目不存在或已被删除'];
  499. if(empty($data['details'])) return [false, '设备日工时单明细不能为空'];
  500. // --- 1. 批量预获取人员信息,用于报错提示 ---
  501. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'device_id')));
  502. $empDisplayMap = Device::whereIn('id', $allEmpIds)
  503. ->get(['id', 'code', 'title'])
  504. ->mapWithKeys(function($item){
  505. return [$item->id => "[{$item->code}]{$item->title}"];
  506. })->toArray();
  507. // 2. 本次提交内部重叠记录
  508. $internalOverlap = [];
  509. foreach ($data['details'] as $key => $value){
  510. $line = $key + 1;
  511. $t = "第" . $line . "行";
  512. $empId = $value['device_id'] ?? 0;
  513. if(empty($empId)) return [false, '设备不能为空'];
  514. $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
  515. // 校验数字有效性
  516. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  517. if(!$res['valid']) return [false, $t . "设备{$empName}开始点:" . $res['error']];
  518. if($value['start_time_hour'] > 23) return [false, false, $t . "设备{$empName}开始点不合法"];
  519. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  520. if(!$res['valid']) return [false, $t ."设备{$empName}开始分:" . $res['error']];
  521. if($value['start_time_min'] > 60) return [false, false, $t . "设备{$empName}开始点不合法"];
  522. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  523. if(!$res['valid']) return [false, $t ."设备{$empName}结束点:" . $res['error']];
  524. if($value['end_time_hour'] > 24) return [false, false, $t . "设备{$empName}结束点不合法"];
  525. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  526. if(!$res['valid']) return [false, $t ."设备{$empName}结束分:" . $res['error']];
  527. if($value['end_time_min'] > 60) return [false, false, $t . "设备{$empName}结束分不合法"];
  528. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  529. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  530. if ($currentStart >= $currentEnd) {
  531. return [false, $t . "设备{$empName}:开始时间必须早于结束时间"];
  532. }
  533. // --- 新增:总分钟数校验 ---
  534. $calculatedTotal = $currentEnd - $currentStart;
  535. if (!isset($value['total_work_min']) || intval($value['total_work_min']) !== $calculatedTotal) {
  536. return [false, $t . "设备{$empName}:工时计算有误,应为 {$calculatedTotal} 分钟"];
  537. }
  538. // --- 3. 内部重叠校验(防止一次提交多行重复) ---
  539. if (isset($internalOverlap[$empId])) {
  540. foreach ($internalOverlap[$empId] as $period) {
  541. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  542. return [false, "设备{$empName}在本次提交的多行明细中时间段重叠"];
  543. }
  544. }
  545. }
  546. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  547. $query = DB::table('daily_dw_order_details as d')
  548. ->join('daily_dw_order as m', 'd.main_id', '=', 'm.id')
  549. ->where('m.top_depart_id', $data['top_depart_id'])
  550. ->where('m.order_time', $orderTime)
  551. ->where('m.item_id', $itemId)
  552. ->where('d.device_id', $empId)
  553. ->where('m.del_time', 0)
  554. ->where('d.del_time', 0);
  555. if (!$is_add && !empty($data['id'])) {
  556. $query->where('m.id', '<>', $data['id']);
  557. }
  558. $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
  559. foreach ($existingPeriods as $p) {
  560. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  561. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  562. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  563. return [false, "设备{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
  564. }
  565. }
  566. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  567. }
  568. if(!$is_add){
  569. if(empty($data['id'])) return [false,'ID不能为空'];
  570. $bool = DailyDwOrder::where('top_depart_id', $data['top_depart_id'])
  571. ->where('id',$data['id'])
  572. ->where('del_time',0)
  573. ->exists();
  574. if(!$bool) return [false, '设备日工时单不存在或已被删除'];
  575. }
  576. return [true, ''];
  577. }
  578. public function fillDataDaily($data, $user){
  579. if(empty($data['data'])) return $data;
  580. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  581. $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_id')));
  582. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'order_time')), $user);
  583. foreach ($data['data'] as $key => $value){
  584. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  585. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  586. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  587. $item_tmp = $item[$value['item_id']] ?? [];
  588. $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
  589. $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
  590. $data['data'][$key]['is_archive'] = $map[$value['order_time']] ?? false;
  591. }
  592. return $data;
  593. }
  594. public function fillDataForExportDaily($data, $column, &$return)
  595. {
  596. if (empty($data)) return;
  597. $mainIds = array_column($data, 'id');
  598. // 1. 获取详情及所有关联档案(项目、设备)的映射
  599. $detailsMap = $this->getDwDailyDetailsMap($mainIds, $data);
  600. foreach ($data as $main) {
  601. $mainId = $main['id'];
  602. $details = $detailsMap[$mainId] ?? [];
  603. // 2. 提取并格式化主表共有信息
  604. $mainInfo = [
  605. 'code' => $main['code'],
  606. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  607. ];
  608. if (empty($details)) {
  609. // 无明细时只导出一行主表信息
  610. $tempRow = [];
  611. foreach ($column as $col) {
  612. $tempRow[] = $mainInfo[$col] ?? '';
  613. }
  614. $return[] = $tempRow;
  615. } else {
  616. // 3. 平铺:将设备明细信息、项目信息与主表信息合并
  617. foreach ($details as $sub) {
  618. $fullRowData = array_merge($mainInfo, $sub);
  619. $tempRow = [];
  620. foreach ($column as $col) {
  621. $tempRow[] = $fullRowData[$col] ?? '';
  622. }
  623. $return[] = $tempRow;
  624. }
  625. }
  626. }
  627. }
  628. public function getDwDailyDetailsMap($mainIds, $mainData)
  629. {
  630. // 1. 获取设备工时子表记录
  631. $details = DB::table('daily_dw_order_details')
  632. ->where('del_time', 0)
  633. ->whereIn('main_id', $mainIds)
  634. ->get();
  635. // 2. 提取关联 ID(设备 ID 和 项目 ID)
  636. $deviceIds = $details->pluck('device_id')->unique();
  637. $itemIds = array_unique(array_column($mainData, 'item_id'));
  638. // 3. 批量获取设备档案和项目档案
  639. $deviceMap = DB::table('device')
  640. ->whereIn('id', $deviceIds)
  641. ->get(['id', 'title', 'code'])
  642. ->keyBy('id');
  643. $itemMap = DB::table('item')
  644. ->whereIn('id', $itemIds)
  645. ->get(['id', 'title', 'code'])
  646. ->keyBy('id');
  647. // 4. 预挂载主表的项目信息(item_code, item_title)
  648. $mainItemInfo = [];
  649. foreach ($mainData as $m) {
  650. $proj = $itemMap[$m['item_id']] ?? null;
  651. $mainItemInfo[$m['id']] = [
  652. 'item_code' => $proj ? $proj->code : '',
  653. 'item_title' => $proj ? $proj->title : '',
  654. ];
  655. }
  656. $res = [];
  657. // 如果没有详情,初始化空结构
  658. if ($details->isEmpty()) {
  659. foreach ($mainItemInfo as $mId => $info) {
  660. $res[$mId] = [];
  661. }
  662. return $res;
  663. }
  664. // 5. 循环子表,合并设备档案信息
  665. foreach ($details as $item) {
  666. $device = $deviceMap[$item->device_id] ?? null;
  667. $detailRow = [
  668. // 设备信息(对应 Excel 配置中的 key)
  669. 'device_code' => $device ? $device->code : '',
  670. 'device_title' => $device ? $device->title : '',
  671. // 时间信息
  672. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  673. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  674. // 项目信息(由主表平铺而来)
  675. 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
  676. 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
  677. ];
  678. $res[$item->main_id][] = $detailRow;
  679. }
  680. return $res;
  681. }
  682. public function dailyDwOrderCreate($data, $user)
  683. {
  684. $topDepartId = $user['top_depart_id'];
  685. if (empty($data['month'])) return [false, '月份不能为空'];
  686. $monthStart = $this->changeDateToDate($data['month']);
  687. // --- 前置核心校验 ---
  688. // 1. 校验设备月度明细是否存在
  689. $hasMonthly = DB::table('monthly_dw_order_details as d')
  690. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  691. ->where('m.month', $monthStart)
  692. ->where('m.top_depart_id', $topDepartId)
  693. ->where('m.del_time', 0)
  694. ->exists();
  695. if (!$hasMonthly) return [false, '未找到该月份的设备月度工时明细'];
  696. // 2. 校验设备项目分配规则
  697. $hasRules = DB::table('rule_set as r')
  698. ->where('r.month', $monthStart)
  699. ->where('r.top_depart_id', $topDepartId)
  700. ->where('r.del_time', 0)
  701. ->exists();
  702. if (!$hasRules) return [false, '未找到该月份的项目比例规则设置'];
  703. // 3. 校验工作日历
  704. $hasCalendar = DB::table('calendar_details')
  705. ->where('month', $monthStart)
  706. ->where('is_work', 1)
  707. ->where('del_time', 0)
  708. ->exists();
  709. if (!$hasCalendar) return [false, '该月份未配置工作日历'];
  710. $data['type'] = 'd_work';
  711. ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
  712. return [true, '设备工时生成任务已提交,请稍后查看结果'];
  713. }
  714. public function dailyDwOrderCreateMain($data, $user)
  715. {
  716. $topDepartId = $user['top_depart_id'];
  717. if (empty($data['month'])) return [false, '月份不能为空'];
  718. $monthStart = $this->changeDateToDate($data['month']);
  719. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  720. $now = time();
  721. DB::beginTransaction();
  722. try {
  723. // --- 0. 清理旧数据 ---
  724. $oldOrderIds = DB::table('daily_dw_order')
  725. ->where('top_depart_id', $topDepartId)
  726. ->where('order_time', '>=', $monthStart)
  727. ->where('order_time', '<=', $monthEnd)
  728. ->where('is_create', 1)
  729. ->where('del_time', 0)
  730. ->pluck('id');
  731. if ($oldOrderIds->isNotEmpty()) {
  732. DB::table('daily_dw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  733. DB::table('daily_dw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  734. }
  735. // --- 1. 基础数据预加载 ---
  736. // 月度设备工时明细
  737. $monthlyOrder = DB::table('monthly_dw_order_details as d')
  738. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  739. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  740. ->where('m.del_time', 0)->where('d.del_time', 0)
  741. ->select('d.*')->get();
  742. if ($monthlyOrder->isEmpty()) return [false, '未找到设备月度工时明细'];
  743. // 设备项目分配比例 (与人员类似,但通常关联 device_id)
  744. $ruleSet = DB::table('rule_set_details as rd')
  745. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  746. ->where('r.month', $monthStart)
  747. ->where('rd.type', RuleSetDetails::type_two) // 假设 type_two 是设备类型
  748. ->where('r.del_time', 0)->where('rd.del_time', 0)
  749. ->select('rd.*')->get()->groupBy('data_id');
  750. // 标准工作时段 (设备通常只走公司标准时段)
  751. $standardWorkRanges = DB::table('work_range_details')
  752. ->where('top_depart_id', $topDepartId)
  753. ->where('del_time', 0)
  754. ->get();
  755. // 工作日历
  756. $workDays = DB::table('calendar_details')
  757. ->where('month', $monthStart)
  758. ->where('is_work', CalendarDetails::TYPE_ONE)
  759. ->where('del_time', 0)
  760. ->orderBy('time', 'asc')
  761. ->get();
  762. if ($workDays->isEmpty()) return [false, '未配置工作日历,无法分配设备工时'];
  763. // --- 2. 核心分配逻辑 ---
  764. $finalAlloc = [];
  765. foreach ($monthlyOrder as $mDetail) {
  766. $deviceId = $mDetail->device_id;
  767. $deviceRules = $ruleSet->get($deviceId);
  768. if (!$deviceRules) continue;
  769. $remainingMin = (float)$mDetail->rd_total_hours * 60;
  770. if ($remainingMin <= 0) continue;
  771. foreach ($workDays as $dayInfo) {
  772. if ($remainingMin <= 0) break;
  773. // 计算当天设备最大可用分钟 (标准时段总和)
  774. $dayMaxAvail = $standardWorkRanges->sum('total_work_min');
  775. $canAllocToday = min($remainingMin, $dayMaxAvail);
  776. foreach ($deviceRules as $rule) {
  777. $rate = (float)$rule->rate / 100;
  778. $projectMin = $canAllocToday * $rate;
  779. if ($projectMin > 0) {
  780. $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = ($finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] ?? 0) + $projectMin;
  781. }
  782. }
  783. $remainingMin -= $canAllocToday;
  784. }
  785. }
  786. // --- 3. 生成单据并填充时段 (防重叠) ---
  787. $newOrderIds = [];
  788. $dailyDevicePools = []; // 追踪每台设备每天的时间消耗情况
  789. foreach ($finalAlloc as $dayTs => $projects) {
  790. foreach ($projects as $itemId => $devices) {
  791. $mainId = DB::table('daily_dw_order')->insertGetId([
  792. 'code' => '',
  793. 'item_id' => $itemId,
  794. 'order_time' => $dayTs,
  795. 'top_depart_id' => $topDepartId,
  796. 'is_create' => 1,
  797. 'crt_id' => $user['id'],
  798. 'crt_time' => $now,
  799. 'upd_time' => $now,
  800. ]);
  801. $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
  802. foreach ($devices as $deviceId => $toAllocMin) {
  803. // 初始化该设备当天的时段池 (仅由标准时段构成)
  804. if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
  805. $pool = [];
  806. foreach ($standardWorkRanges as $swr) {
  807. $pool[] = [
  808. 's' => $swr->start_time_hour * 60 + $swr->start_time_min,
  809. 'e' => $swr->end_time_hour * 60 + $swr->end_time_min
  810. ];
  811. }
  812. $dailyDevicePools[$dayTs][$deviceId] = $pool;
  813. }
  814. $tempRem = $toAllocMin;
  815. foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
  816. if ($tempRem <= 0) break;
  817. $pMax = $p['e'] - $p['s'];
  818. if ($pMax <= 0) continue;
  819. $take = min($tempRem, $pMax);
  820. $start = $p['s'];
  821. $end = $p['s'] + $take;
  822. DB::table('daily_dw_order_details')->insert([
  823. 'main_id' => $mainId,
  824. 'device_id' => $deviceId,
  825. 'top_depart_id' => $topDepartId,
  826. 'start_time_hour' => floor($start / 60),
  827. 'start_time_min' => $start % 60,
  828. 'end_time_hour' => floor($end / 60),
  829. 'end_time_min' => $end % 60,
  830. 'total_work_min' => $take,
  831. 'crt_time' => $now,
  832. 'upd_time' => $now,
  833. ]);
  834. $tempRem -= $take;
  835. $p['s'] = $end; // 指针后移,防重叠
  836. }
  837. }
  838. }
  839. }
  840. // --- 4. 回填单号 ---
  841. if (empty($newOrderIds)) return [false, '未生成任何设备日工时单'];
  842. foreach ($newOrderIds as $item) {
  843. $code = $this->generateBillNo([
  844. 'top_depart_id' => $topDepartId,
  845. 'type' => DailyDwOrder::Order_type, // 确保模型中定义了此常量
  846. 'period' => date("Ym", $item['time'])
  847. ]);
  848. DB::table('daily_dw_order')->where('id', $item['id'])->update(['code' => $code]);
  849. }
  850. DB::commit();
  851. } catch (\Exception $e) {
  852. DB::rollBack();
  853. return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
  854. }
  855. return [true, ''];
  856. }
  857. public function dailyDwOrderPreview($data, $user)
  858. {
  859. $topDepartId = $user['top_depart_id'];
  860. if (empty($data['month'])) return [false, '月份不能为空'];
  861. $monthStart = $this->changeDateToDate($data['month']);
  862. //归档
  863. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  864. if(! $status) return [false, $msg];
  865. // 调用核心计算逻辑
  866. $result = $this->calculateDailyDeviceAllocation($monthStart, $topDepartId, $user);
  867. if (!$result['status']) return [false, $result['msg']];
  868. return [true, [
  869. 'list' => $result['data'] // 返回给前端预览
  870. ]];
  871. }
  872. private function calculateDailyDeviceAllocation1($monthStart, $topDepartId, $user)
  873. {
  874. // 加载月度设备明细
  875. $monthlyOrder = DB::table('monthly_dw_order_details as d')
  876. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  877. ->where('m.month', $monthStart)
  878. ->where('m.top_depart_id', $topDepartId)
  879. ->where('m.del_time', 0)
  880. ->where('d.del_time', 0)
  881. ->select('d.*')
  882. ->get();
  883. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到设备月度工时明细'];
  884. $usedDeviceIds = $monthlyOrder->pluck('device_id')->unique()->toArray();
  885. $deviceMap = DB::table('device')
  886. ->whereIn('id', $usedDeviceIds)
  887. ->pluck('title', 'id')
  888. ->toArray();
  889. // 加载分配规则
  890. $ruleSet = DB::table('rule_set_details as rd')
  891. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  892. ->where('r.month', $monthStart)
  893. ->where('rd.type', 2) // 设备类型
  894. ->where('rd.top_depart_id', $topDepartId)
  895. ->where('r.del_time', 0)
  896. ->where('rd.del_time', 0)
  897. ->select('rd.*')
  898. ->get();
  899. $usedItemIds = $ruleSet->pluck('item_id')->unique()->toArray();
  900. $itemMap = DB::table('item')
  901. ->whereIn('id', $usedItemIds)
  902. ->pluck('title', 'id')
  903. ->toArray();
  904. $ruleSetGrouped = $ruleSet->groupBy('data_id');
  905. // 标准班次 & 日历
  906. $standardWorkRanges = DB::table('work_range_details')
  907. ->where('top_depart_id', $topDepartId)
  908. ->where('del_time', 0)
  909. ->get();
  910. $dayMaxAvail = (int)$standardWorkRanges->sum('total_work_min');
  911. $workDays = DB::table('calendar_details')
  912. ->where('top_depart_id', $topDepartId)
  913. ->where('month', $monthStart)
  914. ->where('is_work', 1)
  915. ->where('del_time', 0)
  916. ->orderBy('time', 'asc')->get();
  917. if ($workDays->isEmpty()) return ['status' => false, 'msg' => '未配置工作日历'];
  918. // --- 2. 阶段一:计算每天每台设备分配的项目分钟数 (保持原逻辑) ---
  919. $finalAlloc = [];
  920. foreach ($monthlyOrder as $mDetail) {
  921. $deviceId = $mDetail->device_id;
  922. $deviceRules = $ruleSetGrouped->get($deviceId);
  923. if (!$deviceRules) continue;
  924. $remainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  925. if ($remainingMin <= 0) continue;
  926. foreach ($workDays as $dayInfo) {
  927. if ($remainingMin <= 0) break;
  928. $canAllocToday = min($remainingMin, $dayMaxAvail);
  929. $allocatedInDay = 0;
  930. $ruleCount = count($deviceRules);
  931. foreach ($deviceRules as $index => $rule) {
  932. $rate = (float)$rule->rate / 100;
  933. if ($index === $ruleCount - 1) {
  934. $projectMin = $canAllocToday - $allocatedInDay;
  935. } else {
  936. $projectMin = (int)round($canAllocToday * $rate);
  937. }
  938. if ($projectMin > 0) {
  939. $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = $projectMin;
  940. $allocatedInDay += $projectMin;
  941. }
  942. }
  943. $remainingMin -= $canAllocToday;
  944. }
  945. }
  946. // --- 3. 阶段二:生成预览行并对齐 30 分钟 ---
  947. $previewList = [];
  948. $dailyDevicePools = [];
  949. $tempMainIdCounter = 1;
  950. $step = 30; // 步长
  951. foreach ($finalAlloc as $dayTs => $projects) {
  952. foreach ($projects as $itemId => $devices) {
  953. $currentTempMainId = $tempMainIdCounter++;
  954. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  955. foreach ($devices as $deviceId => $toAllocMin) {
  956. if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
  957. $pool = [];
  958. foreach ($standardWorkRanges as $swr) {
  959. $pool[] = [
  960. 's' => (int)($swr->start_time_hour * 60 + $swr->start_time_min),
  961. 'e' => (int)($swr->end_time_hour * 60 + $swr->end_time_min)
  962. ];
  963. }
  964. $dailyDevicePools[$dayTs][$deviceId] = $pool;
  965. }
  966. $tempRem = (int)$toAllocMin;
  967. foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
  968. if ($tempRem <= 0) break;
  969. // 【改动】起始点对齐:非30分钟整点则向上对齐
  970. if ($p['s'] % $step != 0) {
  971. $p['s'] = ceil($p['s'] / $step) * $step;
  972. }
  973. $pMax = (int)($p['e'] - $p['s']);
  974. if ($pMax <= 0) continue;
  975. // 【改动】取量对齐逻辑
  976. if ($tempRem >= $step) {
  977. // 尽量按步长分配
  978. $take = min(floor($tempRem / $step) * $step, floor($pMax / $step) * $step);
  979. if ($take <= 0) continue;
  980. } else {
  981. // 最后一丁点零头
  982. $take = min($tempRem, $pMax);
  983. }
  984. $start = (int)$p['s'];
  985. $end = $start + $take;
  986. $previewList[] = [
  987. 'temp_main_id' => $currentTempMainId,
  988. 'order_time' => date('Y-m-d', $dayTs),
  989. 'order_timestamp' => $dayTs,
  990. 'item_id' => $itemId,
  991. 'item_title' => $itemTitle,
  992. 'device_id' => $deviceId,
  993. 'device_title' => $deviceMap[$deviceId] ?? '未知设备',
  994. 'start_time' => sprintf('%02d:%02d', floor($start / 60), $start % 60),
  995. 'end_time' => sprintf('%02d:%02d', floor($end / 60), $end % 60),
  996. 'start_hour' => (int)floor($start / 60),
  997. 'start_min' => (int)($start % 60),
  998. 'end_hour' => (int)floor($end / 60),
  999. 'end_min' => (int)($end % 60),
  1000. 'total_work_min' => $take,
  1001. ];
  1002. $tempRem -= $take;
  1003. $p['s'] = $end;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. return ['status' => true, 'data' => $previewList];
  1009. }
  1010. private function calculateDailyDeviceAllocation($monthStart, $topDepartId, $user)
  1011. {
  1012. // 1. 加载月度设备明细
  1013. $monthlyOrder = DB::table('monthly_dw_order_details as d')
  1014. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  1015. ->where('m.month', $monthStart)
  1016. ->where('m.top_depart_id', $topDepartId)
  1017. ->where('m.del_time', 0)
  1018. ->where('d.del_time', 0)
  1019. ->select('d.*')
  1020. ->get();
  1021. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到设备月度工时明细'];
  1022. $usedDeviceIds = $monthlyOrder->pluck('device_id')->unique()->toArray();
  1023. $deviceMap = DB::table('device')
  1024. ->whereIn('id', $usedDeviceIds)
  1025. ->pluck('title', 'id')
  1026. ->toArray();
  1027. // 加载分配规则
  1028. $ruleSet = DB::table('rule_set_details as rd')
  1029. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  1030. ->where('r.month', $monthStart)
  1031. ->where('rd.type', 2) // 设备类型
  1032. ->where('rd.top_depart_id', $topDepartId)
  1033. ->where('r.del_time', 0)
  1034. ->where('rd.del_time', 0)
  1035. ->select('rd.*')
  1036. ->get();
  1037. $usedItemIds = $ruleSet->pluck('item_id')->unique()->toArray();
  1038. $itemMap = DB::table('item')
  1039. ->whereIn('id', $usedItemIds)
  1040. ->pluck('title', 'id')
  1041. ->toArray();
  1042. $ruleSetGrouped = $ruleSet->groupBy('data_id');
  1043. // 标准班次 & 日历
  1044. $standardWorkRanges = DB::table('work_range_details')
  1045. ->where('top_depart_id', $topDepartId)
  1046. ->where('del_time', 0)
  1047. ->get();
  1048. // 【关键改动】让标准班次的可用时间,天然就是30分钟的整数倍(向下取整,确保格子规整)
  1049. $step = 30;
  1050. $dayMaxAvail = 0;
  1051. $cleanWorkRanges = [];
  1052. foreach ($standardWorkRanges as $swr) {
  1053. $s = (int)($swr->start_time_hour * 60 + $swr->start_time_min);
  1054. $e = (int)($swr->end_time_hour * 60 + $swr->end_time_min);
  1055. // 起始点对齐
  1056. if ($s % $step != 0) $s = (int)ceil($s / $step) * $step;
  1057. if ($e % $step != 0) $e = (int)floor($e / $step) * $step;
  1058. if ($e > $s) {
  1059. $cleanWorkRanges[] = ['s' => $s, 'e' => $e];
  1060. $dayMaxAvail += ($e - $s);
  1061. }
  1062. }
  1063. $workDays = DB::table('calendar_details')
  1064. ->where('top_depart_id', $topDepartId)
  1065. ->where('month', $monthStart)
  1066. ->where('is_work', 1)
  1067. ->where('del_time', 0)
  1068. ->orderBy('time', 'asc')->get();
  1069. if ($workDays->isEmpty()) return ['status' => false, 'msg' => '未配置工作日历'];
  1070. // --- 2. 阶段一:计算每天每台设备分配的项目分钟数 (加入30分钟对齐无损控制) ---
  1071. $finalAlloc = [];
  1072. foreach ($monthlyOrder as $mDetail) {
  1073. $deviceId = $mDetail->device_id;
  1074. $deviceRules = $ruleSetGrouped->get($deviceId);
  1075. if (!$deviceRules) continue;
  1076. $remainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  1077. if ($remainingMin <= 0) continue;
  1078. foreach ($workDays as $dayInfo) {
  1079. if ($remainingMin <= 0) break;
  1080. // 当天最大可分,必须是30的倍数(最后一天除外,最后一天要把零头全部收走)
  1081. $canAllocToday = min($remainingMin, $dayMaxAvail);
  1082. // 确保非最后一天的日额度也是30的倍数
  1083. if ($remainingMin > $dayMaxAvail && $canAllocToday % $step != 0) {
  1084. $canAllocToday = (int)floor($canAllocToday / $step) * $step;
  1085. }
  1086. $allocatedInDay = 0;
  1087. $ruleCount = count($deviceRules);
  1088. foreach ($deviceRules as $index => $rule) {
  1089. if ($index === $ruleCount - 1) {
  1090. // 最后一个项目拿走今天剩下的所有分钟
  1091. $projectMin = $canAllocToday - $allocatedInDay;
  1092. } else {
  1093. $rate = (float)$rule->rate / 100;
  1094. // 【优化】计算出来的项目时间,直接四舍五入到最近的30分钟整数倍
  1095. $rawMin = $canAllocToday * $rate;
  1096. $projectMin = (int)round($rawMin / $step) * $step;
  1097. }
  1098. // 防止四舍五入爆池子
  1099. if ($allocatedInDay + $projectMin > $canAllocToday) {
  1100. $projectMin = $canAllocToday - $allocatedInDay;
  1101. }
  1102. if ($projectMin > 0) {
  1103. $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = $projectMin;
  1104. $allocatedInDay += $projectMin;
  1105. }
  1106. }
  1107. $remainingMin -= $allocatedInDay; // 减去实际扣减的,确保闭环
  1108. }
  1109. // 【大招:溢出工时补偿】如果日历天数走完了,因为设备加班导致 remainingMin 还有剩
  1110. // 将剩下的零头,强行追加分配到有空间的最后几天里,确保总工时 168 小时一分不差
  1111. if ($remainingMin > 0) {
  1112. foreach (array_reverse($workDays->toArray()) as $dayInfo) {
  1113. if ($remainingMin <= 0) break;
  1114. // 找到该设备当天已分配的总量
  1115. $todayAllocated = 0;
  1116. foreach ($finalAlloc[$dayInfo->time] ?? [] as $itemId => $devs) {
  1117. $todayAllocated += $devs[$deviceId] ?? 0;
  1118. }
  1119. // 哪怕超过标准班次,为了不丢工时,硬塞进去(这部分会作为加班在后续无缝拉长)
  1120. $lastRule = $deviceRules->last();
  1121. if ($lastRule) {
  1122. $finalAlloc[$dayInfo->time][$lastRule->item_id][$deviceId] =
  1123. ($finalAlloc[$dayInfo->time][$lastRule->item_id][$deviceId] ?? 0) + $remainingMin;
  1124. $remainingMin = 0;
  1125. }
  1126. }
  1127. }
  1128. }
  1129. // --- 3. 阶段二:生成预览行 (采用无缝滑行指针,杜绝截断丢弃) ---
  1130. $previewList = [];
  1131. $dailyDevicePools = [];
  1132. $tempMainIdCounter = 1;
  1133. foreach ($finalAlloc as $dayTs => $projects) {
  1134. foreach ($projects as $itemId => $devices) {
  1135. $currentTempMainId = $tempMainIdCounter++;
  1136. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  1137. foreach ($devices as $deviceId => $toAllocMin) {
  1138. if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
  1139. // 初始化这台设备今天的标准班次池
  1140. $dailyDevicePools[$dayTs][$deviceId] = $cleanWorkRanges;
  1141. }
  1142. $tempRem = (int)$toAllocMin;
  1143. // 1. 先尝试塞进标准班次
  1144. foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
  1145. if ($tempRem <= 0) break;
  1146. $pMax = $p['e'] - $p['s'];
  1147. if ($pMax <= 0) continue;
  1148. $take = min($tempRem, $pMax);
  1149. $start = (int)$p['s'];
  1150. $end = $start + $take;
  1151. $previewList[] = $this->buildPreviewRow(
  1152. $currentTempMainId, $dayTs, $itemId, $itemTitle,
  1153. $deviceId, $deviceMap[$deviceId] ?? '未知设备', $start, $end, $take
  1154. );
  1155. $tempRem -= $take;
  1156. $p['s'] = $end; // 指针平移
  1157. }
  1158. // 2. 【关键安全阀】如果标准班次格子全满了,但 tempRem 还有剩(说明设备在冲刺加班)
  1159. // 绝对不能扔掉!从当天的最后一个结束时间开始,无上限往后顺延生成“加班行”
  1160. if ($tempRem > 0) {
  1161. // 找到当天的最后落点,如果连标准班次都没有,默认从 18:00 (1080) 开始无缝排
  1162. $lastEnd = 1080;
  1163. if (!empty($cleanWorkRanges)) {
  1164. $lastEnd = end($cleanWorkRanges)['e'];
  1165. }
  1166. // 看看之前有没有已经排上去的加班,有的话紧跟其后
  1167. if (isset($dailyDevicePools[$dayTs][$deviceId]['overtime_last_end'])) {
  1168. $lastEnd = $dailyDevicePools[$dayTs][$deviceId]['overtime_last_end'];
  1169. }
  1170. $start = $lastEnd;
  1171. $end = $start + $tempRem;
  1172. $previewList[] = $this->buildPreviewRow(
  1173. $currentTempMainId, $dayTs, $itemId, $itemTitle,
  1174. $deviceId, $deviceMap[$deviceId] ?? '未知设备', $start, $end, $tempRem
  1175. );
  1176. // 记录该设备今天最新的加班落点
  1177. $dailyDevicePools[$dayTs][$deviceId]['overtime_last_end'] = $end;
  1178. $tempRem = 0;
  1179. }
  1180. }
  1181. }
  1182. }
  1183. return ['status' => true, 'data' => $previewList];
  1184. }
  1185. /**
  1186. * 辅助抽离:组装预览行数据
  1187. */
  1188. private function buildPreviewRow($tempMainId, $dayTs, $itemId, $itemTitle, $deviceId, $deviceTitle, $start, $end, $take)
  1189. {
  1190. return [
  1191. 'temp_main_id' => $tempMainId,
  1192. 'order_time' => date('Y-m-d', $dayTs),
  1193. 'order_timestamp' => $dayTs,
  1194. 'item_id' => $itemId,
  1195. 'item_title' => $itemTitle,
  1196. 'device_id' => $deviceId,
  1197. 'device_title' => $deviceTitle,
  1198. 'start_time' => sprintf('%02d:%02d', floor($start / 60), $start % 60),
  1199. 'end_time' => sprintf('%02d:%02d', floor($end / 60), $end % 60),
  1200. 'start_hour' => (int)floor($start / 60),
  1201. 'start_min' => (int)($start % 60),
  1202. 'end_hour' => (int)floor($end / 60),
  1203. 'end_min' => (int)($end % 60),
  1204. 'total_work_min' => $take,
  1205. ];
  1206. }
  1207. public function dailyDwOrderSave($data, $user)
  1208. {
  1209. $list = $data['list'] ?? [];
  1210. if (empty($list)) return [false, '提交数据不能为空'];
  1211. $topDepartId = $user['top_depart_id'];
  1212. $month = $data['month']; // 格式如: "2026-03"
  1213. $monthStart = $this->changeDateToDate($month);
  1214. //归档
  1215. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  1216. if(! $status) return [false, $msg];
  1217. $now = time();
  1218. // 1. 预加载映射
  1219. $deviceIds = collect($list)->pluck('device_id')->unique()->toArray();
  1220. $deviceMap = DB::table('device')->whereIn('id', $deviceIds)->pluck('title', 'id')->toArray();
  1221. // 2. 重新分组并记录行号
  1222. $groupedByOrder = [];
  1223. foreach ($list as $index => $item) {
  1224. $item['_line'] = $index + 1;
  1225. $groupKey = $item['order_time'] . '_' . $item['item_id'];
  1226. $groupedByOrder[$groupKey][] = $item;
  1227. }
  1228. $deviceTimeline = [];
  1229. DB::beginTransaction();
  1230. try {
  1231. // A. 清理旧数据
  1232. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  1233. $oldOrderIds = DB::table('daily_dw_order')
  1234. ->where('top_depart_id', $topDepartId)
  1235. ->whereBetween('order_time', [$monthStart, $monthEnd])
  1236. ->where('del_time', 0)
  1237. ->pluck('id');
  1238. if ($oldOrderIds->isNotEmpty()) {
  1239. DB::table('daily_dw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  1240. DB::table('daily_dw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  1241. }
  1242. // B. 遍历重组后的分组
  1243. foreach ($groupedByOrder as $details) {
  1244. $first = $details[0];
  1245. $orderTimestamp = strtotime($first['order_time']);
  1246. $itemId = $first['item_id'];
  1247. $mainId = DB::table('daily_dw_order')->insertGetId([
  1248. 'code' => '',
  1249. 'item_id' => $itemId,
  1250. 'order_time' => $orderTimestamp,
  1251. 'top_depart_id' => $topDepartId,
  1252. 'is_create' => 1,
  1253. 'crt_id' => $user['id'],
  1254. 'crt_time' => $now,
  1255. ]);
  1256. $insertDetails = [];
  1257. foreach ($details as $d) {
  1258. $rowNum = $d['_line'];
  1259. $devId = $d['device_id'];
  1260. $devName = $deviceMap[$devId] ?? "设备(ID:{$devId})";
  1261. // --- 新增:校验 order_time 是否属于当前选择的 month ---
  1262. if (date("Y-m", strtotime($d['order_time'])) !== $month) {
  1263. return [false, "第 {$rowNum} 行:日期[{$d['order_time']}]不属于保存月份[{$month}],请修正!"];
  1264. }
  1265. $s = (int)$d['start_hour'] * 60 + (int)$d['start_min'];
  1266. $e = (int)$d['end_hour'] * 60 + (int)$d['end_min'];
  1267. $calcTotalMin = $e - $s;
  1268. if ($calcTotalMin <= 0) {
  1269. return [false, "第 {$rowNum} 行:设备[{$devName}]在[{$d['order_time']}]的结束时间必须晚于开始时间"];
  1270. }
  1271. // 冲突校验
  1272. $dateStr = $d['order_time'];
  1273. if (isset($deviceTimeline[$devId][$dateStr])) {
  1274. foreach ($deviceTimeline[$devId][$dateStr] as $exist) {
  1275. if ($s < $exist['e'] && $e > $exist['s']) {
  1276. return [false, "第 {$rowNum} 行:设备[{$devName}]在[{$dateStr}]存在时间冲突({$d['start_time']}-{$d['end_time']})"];
  1277. }
  1278. }
  1279. }
  1280. $deviceTimeline[$devId][$dateStr][] = ['s' => $s, 'e' => $e];
  1281. $insertDetails[] = [
  1282. 'main_id' => $mainId,
  1283. 'device_id' => $devId,
  1284. 'top_depart_id' => $topDepartId,
  1285. 'start_time_hour' => $d['start_hour'],
  1286. 'start_time_min' => $d['start_min'],
  1287. 'end_time_hour' => $d['end_hour'],
  1288. 'end_time_min' => $d['end_min'],
  1289. 'total_work_min' => $calcTotalMin,
  1290. 'crt_time' => $now,
  1291. 'order_time' => $orderTimestamp,
  1292. 'item_id' => $itemId,
  1293. 'crt_id' => $user['id'],
  1294. ];
  1295. }
  1296. DB::table('daily_dw_order_details')->insert($insertDetails);
  1297. $code = $this->generateBillNo([
  1298. 'top_depart_id' => $topDepartId,
  1299. 'type' => DailyDwOrder::Order_type,
  1300. 'period' => date("Ym", $orderTimestamp)
  1301. ]);
  1302. DB::table('daily_dw_order')->where('id', $mainId)->update(['code' => $code]);
  1303. }
  1304. DB::commit();
  1305. return [true, ''];
  1306. } catch (\Exception $e) {
  1307. DB::rollBack();
  1308. return [false, "保存失败:" . $e->getMessage()];
  1309. }
  1310. }
  1311. }