| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469 |
- <?php
- namespace App\Service;
- use App\Model\CalendarDetails;
- use App\Model\PLeaveOverOrder;
- use App\Model\PLeaveOverOrderDetails;
- use App\Model\Employee;
- use App\Model\Item;
- use App\Model\WorkRangeDetails;
- use Illuminate\Support\Facades\DB;
- class PLeaveOverService extends Service
- {
- public function pLeaveOverEdit($data,$user){
- list($status,$msg) = $this->pLeaveOverRule($data, $user, false);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = PLeaveOverOrder::where('id',$data['id'])->first();
- $model->save();
- $time = time();
- PLeaveOverOrderDetails::where('del_time',0)
- ->where('main_id', $model->id)
- ->update(['del_time' => $time]);
- $this->saveDetail($model->id, $time, $data);
- DB::commit();
- }catch (\Exception $exception){
- DB::rollBack();
- return [false,$exception->getMessage()];
- }
- return [true, ''];
- }
- public function pLeaveOverAdd($data,$user){
- list($status,$msg) = $this->pLeaveOverRule($data, $user);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = new PLeaveOverOrder();
- $model->code = $this->generateBillNo([
- 'top_depart_id' => $user['top_depart_id'],
- 'type' => PLeaveOverOrder::Order_type,
- 'period' => date("Ym", $data['order_time'])
- ]);
- $model->order_time = $data['order_time'] ?? 0;
- $model->type = $data['type'];
- $model->crt_id = $user['id'];
- $model->top_depart_id = $data['top_depart_id'];
- $model->save();
- $this->saveDetail($model->id, time(), $data);
- DB::commit();
- }catch (\Exception $exception){
- DB::rollBack();
- return [false,$exception->getMessage()];
- }
- return [true, ''];
- }
- private function saveDetail($id, $time, $data){
- if(! empty($data['details'])){
- $unit = [];
- foreach ($data['details'] as $value){
- $unit[] = [
- 'main_id' => $id,
- 'employee_id' => $value['employee_id'],
- 'start_time_hour' => $value['start_time_hour'],
- 'start_time_min' => $value['start_time_min'],
- 'end_time_hour' => $value['end_time_hour'],
- 'end_time_min' => $value['end_time_min'],
- 'total_min' => $value['total_min'],
- 'crt_time' => $time,
- 'top_depart_id' => $value['top_depart_id'],
- 'type' => $value['type'],
- ];
- }
- if(! empty($unit)) PLeaveOverOrderDetails::insert($unit);
- }
- }
- private function getDetail($id){
- $data = PLeaveOverOrderDetails::where('del_time',0)
- ->where('main_id', $id)
- ->select('employee_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_min')
- ->get()->toArray();
- $id = array_column($data,'employee_id');
- $map = Employee::whereIn('id', $id)
- ->select('title','id','number')
- ->get()
- ->keyBy('id')
- ->toArray();
- foreach ($data as $key => $value){
- $tmp = $map[$value['employee_id']] ?? [];
- $merge = [];
- $merge['employee_title'] = $tmp['title'];
- $merge['employee_number'] = $tmp['number'];
- $data[$key] = array_merge($value, $merge);
- }
- $detail = [
- 'details' => $data,
- ];
- //foreach ($detail as $key => $value) {
- // if (empty($value)) {
- //$detail[$key] = (object)[]; // 转成 stdClass 对象
- //}
- //}
- return $detail;
- }
- public function pLeaveOverDel($data){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- try {
- DB::beginTransaction();
- $time = time();
- PLeaveOverOrder::where('del_time',0)
- ->whereIn('id',$data['id'])
- ->update(['del_time' => $time]);
- PLeaveOverOrderDetails::where('del_time',0)
- ->whereIn('main_id', $data['id'])
- ->update(['del_time' => $time]);
- DB::commit();
- }catch (\Exception $exception){
- DB::rollBack();
- return [false,$exception->getMessage()];
- }
- return [true, ''];
- }
- public function pLeaveOverDetail($data, $user){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- $customer = PLeaveOverOrder::where('del_time',0)
- ->where('id',$data['id'])
- ->first();
- if(empty($customer)) return [false,'单据不存在或已被删除'];
- $customer = $customer->toArray();
- $customer['type_title'] = PLeaveOverOrder::Type[$customer['type']] ?? "";
- $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
- $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
- $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
- $details = $this->getDetail($data['id']);
- $customer = array_merge($customer, $details);
- return [true, $customer];
- }
- public function pLeaveOverCommon($data,$user, $field = []){
- if(empty($field)) $field = PLeaveOverOrder::$field;
- $model = PLeaveOverOrder::Clear($user,$data);
- $model = $model->where('del_time',0)
- ->select($field)
- ->orderby('id', 'desc');
- if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
- if(! empty($data['type'])) $model->where('type', $data['type']);
- if(! empty($data['id'])) $model->whereIn('id', $data['id']);
- if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
- $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
- $model->where('crt_time','>=',$return[0]);
- $model->where('crt_time','<=',$return[1]);
- }
- if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
- $return = $this->changeDateToTimeStampAboutRange($data['time']);
- $model->where('order_time','>=',$return[0]);
- $model->where('order_time','<=',$return[1]);
- }
- return $model;
- }
- public function pLeaveOverList($data,$user){
- $model = $this->pLeaveOverCommon($data, $user);
- $list = $this->limit($model,'',$data);
- $list = $this->fillData($list);
- return [true, $list];
- }
- public function pLeaveOverRule(&$data, $user, $is_add = true)
- {
- $data['top_depart_id'] = $user['top_depart_id'];
- $topDepartId = $data['top_depart_id'];
- // 1. 基础校验
- if (empty($data['type']) || ! isset(PLeaveOverOrder::Type[$data['type']])) return [false, '单据类型非法'];
- $typeName = PLeaveOverOrder::Type[$data['type']];
- if (empty($data['order_time'])) return [false, '单据日期不能为空'];
- $data['order_time'] = $this->changeDateToDate($data['order_time']);
- $orderTime = $data['order_time'];
- $orderType = $data['type'];
- if (!$is_add) {
- if (empty($data['id'])) return [false, 'ID不能为空'];
- $orderExists = DB::table('p_leave_over_order')
- ->where('id', $data['id'])
- ->where('top_depart_id', $topDepartId)
- ->where('del_time', 0)
- ->exists();
- if (!$orderExists) return [false, '原单据不存在或已被删除'];
- }
- // --- 日历工作日校验 ---
- $calendar = DB::table('calendar_details')
- ->where('del_time', 0)
- ->where('top_depart_id', $topDepartId)
- ->where('time', $orderTime)
- ->first();
- if (!$calendar) return [false, '所选日期未在公司日历中设置,无法校验'];
- $isWorkDay = (int)$calendar->is_work === CalendarDetails::TYPE_ONE;
- if (!$isWorkDay && $orderType == PLeaveOverOrder::TYPE_ONE) {
- return [false, date("Y-m-d", $orderTime) . "为非工作日,无需提交请假单"];
- }
- // 2. 获取【通用】工作时间段
- $commonWorkPeriods = [];
- if ($isWorkDay) {
- $workRanges = DB::table('work_range_details')
- ->where('del_time', 0)
- ->where('top_depart_id', $topDepartId)
- ->get();
- foreach ($workRanges as $wr) {
- $commonWorkPeriods[] = [
- 's' => $wr->start_time_hour * 60 + $wr->start_time_min,
- 'e' => $wr->end_time_hour * 60 + $wr->end_time_min
- ];
- }
- }
- // 3. 预加载明细中所有人员的信息及【个性化】工时
- if (empty($data['details'])) return [false, '明细不能为空'];
- $allEmpIds = array_filter(array_unique(array_column($data['details'], 'employee_id')));
- $empDisplayMap = Employee::whereIn('id', $allEmpIds)
- ->get(['id', 'number', 'title'])
- ->mapWithKeys(fn($item) => [$item->id => "[{$item->number}]{$item->title}"])->toArray();
- // --- 新增:预加载个性化工时 ---
- $specialWorkMap = DB::table('employee_work_range')
- ->whereIn('employee_id', $allEmpIds)
- ->where('top_depart_id', $topDepartId)
- ->get()
- ->groupBy('employee_id');
- // 预查库内已有时段 (保持不变)
- $dbExistingDetails = DB::table('p_leave_over_order_details as d')
- ->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
- ->where('m.top_depart_id', $topDepartId)
- ->where('m.order_time', $orderTime)
- ->where('m.del_time', 0)
- ->where('d.del_time', 0)
- ->whereIn('d.employee_id', $allEmpIds)
- ->when(!$is_add, fn($q) => $q->where('m.id', '<>', $data['id']))
- ->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')
- ->get()
- ->groupBy('employee_id');
- // 4. 循环明细校验
- $internalOverlap = [];
- foreach ($data['details'] as $key => &$value) {
- $empId = $value['employee_id'] ?? 0;
- $empName = $empDisplayMap[$empId] ?? "";
- if(empty($empName)) return [false, '人员不存在或已被删除'];
- // A. 时间合法性校验
- if ($value['start_time_hour'] > 23 || $value['end_time_hour'] > 24 || $value['start_time_min'] > 59 || $value['end_time_min'] > 59) {
- return [false, "人员{$empName}:填写的时间段不合法"];
- }
- $currentStart = $value['start_time_hour'] * 60 + $value['start_time_min'];
- $currentEnd = $value['end_time_hour'] * 60 + $value['end_time_min'];
- if ($currentStart >= $currentEnd) return [false, "人员{$empName}:开始时间必须早于结束时间"];
- $value['total_min'] = $currentEnd - $currentStart;
- $value['type'] = $orderType;
- // B. 工作时间逻辑校验 (重点:确定使用哪套工时标准)
- if ($isWorkDay) {
- // 判定:是个性化还是通用?
- $currentEmpPeriods = [];
- if (isset($specialWorkMap[$empId])) {
- foreach ($specialWorkMap[$empId] as $sw) {
- $currentEmpPeriods[] = [
- 's' => $sw->start_time_hour * 60 + $sw->start_time_min,
- 'e' => $sw->end_time_hour * 60 + $sw->end_time_min
- ];
- }
- } else {
- $currentEmpPeriods = $commonWorkPeriods;
- }
- if (empty($currentEmpPeriods)) return [false, "人员{$empName}:未找到对应的工作时间设置,无法校验"];
- if ($orderType == PLeaveOverOrder::TYPE_ONE) {
- // 请假:必须在工作时间内
- $inWorkRange = false;
- foreach ($currentEmpPeriods as $wp) {
- if ($currentStart >= $wp['s'] && $currentEnd <= $wp['e']) {
- $inWorkRange = true;
- break;
- }
- }
- if (!$inWorkRange) return [false, "人员{$empName}:请假时间必须在对应的工作时间段内"];
- } else {
- // 加班:不能在工作时间段内
- foreach ($currentEmpPeriods as $wp) {
- if ($currentStart < $wp['e'] && $wp['s'] < $currentEnd) {
- return [false, "人员{$empName}:加班时间与正常工作时间重叠"];
- }
- }
- }
- }
- // C. 内部重叠校验
- if (isset($internalOverlap[$empId])) {
- foreach ($internalOverlap[$empId] as $period) {
- if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
- return [false, "人员{$empName}:本次提交的数据中存在时间重叠"];
- }
- }
- }
- $internalOverlap[$empId][] = ['s' => $currentStart, 'e' => $currentEnd];
- // D. 库内同类型重叠校验
- if (isset($dbExistingDetails[$empId])) {
- foreach ($dbExistingDetails[$empId] as $dbD) {
- if ($dbD->order_type == $orderType) {
- $exStart = $dbD->start_time_hour * 60 + $dbD->start_time_min;
- $exEnd = $dbD->end_time_hour * 60 + $dbD->end_time_min;
- if ($currentStart < $exEnd && $exStart < $currentEnd) {
- $typeStr = $orderType == PLeaveOverOrder::TYPE_ONE ? "请假" : "加班";
- return [false, "人员{$empName}:该时段与已有的{$typeStr}记录重叠"];
- }
- }
- }
- }
- $value['top_depart_id'] = $topDepartId;
- }
- // 5. 唯一性校验
- $uniqueCheck = PLeaveOverOrder::where('top_depart_id', $topDepartId)
- ->where('order_time', $orderTime)
- ->where('type', $orderType)
- ->where('del_time', 0);
- if (! $is_add) $uniqueCheck->where('id', '<>', $data['id']);
- if ($uniqueCheck->exists()) {
- return [false, date("Y-m-d", $orderTime) . "已存在{$typeName},请在原单据上修改"];
- }
- return [true, ''];
- }
- public function fillData($data){
- if(empty($data['data'])) return $data;
- $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
- foreach ($data['data'] as $key => $value){
- $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
- $data['data'][$key]['order_time'] = $value['order_time'] ? date('Y-m-d',$value['order_time']) : '';
- $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
- $data['data'][$key]['type_title'] = PLeaveOverOrder::Type[$value['type']] ?? "";
- }
- return $data;
- }
- public function fillDataForExportDaily($data, $column, &$return)
- {
- if (empty($data)) return;
- $mainIds = array_column($data, 'id');
- // 1. 获取子表详情及关联档案映射
- $detailsMap = $this->getLeaveOverDetailsMap($mainIds);
- foreach ($data as $main) {
- $mainId = $main['id'];
- $details = $detailsMap[$mainId] ?? [];
- // 2. 提取并格式化主表共有信息
- $mainInfo = [
- 'code' => $main['code'],
- 'order_time' => !empty($main['order_time']) ? date('Y-m-d', $main['order_time']) : '',
- ];
- if (empty($details)) {
- // 如果主表没有明细,依然根据 column 导出一行(包含主表信息,明细列为空)
- $tempRow = [];
- foreach ($column as $col) {
- $tempRow[] = $mainInfo[$col] ?? '';
- }
- $return[] = $tempRow;
- } else {
- // 3. 平铺导出:每一行明细都带上主表的 code 和日期
- foreach ($details as $sub) {
- $fullRowData = array_merge($mainInfo, $sub);
- $tempRow = [];
- foreach ($column as $col) {
- // $col 对应的是配置里的 export 字段,如 'employee_number', 'start_time' 等
- $tempRow[] = $fullRowData[$col] ?? '';
- }
- $return[] = $tempRow;
- }
- }
- }
- }
- public function getLeaveOverDetailsMap($mainIds)
- {
- // 1. 获取所有子表记录
- $details = DB::table('p_leave_over_order_details')
- ->where('del_time', 0)
- ->whereIn('main_id', $mainIds)
- ->get();
- if ($details->isEmpty()) return [];
- // 2. 批量获取人员档案映射
- $empIds = $details->pluck('employee_id')->unique()->toArray();
- $empMap = DB::table('employee')
- ->whereIn('id', $empIds)
- ->get(['id', 'title', 'number'])
- ->keyBy('id');
- $res = [];
- foreach ($details as $item) {
- $emp = $empMap[$item->employee_id] ?? null;
- // 3. 组装明细行数据(Key 必须与 header 配置中的 export 字段一致)
- $detailRow = [
- // 人员信息
- 'employee_number' => $emp ? $emp->number : '',
- 'employee_title' => $emp ? $emp->title : '',
- // 时间段格式化 8:0 -> 08:00
- 'start_time' => sprintf('%02d:%02d', $item->start_time_hour, $item->start_time_min),
- 'end_time' => sprintf('%02d:%02d', $item->end_time_hour, $item->end_time_min),
- // 时长(分钟)
- 'total_min' => $item->total_min,
- ];
- $res[$item->main_id][] = $detailRow;
- }
- return $res;
- }
- }
|