PLeaveOverService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <?php
  2. namespace App\Service;
  3. use App\Model\CalendarDetails;
  4. use App\Model\PLeaveOverOrder;
  5. use App\Model\PLeaveOverOrderDetails;
  6. use App\Model\Employee;
  7. use App\Model\Item;
  8. use App\Model\WorkRangeDetails;
  9. use Illuminate\Support\Facades\DB;
  10. class PLeaveOverService extends Service
  11. {
  12. public function pLeaveOverEdit($data,$user){
  13. list($status,$msg) = $this->pLeaveOverRule($data, $user, false);
  14. if(!$status) return [$status,$msg];
  15. try {
  16. DB::beginTransaction();
  17. $model = PLeaveOverOrder::where('id',$data['id'])->first();
  18. $model->save();
  19. $time = time();
  20. PLeaveOverOrderDetails::where('del_time',0)
  21. ->where('main_id', $model->id)
  22. ->update(['del_time' => $time]);
  23. $this->saveDetail($model->id, $time, $data);
  24. DB::commit();
  25. }catch (\Exception $exception){
  26. DB::rollBack();
  27. return [false,$exception->getMessage()];
  28. }
  29. return [true, ''];
  30. }
  31. public function pLeaveOverAdd($data,$user){
  32. list($status,$msg) = $this->pLeaveOverRule($data, $user);
  33. if(!$status) return [$status,$msg];
  34. try {
  35. DB::beginTransaction();
  36. $model = new PLeaveOverOrder();
  37. $model->code = $this->generateBillNo([
  38. 'top_depart_id' => $user['top_depart_id'],
  39. 'type' => PLeaveOverOrder::Order_type,
  40. 'period' => date("Ym", $data['order_time'])
  41. ]);
  42. $model->order_time = $data['order_time'] ?? 0;
  43. $model->type = $data['type'];
  44. $model->crt_id = $user['id'];
  45. $model->top_depart_id = $data['top_depart_id'];
  46. $model->save();
  47. $this->saveDetail($model->id, time(), $data);
  48. DB::commit();
  49. }catch (\Exception $exception){
  50. DB::rollBack();
  51. return [false,$exception->getMessage()];
  52. }
  53. return [true, ''];
  54. }
  55. private function saveDetail($id, $time, $data){
  56. if(! empty($data['details'])){
  57. $unit = [];
  58. foreach ($data['details'] as $value){
  59. $unit[] = [
  60. 'main_id' => $id,
  61. 'employee_id' => $value['employee_id'],
  62. 'start_time_hour' => $value['start_time_hour'],
  63. 'start_time_min' => $value['start_time_min'],
  64. 'end_time_hour' => $value['end_time_hour'],
  65. 'end_time_min' => $value['end_time_min'],
  66. 'total_min' => $value['total_min'],
  67. 'crt_time' => $time,
  68. 'top_depart_id' => $value['top_depart_id'],
  69. 'type' => $value['type'],
  70. ];
  71. }
  72. if(! empty($unit)) PLeaveOverOrderDetails::insert($unit);
  73. }
  74. }
  75. private function getDetail($id){
  76. $data = PLeaveOverOrderDetails::where('del_time',0)
  77. ->where('main_id', $id)
  78. ->select('employee_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_min')
  79. ->get()->toArray();
  80. $id = array_column($data,'employee_id');
  81. $map = Employee::whereIn('id', $id)
  82. ->select('title','id','number')
  83. ->get()
  84. ->keyBy('id')
  85. ->toArray();
  86. foreach ($data as $key => $value){
  87. $tmp = $map[$value['employee_id']] ?? [];
  88. $merge = [];
  89. $merge['employee_title'] = $tmp['title'];
  90. $merge['employee_number'] = $tmp['number'];
  91. $data[$key] = array_merge($value, $merge);
  92. }
  93. $detail = [
  94. 'details' => $data,
  95. ];
  96. //foreach ($detail as $key => $value) {
  97. // if (empty($value)) {
  98. //$detail[$key] = (object)[]; // 转成 stdClass 对象
  99. //}
  100. //}
  101. return $detail;
  102. }
  103. public function pLeaveOverDel($data, $user){
  104. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  105. try {
  106. DB::beginTransaction();
  107. $time = time();
  108. $month = PLeaveOverOrder::where('del_time',0)
  109. ->whereIn('id',$data['id'])
  110. ->pluck('order_time')
  111. ->toArray();
  112. //归档
  113. list($status, $msg) = ArchiveService::isArchive($month, $user);
  114. if(! $status) return [false, $msg];
  115. PLeaveOverOrder::where('del_time',0)
  116. ->whereIn('id',$data['id'])
  117. ->update(['del_time' => $time]);
  118. PLeaveOverOrderDetails::where('del_time',0)
  119. ->whereIn('main_id', $data['id'])
  120. ->update(['del_time' => $time]);
  121. DB::commit();
  122. }catch (\Exception $exception){
  123. DB::rollBack();
  124. return [false,$exception->getMessage()];
  125. }
  126. return [true, ''];
  127. }
  128. public function pLeaveOverDetail($data, $user){
  129. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  130. $customer = PLeaveOverOrder::where('del_time',0)
  131. ->where('id',$data['id'])
  132. ->first();
  133. if(empty($customer)) return [false,'单据不存在或已被删除'];
  134. $customer = $customer->toArray();
  135. $customer['type_title'] = PLeaveOverOrder::Type[$customer['type']] ?? "";
  136. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  137. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  138. $map = ArchiveService::fillIsArchive($customer['order_time'], $user);
  139. $customer['is_archive'] = $map[$customer['order_time']] ?? false;
  140. $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
  141. $details = $this->getDetail($data['id']);
  142. $customer = array_merge($customer, $details);
  143. return [true, $customer];
  144. }
  145. public function pLeaveOverCommon($data,$user, $field = []){
  146. if(empty($field)) $field = PLeaveOverOrder::$field;
  147. $model = PLeaveOverOrder::Clear($user,$data);
  148. $model = $model->where('del_time',0)
  149. ->select($field)
  150. ->orderby('id', 'desc');
  151. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  152. if(! empty($data['type'])) $model->where('type', $data['type']);
  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. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  160. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  161. $model->where('order_time','>=',$return[0]);
  162. $model->where('order_time','<=',$return[1]);
  163. }
  164. return $model;
  165. }
  166. public function pLeaveOverList($data,$user){
  167. $model = $this->pLeaveOverCommon($data, $user);
  168. $list = $this->limit($model,'',$data);
  169. $list = $this->fillData($list, $user);
  170. return [true, $list];
  171. }
  172. public function pLeaveOverRule(&$data, $user, $is_add = true)
  173. {
  174. $data['top_depart_id'] = $user['top_depart_id'];
  175. $topDepartId = $data['top_depart_id'];
  176. // 1. 基础校验
  177. if (empty($data['type']) || ! isset(PLeaveOverOrder::Type[$data['type']])) return [false, '单据类型非法'];
  178. $typeName = PLeaveOverOrder::Type[$data['type']];
  179. if (empty($data['order_time'])) return [false, '单据日期不能为空'];
  180. $data['order_time'] = $this->changeDateToDate($data['order_time']);
  181. $orderTime = $data['order_time'];
  182. $orderType = $data['type'];
  183. // 使用日期范围限制
  184. list($status, $msg) = MiddleGroundService::checkTimestampInRange($data['order_time'], $data['top_depart_id']);
  185. if(! $status) return [false, $msg];
  186. //归档
  187. list($status, $msg) = ArchiveService::isArchive($data['order_time'], $user);
  188. if(! $status) return [false, $msg];
  189. if (!$is_add) {
  190. if (empty($data['id'])) return [false, 'ID不能为空'];
  191. $orderExists = DB::table('p_leave_over_order')
  192. ->where('id', $data['id'])
  193. ->where('top_depart_id', $topDepartId)
  194. ->where('del_time', 0)
  195. ->exists();
  196. if (!$orderExists) return [false, '原单据不存在或已被删除'];
  197. }
  198. // --- 日历工作日校验 ---
  199. $calendar = DB::table('calendar_details')
  200. ->where('del_time', 0)
  201. ->where('top_depart_id', $topDepartId)
  202. ->where('time', $orderTime)
  203. ->first();
  204. if (!$calendar) return [false, '所选日期未在公司日历中设置,无法校验'];
  205. $isWorkDay = (int)$calendar->is_work === CalendarDetails::TYPE_ONE;
  206. if (!$isWorkDay && $orderType == PLeaveOverOrder::TYPE_ONE) {
  207. return [false, date("Y-m-d", $orderTime) . "为非工作日,无需提交请假单"];
  208. }
  209. // 2. 获取【通用】工作时间段
  210. $commonWorkPeriods = [];
  211. if ($isWorkDay) {
  212. $workRanges = DB::table('work_range_details')
  213. ->where('del_time', 0)
  214. ->where('top_depart_id', $topDepartId)
  215. ->get();
  216. foreach ($workRanges as $wr) {
  217. $commonWorkPeriods[] = [
  218. 's' => $wr->start_time_hour * 60 + $wr->start_time_min,
  219. 'e' => $wr->end_time_hour * 60 + $wr->end_time_min
  220. ];
  221. }
  222. }
  223. // 3. 预加载明细中所有人员的信息及【个性化】工时
  224. if (empty($data['details'])) return [false, '明细不能为空'];
  225. $allEmpIds = array_filter(array_unique(array_column($data['details'], 'employee_id')));
  226. $empDisplayMap = Employee::whereIn('id', $allEmpIds)
  227. ->get(['id', 'number', 'title'])
  228. ->mapWithKeys(fn($item) => [$item->id => "[{$item->number}]{$item->title}"])->toArray();
  229. // --- 新增:预加载个性化工时 ---
  230. $specialWorkMap = DB::table('employee_work_range')
  231. ->whereIn('employee_id', $allEmpIds)
  232. ->where('top_depart_id', $topDepartId)
  233. ->get()
  234. ->groupBy('employee_id');
  235. // 预查库内已有时段 (保持不变)
  236. $dbExistingDetails = DB::table('p_leave_over_order_details as d')
  237. ->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  238. ->where('m.top_depart_id', $topDepartId)
  239. ->where('m.order_time', $orderTime)
  240. ->where('m.del_time', 0)
  241. ->where('d.del_time', 0)
  242. ->whereIn('d.employee_id', $allEmpIds)
  243. ->when(!$is_add, fn($q) => $q->where('m.id', '<>', $data['id']))
  244. ->select('d.employee_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min', 'm.type as order_type')
  245. ->get()
  246. ->groupBy('employee_id');
  247. // 4. 循环明细校验
  248. $internalOverlap = [];
  249. foreach ($data['details'] as $key => &$value) {
  250. $empId = $value['employee_id'] ?? 0;
  251. $empName = $empDisplayMap[$empId] ?? "";
  252. if(empty($empName)) return [false, '人员不存在或已被删除'];
  253. // A. 时间合法性校验
  254. if ($value['start_time_hour'] > 23 || $value['end_time_hour'] > 24 || $value['start_time_min'] > 59 || $value['end_time_min'] > 59) {
  255. return [false, "人员{$empName}:填写的时间段不合法"];
  256. }
  257. $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
  258. $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
  259. if ($currentStart >= $currentEnd) return [false, "人员{$empName}:开始时间必须早于结束时间"];
  260. $value['total_min'] = $currentEnd - $currentStart;
  261. $value['type'] = $orderType;
  262. // B. 工作时间逻辑校验 (重点:确定使用哪套工时标准)
  263. if ($isWorkDay) {
  264. // 判定:是个性化还是通用?
  265. $currentEmpPeriods = [];
  266. if (isset($specialWorkMap[$empId])) {
  267. foreach ($specialWorkMap[$empId] as $sw) {
  268. $currentEmpPeriods[] = [
  269. 's' => $sw->start_time_hour * 60 + $sw->start_time_min,
  270. 'e' => $sw->end_time_hour * 60 + $sw->end_time_min
  271. ];
  272. }
  273. } else {
  274. $currentEmpPeriods = $commonWorkPeriods;
  275. }
  276. if (empty($currentEmpPeriods)) return [false, "人员{$empName}:未找到对应的工作时间设置,无法校验"];
  277. if ($orderType == PLeaveOverOrder::TYPE_ONE) {
  278. // 请假:必须在工作时间内
  279. $inWorkRange = false;
  280. foreach ($currentEmpPeriods as $wp) {
  281. if ($currentStart >= $wp['s'] && $currentEnd <= $wp['e']) {
  282. $inWorkRange = true;
  283. break;
  284. }
  285. }
  286. if (!$inWorkRange) return [false, "人员{$empName}:请假时间必须在对应的工作时间段内"];
  287. } else {
  288. // 加班:不能在工作时间段内
  289. foreach ($currentEmpPeriods as $wp) {
  290. if ($currentStart < $wp['e'] && $wp['s'] < $currentEnd) {
  291. return [false, "人员{$empName}:加班时间与正常工作时间重叠"];
  292. }
  293. }
  294. }
  295. }
  296. // C. 内部重叠校验
  297. if (isset($internalOverlap[$empId])) {
  298. foreach ($internalOverlap[$empId] as $period) {
  299. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  300. return [false, "人员{$empName}:本次提交的数据中存在时间重叠"];
  301. }
  302. }
  303. }
  304. $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
  305. // D. 库内同类型重叠校验
  306. if (isset($dbExistingDetails[$empId])) {
  307. foreach ($dbExistingDetails[$empId] as $dbD) {
  308. if ($dbD->order_type == $orderType) {
  309. $exStart = $dbD->start_time_hour * 60 + $dbD->start_time_min;
  310. $exEnd = $dbD->end_time_hour * 60 + $dbD->end_time_min;
  311. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  312. $typeStr = $orderType == PLeaveOverOrder::TYPE_ONE ? "请假" : "加班";
  313. return [false, "人员{$empName}:该时段与已有的{$typeStr}记录重叠"];
  314. }
  315. }
  316. }
  317. }
  318. $value['top_depart_id'] = $topDepartId;
  319. }
  320. // 5. 唯一性校验
  321. $uniqueCheck = PLeaveOverOrder::where('top_depart_id', $topDepartId)
  322. ->where('order_time', $orderTime)
  323. ->where('type', $orderType)
  324. ->where('del_time', 0);
  325. if (! $is_add) $uniqueCheck->where('id', '<>', $data['id']);
  326. if ($uniqueCheck->exists()) {
  327. return [false, date("Y-m-d", $orderTime) . "已存在{$typeName},请在原单据上修改"];
  328. }
  329. return [true, ''];
  330. }
  331. public function fillData($data, $user){
  332. if(empty($data['data'])) return $data;
  333. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  334. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'order_time')), $user);
  335. foreach ($data['data'] as $key => $value){
  336. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  337. $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
  338. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  339. $data['data'][$key]['type_title'] = PLeaveOverOrder::Type[$value['type']] ?? "";
  340. $data['data'][$key]['is_archive'] = $map[$value['order_time']] ?? false;
  341. }
  342. return $data;
  343. }
  344. public function fillDataForExportDaily($data, $column, &$return)
  345. {
  346. if (empty($data)) return;
  347. $mainIds = array_column($data, 'id');
  348. // 1. 获取子表详情及关联档案映射
  349. $detailsMap = $this->getLeaveOverDetailsMap($mainIds);
  350. foreach ($data as $main) {
  351. $mainId = $main['id'];
  352. $details = $detailsMap[$mainId] ?? [];
  353. // 2. 提取并格式化主表共有信息
  354. $mainInfo = [
  355. 'code' => $main['code'],
  356. 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
  357. ];
  358. if (empty($details)) {
  359. // 如果主表没有明细,依然根据 column 导出一行(包含主表信息,明细列为空)
  360. $tempRow = [];
  361. foreach ($column as $col) {
  362. $tempRow[] = $mainInfo[$col] ?? '';
  363. }
  364. $return[] = $tempRow;
  365. } else {
  366. // 3. 平铺导出:每一行明细都带上主表的 code 和日期
  367. foreach ($details as $sub) {
  368. $fullRowData = array_merge($mainInfo, $sub);
  369. $tempRow = [];
  370. foreach ($column as $col) {
  371. // $col 对应的是配置里的 export 字段,如 'employee_number', 'start_time' 等
  372. $tempRow[] = $fullRowData[$col] ?? '';
  373. }
  374. $return[] = $tempRow;
  375. }
  376. }
  377. }
  378. }
  379. public function getLeaveOverDetailsMap($mainIds)
  380. {
  381. // 1. 获取所有子表记录
  382. $details = DB::table('p_leave_over_order_details')
  383. ->where('del_time', 0)
  384. ->whereIn('main_id', $mainIds)
  385. ->get();
  386. if ($details->isEmpty()) return [];
  387. // 2. 批量获取人员档案映射
  388. $empIds = $details->pluck('employee_id')->unique()->toArray();
  389. $empMap = DB::table('employee')
  390. ->whereIn('id', $empIds)
  391. ->get(['id', 'title', 'number'])
  392. ->keyBy('id');
  393. $res = [];
  394. foreach ($details as $item) {
  395. $emp = $empMap[$item->employee_id] ?? null;
  396. // 3. 组装明细行数据(Key 必须与 header 配置中的 export 字段一致)
  397. $detailRow = [
  398. // 人员信息
  399. 'employee_number' => $emp ? $emp->number : '',
  400. 'employee_title' => $emp ? $emp->title : '',
  401. // 时间段格式化 8:0 -> 08:00
  402. 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
  403. 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
  404. // 时长(分钟)
  405. 'total_min' => $item->total_min,
  406. ];
  407. $res[$item->main_id][] = $detailRow;
  408. }
  409. return $res;
  410. }
  411. }