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