PersonWorkService.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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){
  103. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  104. try {
  105. DB::beginTransaction();
  106. $time = time();
  107. MonthlyPwOrder::where('del_time',0)
  108. ->whereIn('id',$data['id'])
  109. ->update(['del_time' => $time]);
  110. MonthlyPwOrderDetails::where('del_time',0)
  111. ->whereIn('main_id', $data['id'])
  112. ->update(['del_time' => $time]);
  113. DB::commit();
  114. }catch (\Exception $exception){
  115. DB::rollBack();
  116. return [false,$exception->getMessage()];
  117. }
  118. return [true, ''];
  119. }
  120. public function monthlyPwOrderDetail($data, $user){
  121. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  122. $customer = MonthlyPwOrder::where('del_time',0)
  123. ->where('id',$data['id'])
  124. ->first();
  125. if(empty($customer)) return [false,'人员月度工时单不存在或已被删除'];
  126. $customer = $customer->toArray();
  127. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  128. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  129. $customer['month'] = $customer['month'] ? date("Y-m",$customer['month']): '';
  130. $details = $this->getDetail($data['id']);
  131. $customer = array_merge($customer, $details);
  132. return [true, $customer];
  133. }
  134. public function monthlyPwOrderCommon($data,$user, $field = []){
  135. if(empty($field)) $field = MonthlyPwOrder::$field;
  136. $model = MonthlyPwOrder::Clear($user,$data);
  137. $model = $model->where('del_time',0)
  138. ->select($field)
  139. ->orderby('id', 'desc');
  140. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  141. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  142. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  143. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  144. $model->where('crt_time','>=',$return[0]);
  145. $model->where('crt_time','<=',$return[1]);
  146. }
  147. return $model;
  148. }
  149. public function monthlyPwOrderList($data,$user){
  150. $model = $this->monthlyPwOrderCommon($data, $user);
  151. $list = $this->limit($model,'',$data);
  152. $list = $this->fillData($list);
  153. return [true, $list];
  154. }
  155. public function monthlyPwOrderRule(&$data, $user, $is_add = true)
  156. {
  157. if (empty($data['month'])) return [false, '月份不能为空'];
  158. $data['month'] = $this->changeDateToDate($data['month']);
  159. $data['top_depart_id'] = $user['top_depart_id'];
  160. if (empty($data['details'])) return [false, '人员月度工时单明细不能为空'];
  161. //获取系统计算的考勤基准数据 ---
  162. $empIds = array_column($data['details'], 'employee_id');
  163. list($status, $systemStats) = (new EmployeeService())->getEmployeesMonthStats($empIds, $data['month'], $user);
  164. if (!$status) return [false, $systemStats]; // 如果日历未设置,直接拦截
  165. foreach ($data['details'] as $key => $value) {
  166. if (empty($value['employee_id'])) return [false, '人员不能为空'];
  167. $empId = $value['employee_id'];
  168. // 基础数字格式检查
  169. foreach (['total_days', 'rd_total_days', 'total_hours', 'rd_total_hours'] as $field) {
  170. $precision = 2;
  171. $res = $this->checkNumber($value[$field], $precision, 'non-negative');
  172. if (!$res['valid']) return [false, $value['employee_title'] . "的" . $field . ":" . $res['error']];
  173. }
  174. // --- 业务逻辑校验:出勤天数与工时合法性 ---
  175. $sysData = $systemStats[$empId] ?? null;
  176. if ($sysData) {
  177. // 1. 研发天数不能大于出勤总天数
  178. if ($value['rd_total_days'] > $value['total_days']) {
  179. return [false, "第" . ($key + 1) . "行:研发出勤天数不能大于出勤总天数"];
  180. }
  181. // 2. 研发工时不能大于出勤总工时
  182. if ($value['rd_total_hours'] > $value['total_hours']) {
  183. return [false, "第" . ($key + 1) . "行:研发总工时不能大于出勤总工时"];
  184. }
  185. // 4. 校验出勤总天数是否超过了系统计算的上限
  186. if ($value['total_days'] != $sysData['attendance_days']) {
  187. return [false, "人员[{$empId}]填写的出勤总天数({$value['total_days']})不等于系统核算的天数({$sysData['attendance_days']})"];
  188. }
  189. //校验出勤总工时是否超过了系统计算的上限
  190. if ($value['total_hours'] != $sysData['final_work_hour']) {
  191. return [false, "人员[{$empId}]填写的出勤总工时({$value['total_hours']})不等于系统核算的工时({$sysData['final_work_hour']})"];
  192. }
  193. }
  194. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  195. }
  196. // --- 查重与唯一性校验 ---
  197. list($status, $msg) = $this->checkArrayRepeat($data['details'], 'employee_id', '人员');
  198. if (!$status) return [false, $msg];
  199. $query = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
  200. ->where('month', $data['month'])
  201. ->where('del_time', 0);
  202. if (!$is_add) {
  203. if (empty($data['id'])) return [false, 'ID不能为空'];
  204. $query->where('id', '<>', $data['id']);
  205. }
  206. if ($query->exists()) {
  207. return [false, date("Y-m", $data['month']) . '已存在人员月度研发工时单'];
  208. }
  209. return [true, ''];
  210. }
  211. public function monthlyPwOrderRule1(&$data, $user, $is_add = true){
  212. if(empty($data['month'])) return [false, '月份不能为空'];
  213. $data['month'] = $this->changeDateToDate($data['month']);
  214. $data['top_depart_id'] = $user['top_depart_id'];
  215. if(empty($data['details'])) return [false, '人员月度工时单明细不能为空'];
  216. foreach ($data['details'] as $key => $value){
  217. if(empty($value['employee_id'])) return [false, '人员不能为空'];
  218. $res = $this->checkNumber($value['total_days'],0,'non-negative');
  219. if(! $res['valid']) return [false,'出勤总天数:' . $res['error']];
  220. $res = $this->checkNumber($value['rd_total_days'],0,'non-negative');
  221. if(! $res['valid']) return [false,'研发出勤总天数:' . $res['error']];
  222. $res = $this->checkNumber($value['total_hours'],2,'non-negative');
  223. if(! $res['valid']) return [false,'出勤总工时:' . $res['error']];
  224. $res = $this->checkNumber($value['rd_total_hours'],2,'non-negative');
  225. if(! $res['valid']) return [false,'研发总工时:' . $res['error']];
  226. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  227. }
  228. list($status, $msg) = $this->checkArrayRepeat($data['details'],'employee_id','人员');
  229. if(! $status) return [false, $msg];
  230. if($is_add){
  231. $bool = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
  232. ->where('month', $data['month'])
  233. ->where('del_time',0)
  234. ->exists();
  235. }else{
  236. if(empty($data['id'])) return [false,'ID不能为空'];
  237. $bool = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
  238. ->where('month', $data['month'])
  239. ->where('id','<>',$data['id'])
  240. ->where('del_time',0)
  241. ->exists();
  242. }
  243. if($bool) return [false, date("Y-m", $data['month']) . '已存在人员月度研发工时单'];
  244. return [true, ''];
  245. }
  246. public function fillData($data){
  247. if(empty($data['data'])) return $data;
  248. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  249. foreach ($data['data'] as $key => $value){
  250. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  251. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  252. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  253. }
  254. return $data;
  255. }
  256. public function fillDataForExport($data, $column, &$return)
  257. {
  258. if(empty($data)) return;
  259. $mainIds = array_column($data, 'id');
  260. // 获取详情映射 [main_id => [details...]]
  261. $detailsMap = $this->getDetailsMap($mainIds);
  262. // 默认空行模板
  263. $defaultRow = array_fill_keys($column, '');
  264. foreach ($data as $main) {
  265. $mainId = $main['id'];
  266. $details = $detailsMap[$mainId] ?? [];
  267. // 提取主表信息
  268. $mainInfo = [
  269. 'code' => $main['code'],
  270. 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
  271. ];
  272. if (empty($details)) {
  273. // 如果没有详情,至少导出一行主表信息(可选)
  274. $return[] = array_merge($defaultRow, $mainInfo);
  275. } else {
  276. // 核心:遍历详情,每一行详情都合并主表信息
  277. foreach ($details as $sub) {
  278. // 合并主表字段 + 详情字段
  279. $fullRow = array_merge($mainInfo, $sub);
  280. // 过滤掉不在导出列里的字段,并补充缺失列
  281. $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
  282. }
  283. }
  284. }
  285. }
  286. public function getDetailsMap($main_ids)
  287. {
  288. // 获取详情
  289. $details = MonthlyPwOrderDetails::where('del_time', 0)
  290. ->whereIn('main_id', $main_ids)
  291. ->get();
  292. // 获取人员信息
  293. $empIds = $details->pluck('employee_id')->unique();
  294. $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id');
  295. $res = [];
  296. foreach ($details as $item) {
  297. $tmpEmp = $empMap[$item->employee_id] ?? null;
  298. // 组装每一行详情需要展示的字段
  299. $res[$item->main_id][] = [
  300. 'employee_number' => $tmpEmp ? $tmpEmp->number : '',
  301. 'employee_title' => $tmpEmp ? $tmpEmp->title : '',
  302. 'total_days' => $item->total_days,
  303. 'rd_total_days' => $item->rd_total_days,
  304. 'total_hours' => $item->total_hours,
  305. 'rd_total_hours' => $item->rd_total_hours,
  306. ];
  307. }
  308. return $res; // 返回 [main_id => [detail_row, detail_row]]
  309. }
  310. // 人员日工时单 ------------------------------------------------
  311. public function dailyPwOrderEdit($data,$user){
  312. list($status,$msg) = $this->dailyPwOrderRule($data, $user, false);
  313. if(!$status) return [$status,$msg];
  314. try {
  315. DB::beginTransaction();
  316. $model = DailyPwOrder::where('id',$data['id'])->first();
  317. $model->item_id = $data['item_id'] ?? 0;
  318. $model->save();
  319. $time = time();
  320. DailyPwOrderDetails::where('del_time',0)
  321. ->where('main_id', $model->id)
  322. ->update(['del_time' => $time]);
  323. $this->saveDetailDaily($model->id, $time, $data);
  324. DB::commit();
  325. }catch (\Exception $exception){
  326. DB::rollBack();
  327. return [false,$exception->getMessage()];
  328. }
  329. return [true, ''];
  330. }
  331. public function dailyPwOrderAdd($data,$user){
  332. list($status,$msg) = $this->dailyPwOrderRule($data, $user);
  333. if(!$status) return [$status,$msg];
  334. try {
  335. DB::beginTransaction();
  336. $model = new DailyPwOrder();
  337. $model->code = $this->generateBillNo([
  338. 'top_depart_id' => $user['top_depart_id'],
  339. 'type' => DailyPwOrder::Order_type,
  340. 'period' => date("Ym", $data['order_time'])
  341. ]);
  342. $model->order_time = $data['order_time'] ?? 0;
  343. $model->item_id = $data['item_id'] ?? 0;
  344. $model->crt_id = $user['id'];
  345. $model->top_depart_id = $data['top_depart_id'];
  346. $model->save();
  347. $this->saveDetailDaily($model->id, time(), $data);
  348. DB::commit();
  349. }catch (\Exception $exception){
  350. DB::rollBack();
  351. return [false,$exception->getMessage()];
  352. }
  353. return [true, ''];
  354. }
  355. private function saveDetailDaily($id, $time, $data){
  356. if(! empty($data['details'])){
  357. $unit = [];
  358. foreach ($data['details'] as $value){
  359. $unit[] = [
  360. 'main_id' => $id,
  361. 'employee_id' => $value['employee_id'],
  362. 'start_time_hour' => $value['start_time_hour'],
  363. 'start_time_min' => $value['start_time_min'],
  364. 'end_time_hour' => $value['end_time_hour'],
  365. 'end_time_min' => $value['end_time_min'],
  366. 'total_work_min' => $value['total_work_min'],
  367. 'crt_time' => $time,
  368. 'top_depart_id' => $value['top_depart_id'],
  369. ];
  370. }
  371. if(! empty($unit)) DailyPwOrderDetails::insert($unit);
  372. }
  373. }
  374. private function getDetailDaily($id){
  375. $data = DailyPwOrderDetails::where('del_time',0)
  376. ->where('main_id', $id)
  377. ->select('employee_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_work_min')
  378. ->get()->toArray();
  379. $id = array_column($data,'employee_id');
  380. $map = Employee::whereIn('id', $id)
  381. ->select('title','id','number')
  382. ->get()
  383. ->keyBy('id')
  384. ->toArray();
  385. foreach ($data as $key => $value){
  386. $tmp = $map[$value['employee_id']] ?? [];
  387. $merge = [];
  388. $merge['employee_title'] = $tmp['title'];
  389. $merge['employee_number'] = $tmp['number'];
  390. $data[$key] = array_merge($value, $merge);
  391. }
  392. $detail = [
  393. 'details' => $data,
  394. ];
  395. foreach ($detail as $key => $value) {
  396. if (empty($value)) {
  397. $detail[$key] = (object)[]; // 转成 stdClass 对象
  398. }
  399. }
  400. return $detail;
  401. }
  402. public function dailyPwOrderDel($data){
  403. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  404. try {
  405. DB::beginTransaction();
  406. $time = time();
  407. DailyPwOrder::where('del_time',0)
  408. ->whereIn('id',$data['id'])
  409. ->update(['del_time' => $time]);
  410. DailyPwOrderDetails::where('del_time',0)
  411. ->whereIn('main_id', $data['id'])
  412. ->update(['del_time' => $time]);
  413. DB::commit();
  414. }catch (\Exception $exception){
  415. DB::rollBack();
  416. return [false,$exception->getMessage()];
  417. }
  418. return [true, ''];
  419. }
  420. public function dailyPwOrderDetail($data, $user){
  421. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  422. $customer = DailyPwOrder::where('del_time',0)
  423. ->where('id',$data['id'])
  424. ->first();
  425. if(empty($customer)) return [false,'人员日工时单不存在或已被删除'];
  426. $customer = $customer->toArray();
  427. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  428. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  429. $item = Item::where('id', $customer['item_id'])->first();
  430. $customer['item_title'] = $item->title;
  431. $customer['item_code'] = $item->code;
  432. $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
  433. $details = $this->getDetailDaily($data['id']);
  434. $customer = array_merge($customer, $details);
  435. return [true, $customer];
  436. }
  437. public function dailyPwOrderCommon($data,$user, $field = []){
  438. if(empty($field)) $field = DailyPwOrder::$field;
  439. $model = DailyPwOrder::Clear($user,$data);
  440. $model = $model->where('del_time',0)
  441. ->select($field)
  442. ->orderby('id', 'desc');
  443. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  444. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  445. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  446. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  447. $model->where('crt_time','>=',$return[0]);
  448. $model->where('crt_time','<=',$return[1]);
  449. }
  450. return $model;
  451. }
  452. public function dailyPwOrderList($data,$user){
  453. $model = $this->dailyPwOrderCommon($data, $user);
  454. $list = $this->limit($model,'',$data);
  455. $list = $this->fillDataDaily($list);
  456. return [true, $list];
  457. }
  458. public function dailyPwOrderRule(&$data, $user, $is_add = true){
  459. if(empty($data['order_time'])) return [false, '单据日期不能为空'];
  460. $data['order_time'] = $this->changeDateToDate($data['order_time']);
  461. $orderTime = $data['order_time'];
  462. $itemId = $data['item_id'] ?? 0;
  463. if(empty($itemId)) return [false, '项目不能为空'];
  464. $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
  465. if(!$bool) return [false, '项目不存在或已被删除'];
  466. $data['top_depart_id'] = $user['top_depart_id'];
  467. if(empty($data['details'])) return [false, '人员日工时单明细不能为空'];
  468. // --- 1. 批量预获取人员信息,用于报错提示 ---
  469. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'employee_id')));
  470. // 如果需要工号+姓名,建议这样获取:
  471. $empDisplayMap = Employee::whereIn('id', $allEmpIds)
  472. ->get(['id', 'number', 'title'])
  473. ->mapWithKeys(function($item){
  474. return [$item->id => "[{$item->number}]{$item->title}"];
  475. })->toArray();
  476. // 2. 本次提交内部重叠记录器
  477. $internalOverlap = [];
  478. foreach ($data['details'] as $key => $value){
  479. $empId = $value['employee_id'] ?? 0;
  480. if(empty($empId)) return [false, '人员不能为空'];
  481. $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
  482. $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
  483. if(!$res['valid']) return [false, "人员{$empName}开始点:" . $res['error']];
  484. if($value['start_time_hour'] > 23) return [false, false, "人员{$empName}开始点不合法"];
  485. $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
  486. if(!$res['valid']) return [false, "人员{$empName}开始分:" . $res['error']];
  487. if($value['start_time_min'] > 60) return [false, false, "人员{$empName}开始点不合法"];
  488. $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
  489. if(!$res['valid']) return [false, "人员{$empName}结束点:" . $res['error']];
  490. if($value['end_time_hour'] > 24) return [false, false, "人员{$empName}结束点不合法"];
  491. $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
  492. if(!$res['valid']) return [false, "人员{$empName}结束分:" . $res['error']];
  493. if($value['end_time_min'] > 60) return [false, false, "人员{$empName}结束分不合法"];
  494. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  495. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  496. if ($currentStart >= $currentEnd) {
  497. return [false, "人员{$empName}:开始时间必须早于结束时间"];
  498. }
  499. // --- 3. 内部重叠校验(防止一次提交多行重复) ---
  500. if (isset($internalOverlap[$empId])) {
  501. foreach ($internalOverlap[$empId] as $period) {
  502. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  503. return [false, "人员{$empName}在本次提交的多行明细中时间段重叠"];
  504. }
  505. }
  506. }
  507. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  508. $query = DB::table('daily_pw_order_details as d')
  509. ->join('daily_pw_order as m', 'd.main_id', '=', 'm.id')
  510. ->where('m.top_depart_id', $data['top_depart_id'])
  511. ->where('m.order_time', $orderTime)
  512. ->where('m.item_id', $itemId)
  513. ->where('d.employee_id', $empId)
  514. ->where('m.del_time', 0)
  515. ->where('d.del_time', 0);
  516. if (!$is_add && !empty($data['id'])) {
  517. $query->where('m.id', '<>', $data['id']);
  518. }
  519. $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
  520. foreach ($existingPeriods as $p) {
  521. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  522. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  523. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  524. return [false, "人员{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
  525. }
  526. }
  527. $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
  528. }
  529. if(!$is_add){
  530. if(empty($data['id'])) return [false,'ID不能为空'];
  531. $bool = DailyPwOrder::where('top_depart_id', $data['top_depart_id'])
  532. ->where('id',$data['id'])
  533. ->where('del_time',0)
  534. ->exists();
  535. if(!$bool) return [false, '人员日工时单不存在或已被删除'];
  536. }
  537. return [true, ''];
  538. }
  539. public function fillDataDaily($data){
  540. if(empty($data['data'])) return $data;
  541. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  542. $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_id')));
  543. foreach ($data['data'] as $key => $value){
  544. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  545. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  546. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  547. $item_tmp = $item[$value['item_id']] ?? [];
  548. $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
  549. $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
  550. }
  551. return $data;
  552. }
  553. public function fillDataForExportDaily($data, $column, &$return)
  554. {
  555. if (empty($data)) return;
  556. $mainIds = array_column($data, 'id');
  557. // 1. 获取详情及所有关联档案(项目、人员)的映射
  558. $detailsMap = $this->getDailyDetailsMap($mainIds, $data);
  559. foreach ($data as $main) {
  560. $mainId = $main['id'];
  561. $details = $detailsMap[$mainId] ?? [];
  562. // 2. 提取并格式化主表共有信息
  563. $mainInfo = [
  564. 'code' => $main['code'],
  565. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  566. ];
  567. if (empty($details)) {
  568. // 无明细时只导出一行主表信息
  569. $tempRow = [];
  570. foreach ($column as $col) {
  571. $tempRow[] = $mainInfo[$col] ?? '';
  572. }
  573. $return[] = $tempRow;
  574. } else {
  575. // 3. 平铺:将详情里的项目信息、人员信息与主表信息合并
  576. foreach ($details as $sub) {
  577. $fullRowData = array_merge($mainInfo, $sub);
  578. $tempRow = [];
  579. foreach ($column as $col) {
  580. $tempRow[] = $fullRowData[$col] ?? '';
  581. }
  582. $return[] = $tempRow;
  583. }
  584. }
  585. }
  586. }
  587. public function getDailyDetailsMap($mainIds, $mainData)
  588. {
  589. // 1. 获取所有子表记录
  590. $details = DB::table('daily_pw_order_details')
  591. ->where('del_time', 0)
  592. ->whereIn('main_id', $mainIds)
  593. ->get();
  594. // 2. 提取所有关联 ID
  595. $empIds = $details->pluck('employee_id')->unique();
  596. $itemIds = array_unique(array_column($mainData, 'item_id')); // 从主表数组提取项目ID
  597. // 3. 批量获取档案 Map
  598. $empMap = DB::table('employee')
  599. ->whereIn('id', $empIds)
  600. ->get(['id', 'title', 'number'])
  601. ->keyBy('id');
  602. $itemMap = DB::table('item')
  603. ->whereIn('id', $itemIds)
  604. ->get(['id', 'title', 'code'])
  605. ->keyBy('id');
  606. // 4. 将主表的项目信息预先挂载到主表 ID 下,方便后续合并
  607. $mainItemInfo = [];
  608. foreach ($mainData as $m) {
  609. $proj = $itemMap[$m['item_id']] ?? null;
  610. $mainItemInfo[$m['id']] = [
  611. 'item_code' => $proj ? $proj->code : '',
  612. 'item_title' => $proj ? $proj->title : '',
  613. ];
  614. }
  615. $res = [];
  616. if ($details->isEmpty()) {
  617. // 如果没有详情,把项目信息返回去,确保主表能导出行
  618. foreach ($mainItemInfo as $mId => $info) {
  619. $res[$mId] = [];
  620. }
  621. return $res;
  622. }
  623. foreach ($details as $item) {
  624. $emp = $empMap[$item->employee_id] ?? null;
  625. // 组装明细行数据
  626. $detailRow = [
  627. // 人员信息
  628. 'employee_number' => $emp ? $emp->number : '',
  629. 'employee_title' => $emp ? $emp->title : '',
  630. // 时间信息
  631. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  632. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  633. // 将主表的项目信息也塞进每一行详情里实现平铺
  634. 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
  635. 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
  636. ];
  637. $res[$item->main_id][] = $detailRow;
  638. }
  639. return $res;
  640. }
  641. public function dailyPwOrderCreate($data, $user)
  642. {
  643. $topDepartId = $user['top_depart_id'];
  644. if (empty($data['month'])) return [false, '月份不能为空'];
  645. $monthStart = $this->changeDateToDate($data['month']);
  646. // --- 一开始就做的核心校验 ---
  647. // 1. 检查是否存在月度工时明细(如果没有,队列执行也是徒劳)
  648. $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
  649. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  650. ->where('m.month', $monthStart)
  651. ->where('m.top_depart_id', $topDepartId)
  652. ->where('m.del_time', 0)
  653. ->where('d.del_time', 0)
  654. ->exists();
  655. if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
  656. // 2. 检查是否配置了工作日历
  657. $hasCalendar = DB::table('calendar_details')
  658. ->where('month', $monthStart)
  659. ->where('del_time', 0)
  660. ->exists();
  661. if (!$hasCalendar) return [false, '该月份工作日历未配置'];
  662. // 3. 检查是否配置了项目比例规则
  663. $hasRules = DB::table('rule_set as r')
  664. ->where('r.month', $monthStart)
  665. ->where('r.top_depart_id', $topDepartId)
  666. ->where('r.del_time', 0)
  667. ->exists();
  668. if (!$hasRules) return [false, '未找到该月份的规则配置单'];
  669. $data['type'] = "p_work";
  670. ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
  671. return [true, '生成任务已提交,系统正在后台处理,请稍后查看'];
  672. }
  673. public function dailyPwOrderCreateMain($data, $user)
  674. {
  675. $topDepartId = $user['top_depart_id'];
  676. if (empty($data['month'])) return [false, '月份不能为空'];
  677. $monthStart = $this->changeDateToDate($data['month']);
  678. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  679. $now = time();
  680. DB::beginTransaction();
  681. try {
  682. // --- 0. 清理旧数据 ---
  683. $oldOrderIds = DB::table('daily_pw_order')
  684. ->where('top_depart_id', $topDepartId)
  685. ->where('order_time', '>=', $monthStart)
  686. ->where('order_time', '<=', $monthEnd)
  687. ->where('is_create', 1)
  688. ->where('del_time', 0)
  689. ->pluck('id');
  690. if ($oldOrderIds->isNotEmpty()) {
  691. DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
  692. DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
  693. }
  694. // --- 1. 基础数据加载 ---
  695. $monthlyOrder = DB::table('monthly_pw_order_details as d')
  696. ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
  697. ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
  698. ->where('m.del_time', 0)->where('d.del_time', 0)
  699. ->select('d.*')->get();
  700. if ($monthlyOrder->isEmpty()) return [false, '未找到月度工时明细'];
  701. $empIds = $monthlyOrder->pluck('employee_id')->unique()->toArray();
  702. $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  703. $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
  704. $ruleSet = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
  705. ->where('r.month', $monthStart)->where('rd.type', RuleSetDetails::type_one)
  706. ->where('r.del_time', 0)->where('rd.del_time', 0)
  707. ->select('rd.*')->get()->groupBy('data_id');
  708. $allDays = DB::table('calendar_details')->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
  709. $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  710. ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('m.del_time', 0)
  711. ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
  712. // --- 2. 核心分配逻辑:计算每天、每个项目、每个人的分钟数 ---
  713. $finalAlloc = [];
  714. foreach ($monthlyOrder as $mDetail) {
  715. $empId = $mDetail->employee_id;
  716. $empRules = $ruleSet->get($empId);
  717. if (!$empRules) continue;
  718. $empRemainingMin = (float)$mDetail->rd_total_hours * 60;
  719. if ($empRemainingMin <= 0) continue;
  720. foreach ($allDays as $dayInfo) {
  721. if ($empRemainingMin <= 0) break;
  722. $dayTs = $dayInfo->time;
  723. $isWorkDay = ($dayInfo->is_work == CalendarDetails::TYPE_ONE);
  724. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  725. $todayOvertimes = $todaySpecials->where('main_type', 2);
  726. if (!$isWorkDay && $todayOvertimes->isEmpty()) continue;
  727. // 计算当天可用总时长
  728. $dayAvailableMin = 0;
  729. if ($isWorkDay) {
  730. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  731. foreach ($baseRanges as $br) {
  732. $brS = $br->start_time_hour * 60 + $br->start_time_min;
  733. $brE = $br->end_time_hour * 60 + $br->end_time_min;
  734. $avail = (float)$br->total_work_min;
  735. foreach ($todaySpecials->where('main_type', 1) as $lv) {
  736. $overlap = min($brE, ($lv->end_time_hour * 60 + $lv->end_time_min)) - max($brS, ($lv->start_time_hour * 60 + $lv->start_time_min));
  737. if ($overlap > 0) $avail -= $overlap;
  738. }
  739. $dayAvailableMin += max(0, $avail);
  740. }
  741. }
  742. foreach ($todayOvertimes as $ot) $dayAvailableMin += (float)$ot->total_min;
  743. $canAllocToday = min($empRemainingMin, $dayAvailableMin);
  744. if ($canAllocToday <= 0) continue;
  745. foreach ($empRules as $rule) {
  746. $rate = (float)$rule->rate / 100;
  747. $projectMin = $canAllocToday * $rate;
  748. if ($projectMin > 0) {
  749. // 结果存入:[日期][项目][人员]
  750. $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
  751. }
  752. }
  753. $empRemainingMin -= $canAllocToday;
  754. }
  755. }
  756. // --- 3. 生成单据:解决时间重叠的核心逻辑 ---
  757. $newOrderIds = [];
  758. // 为了解决重叠,我们需要按 [日期][人员] 来追踪时间池的消耗进度
  759. $dailyEmpTimePools = [];
  760. foreach ($finalAlloc as $dayTs => $projects) {
  761. foreach ($projects as $itemId => $employees) {
  762. $mainId = DB::table('daily_pw_order')->insertGetId([
  763. 'code' => '', 'item_id' => $itemId, 'order_time' => $dayTs, 'top_depart_id' => $topDepartId,
  764. 'is_create' => 1, 'crt_id' => $user['id'], 'crt_time' => $now, 'upd_time' => $now,
  765. ]);
  766. $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
  767. foreach ($employees as $empId => $toAllocMin) {
  768. // 如果该员工当天的池子还没构建,先构建一次
  769. if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
  770. $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
  771. }
  772. $tempRem = $toAllocMin;
  773. // 指向该员工当天的可用池引用,这样处理完项目A,池子里的时间会自动被“消耗”
  774. foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
  775. if ($tempRem <= 0) break;
  776. $pMax = $p['e'] - $p['s'];
  777. if ($pMax <= 0) continue;
  778. $take = min($tempRem, $pMax);
  779. $realStart = $p['s'];
  780. $realEnd = $p['s'] + $take;
  781. DB::table('daily_pw_order_details')->insert([
  782. 'main_id' => $mainId, 'employee_id' => $empId, 'top_depart_id' => $topDepartId,
  783. 'start_time_hour' => floor($realStart / 60), 'start_time_min' => $realStart % 60,
  784. 'end_time_hour' => floor($realEnd / 60), 'end_time_min' => $realEnd % 60,
  785. 'total_work_min' => $take, 'crt_time' => $now, 'upd_time' => $now,
  786. ]);
  787. $tempRem -= $take;
  788. // 重要:消耗掉这个时段的起始位置,确保下一个项目从这里开始
  789. $p['s'] = $realEnd;
  790. }
  791. }
  792. }
  793. }
  794. // --- 4. 回填单号 ---
  795. if (empty($newOrderIds)) return [false, '未生成数据'];
  796. foreach ($newOrderIds as $item) {
  797. $code = $this->generateBillNo(['top_depart_id' => $topDepartId, 'type' => DailyPwOrder::Order_type, 'period' => date("Ym", $item['time'])]);
  798. DB::table('daily_pw_order')->where('id', $item['id'])->update(['code' => $code]);
  799. }
  800. DB::commit();
  801. } catch (\Exception $e) {
  802. DB::rollBack();
  803. return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
  804. }
  805. return [true, ''];
  806. }
  807. /**
  808. * 辅助函数:构建某人某天的初始可用时段池
  809. */
  810. private function buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData)
  811. {
  812. $dayInfo = $allDays->where('time', $dayTs)->first();
  813. $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
  814. $pool = [];
  815. if ($dayInfo && $dayInfo->is_work == CalendarDetails::TYPE_ONE) {
  816. $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
  817. foreach ($baseRanges as $br) {
  818. $currentS = $br->start_time_hour * 60 + $br->start_time_min;
  819. $eMin = $br->end_time_hour * 60 + $br->end_time_min;
  820. $sortedLeaves = $todaySpecials->where('main_type', 1)->sortBy('start_time_hour');
  821. foreach ($sortedLeaves as $lv) {
  822. $lvS = $lv->start_time_hour * 60 + $lv->start_time_min;
  823. $lvE = $lv->end_time_hour * 60 + $lv->end_time_min;
  824. if ($lvS < $eMin && $lvE > $currentS) {
  825. if ($lvS > $currentS) $pool[] = ['s' => $currentS, 'e' => $lvS];
  826. $currentS = max($currentS, $lvE);
  827. }
  828. }
  829. if ($currentS < $eMin) $pool[] = ['s' => $currentS, 'e' => $eMin];
  830. }
  831. }
  832. foreach ($todaySpecials->where('main_type', 2) as $ot) {
  833. $otS = $ot->start_time_hour * 60 + $ot->start_time_min;
  834. $pool[] = ['s' => $otS, 'e' => $otS + (float)$ot->total_min];
  835. }
  836. return $pool;
  837. }
  838. }