PersonWorkService.php 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  1. <?php
  2. namespace App\Service;
  3. use App\Jobs\ProcessDataJob;
  4. use App\Model\CalendarDetails;
  5. use App\Model\DailyPwOrder;
  6. use App\Model\DailyPwOrderDetails;
  7. use App\Model\Employee;
  8. use App\Model\Item;
  9. use App\Model\MonthlyPwOrder;
  10. use App\Model\MonthlyPwOrderDetails;
  11. use App\Model\RuleSetDetails;
  12. use Illuminate\Support\Facades\DB;
  13. class PersonWorkService extends Service
  14. {
  15. // 人员月工时单-------------------------------------------
  16. public function monthlyPwOrderEdit($data,$user){
  17. list($status,$msg) = $this->monthlyPwOrderRule($data, $user, false);
  18. if(!$status) return [$status,$msg];
  19. try {
  20. DB::beginTransaction();
  21. $model = MonthlyPwOrder::where('id',$data['id'])->first();
  22. // $model->month = $data['month'] ?? 0;
  23. // $model->save();
  24. $time = time();
  25. MonthlyPwOrderDetails::where('del_time',0)
  26. ->where('main_id', $model->id)
  27. ->update(['del_time' => $time]);
  28. $this->saveDetail($model->id, $time, $data);
  29. DB::commit();
  30. }catch (\Exception $exception){
  31. DB::rollBack();
  32. return [false,$exception->getMessage()];
  33. }
  34. return [true, ''];
  35. }
  36. public function monthlyPwOrderAdd($data,$user){
  37. list($status,$msg) = $this->monthlyPwOrderRule($data, $user);
  38. if(!$status) return [$status,$msg];
  39. try {
  40. DB::beginTransaction();
  41. $model = new MonthlyPwOrder();
  42. $model->code = $this->generateBillNo([
  43. 'top_depart_id' => $user['top_depart_id'],
  44. 'type' => MonthlyPwOrder::Order_type,
  45. 'period' => date("Ym", $data['month'])
  46. ]);
  47. $model->month = $data['month'] ?? 0;
  48. $model->crt_id = $user['id'];
  49. $model->top_depart_id = $data['top_depart_id'];
  50. $model->save();
  51. $this->saveDetail($model->id, time(), $data);
  52. DB::commit();
  53. }catch (\Exception $exception){
  54. DB::rollBack();
  55. return [false,$exception->getMessage()];
  56. }
  57. return [true, ''];
  58. }
  59. private function saveDetail($id, $time, $data){
  60. if(! empty($data['details'])){
  61. $unit = [];
  62. foreach ($data['details'] as $value){
  63. $unit[] = [
  64. 'main_id' => $id,
  65. 'employee_id' => $value['employee_id'],
  66. 'total_days' => $value['total_days'],
  67. 'rd_total_days' => $value['rd_total_days'],
  68. 'total_hours' => $value['total_hours'],
  69. 'rd_total_hours' => $value['rd_total_hours'],
  70. 'crt_time' => $time,
  71. 'top_depart_id' => $value['top_depart_id'],
  72. ];
  73. }
  74. if(! empty($unit)) MonthlyPwOrderDetails::insert($unit);
  75. }
  76. }
  77. private function getDetail($id){
  78. $data = MonthlyPwOrderDetails::where('del_time',0)
  79. ->where('main_id', $id)
  80. ->select('employee_id', 'total_days', 'rd_total_days', 'total_hours', 'rd_total_hours')
  81. ->get()->toArray();
  82. $id = array_column($data,'employee_id');
  83. $map = Employee::whereIn('id', $id)->select('title','id','number')->get()->toArray();
  84. $map = array_column($map,null,'id');
  85. foreach ($data as $key => $value){
  86. $tmp = $map[$value['employee_id']] ?? [];
  87. $merge = [];
  88. $merge['employee_title'] = $tmp['title'];
  89. $merge['employee_number'] = $tmp['number'];
  90. $data[$key] = array_merge($value, $merge);
  91. }
  92. $detail = [
  93. 'details' => $data,
  94. ];
  95. //foreach ($detail as $key => $value) {
  96. // if (empty($value)) {
  97. //$detail[$key] = (object)[]; // 转成 stdClass 对象
  98. //}
  99. //}
  100. return $detail;
  101. }
  102. public function monthlyPwOrderDel($data, $user){
  103. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  104. try {
  105. DB::beginTransaction();
  106. $time = time();
  107. $month = MonthlyPwOrder::where('del_time',0)
  108. ->whereIn('id',$data['id'])
  109. ->pluck('month')
  110. ->toArray();
  111. //归档
  112. list($status, $msg) = ArchiveService::isArchive($month, $user);
  113. if(! $status) return [false, $msg];
  114. MonthlyPwOrder::where('del_time',0)
  115. ->whereIn('id',$data['id'])
  116. ->update(['del_time' => $time]);
  117. MonthlyPwOrderDetails::where('del_time',0)
  118. ->whereIn('main_id', $data['id'])
  119. ->update(['del_time' => $time]);
  120. DB::commit();
  121. }catch (\Exception $exception){
  122. DB::rollBack();
  123. return [false,$exception->getMessage()];
  124. }
  125. return [true, ''];
  126. }
  127. public function monthlyPwOrderDetail($data, $user){
  128. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  129. $customer = MonthlyPwOrder::where('del_time',0)
  130. ->where('id',$data['id'])
  131. ->first();
  132. if(empty($customer)) return [false,'人员月度工时单不存在或已被删除'];
  133. $customer = $customer->toArray();
  134. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  135. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  136. $map = ArchiveService::fillIsArchive($customer['month'], $user);
  137. $customer['is_archive'] = $map[$customer['month']] ?? false;
  138. $customer['month'] = $customer['month'] ? date("Y-m",$customer['month']): '';
  139. $details = $this->getDetail($data['id']);
  140. $customer = array_merge($customer, $details);
  141. return [true, $customer];
  142. }
  143. public function monthlyPwOrderCommon($data,$user, $field = []){
  144. if(empty($field)) $field = MonthlyPwOrder::$field;
  145. $model = MonthlyPwOrder::Clear($user,$data);
  146. $model = $model->where('del_time',0)
  147. ->select($field)
  148. ->orderby('id', 'desc');
  149. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  150. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  151. $model->where('month','>=',$return[0]);
  152. $model->where('month','<=',$return[1]);
  153. }
  154. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  155. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  156. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  157. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  158. $model->where('crt_time','>=',$return[0]);
  159. $model->where('crt_time','<=',$return[1]);
  160. }
  161. return $model;
  162. }
  163. public function monthlyPwOrderList($data,$user){
  164. $model = $this->monthlyPwOrderCommon($data, $user);
  165. $list = $this->limit($model,'',$data);
  166. $list = $this->fillData($list, $user);
  167. return [true, $list];
  168. }
  169. public function monthlyPwOrderRule(&$data, $user, $is_add = true)
  170. {
  171. if (empty($data['month'])) return [false, '月份不能为空'];
  172. $data['month'] = $this->changeDateToDate($data['month']);
  173. $data['top_depart_id'] = $user['top_depart_id'];
  174. //归档
  175. list($status, $msg) = ArchiveService::isArchive($data['month'], $user);
  176. if(! $status) return [false, $msg];
  177. if (empty($data['details'])) return [false, '人员月度工时单明细不能为空'];
  178. //获取系统计算的考勤基准数据 ---
  179. $empIds = array_column($data['details'], 'employee_id');
  180. list($status, $systemStats) = (new EmployeeService())->getEmployeesMonthStats($empIds, $data['month'], $user);
  181. if (!$status) return [false, $systemStats]; // 如果日历未设置,直接拦截
  182. // 字段中文映射,用于报错
  183. $fieldNames = [
  184. 'total_days' => '出勤总天数',
  185. 'rd_total_days' => '研发出勤总天数',
  186. 'total_hours' => '出勤总工时',
  187. 'rd_total_hours'=> '研发总工时'
  188. ];
  189. foreach ($data['details'] as $key => $value) {
  190. $lineTitle = "第" . ($key + 1) . "行:";
  191. if (empty($value['employee_id'])) return [false, '人员不能为空'];
  192. $empId = $value['employee_id'];
  193. // 基础数字格式检查
  194. foreach ($fieldNames as $field => $title) {
  195. if(! isset($value[$field])) return [false, $lineTitle . $title . "不存在"];
  196. $precision = 2;
  197. $res = $this->checkNumber($value[$field], $precision, 'non-negative');
  198. if (!$res['valid']) return [false, $lineTitle . $value['employee_title'] . "的" . $title . ":" . $res['error']];
  199. }
  200. // --- 业务逻辑校验:出勤天数与工时合法性 ---
  201. $sysData = $systemStats[$empId] ?? null;
  202. if ($sysData) {
  203. // 1. 研发天数不能大于出勤总天数
  204. if ($value['rd_total_days'] > $value['total_days']) {
  205. return [false, $lineTitle . "研发出勤天数不能大于出勤总天数"];
  206. }
  207. // 2. 研发工时不能大于出勤总工时
  208. if ($value['rd_total_hours'] > $value['total_hours']) {
  209. return [false, $lineTitle . "研发总工时不能大于出勤总工时"];
  210. }
  211. // 4. 校验出勤总天数是否超过了系统计算的上限
  212. if ($value['total_days'] != $sysData['attendance_days']) {
  213. return [false, $lineTitle . "人员[{$empId}]填写的出勤总天数({$value['total_days']})不等于系统核算的天数({$sysData['attendance_days']})"];
  214. }
  215. //校验出勤总工时是否超过了系统计算的上限
  216. if ($value['total_hours'] != $sysData['final_work_hour']) {
  217. return [false, $lineTitle . "人员[{$empId}]填写的出勤总工时({$value['total_hours']})不等于系统核算的工时({$sysData['final_work_hour']})"];
  218. }
  219. }
  220. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  221. }
  222. // --- 查重与唯一性校验 ---
  223. list($status, $msg) = $this->checkArrayRepeat($data['details'], 'employee_id', '人员');
  224. if (!$status) return [false, $msg];
  225. $query = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
  226. ->where('month', $data['month'])
  227. ->where('del_time', 0);
  228. if (!$is_add) {
  229. if (empty($data['id'])) return [false, 'ID不能为空'];
  230. $query->where('id', '<>', $data['id']);
  231. }
  232. if ($query->exists()) {
  233. return [false, date("Y-m", $data['month']) . '已存在人员月度研发工时单'];
  234. }
  235. return [true, ''];
  236. }
  237. public function fillData($data, $user){
  238. if(empty($data['data'])) return $data;
  239. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  240. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'month')), $user);
  241. foreach ($data['data'] as $key => $value){
  242. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  243. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  244. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  245. $data['data'][$key]['is_archive'] = $map[$value['month']] ?? false;
  246. }
  247. return $data;
  248. }
  249. public function fillDataForExport($data, $column, &$return)
  250. {
  251. if(empty($data)) return;
  252. $mainIds = array_column($data, 'id');
  253. // 获取详情映射 [main_id => [details...]]
  254. $detailsMap = $this->getDetailsMap($mainIds);
  255. // 默认空行模板
  256. $defaultRow = array_fill_keys($column, '');
  257. foreach ($data as $main) {
  258. $mainId = $main['id'];
  259. $details = $detailsMap[$mainId] ?? [];
  260. // 提取主表信息
  261. $mainInfo = [
  262. 'code' => $main['code'],
  263. 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
  264. ];
  265. if (empty($details)) {
  266. // 如果没有详情,至少导出一行主表信息(可选)
  267. $return[] = array_merge($defaultRow, $mainInfo);
  268. } else {
  269. // 核心:遍历详情,每一行详情都合并主表信息
  270. foreach ($details as $sub) {
  271. // 合并主表字段 + 详情字段
  272. $fullRow = array_merge($mainInfo, $sub);
  273. // 过滤掉不在导出列里的字段,并补充缺失列
  274. $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
  275. }
  276. }
  277. }
  278. }
  279. public function getDetailsMap($main_ids)
  280. {
  281. // 获取详情
  282. $details = MonthlyPwOrderDetails::where('del_time', 0)
  283. ->whereIn('main_id', $main_ids)
  284. ->get();
  285. // 获取人员信息
  286. $empIds = $details->pluck('employee_id')->unique();
  287. $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id');
  288. $res = [];
  289. foreach ($details as $item) {
  290. $tmpEmp = $empMap[$item->employee_id] ?? null;
  291. // 组装每一行详情需要展示的字段
  292. $res[$item->main_id][] = [
  293. 'employee_number' => $tmpEmp ? $tmpEmp->number : '',
  294. 'employee_title' => $tmpEmp ? $tmpEmp->title : '',
  295. 'total_days' => $item->total_days,
  296. 'rd_total_days' => $item->rd_total_days,
  297. 'total_hours' => $item->total_hours,
  298. 'rd_total_hours' => $item->rd_total_hours,
  299. ];
  300. }
  301. return $res; // 返回 [main_id => [detail_row, detail_row]]
  302. }
  303. // 人员日工时单 ------------------------------------------------
  304. public function dailyPwOrderEdit($data,$user){
  305. list($status,$msg) = $this->dailyPwOrderRule($data, $user, false);
  306. if(!$status) return [$status,$msg];
  307. try {
  308. DB::beginTransaction();
  309. $model = DailyPwOrder::where('id',$data['id'])->first();
  310. $model->item_id = $data['item_id'] ?? 0;
  311. $model->save();
  312. $time = time();
  313. DailyPwOrderDetails::where('del_time',0)
  314. ->where('main_id', $model->id)
  315. ->update(['del_time' => $time]);
  316. $this->saveDetailDaily($model->id, $time, $data, $user);
  317. DB::commit();
  318. }catch (\Exception $exception){
  319. DB::rollBack();
  320. return [false,$exception->getMessage()];
  321. }
  322. return [true, ''];
  323. }
  324. public function dailyPwOrderAdd($data,$user){
  325. list($status,$msg) = $this->dailyPwOrderRule($data, $user);
  326. if(!$status) return [$status,$msg];
  327. try {
  328. DB::beginTransaction();
  329. $model = new DailyPwOrder();
  330. $model->code = $this->generateBillNo([
  331. 'top_depart_id' => $user['top_depart_id'],
  332. 'type' => DailyPwOrder::Order_type,
  333. 'period' => date("Ym", $data['order_time'])
  334. ]);
  335. $model->order_time = $data['order_time'] ?? 0;
  336. $model->item_id = $data['item_id'] ?? 0;
  337. $model->crt_id = $user['id'];
  338. $model->top_depart_id = $data['top_depart_id'];
  339. $model->save();
  340. $this->saveDetailDaily($model->id, time(), $data, $user);
  341. DB::commit();
  342. }catch (\Exception $exception){
  343. DB::rollBack();
  344. return [false,$exception->getMessage()];
  345. }
  346. return [true, ''];
  347. }
  348. private function saveDetailDaily($id, $time, $data, $user){
  349. if(! empty($data['details'])){
  350. $unit = [];
  351. foreach ($data['details'] as $value){
  352. $unit[] = [
  353. 'main_id' => $id,
  354. 'employee_id' => $value['employee_id'],
  355. 'start_time_hour' => $value['start_time_hour'],
  356. 'start_time_min' => $value['start_time_min'],
  357. 'end_time_hour' => $value['end_time_hour'],
  358. 'end_time_min' => $value['end_time_min'],
  359. 'total_work_min' => $value['total_work_min'],
  360. 'crt_time' => $time,
  361. 'top_depart_id' => $value['top_depart_id'],
  362. 'order_time' => $data['order_time'] ?? 0,
  363. 'item_id' => $data['item_id'],
  364. 'crt_id' => $user['id'],
  365. ];
  366. }
  367. if(! empty($unit)) DailyPwOrderDetails::insert($unit);
  368. }
  369. }
  370. private function getDetailDaily($id){
  371. $data = DailyPwOrderDetails::where('del_time',0)
  372. ->where('main_id', $id)
  373. ->select('employee_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_work_min')
  374. ->get()->toArray();
  375. $id = array_column($data,'employee_id');
  376. $map = Employee::whereIn('id', $id)
  377. ->select('title','id','number')
  378. ->get()
  379. ->keyBy('id')
  380. ->toArray();
  381. foreach ($data as $key => $value){
  382. $tmp = $map[$value['employee_id']] ?? [];
  383. $merge = [];
  384. $merge['employee_title'] = $tmp['title'];
  385. $merge['employee_number'] = $tmp['number'];
  386. $data[$key] = array_merge($value, $merge);
  387. }
  388. $detail = [
  389. 'details' => $data,
  390. ];
  391. //foreach ($detail as $key => $value) {
  392. // if (empty($value)) {
  393. //$detail[$key] = (object)[]; // 转成 stdClass 对象
  394. //}
  395. //}
  396. return $detail;
  397. }
  398. public function dailyPwOrderDel($data, $user){
  399. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  400. try {
  401. DB::beginTransaction();
  402. $time = time();
  403. $month = DailyPwOrder::where('del_time',0)
  404. ->whereIn('id',$data['id'])
  405. ->pluck('order_time')
  406. ->toArray();
  407. //归档
  408. list($status, $msg) = ArchiveService::isArchive($month, $user);
  409. if(! $status) return [false, $msg];
  410. DailyPwOrder::where('del_time',0)
  411. ->whereIn('id',$data['id'])
  412. ->update(['del_time' => $time]);
  413. DailyPwOrderDetails::where('del_time',0)
  414. ->whereIn('main_id', $data['id'])
  415. ->update(['del_time' => $time]);
  416. DB::commit();
  417. }catch (\Exception $exception){
  418. DB::rollBack();
  419. return [false,$exception->getMessage()];
  420. }
  421. return [true, ''];
  422. }
  423. public function dailyPwOrderDetail($data, $user){
  424. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  425. $customer = DailyPwOrder::where('del_time',0)
  426. ->where('id',$data['id'])
  427. ->first();
  428. if(empty($customer)) return [false,'人员日工时单不存在或已被删除'];
  429. $customer = $customer->toArray();
  430. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  431. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  432. $item = Item::where('id', $customer['item_id'])->first();
  433. $customer['item_title'] = $item->title ?? '';
  434. $customer['item_code'] = $item->code ?? '';
  435. $map = ArchiveService::fillIsArchive($customer['order_time'], $user);
  436. $customer['is_archive'] = $map[$customer['order_time']] ?? false;
  437. $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
  438. $details = $this->getDetailDaily($data['id']);
  439. $customer = array_merge($customer, $details);
  440. return [true, $customer];
  441. }
  442. public function dailyPwOrderCommon($data,$user, $field = []){
  443. if(empty($field)) $field = DailyPwOrder::$field;
  444. $model = DailyPwOrder::Clear($user,$data);
  445. $model = $model->where('del_time',0)
  446. ->select($field)
  447. ->orderby('id', 'desc');
  448. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  449. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  450. $model->where('order_time','>=',$return[0]);
  451. $model->where('order_time','<=',$return[1]);
  452. }
  453. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  454. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  455. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  456. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  457. $model->where('crt_time','>=',$return[0]);
  458. $model->where('crt_time','<=',$return[1]);
  459. }
  460. if (!empty($data['item_title'])) {
  461. $models = Item::TopClear($user,$data);
  462. $id = $models->where('del_time',0)
  463. ->where('title', 'LIKE', '%'.$data['item_title'].'%')
  464. ->pluck('id')
  465. ->all();
  466. $model->whereIn('item_id', $id);
  467. }
  468. return $model;
  469. }
  470. public function dailyPwOrderList($data,$user){
  471. $model = $this->dailyPwOrderCommon($data, $user);
  472. $list = $this->limit($model,'',$data);
  473. $list = $this->fillDataDaily($list, $user);
  474. return [true, $list];
  475. }
  476. public function dailyPwOrderRule(&$data, $user, $is_add = true){
  477. $data['top_depart_id'] = $user['top_depart_id'];
  478. if(empty($data['order_time'])) return [false, '单据日期不能为空'];
  479. $data['order_time'] = $this->changeDateToDate($data['order_time']);
  480. $orderTime = $data['order_time'];
  481. $itemId = $data['item_id'] ?? 0;
  482. // 使用日期范围限制
  483. list($status, $msg) = MiddleGroundService::checkTimestampInRange($data['order_time'], $data['top_depart_id']);
  484. if(! $status) return [false, $msg];
  485. //归档
  486. list($status, $msg) = ArchiveService::isArchive($data['order_time'], $user);
  487. if(! $status) return [false, $msg];
  488. if(empty($itemId)) return [false, '项目不能为空'];
  489. $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
  490. if(!$bool) return [false, '项目不存在或已被删除'];
  491. if(empty($data['details'])) return [false, '人员日工时单明细不能为空'];
  492. // --- 1. 批量预获取人员信息,用于报错提示 ---
  493. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'employee_id')));
  494. // 如果需要工号+姓名,建议这样获取:
  495. $empDisplayMap = Employee::whereIn('id', $allEmpIds)
  496. ->get(['id', 'number', 'title'])
  497. ->mapWithKeys(function($item){
  498. return [$item->id => "[{$item->number}]{$item->title}"];
  499. })->toArray();
  500. // 2. 本次提交内部重叠记录器
  501. $internalOverlap = [];
  502. foreach ($data['details'] as $key => $value){
  503. $line = $key + 1;
  504. $t = "第" . $line . "行";
  505. $empId = $value['employee_id'] ?? 0;
  506. if(empty($empId)) return [false, '人员不能为空'];
  507. $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
  508. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  509. if(!$res['valid']) return [false, $t . "人员{$empName}开始点:" . $res['error']];
  510. if($value['start_time_hour'] > 23) return [false, false, $t . "人员{$empName}开始点不合法"];
  511. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  512. if(!$res['valid']) return [false, $t . "人员{$empName}开始分:" . $res['error']];
  513. if($value['start_time_min'] > 60) return [false, false, $t . "人员{$empName}开始点不合法"];
  514. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  515. if(!$res['valid']) return [false, $t . "人员{$empName}结束点:" . $res['error']];
  516. if($value['end_time_hour'] > 24) return [false, false, $t . "人员{$empName}结束点不合法"];
  517. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  518. if(!$res['valid']) return [false, $t . "人员{$empName}结束分:" . $res['error']];
  519. if($value['end_time_min'] > 60) return [false, false, $t . "人员{$empName}结束分不合法"];
  520. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  521. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  522. if ($currentStart >= $currentEnd) {
  523. return [false, $t . "人员{$empName}:开始时间必须早于结束时间"];
  524. }
  525. // --- 新增:总分钟数校验 ---
  526. $calculatedTotal = $currentEnd - $currentStart;
  527. if (!isset($value['total_work_min']) || intval($value['total_work_min']) !== $calculatedTotal) {
  528. return [false, $t . "人员{$empName}:总工时计算有误,应为 {$calculatedTotal} 分钟"];
  529. }
  530. // --- 3. 内部重叠校验(防止一次提交多行重复) ---
  531. if (isset($internalOverlap[$empId])) {
  532. foreach ($internalOverlap[$empId] as $period) {
  533. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  534. return [false, "人员{$empName}在本次提交的多行明细中时间段重叠"];
  535. }
  536. }
  537. }
  538. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  539. $query = DB::table('daily_pw_order_details as d')
  540. ->join('daily_pw_order as m', 'd.main_id', '=', 'm.id')
  541. ->where('m.top_depart_id', $data['top_depart_id'])
  542. ->where('m.order_time', $orderTime)
  543. ->where('m.item_id', $itemId)
  544. ->where('d.employee_id', $empId)
  545. ->where('m.del_time', 0)
  546. ->where('d.del_time', 0);
  547. if (!$is_add && !empty($data['id'])) {
  548. $query->where('m.id', '<>', $data['id']);
  549. }
  550. $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
  551. foreach ($existingPeriods as $p) {
  552. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  553. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  554. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  555. return [false, "人员{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
  556. }
  557. }
  558. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  559. }
  560. if(!$is_add){
  561. if(empty($data['id'])) return [false,'ID不能为空'];
  562. $bool = DailyPwOrder::where('top_depart_id', $data['top_depart_id'])
  563. ->where('id',$data['id'])
  564. ->where('del_time',0)
  565. ->exists();
  566. if(!$bool) return [false, '人员日工时单不存在或已被删除'];
  567. }
  568. return [true, ''];
  569. }
  570. public function fillDataDaily($data, $user){
  571. if(empty($data['data'])) return $data;
  572. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  573. $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_id')));
  574. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'order_time')), $user);
  575. foreach ($data['data'] as $key => $value){
  576. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  577. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  578. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  579. $item_tmp = $item[$value['item_id']] ?? [];
  580. $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
  581. $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
  582. $data['data'][$key]['is_archive'] = $map[$value['order_time']] ?? false;
  583. }
  584. return $data;
  585. }
  586. public function fillDataForExportDaily($data, $column, &$return)
  587. {
  588. if (empty($data)) return;
  589. $mainIds = array_column($data, 'id');
  590. // 1. 获取详情及所有关联档案(项目、人员)的映射
  591. $detailsMap = $this->getDailyDetailsMap($mainIds, $data);
  592. foreach ($data as $main) {
  593. $mainId = $main['id'];
  594. $details = $detailsMap[$mainId] ?? [];
  595. // 2. 提取并格式化主表共有信息
  596. $mainInfo = [
  597. 'code' => $main['code'],
  598. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  599. ];
  600. if (empty($details)) {
  601. // 无明细时只导出一行主表信息
  602. $tempRow = [];
  603. foreach ($column as $col) {
  604. $tempRow[] = $mainInfo[$col] ?? '';
  605. }
  606. $return[] = $tempRow;
  607. } else {
  608. // 3. 平铺:将详情里的项目信息、人员信息与主表信息合并
  609. foreach ($details as $sub) {
  610. $fullRowData = array_merge($mainInfo, $sub);
  611. $tempRow = [];
  612. foreach ($column as $col) {
  613. $tempRow[] = $fullRowData[$col] ?? '';
  614. }
  615. $return[] = $tempRow;
  616. }
  617. }
  618. }
  619. }
  620. public function getDailyDetailsMap($mainIds, $mainData)
  621. {
  622. // 1. 获取所有子表记录
  623. $details = DB::table('daily_pw_order_details')
  624. ->where('del_time', 0)
  625. ->whereIn('main_id', $mainIds)
  626. ->get();
  627. // 2. 提取所有关联 ID
  628. $empIds = $details->pluck('employee_id')->unique();
  629. $itemIds = array_unique(array_column($mainData, 'item_id')); // 从主表数组提取项目ID
  630. // 3. 批量获取档案 Map
  631. $empMap = DB::table('employee')
  632. ->whereIn('id', $empIds)
  633. ->get(['id', 'title', 'number'])
  634. ->keyBy('id');
  635. $itemMap = DB::table('item')
  636. ->whereIn('id', $itemIds)
  637. ->get(['id', 'title', 'code'])
  638. ->keyBy('id');
  639. // 4. 将主表的项目信息预先挂载到主表 ID 下,方便后续合并
  640. $mainItemInfo = [];
  641. foreach ($mainData as $m) {
  642. $proj = $itemMap[$m['item_id']] ?? null;
  643. $mainItemInfo[$m['id']] = [
  644. 'item_code' => $proj ? $proj->code : '',
  645. 'item_title' => $proj ? $proj->title : '',
  646. ];
  647. }
  648. $res = [];
  649. if ($details->isEmpty()) {
  650. // 如果没有详情,把项目信息返回去,确保主表能导出行
  651. foreach ($mainItemInfo as $mId => $info) {
  652. $res[$mId] = [];
  653. }
  654. return $res;
  655. }
  656. foreach ($details as $item) {
  657. $emp = $empMap[$item->employee_id] ?? null;
  658. // 组装明细行数据
  659. $detailRow = [
  660. // 人员信息
  661. 'employee_number' => $emp ? $emp->number : '',
  662. 'employee_title' => $emp ? $emp->title : '',
  663. // 时间信息
  664. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  665. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  666. // 将主表的项目信息也塞进每一行详情里实现平铺
  667. 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
  668. 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
  669. ];
  670. $res[$item->main_id][] = $detailRow;
  671. }
  672. return $res;
  673. }
  674. public function dailyPwOrderCreate($data, $user)
  675. {
  676. $topDepartId = $user['top_depart_id'];
  677. if (empty($data['month'])) return [false, '月份不能为空'];
  678. $monthStart = $this->changeDateToDate($data['month']);
  679. // --- 一开始就做的核心校验 ---
  680. // 1. 检查是否存在月度工时明细(如果没有,队列执行也是徒劳)
  681. $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
  682. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  683. ->where('m.month', $monthStart)
  684. ->where('m.top_depart_id', $topDepartId)
  685. ->where('m.del_time', 0)
  686. ->where('d.del_time', 0)
  687. ->exists();
  688. if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
  689. // 2. 检查是否配置了工作日历
  690. $hasCalendar = DB::table('calendar_details')
  691. ->where('month', $monthStart)
  692. ->where('del_time', 0)
  693. ->exists();
  694. if (!$hasCalendar) return [false, '该月份工作日历未配置'];
  695. // 3. 检查是否配置了项目比例规则
  696. $hasRules = DB::table('rule_set as r')
  697. ->where('r.month', $monthStart)
  698. ->where('r.top_depart_id', $topDepartId)
  699. ->where('r.del_time', 0)
  700. ->exists();
  701. if (!$hasRules) return [false, '未找到该月份的规则配置单'];
  702. $data['type'] = "p_work";
  703. ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
  704. return [true, '生成任务已提交,系统正在后台处理,请稍后查看'];
  705. }
  706. public function dailyPwOrderCreateMain($data, $user)
  707. {
  708. $topDepartId = $user['top_depart_id'];
  709. if (empty($data['month'])) return [false, '月份不能为空'];
  710. $monthStart = $this->changeDateToDate($data['month']);
  711. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  712. $now = time();
  713. DB::beginTransaction();
  714. try {
  715. // --- 0. 清理旧数据 ---
  716. $oldOrderIds = DB::table('daily_pw_order')
  717. ->where('top_depart_id', $topDepartId)
  718. ->where('order_time', '>=', $monthStart)
  719. ->where('order_time', '<=', $monthEnd)
  720. ->where('is_create', 1)
  721. ->where('del_time', 0)
  722. ->pluck('id');
  723. if ($oldOrderIds->isNotEmpty()) {
  724. DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  725. DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  726. }
  727. // --- 1. 基础数据加载 ---
  728. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  729. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  730. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  731. ->where('m.del_time', 0)->where('d.del_time', 0)
  732. ->select('d.*')->get();
  733. if ($monthlyOrder->isEmpty()) return [false, '未找到月度工时明细'];
  734. $empIds = $monthlyOrder->pluck('employee_id')->unique()->toArray();
  735. $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  736. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  737. $ruleSet = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  738. ->where('r.month', $monthStart)->where('rd.type', RuleSetDetails::type_one)
  739. ->where('r.del_time', 0)->where('rd.del_time', 0)
  740. ->select('rd.*')->get()->groupBy('data_id');
  741. $allDays = DB::table('calendar_details')->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
  742. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  743. ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('m.del_time', 0)
  744. ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
  745. // --- 2. 核心分配逻辑:计算每天、每个项目、每个人的分钟数 ---
  746. $finalAlloc = [];
  747. foreach ($monthlyOrder as $mDetail) {
  748. $empId = $mDetail->employee_id;
  749. $empRules = $ruleSet->get($empId);
  750. if (!$empRules) continue;
  751. $empRemainingMin = (float)$mDetail->rd_total_hours * 60;
  752. if ($empRemainingMin <= 0) continue;
  753. foreach ($allDays as $dayInfo) {
  754. if ($empRemainingMin <= 0) break;
  755. $dayTs = $dayInfo->time;
  756. $isWorkDay = ($dayInfo->is_work == CalendarDetails::TYPE_ONE);
  757. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  758. $todayOvertimes = $todaySpecials->where('main_type', 2);
  759. if (!$isWorkDay && $todayOvertimes->isEmpty()) continue;
  760. // 计算当天可用总时长
  761. $dayAvailableMin = 0;
  762. if ($isWorkDay) {
  763. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  764. foreach ($baseRanges as $br) {
  765. $brS = $br->start_time_hour * 60 + $br->start_time_min;
  766. $brE = $br->end_time_hour * 60 + $br->end_time_min;
  767. $avail = (float)$br->total_work_min;
  768. foreach ($todaySpecials->where('main_type', 1) as $lv) {
  769. $overlap = min($brE, ($lv->end_time_hour * 60 + $lv->end_time_min)) - max($brS, ($lv->start_time_hour * 60 + $lv->start_time_min));
  770. if ($overlap > 0) $avail -= $overlap;
  771. }
  772. $dayAvailableMin += max(0, $avail);
  773. }
  774. }
  775. foreach ($todayOvertimes as $ot) $dayAvailableMin += (float)$ot->total_min;
  776. $canAllocToday = min($empRemainingMin, $dayAvailableMin);
  777. if ($canAllocToday <= 0) continue;
  778. foreach ($empRules as $rule) {
  779. $rate = (float)$rule->rate / 100;
  780. $projectMin = $canAllocToday * $rate;
  781. if ($projectMin > 0) {
  782. // 结果存入:[日期][项目][人员]
  783. $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
  784. }
  785. }
  786. $empRemainingMin -= $canAllocToday;
  787. }
  788. }
  789. // --- 3. 生成单据:解决时间重叠的核心逻辑 ---
  790. $newOrderIds = [];
  791. // 为了解决重叠,我们需要按 [日期][人员] 来追踪时间池的消耗进度
  792. $dailyEmpTimePools = [];
  793. foreach ($finalAlloc as $dayTs => $projects) {
  794. foreach ($projects as $itemId => $employees) {
  795. $mainId = DB::table('daily_pw_order')->insertGetId([
  796. 'code' => '', 'item_id' => $itemId, 'order_time' => $dayTs, 'top_depart_id' => $topDepartId,
  797. 'is_create' => 1, 'crt_id' => $user['id'], 'crt_time' => $now, 'upd_time' => $now,
  798. ]);
  799. $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
  800. foreach ($employees as $empId => $toAllocMin) {
  801. // 如果该员工当天的池子还没构建,先构建一次
  802. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  803. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  804. }
  805. $tempRem = $toAllocMin;
  806. // 指向该员工当天的可用池引用,这样处理完项目A,池子里的时间会自动被“消耗”
  807. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  808. if ($tempRem <= 0) break;
  809. $pMax = $p['e'] - $p['s'];
  810. if ($pMax <= 0) continue;
  811. $take = min($tempRem, $pMax);
  812. $realStart = $p['s'];
  813. $realEnd = $p['s'] + $take;
  814. DB::table('daily_pw_order_details')->insert([
  815. 'main_id' => $mainId, 'employee_id' => $empId, 'top_depart_id' => $topDepartId,
  816. 'start_time_hour' => floor($realStart / 60), 'start_time_min' => $realStart % 60,
  817. 'end_time_hour' => floor($realEnd / 60), 'end_time_min' => $realEnd % 60,
  818. 'total_work_min' => $take, 'crt_time' => $now, 'upd_time' => $now,
  819. ]);
  820. $tempRem -= $take;
  821. // 重要:消耗掉这个时段的起始位置,确保下一个项目从这里开始
  822. $p['s'] = $realEnd;
  823. }
  824. }
  825. }
  826. }
  827. // --- 4. 回填单号 ---
  828. if (empty($newOrderIds)) return [false, '未生成数据'];
  829. foreach ($newOrderIds as $item) {
  830. $code = $this->generateBillNo(['top_depart_id' => $topDepartId, 'type' => DailyPwOrder::Order_type, 'period' => date("Ym", $item['time'])]);
  831. DB::table('daily_pw_order')->where('id', $item['id'])->update(['code' => $code]);
  832. }
  833. DB::commit();
  834. } catch (\Exception $e) {
  835. DB::rollBack();
  836. return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
  837. }
  838. return [true, ''];
  839. }
  840. /**
  841. * 辅助函数:构建某人某天的初始可用时段池
  842. */
  843. private function buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData)
  844. {
  845. $dayInfo = $allDays->where('time', $dayTs)->first();
  846. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  847. $pool = [];
  848. if ($dayInfo && $dayInfo->is_work == CalendarDetails::TYPE_ONE) {
  849. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  850. foreach ($baseRanges as $br) {
  851. $currentS = $br->start_time_hour * 60 + $br->start_time_min;
  852. $eMin = $br->end_time_hour * 60 + $br->end_time_min;
  853. $sortedLeaves = $todaySpecials->where('main_type', 1)->sortBy('start_time_hour');
  854. foreach ($sortedLeaves as $lv) {
  855. $lvS = $lv->start_time_hour * 60 + $lv->start_time_min;
  856. $lvE = $lv->end_time_hour * 60 + $lv->end_time_min;
  857. if ($lvS < $eMin && $lvE > $currentS) {
  858. if ($lvS > $currentS) $pool[] = ['s' => $currentS, 'e' => $lvS];
  859. $currentS = max($currentS, $lvE);
  860. }
  861. }
  862. if ($currentS < $eMin) $pool[] = ['s' => $currentS, 'e' => $eMin];
  863. }
  864. }
  865. foreach ($todaySpecials->where('main_type', 2) as $ot) {
  866. $otS = $ot->start_time_hour * 60 + $ot->start_time_min;
  867. $pool[] = ['s' => $otS, 'e' => $otS + (float)$ot->total_min];
  868. }
  869. return $pool;
  870. }
  871. public function dailyPwOrderPreview($data, $user)
  872. {
  873. $topDepartId = $user['top_depart_id'];
  874. if (empty($data['month'])) return [false, '月份不能为空'];
  875. // 1. 前置校验 (保留你之前的校验逻辑)
  876. $monthStart = $this->changeDateToDate($data['month']);
  877. //归档
  878. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  879. if(! $status) return [false, $msg];
  880. // 1. 检查是否存在月度工时明细
  881. $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
  882. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  883. ->where('m.month', $monthStart)
  884. ->where('m.top_depart_id', $topDepartId)
  885. ->where('m.del_time', 0)
  886. ->where('d.del_time', 0)
  887. ->exists();
  888. if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
  889. // 2. 检查是否配置了工作日历
  890. $hasCalendar = DB::table('calendar_details')
  891. ->where('month', $monthStart)
  892. ->where('del_time', 0)
  893. ->exists();
  894. if (!$hasCalendar) return [false, '该月份工作日历未配置'];
  895. // 3. 检查是否配置了项目比例规则
  896. $hasRules = DB::table('rule_set as r')
  897. ->where('r.month', $monthStart)
  898. ->where('r.top_depart_id', $topDepartId)
  899. ->where('r.del_time', 0)
  900. ->exists();
  901. if (!$hasRules) return [false, '未找到该月份的规则配置单'];
  902. // 2. 调用核心计算逻辑 (抽取出的私有方法)
  903. $result = $this->calculateDailyAllocation($monthStart, $topDepartId, $user);
  904. if (!$result['status']) return [false, $result['msg']];
  905. // 3. 将结果存入临时表或直接返回
  906. // 建议增加一个 batch_id,防止多人操作冲突
  907. $batchId = uniqid('batch_');
  908. $previewData = $result['data'];
  909. return [true, [
  910. 'batch_id' => $batchId,
  911. 'list' => $previewData // 返回给前端展示
  912. ]];
  913. }
  914. /**
  915. * 核心分配逻辑:计算预览数据(确保全整数分钟)
  916. * @param int $monthStart 月初时间戳
  917. * @param int $topDepartId 顶级部门ID
  918. * @param array $user 用户信息
  919. * @return array
  920. */
  921. private function calculateDailyAllocation1($monthStart, $topDepartId, $user)
  922. {
  923. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  924. $now = time();
  925. // --- 1. 基础数据加载 ---
  926. // 加载月度工时明细,并关联人员姓名
  927. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  928. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  929. ->leftJoin('employee as e', 'e.id', '=', 'd.employee_id') // 关联人员表
  930. ->where('m.month', $monthStart)
  931. ->where('m.top_depart_id', $topDepartId)
  932. ->where('m.del_time', 0)
  933. ->where('d.del_time', 0)
  934. ->select('d.*', 'e.title as employee_title') // 获取人员姓名
  935. ->get();
  936. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到该月份的月度工时明细'];
  937. // 建立人员 ID -> 姓名的映射,方便后续取用
  938. $empNameMap = $monthlyOrder->pluck('employee_title', 'employee_id')->toArray();
  939. $empIds = array_keys($empNameMap);
  940. // 加载项目信息,用于获取项目名称
  941. // 假设项目表名为 items,请根据你实际的表名修改
  942. $itemIds = DB::table('rule_set_details as rd')
  943. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  944. ->where('r.month', $monthStart)
  945. ->where('r.top_depart_id', $topDepartId)
  946. ->pluck('rd.item_id')->unique()->toArray();
  947. $itemMap = DB::table('item')
  948. ->whereIn('id', $itemIds)
  949. ->pluck('title', 'id')
  950. ->toArray();
  951. // 加载分配规则
  952. $ruleSet = DB::table('rule_set_details as rd')
  953. ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  954. ->where('r.month', $monthStart)
  955. ->where('rd.type', 1)
  956. ->where('r.del_time', 0)
  957. ->where('rd.del_time', 0)
  958. ->select('rd.*')
  959. ->get()
  960. ->groupBy('data_id');
  961. // 加载员工/标准班次、日历、请假加班数据 (逻辑同前)
  962. $empWorkRanges = DB::table('employee_work_range')
  963. ->whereIn('employee_id', $empIds)
  964. ->where('top_depart_id', $topDepartId)
  965. ->get()->groupBy('employee_id');
  966. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)
  967. ->where('del_time', 0)->get();
  968. $allDays = DB::table('calendar_details')->where('top_depart_id', $topDepartId)
  969. ->where('month', $monthStart)
  970. ->where('del_time', 0)
  971. ->orderBy('time', 'asc')
  972. ->get();
  973. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  974. ->whereBetween('m.order_time', [$monthStart, $monthEnd])
  975. ->where('d.top_depart_id', $topDepartId)
  976. ->where('m.del_time', 0)
  977. ->select('d.*', 'm.order_time', 'm.type as main_type')
  978. ->get()->groupBy(['employee_id', 'order_time']);
  979. // --- 2. 阶段一:计算每个人每天在每个项目上应分配的整数分钟数 ---
  980. $finalAlloc = [];
  981. foreach ($monthlyOrder as $mDetail) {
  982. $empId = $mDetail->employee_id;
  983. $empRules = $ruleSet->get($empId);
  984. if (!$empRules) continue;
  985. $empRemainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  986. if ($empRemainingMin <= 0) continue;
  987. foreach ($allDays as $dayInfo) {
  988. if ($empRemainingMin <= 0) break;
  989. $dayTs = $dayInfo->time;
  990. $tempPool = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  991. $dayAvailableMin = 0;
  992. foreach ($tempPool as $p) { $dayAvailableMin += (int)($p['e'] - $p['s']); }
  993. if ($dayAvailableMin <= 0) continue;
  994. $canAllocToday = min($empRemainingMin, $dayAvailableMin);
  995. $allocatedInDay = 0;
  996. $ruleCount = count($empRules);
  997. foreach ($empRules as $index => $rule) {
  998. $rate = (float)$rule->rate / 100;
  999. if ($index === $ruleCount - 1) {
  1000. $projectMin = $canAllocToday - $allocatedInDay;
  1001. } else {
  1002. $projectMin = (int)round($canAllocToday * $rate);
  1003. }
  1004. if ($projectMin > 0) {
  1005. $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
  1006. $allocatedInDay += $projectMin;
  1007. }
  1008. }
  1009. $empRemainingMin -= $canAllocToday;
  1010. }
  1011. }
  1012. // --- 3. 阶段二:打散到具体时间点并生成预览行 ---
  1013. $previewList = [];
  1014. $dailyEmpTimePools = [];
  1015. $tempMainIdCounter = 1;
  1016. foreach ($finalAlloc as $dayTs => $projects) {
  1017. foreach ($projects as $itemId => $employees) {
  1018. $currentTempMainId = $tempMainIdCounter++;
  1019. // 获取项目名称
  1020. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  1021. foreach ($employees as $empId => $toAllocMin) {
  1022. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  1023. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  1024. }
  1025. $tempRem = (int)$toAllocMin;
  1026. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  1027. if ($tempRem <= 0) break;
  1028. $pMax = (int)($p['e'] - $p['s']);
  1029. if ($pMax <= 0) continue;
  1030. $take = min($tempRem, $pMax);
  1031. $realStart = (int)$p['s'];
  1032. $realEnd = $realStart + $take;
  1033. // 写入带 Title 的结果
  1034. $previewList[] = [
  1035. 'temp_main_id' => $currentTempMainId,
  1036. 'order_time' => date('Y-m-d', $dayTs),
  1037. 'order_timestamp' => $dayTs,
  1038. 'item_id' => $itemId,
  1039. 'item_title' => $itemTitle, // 项目名称
  1040. 'employee_id' => $empId,
  1041. 'employee_title' => $empNameMap[$empId] ?? '未知人员', // 人员姓名
  1042. 'start_time' => sprintf('%02d:%02d', floor($realStart / 60), $realStart % 60),
  1043. 'end_time' => sprintf('%02d:%02d', floor($realEnd / 60), $realEnd % 60),
  1044. 'start_hour' => (int)floor($realStart / 60),
  1045. 'start_min' => (int)($realStart % 60),
  1046. 'end_hour' => (int)floor($realEnd / 60),
  1047. 'end_min' => (int)($realEnd % 60),
  1048. 'total_work_min' => $take,
  1049. ];
  1050. $tempRem -= $take;
  1051. $p['s'] = $realEnd;
  1052. }
  1053. }
  1054. }
  1055. }
  1056. return ['status' => true, 'data' => $previewList];
  1057. }
  1058. private function calculateDailyAllocation($monthStart, $topDepartId, $user)
  1059. {
  1060. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  1061. $step = 5; // 5分钟硬对齐
  1062. // --- 1. 基础数据加载 (保持原版结构) ---
  1063. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  1064. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  1065. ->leftJoin('employee as e', 'e.id', '=', 'd.employee_id')
  1066. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  1067. ->where('m.del_time', 0)->where('d.del_time', 0)
  1068. ->select('d.*', 'e.title as employee_title')->get();
  1069. if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到明细'];
  1070. $empNameMap = $monthlyOrder->pluck('employee_title', 'employee_id')->toArray();
  1071. $empIds = array_keys($empNameMap);
  1072. $itemIds = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  1073. ->where('r.month', $monthStart)->where('r.top_depart_id', $topDepartId)->pluck('rd.item_id')->unique()->toArray();
  1074. $itemMap = DB::table('item')->whereIn('id', $itemIds)->pluck('title', 'id')->toArray();
  1075. $ruleSet = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  1076. ->where('r.month', $monthStart)->where('rd.type', 1)->where('r.del_time', 0)->where('rd.del_time', 0)
  1077. ->select('rd.*')->get()->groupBy('data_id');
  1078. $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  1079. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  1080. $allDays = DB::table('calendar_details')->where('top_depart_id', $topDepartId)->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
  1081. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  1082. ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('d.top_depart_id', $topDepartId)->where('m.del_time', 0)
  1083. ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
  1084. // --- 2. 阶段一:计算预分配 (加入动态余数抵消) ---
  1085. $finalAlloc = [];
  1086. $empBalance = []; // 记录每个人的“工时余额” [emp_id => minutes]
  1087. foreach ($monthlyOrder as $mDetail) {
  1088. $empId = $mDetail->employee_id;
  1089. $empRules = $ruleSet->get($empId);
  1090. if (!$empRules) continue;
  1091. $empRemainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
  1092. foreach ($allDays as $dayInfo) {
  1093. if ($empRemainingMin <= 0) break;
  1094. $dayTs = $dayInfo->time;
  1095. $tempPool = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  1096. $dayCapacity = 0;
  1097. foreach ($tempPool as $p) { $dayCapacity += (int)($p['e'] - $p['s']); }
  1098. if ($dayCapacity <= 0) continue;
  1099. // 核心变动:计算今天理想分配量,并尝试 5 分钟取整
  1100. $theoryAlloc = min($empRemainingMin, $dayCapacity);
  1101. // 如果还没到最后一天,强行把当天的分配量凑成 5 的倍数
  1102. if ($theoryAlloc < $empRemainingMin) {
  1103. // 结合之前的余额进行取整
  1104. $currentWithBalance = $theoryAlloc + ($empBalance[$empId] ?? 0);
  1105. $roundedAlloc = (int)round($currentWithBalance / $step) * $step;
  1106. // 不能超过当天池子上限
  1107. $canAllocToday = min($roundedAlloc, $dayCapacity);
  1108. $empBalance[$empId] = $currentWithBalance - $canAllocToday; // 剩下的留给明天
  1109. } else {
  1110. // 最后一天,全部吃掉(包含之前剩下的所有余额)
  1111. $canAllocToday = $empRemainingMin;
  1112. }
  1113. $allocatedInDay = 0;
  1114. $ruleCount = count($empRules);
  1115. foreach ($empRules as $index => $rule) {
  1116. $rate = (float)$rule->rate / 100;
  1117. $projectMin = ($index === $ruleCount - 1) ? ($canAllocToday - $allocatedInDay) : (int)round($canAllocToday * $rate);
  1118. // 内部项目分配也尽量 5 分钟取整
  1119. if ($index < $ruleCount - 1 && $projectMin > $step) {
  1120. $projectMin = (int)round($projectMin / $step) * $step;
  1121. }
  1122. if ($projectMin > 0) {
  1123. $finalAlloc[$dayTs][$rule->item_id][$empId] = ($finalAlloc[$dayTs][$rule->item_id][$empId] ?? 0) + $projectMin;
  1124. $allocatedInDay += $projectMin;
  1125. }
  1126. }
  1127. $empRemainingMin -= $canAllocToday;
  1128. }
  1129. }
  1130. // --- 3. 阶段二:打散到具体点 ---
  1131. $previewList = [];
  1132. $dailyEmpTimePools = [];
  1133. $tempMainIdCounter = 1;
  1134. foreach ($finalAlloc as $dayTs => $projects) {
  1135. foreach ($projects as $itemId => $employees) {
  1136. $itemTitle = $itemMap[$itemId] ?? '未知项目';
  1137. foreach ($employees as $empId => $toAllocMin) {
  1138. $currentTempMainId = $tempMainIdCounter++;
  1139. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  1140. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  1141. }
  1142. $tempRem = (int)$toAllocMin;
  1143. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  1144. if ($tempRem <= 0) break;
  1145. // 起点必须对齐 5 分钟
  1146. $realStart = (int)ceil($p['s'] / $step) * $step;
  1147. if ($realStart >= $p['e']) continue;
  1148. $pMax = (int)($p['e'] - $realStart);
  1149. $take = min($tempRem, $pMax);
  1150. $realEnd = $realStart + $take;
  1151. $previewList[] = [
  1152. 'temp_main_id' => $currentTempMainId,
  1153. 'order_time' => date('Y-m-d', $dayTs),
  1154. 'order_timestamp' => $dayTs,
  1155. 'item_id' => $itemId,
  1156. 'item_title' => $itemTitle,
  1157. 'employee_id' => $empId,
  1158. 'employee_title' => $empNameMap[$empId] ?? '未知人员',
  1159. 'start_time' => sprintf('%02d:%02d', floor($realStart / 60), $realStart % 60),
  1160. 'end_time' => sprintf('%02d:%02d', floor($realEnd / 60), $realEnd % 60),
  1161. 'start_hour' => (int)floor($realStart / 60),
  1162. 'start_min' => (int)($realStart % 60),
  1163. 'end_hour' => (int)floor($realEnd / 60),
  1164. 'end_min' => (int)($realEnd % 60),
  1165. 'total_work_min' => $take,
  1166. ];
  1167. $tempRem -= $take;
  1168. $p['s'] = $realEnd;
  1169. }
  1170. }
  1171. }
  1172. }
  1173. return ['status' => true, 'data' => $previewList];
  1174. }
  1175. public function dailyPwOrderSave($data, $user)
  1176. {
  1177. $list = $data['list'] ?? [];
  1178. if (empty($list)) return [false, '没有可保存的数据'];
  1179. $topDepartId = $user['top_depart_id'];
  1180. $month = $data['month'];
  1181. $monthStart = $this->changeDateToDate($month);
  1182. //归档
  1183. list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
  1184. if(! $status) return [false, $msg];
  1185. $now = time();
  1186. // 1. 预加载员工名称映射 (使用 title 字段)
  1187. $empIds = collect($list)->pluck('employee_id')->unique()->toArray();
  1188. $empMap = DB::table('employee')->whereIn('id', $empIds)->pluck('title', 'id')->toArray();
  1189. // --- 2. 重新分组并记录行号 ---
  1190. $groupedByOrder = [];
  1191. foreach ($list as $index => $item) {
  1192. $item['_line'] = $index + 1; // 记录原始行号(从1开始)
  1193. // 以日期字符串和项目ID作为分组 Key
  1194. $groupKey = $item['order_time'] . '_' . $item['item_id'];
  1195. $groupedByOrder[$groupKey][] = $item;
  1196. }
  1197. // 冲突校验器容器:记录 [员工ID][日期字符串] 下已占用的时间段
  1198. $empTimeline = [];
  1199. DB::beginTransaction();
  1200. try {
  1201. // A. 清理该月份旧数据
  1202. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  1203. $oldOrderIds = DB::table('daily_pw_order')
  1204. ->where('top_depart_id', $topDepartId)
  1205. ->whereBetween('order_time', [$monthStart, $monthEnd])
  1206. ->where('del_time', 0)
  1207. ->pluck('id');
  1208. if ($oldOrderIds->isNotEmpty()) {
  1209. DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  1210. DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  1211. }
  1212. // B. 遍历重组后的分组写入
  1213. foreach ($groupedByOrder as $details) {
  1214. $first = $details[0];
  1215. // 【修正】统一将前端日期字符串转为时间戳入库
  1216. $orderTimestamp = strtotime($first['order_time']);
  1217. $itemId = $first['item_id'];
  1218. // 写入主表
  1219. $mainId = DB::table('daily_pw_order')->insertGetId([
  1220. 'code' => '',
  1221. 'item_id' => $itemId,
  1222. 'order_time' => $orderTimestamp,
  1223. 'top_depart_id' => $topDepartId,
  1224. 'is_create' => 1,
  1225. 'crt_id' => $user['id'],
  1226. 'crt_time' => $now,
  1227. ]);
  1228. $insertDetails = [];
  1229. foreach ($details as $d) {
  1230. $rowNum = $d['_line'];
  1231. $empId = $d['employee_id'];
  1232. $empName = $empMap[$empId] ?? "人员(ID:{$empId})";
  1233. // --- 新增:月份一致性校验 ---
  1234. // 校验这行数据的日期是否属于当前保存的月份
  1235. if (date("Y-m", strtotime($d['order_time'])) !== $month) {
  1236. return [false, "第 {$rowNum} 行:人员[{$empName}]的日期[{$d['order_time']}]不属于保存月份[{$month}]"];
  1237. }
  1238. // 【修正】强制由后端计算分钟数
  1239. $s = (int)$d['start_hour'] * 60 + (int)$d['start_min'];
  1240. $e = (int)$d['end_hour'] * 60 + (int)$d['end_min'];
  1241. $calcTotalMin = $e - $s;
  1242. // 校验1:逻辑合法性
  1243. if ($calcTotalMin <= 0) {
  1244. return [false, "第 {$rowNum} 行:人员[{$empName}]在[{$d['order_time']}]的时间段无效:结束时间必须晚于开始时间"];
  1245. }
  1246. // 校验2:跨单据时间重叠校验
  1247. $dateStr = $d['order_time'];
  1248. if (isset($empTimeline[$empId][$dateStr])) {
  1249. foreach ($empTimeline[$empId][$dateStr] as $exist) {
  1250. if ($s < $exist['e'] && $e > $exist['s']) {
  1251. return [false, "第 {$rowNum} 行:人员[{$empName}]在[{$dateStr}]存在时间冲突({$d['start_time']}-{$d['end_time']}),请检查!"];
  1252. }
  1253. }
  1254. }
  1255. $empTimeline[$empId][$dateStr][] = ['s' => $s, 'e' => $e];
  1256. $insertDetails[] = [
  1257. 'main_id' => $mainId,
  1258. 'employee_id' => $empId,
  1259. 'top_depart_id' => $topDepartId,
  1260. 'start_time_hour' => $d['start_hour'],
  1261. 'start_time_min' => $d['start_min'],
  1262. 'end_time_hour' => $d['end_hour'],
  1263. 'end_time_min' => $d['end_min'],
  1264. 'total_work_min' => $calcTotalMin,
  1265. 'crt_time' => $now,
  1266. 'item_id' => $itemId,
  1267. 'order_time' => $orderTimestamp,
  1268. 'crt_id' => $user['id'],
  1269. ];
  1270. }
  1271. // 批量写入明细
  1272. DB::table('daily_pw_order_details')->insert($insertDetails);
  1273. // C. 回填单号
  1274. $code = $this->generateBillNo([
  1275. 'top_depart_id' => $topDepartId,
  1276. 'type' => DailyPwOrder::Order_type,
  1277. 'period' => date("Ym", $orderTimestamp)
  1278. ]);
  1279. DB::table('daily_pw_order')->where('id', $mainId)->update(['code' => $code]);
  1280. }
  1281. DB::commit();
  1282. return [true, ''];
  1283. } catch (\Exception $e) {
  1284. DB::rollBack();
  1285. return [false, "保存失败:" . $e->getMessage()];
  1286. }
  1287. }
  1288. }