DeviceWorkService.php 60 KB

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