DeviceWorkService.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  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) = MiddleGroundService::checkTimestampInRange($data['order_time'], $data['top_depart_id']);
  495. if(! $status) return [false, $msg];
  496. //归档
  497. list($status, $msg) = ArchiveService::isArchive($data['order_time'], $user);
  498. if(! $status) return [false, $msg];
  499. if(empty($itemId)) return [false, '项目不能为空'];
  500. $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
  501. if(!$bool) return [false, '项目不存在或已被删除'];
  502. if(empty($data['details'])) return [false, '设备日工时单明细不能为空'];
  503. // --- 1. 批量预获取人员信息,用于报错提示 ---
  504. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'device_id')));
  505. $empDisplayMap = Device::whereIn('id', $allEmpIds)
  506. ->get(['id', 'code', 'title'])
  507. ->mapWithKeys(function($item){
  508. return [$item->id => "[{$item->code}]{$item->title}"];
  509. })->toArray();
  510. // 2. 本次提交内部重叠记录
  511. $internalOverlap = [];
  512. foreach ($data['details'] as $key => $value){
  513. $line = $key + 1;
  514. $t = "第" . $line . "行";
  515. $empId = $value['device_id'] ?? 0;
  516. if(empty($empId)) return [false, '设备不能为空'];
  517. $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
  518. // 校验数字有效性
  519. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  520. if(!$res['valid']) return [false, $t . "设备{$empName}开始点:" . $res['error']];
  521. if($value['start_time_hour'] > 23) return [false, false, $t . "设备{$empName}开始点不合法"];
  522. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  523. if(!$res['valid']) return [false, $t ."设备{$empName}开始分:" . $res['error']];
  524. if($value['start_time_min'] > 60) return [false, false, $t . "设备{$empName}开始点不合法"];
  525. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  526. if(!$res['valid']) return [false, $t ."设备{$empName}结束点:" . $res['error']];
  527. if($value['end_time_hour'] > 24) return [false, false, $t . "设备{$empName}结束点不合法"];
  528. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  529. if(!$res['valid']) return [false, $t ."设备{$empName}结束分:" . $res['error']];
  530. if($value['end_time_min'] > 60) return [false, false, $t . "设备{$empName}结束分不合法"];
  531. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  532. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  533. if ($currentStart >= $currentEnd) {
  534. return [false, $t . "设备{$empName}:开始时间必须早于结束时间"];
  535. }
  536. // --- 新增:总分钟数校验 ---
  537. $calculatedTotal = $currentEnd - $currentStart;
  538. if (!isset($value['total_work_min']) || intval($value['total_work_min']) !== $calculatedTotal) {
  539. return [false, $t . "设备{$empName}:工时计算有误,应为 {$calculatedTotal} 分钟"];
  540. }
  541. // --- 3. 内部重叠校验(防止一次提交多行重复) ---
  542. if (isset($internalOverlap[$empId])) {
  543. foreach ($internalOverlap[$empId] as $period) {
  544. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  545. return [false, "设备{$empName}在本次提交的多行明细中时间段重叠"];
  546. }
  547. }
  548. }
  549. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  550. $query = DB::table('daily_dw_order_details as d')
  551. ->join('daily_dw_order as m', 'd.main_id', '=', 'm.id')
  552. ->where('m.top_depart_id', $data['top_depart_id'])
  553. ->where('m.order_time', $orderTime)
  554. ->where('m.item_id', $itemId)
  555. ->where('d.device_id', $empId)
  556. ->where('m.del_time', 0)
  557. ->where('d.del_time', 0);
  558. if (!$is_add && !empty($data['id'])) {
  559. $query->where('m.id', '<>', $data['id']);
  560. }
  561. $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
  562. foreach ($existingPeriods as $p) {
  563. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  564. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  565. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  566. return [false, "设备{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
  567. }
  568. }
  569. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  570. }
  571. if(!$is_add){
  572. if(empty($data['id'])) return [false,'ID不能为空'];
  573. $bool = DailyDwOrder::where('top_depart_id', $data['top_depart_id'])
  574. ->where('id',$data['id'])
  575. ->where('del_time',0)
  576. ->exists();
  577. if(!$bool) return [false, '设备日工时单不存在或已被删除'];
  578. }
  579. return [true, ''];
  580. }
  581. public function fillDataDaily($data, $user){
  582. if(empty($data['data'])) return $data;
  583. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  584. $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_id')));
  585. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'order_time')), $user);
  586. foreach ($data['data'] as $key => $value){
  587. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  588. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  589. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  590. $item_tmp = $item[$value['item_id']] ?? [];
  591. $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
  592. $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
  593. $data['data'][$key]['is_archive'] = $map[$value['order_time']] ?? false;
  594. }
  595. return $data;
  596. }
  597. public function fillDataForExportDaily($data, $column, &$return)
  598. {
  599. if (empty($data)) return;
  600. $mainIds = array_column($data, 'id');
  601. // 1. 获取详情及所有关联档案(项目、设备)的映射
  602. $detailsMap = $this->getDwDailyDetailsMap($mainIds, $data);
  603. foreach ($data as $main) {
  604. $mainId = $main['id'];
  605. $details = $detailsMap[$mainId] ?? [];
  606. // 2. 提取并格式化主表共有信息
  607. $mainInfo = [
  608. 'code' => $main['code'],
  609. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  610. ];
  611. if (empty($details)) {
  612. // 无明细时只导出一行主表信息
  613. $tempRow = [];
  614. foreach ($column as $col) {
  615. $tempRow[] = $mainInfo[$col] ?? '';
  616. }
  617. $return[] = $tempRow;
  618. } else {
  619. // 3. 平铺:将设备明细信息、项目信息与主表信息合并
  620. foreach ($details as $sub) {
  621. $fullRowData = array_merge($mainInfo, $sub);
  622. $tempRow = [];
  623. foreach ($column as $col) {
  624. $tempRow[] = $fullRowData[$col] ?? '';
  625. }
  626. $return[] = $tempRow;
  627. }
  628. }
  629. }
  630. }
  631. public function getDwDailyDetailsMap($mainIds, $mainData)
  632. {
  633. // 1. 获取设备工时子表记录
  634. $details = DB::table('daily_dw_order_details')
  635. ->where('del_time', 0)
  636. ->whereIn('main_id', $mainIds)
  637. ->get();
  638. // 2. 提取关联 ID(设备 ID 和 项目 ID)
  639. $deviceIds = $details->pluck('device_id')->unique();
  640. $itemIds = array_unique(array_column($mainData, 'item_id'));
  641. // 3. 批量获取设备档案和项目档案
  642. $deviceMap = DB::table('device')
  643. ->whereIn('id', $deviceIds)
  644. ->get(['id', 'title', 'code'])
  645. ->keyBy('id');
  646. $itemMap = DB::table('item')
  647. ->whereIn('id', $itemIds)
  648. ->get(['id', 'title', 'code'])
  649. ->keyBy('id');
  650. // 4. 预挂载主表的项目信息(item_code, item_title)
  651. $mainItemInfo = [];
  652. foreach ($mainData as $m) {
  653. $proj = $itemMap[$m['item_id']] ?? null;
  654. $mainItemInfo[$m['id']] = [
  655. 'item_code' => $proj ? $proj->code : '',
  656. 'item_title' => $proj ? $proj->title : '',
  657. ];
  658. }
  659. $res = [];
  660. // 如果没有详情,初始化空结构
  661. if ($details->isEmpty()) {
  662. foreach ($mainItemInfo as $mId => $info) {
  663. $res[$mId] = [];
  664. }
  665. return $res;
  666. }
  667. // 5. 循环子表,合并设备档案信息
  668. foreach ($details as $item) {
  669. $device = $deviceMap[$item->device_id] ?? null;
  670. $detailRow = [
  671. // 设备信息(对应 Excel 配置中的 key)
  672. 'device_code' => $device ? $device->code : '',
  673. 'device_title' => $device ? $device->title : '',
  674. // 时间信息
  675. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  676. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  677. // 项目信息(由主表平铺而来)
  678. 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
  679. 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
  680. 'total_work_min' => $item->total_work_min,
  681. ];
  682. $res[$item->main_id][] = $detailRow;
  683. }
  684. return $res;
  685. }
  686. public function dailyDwOrderCreate($data, $user)
  687. {
  688. $topDepartId = $user['top_depart_id'];
  689. if (empty($data['month'])) return [false, '月份不能为空'];
  690. $monthStart = $this->changeDateToDate($data['month']);
  691. // --- 前置核心校验 ---
  692. // 1. 校验设备月度明细是否存在
  693. $hasMonthly = DB::table('monthly_dw_order_details as d')
  694. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  695. ->where('m.month', $monthStart)
  696. ->where('m.top_depart_id', $topDepartId)
  697. ->where('m.del_time', 0)
  698. ->exists();
  699. if (!$hasMonthly) return [false, '未找到该月份的设备月度工时明细'];
  700. // 2. 校验设备项目分配规则
  701. $hasRules = DB::table('rule_set as r')
  702. ->where('r.month', $monthStart)
  703. ->where('r.top_depart_id', $topDepartId)
  704. ->where('r.del_time', 0)
  705. ->exists();
  706. if (!$hasRules) return [false, '未找到该月份的项目比例规则设置'];
  707. // 3. 校验工作日历
  708. $hasCalendar = DB::table('calendar_details')
  709. ->where('month', $monthStart)
  710. ->where('is_work', 1)
  711. ->where('del_time', 0)
  712. ->exists();
  713. if (!$hasCalendar) return [false, '该月份未配置工作日历'];
  714. $data['type'] = 'd_work';
  715. ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
  716. return [true, '设备工时生成任务已提交,请稍后查看结果'];
  717. }
  718. public function dailyDwOrderCreateMain($data, $user)
  719. {
  720. $topDepartId = $user['top_depart_id'];
  721. if (empty($data['month'])) return [false, '月份不能为空'];
  722. $monthStart = $this->changeDateToDate($data['month']);
  723. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  724. $now = time();
  725. DB::beginTransaction();
  726. try {
  727. // --- 0. 清理旧数据 ---
  728. $oldOrderIds = DB::table('daily_dw_order')
  729. ->where('top_depart_id', $topDepartId)
  730. ->where('order_time', '>=', $monthStart)
  731. ->where('order_time', '<=', $monthEnd)
  732. ->where('is_create', 1)
  733. ->where('del_time', 0)
  734. ->pluck('id');
  735. if ($oldOrderIds->isNotEmpty()) {
  736. DB::table('daily_dw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  737. DB::table('daily_dw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  738. }
  739. // --- 1. 基础数据预加载 ---
  740. // 月度设备工时明细
  741. $monthlyOrder = DB::table('monthly_dw_order_details as d')
  742. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  743. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  744. ->where('m.del_time', 0)->where('d.del_time', 0)
  745. ->select('d.*')->get();
  746. if ($monthlyOrder->isEmpty()) return [false, '未找到设备月度工时明细'];
  747. // 设备项目分配比例 (与人员类似,但通常关联 device_id)
  748. $ruleSet = DB::table('rule_set_details as rd')
  749. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  750. ->where('r.month', $monthStart)
  751. ->where('rd.type', RuleSetDetails::type_two) // 假设 type_two 是设备类型
  752. ->where('r.del_time', 0)->where('rd.del_time', 0)
  753. ->select('rd.*')->get()->groupBy('data_id');
  754. // 标准工作时段 (设备通常只走公司标准时段)
  755. $standardWorkRanges = DB::table('work_range_details')
  756. ->where('top_depart_id', $topDepartId)
  757. ->where('del_time', 0)
  758. ->get();
  759. // 工作日历
  760. $workDays = DB::table('calendar_details')
  761. ->where('month', $monthStart)
  762. ->where('is_work', CalendarDetails::TYPE_ONE)
  763. ->where('del_time', 0)
  764. ->orderBy('time', 'asc')
  765. ->get();
  766. if ($workDays->isEmpty()) return [false, '未配置工作日历,无法分配设备工时'];
  767. // --- 2. 核心分配逻辑 ---
  768. $finalAlloc = [];
  769. foreach ($monthlyOrder as $mDetail) {
  770. $deviceId = $mDetail->device_id;
  771. $deviceRules = $ruleSet->get($deviceId);
  772. if (!$deviceRules) continue;
  773. $remainingMin = (float)$mDetail->rd_total_hours * 60;
  774. if ($remainingMin <= 0) continue;
  775. foreach ($workDays as $dayInfo) {
  776. if ($remainingMin <= 0) break;
  777. // 计算当天设备最大可用分钟 (标准时段总和)
  778. $dayMaxAvail = $standardWorkRanges->sum('total_work_min');
  779. $canAllocToday = min($remainingMin, $dayMaxAvail);
  780. foreach ($deviceRules as $rule) {
  781. $rate = (float)$rule->rate / 100;
  782. $projectMin = $canAllocToday * $rate;
  783. if ($projectMin > 0) {
  784. $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = ($finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] ?? 0) + $projectMin;
  785. }
  786. }
  787. $remainingMin -= $canAllocToday;
  788. }
  789. }
  790. // --- 3. 生成单据并填充时段 (防重叠) ---
  791. $newOrderIds = [];
  792. $dailyDevicePools = []; // 追踪每台设备每天的时间消耗情况
  793. foreach ($finalAlloc as $dayTs => $projects) {
  794. foreach ($projects as $itemId => $devices) {
  795. $mainId = DB::table('daily_dw_order')->insertGetId([
  796. 'code' => '',
  797. 'item_id' => $itemId,
  798. 'order_time' => $dayTs,
  799. 'top_depart_id' => $topDepartId,
  800. 'is_create' => 1,
  801. 'crt_id' => $user['id'],
  802. 'crt_time' => $now,
  803. 'upd_time' => $now,
  804. ]);
  805. $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
  806. foreach ($devices as $deviceId => $toAllocMin) {
  807. // 初始化该设备当天的时段池 (仅由标准时段构成)
  808. if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
  809. $pool = [];
  810. foreach ($standardWorkRanges as $swr) {
  811. $pool[] = [
  812. 's' => $swr->start_time_hour * 60 + $swr->start_time_min,
  813. 'e' => $swr->end_time_hour * 60 + $swr->end_time_min
  814. ];
  815. }
  816. $dailyDevicePools[$dayTs][$deviceId] = $pool;
  817. }
  818. $tempRem = $toAllocMin;
  819. foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
  820. if ($tempRem <= 0) break;
  821. $pMax = $p['e'] - $p['s'];
  822. if ($pMax <= 0) continue;
  823. $take = min($tempRem, $pMax);
  824. $start = $p['s'];
  825. $end = $p['s'] + $take;
  826. DB::table('daily_dw_order_details')->insert([
  827. 'main_id' => $mainId,
  828. 'device_id' => $deviceId,
  829. 'top_depart_id' => $topDepartId,
  830. 'start_time_hour' => floor($start / 60),
  831. 'start_time_min' => $start % 60,
  832. 'end_time_hour' => floor($end / 60),
  833. 'end_time_min' => $end % 60,
  834. 'total_work_min' => $take,
  835. 'crt_time' => $now,
  836. 'upd_time' => $now,
  837. ]);
  838. $tempRem -= $take;
  839. $p['s'] = $end; // 指针后移,防重叠
  840. }
  841. }
  842. }
  843. }
  844. // --- 4. 回填单号 ---
  845. if (empty($newOrderIds)) return [false, '未生成任何设备日工时单'];
  846. foreach ($newOrderIds as $item) {
  847. $code = $this->generateBillNo([
  848. 'top_depart_id' => $topDepartId,
  849. 'type' => DailyDwOrder::Order_type, // 确保模型中定义了此常量
  850. 'period' => date("Ym", $item['time'])
  851. ]);
  852. DB::table('daily_dw_order')->where('id', $item['id'])->update(['code' => $code]);
  853. }
  854. DB::commit();
  855. } catch (\Exception $e) {
  856. DB::rollBack();
  857. return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
  858. }
  859. return [true, ''];
  860. }
  861. public function dailyDwOrderPreview($data, $user)
  862. {
  863. $topDepartId = $user['top_depart_id'];
  864. if (empty($data['month'])) return [false, '月份不能为空'];
  865. $monthStart = $this->changeDateToDate($data['month']);
  866. //归档
  867. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  868. if(! $status) return [false, $msg];
  869. // 调用核心计算逻辑
  870. $result = $this->calculateDailyDeviceAllocation($monthStart, $topDepartId, $user);
  871. if (!$result['status']) return [false, $result['msg']];
  872. return [true, [
  873. 'list' => $result['data'] // 返回给前端预览
  874. ]];
  875. }
  876. private function calculateDailyDeviceAllocation1($monthStart, $topDepartId, $user)
  877. {
  878. // 加载月度设备明细
  879. $monthlyOrder = DB::table('monthly_dw_order_details as d')
  880. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  881. ->where('m.month', $monthStart)
  882. ->where('m.top_depart_id', $topDepartId)
  883. ->where('m.del_time', 0)
  884. ->where('d.del_time', 0)
  885. ->select('d.*')
  886. ->get();
  887. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到设备月度工时明细'];
  888. $usedDeviceIds = $monthlyOrder->pluck('device_id')->unique()->toArray();
  889. $deviceMap = DB::table('device')
  890. ->whereIn('id', $usedDeviceIds)
  891. ->pluck('title', 'id')
  892. ->toArray();
  893. // 加载分配规则
  894. $ruleSet = DB::table('rule_set_details as rd')
  895. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  896. ->where('r.month', $monthStart)
  897. ->where('rd.type', 2) // 设备类型
  898. ->where('rd.top_depart_id', $topDepartId)
  899. ->where('r.del_time', 0)
  900. ->where('rd.del_time', 0)
  901. ->select('rd.*')
  902. ->get();
  903. $usedItemIds = $ruleSet->pluck('item_id')->unique()->toArray();
  904. $itemMap = DB::table('item')
  905. ->whereIn('id', $usedItemIds)
  906. ->pluck('title', 'id')
  907. ->toArray();
  908. $ruleSetGrouped = $ruleSet->groupBy('data_id');
  909. // 标准班次 & 日历
  910. $standardWorkRanges = DB::table('work_range_details')
  911. ->where('top_depart_id', $topDepartId)
  912. ->where('del_time', 0)
  913. ->get();
  914. $dayMaxAvail = (int)$standardWorkRanges->sum('total_work_min');
  915. $workDays = DB::table('calendar_details')
  916. ->where('top_depart_id', $topDepartId)
  917. ->where('month', $monthStart)
  918. ->where('is_work', 1)
  919. ->where('del_time', 0)
  920. ->orderBy('time', 'asc')->get();
  921. if ($workDays->isEmpty()) return ['status' => false, 'msg' => '未配置工作日历'];
  922. // --- 2. 阶段一:计算每天每台设备分配的项目分钟数 (保持原逻辑) ---
  923. $finalAlloc = [];
  924. foreach ($monthlyOrder as $mDetail) {
  925. $deviceId = $mDetail->device_id;
  926. $deviceRules = $ruleSetGrouped->get($deviceId);
  927. if (!$deviceRules) continue;
  928. $remainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  929. if ($remainingMin <= 0) continue;
  930. foreach ($workDays as $dayInfo) {
  931. if ($remainingMin <= 0) break;
  932. $canAllocToday = min($remainingMin, $dayMaxAvail);
  933. $allocatedInDay = 0;
  934. $ruleCount = count($deviceRules);
  935. foreach ($deviceRules as $index => $rule) {
  936. $rate = (float)$rule->rate / 100;
  937. if ($index === $ruleCount - 1) {
  938. $projectMin = $canAllocToday - $allocatedInDay;
  939. } else {
  940. $projectMin = (int)round($canAllocToday * $rate);
  941. }
  942. if ($projectMin > 0) {
  943. $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = $projectMin;
  944. $allocatedInDay += $projectMin;
  945. }
  946. }
  947. $remainingMin -= $canAllocToday;
  948. }
  949. }
  950. // --- 3. 阶段二:生成预览行并对齐 30 分钟 ---
  951. $previewList = [];
  952. $dailyDevicePools = [];
  953. $tempMainIdCounter = 1;
  954. $step = 30; // 步长
  955. foreach ($finalAlloc as $dayTs => $projects) {
  956. foreach ($projects as $itemId => $devices) {
  957. $currentTempMainId = $tempMainIdCounter++;
  958. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  959. foreach ($devices as $deviceId => $toAllocMin) {
  960. if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
  961. $pool = [];
  962. foreach ($standardWorkRanges as $swr) {
  963. $pool[] = [
  964. 's' => (int)($swr->start_time_hour * 60 + $swr->start_time_min),
  965. 'e' => (int)($swr->end_time_hour * 60 + $swr->end_time_min)
  966. ];
  967. }
  968. $dailyDevicePools[$dayTs][$deviceId] = $pool;
  969. }
  970. $tempRem = (int)$toAllocMin;
  971. foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
  972. if ($tempRem <= 0) break;
  973. // 【改动】起始点对齐:非30分钟整点则向上对齐
  974. if ($p['s'] % $step != 0) {
  975. $p['s'] = ceil($p['s'] / $step) * $step;
  976. }
  977. $pMax = (int)($p['e'] - $p['s']);
  978. if ($pMax <= 0) continue;
  979. // 【改动】取量对齐逻辑
  980. if ($tempRem >= $step) {
  981. // 尽量按步长分配
  982. $take = min(floor($tempRem / $step) * $step, floor($pMax / $step) * $step);
  983. if ($take <= 0) continue;
  984. } else {
  985. // 最后一丁点零头
  986. $take = min($tempRem, $pMax);
  987. }
  988. $start = (int)$p['s'];
  989. $end = $start + $take;
  990. $previewList[] = [
  991. 'temp_main_id' => $currentTempMainId,
  992. 'order_time' => date('Y-m-d', $dayTs),
  993. 'order_timestamp' => $dayTs,
  994. 'item_id' => $itemId,
  995. 'item_title' => $itemTitle,
  996. 'device_id' => $deviceId,
  997. 'device_title' => $deviceMap[$deviceId] ?? '未知设备',
  998. 'start_time' => sprintf('%02d:%02d', floor($start / 60), $start % 60),
  999. 'end_time' => sprintf('%02d:%02d', floor($end / 60), $end % 60),
  1000. 'start_hour' => (int)floor($start / 60),
  1001. 'start_min' => (int)($start % 60),
  1002. 'end_hour' => (int)floor($end / 60),
  1003. 'end_min' => (int)($end % 60),
  1004. 'total_work_min' => $take,
  1005. ];
  1006. $tempRem -= $take;
  1007. $p['s'] = $end;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. return ['status' => true, 'data' => $previewList];
  1013. }
  1014. private function calculateDailyDeviceAllocation($monthStart, $topDepartId, $user)
  1015. {
  1016. // 1. 加载月度设备明细
  1017. $monthlyOrder = DB::table('monthly_dw_order_details as d')
  1018. ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
  1019. ->where('m.month', $monthStart)
  1020. ->where('m.top_depart_id', $topDepartId)
  1021. ->where('m.del_time', 0)
  1022. ->where('d.del_time', 0)
  1023. ->select('d.*')
  1024. ->get();
  1025. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到设备月度工时明细'];
  1026. $usedDeviceIds = $monthlyOrder->pluck('device_id')->unique()->toArray();
  1027. $deviceMap = DB::table('device')
  1028. ->whereIn('id', $usedDeviceIds)
  1029. ->pluck('title', 'id')
  1030. ->toArray();
  1031. // 加载分配规则
  1032. $ruleSet = DB::table('rule_set_details as rd')
  1033. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  1034. ->where('r.month', $monthStart)
  1035. ->where('rd.type', 2) // 设备类型
  1036. ->where('rd.top_depart_id', $topDepartId)
  1037. ->where('r.del_time', 0)
  1038. ->where('rd.del_time', 0)
  1039. ->select('rd.*')
  1040. ->get();
  1041. $usedItemIds = $ruleSet->pluck('item_id')->unique()->toArray();
  1042. $itemMap = DB::table('item')
  1043. ->whereIn('id', $usedItemIds)
  1044. ->pluck('title', 'id')
  1045. ->toArray();
  1046. $ruleSetGrouped = $ruleSet->groupBy('data_id');
  1047. // 标准班次 & 日历
  1048. $standardWorkRanges = DB::table('work_range_details')
  1049. ->where('top_depart_id', $topDepartId)
  1050. ->where('del_time', 0)
  1051. ->get();
  1052. // 【关键改动】让标准班次的可用时间,天然就是30分钟的整数倍(向下取整,确保格子规整)
  1053. $step = 30;
  1054. $dayMaxAvail = 0;
  1055. $cleanWorkRanges = [];
  1056. foreach ($standardWorkRanges as $swr) {
  1057. $s = (int)($swr->start_time_hour * 60 + $swr->start_time_min);
  1058. $e = (int)($swr->end_time_hour * 60 + $swr->end_time_min);
  1059. // 起始点对齐
  1060. if ($s % $step != 0) $s = (int)ceil($s / $step) * $step;
  1061. if ($e % $step != 0) $e = (int)floor($e / $step) * $step;
  1062. if ($e > $s) {
  1063. $cleanWorkRanges[] = ['s' => $s, 'e' => $e];
  1064. $dayMaxAvail += ($e - $s);
  1065. }
  1066. }
  1067. $workDays = DB::table('calendar_details')
  1068. ->where('top_depart_id', $topDepartId)
  1069. ->where('month', $monthStart)
  1070. ->where('is_work', 1)
  1071. ->where('del_time', 0)
  1072. ->orderBy('time', 'asc')->get();
  1073. if ($workDays->isEmpty()) return ['status' => false, 'msg' => '未配置工作日历'];
  1074. // --- 2. 阶段一:计算每天每台设备分配的项目分钟数 (加入30分钟对齐无损控制) ---
  1075. $finalAlloc = [];
  1076. foreach ($monthlyOrder as $mDetail) {
  1077. $deviceId = $mDetail->device_id;
  1078. $deviceRules = $ruleSetGrouped->get($deviceId);
  1079. if (!$deviceRules) continue;
  1080. $remainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  1081. if ($remainingMin <= 0) continue;
  1082. foreach ($workDays as $dayInfo) {
  1083. if ($remainingMin <= 0) break;
  1084. // 当天最大可分,必须是30的倍数(最后一天除外,最后一天要把零头全部收走)
  1085. $canAllocToday = min($remainingMin, $dayMaxAvail);
  1086. // 确保非最后一天的日额度也是30的倍数
  1087. if ($remainingMin > $dayMaxAvail && $canAllocToday % $step != 0) {
  1088. $canAllocToday = (int)floor($canAllocToday / $step) * $step;
  1089. }
  1090. $allocatedInDay = 0;
  1091. $ruleCount = count($deviceRules);
  1092. foreach ($deviceRules as $index => $rule) {
  1093. if ($index === $ruleCount - 1) {
  1094. // 最后一个项目拿走今天剩下的所有分钟
  1095. $projectMin = $canAllocToday - $allocatedInDay;
  1096. } else {
  1097. $rate = (float)$rule->rate / 100;
  1098. // 【优化】计算出来的项目时间,直接四舍五入到最近的30分钟整数倍
  1099. $rawMin = $canAllocToday * $rate;
  1100. $projectMin = (int)round($rawMin / $step) * $step;
  1101. }
  1102. // 防止四舍五入爆池子
  1103. if ($allocatedInDay + $projectMin > $canAllocToday) {
  1104. $projectMin = $canAllocToday - $allocatedInDay;
  1105. }
  1106. if ($projectMin > 0) {
  1107. $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = $projectMin;
  1108. $allocatedInDay += $projectMin;
  1109. }
  1110. }
  1111. $remainingMin -= $allocatedInDay; // 减去实际扣减的,确保闭环
  1112. }
  1113. // 【大招:溢出工时补偿】如果日历天数走完了,因为设备加班导致 remainingMin 还有剩
  1114. // 将剩下的零头,强行追加分配到有空间的最后几天里,确保总工时 168 小时一分不差
  1115. if ($remainingMin > 0) {
  1116. foreach (array_reverse($workDays->toArray()) as $dayInfo) {
  1117. if ($remainingMin <= 0) break;
  1118. // 找到该设备当天已分配的总量
  1119. $todayAllocated = 0;
  1120. foreach ($finalAlloc[$dayInfo->time] ?? [] as $itemId => $devs) {
  1121. $todayAllocated += $devs[$deviceId] ?? 0;
  1122. }
  1123. // 哪怕超过标准班次,为了不丢工时,硬塞进去(这部分会作为加班在后续无缝拉长)
  1124. $lastRule = $deviceRules->last();
  1125. if ($lastRule) {
  1126. $finalAlloc[$dayInfo->time][$lastRule->item_id][$deviceId] =
  1127. ($finalAlloc[$dayInfo->time][$lastRule->item_id][$deviceId] ?? 0) + $remainingMin;
  1128. $remainingMin = 0;
  1129. }
  1130. }
  1131. }
  1132. }
  1133. // --- 3. 阶段二:生成预览行 (采用无缝滑行指针,杜绝截断丢弃) ---
  1134. $previewList = [];
  1135. $dailyDevicePools = [];
  1136. $tempMainIdCounter = 1;
  1137. foreach ($finalAlloc as $dayTs => $projects) {
  1138. foreach ($projects as $itemId => $devices) {
  1139. $currentTempMainId = $tempMainIdCounter++;
  1140. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  1141. foreach ($devices as $deviceId => $toAllocMin) {
  1142. if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
  1143. // 初始化这台设备今天的标准班次池
  1144. $dailyDevicePools[$dayTs][$deviceId] = $cleanWorkRanges;
  1145. }
  1146. $tempRem = (int)$toAllocMin;
  1147. // 1. 先尝试塞进标准班次
  1148. foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
  1149. if ($tempRem <= 0) break;
  1150. $pMax = $p['e'] - $p['s'];
  1151. if ($pMax <= 0) continue;
  1152. $take = min($tempRem, $pMax);
  1153. $start = (int)$p['s'];
  1154. $end = $start + $take;
  1155. $previewList[] = $this->buildPreviewRow(
  1156. $currentTempMainId, $dayTs, $itemId, $itemTitle,
  1157. $deviceId, $deviceMap[$deviceId] ?? '未知设备', $start, $end, $take
  1158. );
  1159. $tempRem -= $take;
  1160. $p['s'] = $end; // 指针平移
  1161. }
  1162. // 2. 【关键安全阀】如果标准班次格子全满了,但 tempRem 还有剩(说明设备在冲刺加班)
  1163. // 绝对不能扔掉!从当天的最后一个结束时间开始,无上限往后顺延生成“加班行”
  1164. if ($tempRem > 0) {
  1165. // 找到当天的最后落点,如果连标准班次都没有,默认从 18:00 (1080) 开始无缝排
  1166. $lastEnd = 1080;
  1167. if (!empty($cleanWorkRanges)) {
  1168. $lastEnd = end($cleanWorkRanges)['e'];
  1169. }
  1170. // 看看之前有没有已经排上去的加班,有的话紧跟其后
  1171. if (isset($dailyDevicePools[$dayTs][$deviceId]['overtime_last_end'])) {
  1172. $lastEnd = $dailyDevicePools[$dayTs][$deviceId]['overtime_last_end'];
  1173. }
  1174. $start = $lastEnd;
  1175. $end = $start + $tempRem;
  1176. $previewList[] = $this->buildPreviewRow(
  1177. $currentTempMainId, $dayTs, $itemId, $itemTitle,
  1178. $deviceId, $deviceMap[$deviceId] ?? '未知设备', $start, $end, $tempRem
  1179. );
  1180. // 记录该设备今天最新的加班落点
  1181. $dailyDevicePools[$dayTs][$deviceId]['overtime_last_end'] = $end;
  1182. $tempRem = 0;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. return ['status' => true, 'data' => $previewList];
  1188. }
  1189. /**
  1190. * 辅助抽离:组装预览行数据
  1191. */
  1192. private function buildPreviewRow($tempMainId, $dayTs, $itemId, $itemTitle, $deviceId, $deviceTitle, $start, $end, $take)
  1193. {
  1194. return [
  1195. 'temp_main_id' => $tempMainId,
  1196. 'order_time' => date('Y-m-d', $dayTs),
  1197. 'order_timestamp' => $dayTs,
  1198. 'item_id' => $itemId,
  1199. 'item_title' => $itemTitle,
  1200. 'device_id' => $deviceId,
  1201. 'device_title' => $deviceTitle,
  1202. 'start_time' => sprintf('%02d:%02d', floor($start / 60), $start % 60),
  1203. 'end_time' => sprintf('%02d:%02d', floor($end / 60), $end % 60),
  1204. 'start_hour' => (int)floor($start / 60),
  1205. 'start_min' => (int)($start % 60),
  1206. 'end_hour' => (int)floor($end / 60),
  1207. 'end_min' => (int)($end % 60),
  1208. 'total_work_min' => $take,
  1209. ];
  1210. }
  1211. public function dailyDwOrderSave($data, $user)
  1212. {
  1213. $list = $data['list'] ?? [];
  1214. if (empty($list)) return [false, '提交数据不能为空'];
  1215. $topDepartId = $user['top_depart_id'];
  1216. $month = $data['month']; // 格式如: "2026-03"
  1217. $monthStart = $this->changeDateToDate($month);
  1218. //归档
  1219. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  1220. if(! $status) return [false, $msg];
  1221. $now = time();
  1222. // 1. 预加载映射
  1223. $deviceIds = collect($list)->pluck('device_id')->unique()->toArray();
  1224. $deviceMap = DB::table('device')->whereIn('id', $deviceIds)->pluck('title', 'id')->toArray();
  1225. // 2. 重新分组并记录行号
  1226. $groupedByOrder = [];
  1227. foreach ($list as $index => $item) {
  1228. $item['_line'] = $index + 1;
  1229. $groupKey = $item['order_time'] . '_' . $item['item_id'];
  1230. $groupedByOrder[$groupKey][] = $item;
  1231. }
  1232. $deviceTimeline = [];
  1233. DB::beginTransaction();
  1234. try {
  1235. // A. 清理旧数据
  1236. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  1237. $oldOrderIds = DB::table('daily_dw_order')
  1238. ->where('top_depart_id', $topDepartId)
  1239. ->whereBetween('order_time', [$monthStart, $monthEnd])
  1240. ->where('del_time', 0)
  1241. ->pluck('id');
  1242. if ($oldOrderIds->isNotEmpty()) {
  1243. DB::table('daily_dw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  1244. DB::table('daily_dw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  1245. }
  1246. // B. 遍历重组后的分组
  1247. foreach ($groupedByOrder as $details) {
  1248. $first = $details[0];
  1249. $orderTimestamp = strtotime($first['order_time']);
  1250. $itemId = $first['item_id'];
  1251. $mainId = DB::table('daily_dw_order')->insertGetId([
  1252. 'code' => '',
  1253. 'item_id' => $itemId,
  1254. 'order_time' => $orderTimestamp,
  1255. 'top_depart_id' => $topDepartId,
  1256. 'is_create' => 1,
  1257. 'crt_id' => $user['id'],
  1258. 'crt_time' => $now,
  1259. ]);
  1260. $insertDetails = [];
  1261. foreach ($details as $d) {
  1262. $rowNum = $d['_line'];
  1263. $devId = $d['device_id'];
  1264. $devName = $deviceMap[$devId] ?? "设备(ID:{$devId})";
  1265. // --- 新增:校验 order_time 是否属于当前选择的 month ---
  1266. if (date("Y-m", strtotime($d['order_time'])) !== $month) {
  1267. return [false, "第 {$rowNum} 行:日期[{$d['order_time']}]不属于保存月份[{$month}],请修正!"];
  1268. }
  1269. $s = (int)$d['start_hour'] * 60 + (int)$d['start_min'];
  1270. $e = (int)$d['end_hour'] * 60 + (int)$d['end_min'];
  1271. $calcTotalMin = $e - $s;
  1272. if ($calcTotalMin <= 0) {
  1273. return [false, "第 {$rowNum} 行:设备[{$devName}]在[{$d['order_time']}]的结束时间必须晚于开始时间"];
  1274. }
  1275. // 冲突校验
  1276. $dateStr = $d['order_time'];
  1277. if (isset($deviceTimeline[$devId][$dateStr])) {
  1278. foreach ($deviceTimeline[$devId][$dateStr] as $exist) {
  1279. if ($s < $exist['e'] && $e > $exist['s']) {
  1280. return [false, "第 {$rowNum} 行:设备[{$devName}]在[{$dateStr}]存在时间冲突({$d['start_time']}-{$d['end_time']})"];
  1281. }
  1282. }
  1283. }
  1284. $deviceTimeline[$devId][$dateStr][] = ['s' => $s, 'e' => $e];
  1285. $insertDetails[] = [
  1286. 'main_id' => $mainId,
  1287. 'device_id' => $devId,
  1288. 'top_depart_id' => $topDepartId,
  1289. 'start_time_hour' => $d['start_hour'],
  1290. 'start_time_min' => $d['start_min'],
  1291. 'end_time_hour' => $d['end_hour'],
  1292. 'end_time_min' => $d['end_min'],
  1293. 'total_work_min' => $calcTotalMin,
  1294. 'crt_time' => $now,
  1295. 'order_time' => $orderTimestamp,
  1296. 'item_id' => $itemId,
  1297. 'crt_id' => $user['id'],
  1298. ];
  1299. }
  1300. DB::table('daily_dw_order_details')->insert($insertDetails);
  1301. $code = $this->generateBillNo([
  1302. 'top_depart_id' => $topDepartId,
  1303. 'type' => DailyDwOrder::Order_type,
  1304. 'period' => date("Ym", $orderTimestamp)
  1305. ]);
  1306. DB::table('daily_dw_order')->where('id', $mainId)->update(['code' => $code]);
  1307. }
  1308. DB::commit();
  1309. return [true, ''];
  1310. } catch (\Exception $e) {
  1311. DB::rollBack();
  1312. return [false, "保存失败:" . $e->getMessage()];
  1313. }
  1314. }
  1315. }