| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312 |
- <?php
- namespace App\Service;
- use App\Jobs\ProcessDataJob;
- use App\Model\CalendarDetails;
- use App\Model\DailyPwOrder;
- use App\Model\DailyPwOrderDetails;
- use App\Model\Employee;
- use App\Model\Item;
- use App\Model\MonthlyPwOrder;
- use App\Model\MonthlyPwOrderDetails;
- use App\Model\RuleSetDetails;
- use Illuminate\Support\Facades\DB;
- class PersonWorkService extends Service
- {
- // 人员月工时单-------------------------------------------
- public function monthlyPwOrderEdit($data,$user){
- list($status,$msg) = $this->monthlyPwOrderRule($data, $user, false);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = MonthlyPwOrder::where('id',$data['id'])->first();
- // $model->month = $data['month'] ?? 0;
- // $model->save();
- $time = time();
- MonthlyPwOrderDetails::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 monthlyPwOrderAdd($data,$user){
- list($status,$msg) = $this->monthlyPwOrderRule($data, $user);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = new MonthlyPwOrder();
- $model->code = $this->generateBillNo([
- 'top_depart_id' => $user['top_depart_id'],
- 'type' => MonthlyPwOrder::Order_type,
- 'period' => date("Ym", $data['month'])
- ]);
- $model->month = $data['month'] ?? 0;
- $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'],
- 'total_days' => $value['total_days'],
- 'rd_total_days' => $value['rd_total_days'],
- 'total_hours' => $value['total_hours'],
- 'rd_total_hours' => $value['rd_total_hours'],
- 'crt_time' => $time,
- 'top_depart_id' => $value['top_depart_id'],
- ];
- }
- if(! empty($unit)) MonthlyPwOrderDetails::insert($unit);
- }
- }
- private function getDetail($id){
- $data = MonthlyPwOrderDetails::where('del_time',0)
- ->where('main_id', $id)
- ->select('employee_id', 'total_days', 'rd_total_days', 'total_hours', 'rd_total_hours')
- ->get()->toArray();
- $id = array_column($data,'employee_id');
- $map = Employee::whereIn('id', $id)->select('title','id','number')->get()->toArray();
- $map = array_column($map,null,'id');
- 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 monthlyPwOrderDel($data){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- try {
- DB::beginTransaction();
- $time = time();
- MonthlyPwOrder::where('del_time',0)
- ->whereIn('id',$data['id'])
- ->update(['del_time' => $time]);
- MonthlyPwOrderDetails::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 monthlyPwOrderDetail($data, $user){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- $customer = MonthlyPwOrder::where('del_time',0)
- ->where('id',$data['id'])
- ->first();
- if(empty($customer)) return [false,'人员月度工时单不存在或已被删除'];
- $customer = $customer->toArray();
- $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['month'] = $customer['month'] ? date("Y-m",$customer['month']): '';
- $details = $this->getDetail($data['id']);
- $customer = array_merge($customer, $details);
- return [true, $customer];
- }
- public function monthlyPwOrderCommon($data,$user, $field = []){
- if(empty($field)) $field = MonthlyPwOrder::$field;
- $model = MonthlyPwOrder::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['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]);
- }
- return $model;
- }
- public function monthlyPwOrderList($data,$user){
- $model = $this->monthlyPwOrderCommon($data, $user);
- $list = $this->limit($model,'',$data);
- $list = $this->fillData($list);
- return [true, $list];
- }
- public function monthlyPwOrderRule(&$data, $user, $is_add = true)
- {
- if (empty($data['month'])) return [false, '月份不能为空'];
- $data['month'] = $this->changeDateToDate($data['month']);
- $data['top_depart_id'] = $user['top_depart_id'];
- if (empty($data['details'])) return [false, '人员月度工时单明细不能为空'];
- //获取系统计算的考勤基准数据 ---
- $empIds = array_column($data['details'], 'employee_id');
- list($status, $systemStats) = (new EmployeeService())->getEmployeesMonthStats($empIds, $data['month'], $user);
- if (!$status) return [false, $systemStats]; // 如果日历未设置,直接拦截
- foreach ($data['details'] as $key => $value) {
- if (empty($value['employee_id'])) return [false, '人员不能为空'];
- $empId = $value['employee_id'];
- // 基础数字格式检查
- foreach (['total_days', 'rd_total_days', 'total_hours', 'rd_total_hours'] as $field) {
- $precision = 2;
- $res = $this->checkNumber($value[$field], $precision, 'non-negative');
- if (!$res['valid']) return [false, $value['employee_title'] . "的" . $field . ":" . $res['error']];
- }
- // --- 业务逻辑校验:出勤天数与工时合法性 ---
- $sysData = $systemStats[$empId] ?? null;
- if ($sysData) {
- // 1. 研发天数不能大于出勤总天数
- if ($value['rd_total_days'] > $value['total_days']) {
- return [false, "第" . ($key + 1) . "行:研发出勤天数不能大于出勤总天数"];
- }
- // 2. 研发工时不能大于出勤总工时
- if ($value['rd_total_hours'] > $value['total_hours']) {
- return [false, "第" . ($key + 1) . "行:研发总工时不能大于出勤总工时"];
- }
- // 4. 校验出勤总天数是否超过了系统计算的上限
- if ($value['total_days'] != $sysData['attendance_days']) {
- return [false, "人员[{$empId}]填写的出勤总天数({$value['total_days']})不等于系统核算的天数({$sysData['attendance_days']})"];
- }
- //校验出勤总工时是否超过了系统计算的上限
- if ($value['total_hours'] != $sysData['final_work_hour']) {
- return [false, "人员[{$empId}]填写的出勤总工时({$value['total_hours']})不等于系统核算的工时({$sysData['final_work_hour']})"];
- }
- }
- $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
- }
- // --- 查重与唯一性校验 ---
- list($status, $msg) = $this->checkArrayRepeat($data['details'], 'employee_id', '人员');
- if (!$status) return [false, $msg];
- $query = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
- ->where('month', $data['month'])
- ->where('del_time', 0);
- if (!$is_add) {
- if (empty($data['id'])) return [false, 'ID不能为空'];
- $query->where('id', '<>', $data['id']);
- }
- if ($query->exists()) {
- return [false, date("Y-m", $data['month']) . '已存在人员月度研发工时单'];
- }
- return [true, ''];
- }
- public function monthlyPwOrderRule1(&$data, $user, $is_add = true){
- if(empty($data['month'])) return [false, '月份不能为空'];
- $data['month'] = $this->changeDateToDate($data['month']);
- $data['top_depart_id'] = $user['top_depart_id'];
- if(empty($data['details'])) return [false, '人员月度工时单明细不能为空'];
- foreach ($data['details'] as $key => $value){
- if(empty($value['employee_id'])) return [false, '人员不能为空'];
- $res = $this->checkNumber($value['total_days'],0,'non-negative');
- if(! $res['valid']) return [false,'出勤总天数:' . $res['error']];
- $res = $this->checkNumber($value['rd_total_days'],0,'non-negative');
- if(! $res['valid']) return [false,'研发出勤总天数:' . $res['error']];
- $res = $this->checkNumber($value['total_hours'],2,'non-negative');
- if(! $res['valid']) return [false,'出勤总工时:' . $res['error']];
- $res = $this->checkNumber($value['rd_total_hours'],2,'non-negative');
- if(! $res['valid']) return [false,'研发总工时:' . $res['error']];
- $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
- }
- list($status, $msg) = $this->checkArrayRepeat($data['details'],'employee_id','人员');
- if(! $status) return [false, $msg];
- if($is_add){
- $bool = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
- ->where('month', $data['month'])
- ->where('del_time',0)
- ->exists();
- }else{
- if(empty($data['id'])) return [false,'ID不能为空'];
- $bool = MonthlyPwOrder::where('top_depart_id', $data['top_depart_id'])
- ->where('month', $data['month'])
- ->where('id','<>',$data['id'])
- ->where('del_time',0)
- ->exists();
- }
- if($bool) return [false, date("Y-m", $data['month']) . '已存在人员月度研发工时单'];
- 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]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
- $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
- }
- return $data;
- }
- public function fillDataForExport($data, $column, &$return)
- {
- if(empty($data)) return;
- $mainIds = array_column($data, 'id');
- // 获取详情映射 [main_id => [details...]]
- $detailsMap = $this->getDetailsMap($mainIds);
- // 默认空行模板
- $defaultRow = array_fill_keys($column, '');
- foreach ($data as $main) {
- $mainId = $main['id'];
- $details = $detailsMap[$mainId] ?? [];
- // 提取主表信息
- $mainInfo = [
- 'code' => $main['code'],
- 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
- ];
- if (empty($details)) {
- // 如果没有详情,至少导出一行主表信息(可选)
- $return[] = array_merge($defaultRow, $mainInfo);
- } else {
- // 核心:遍历详情,每一行详情都合并主表信息
- foreach ($details as $sub) {
- // 合并主表字段 + 详情字段
- $fullRow = array_merge($mainInfo, $sub);
- // 过滤掉不在导出列里的字段,并补充缺失列
- $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
- }
- }
- }
- }
- public function getDetailsMap($main_ids)
- {
- // 获取详情
- $details = MonthlyPwOrderDetails::where('del_time', 0)
- ->whereIn('main_id', $main_ids)
- ->get();
- // 获取人员信息
- $empIds = $details->pluck('employee_id')->unique();
- $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id');
- $res = [];
- foreach ($details as $item) {
- $tmpEmp = $empMap[$item->employee_id] ?? null;
- // 组装每一行详情需要展示的字段
- $res[$item->main_id][] = [
- 'employee_number' => $tmpEmp ? $tmpEmp->number : '',
- 'employee_title' => $tmpEmp ? $tmpEmp->title : '',
- 'total_days' => $item->total_days,
- 'rd_total_days' => $item->rd_total_days,
- 'total_hours' => $item->total_hours,
- 'rd_total_hours' => $item->rd_total_hours,
- ];
- }
- return $res; // 返回 [main_id => [detail_row, detail_row]]
- }
- // 人员日工时单 ------------------------------------------------
- public function dailyPwOrderEdit($data,$user){
- list($status,$msg) = $this->dailyPwOrderRule($data, $user, false);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = DailyPwOrder::where('id',$data['id'])->first();
- $model->item_id = $data['item_id'] ?? 0;
- $model->save();
- $time = time();
- DailyPwOrderDetails::where('del_time',0)
- ->where('main_id', $model->id)
- ->update(['del_time' => $time]);
- $this->saveDetailDaily($model->id, $time, $data);
- DB::commit();
- }catch (\Exception $exception){
- DB::rollBack();
- return [false,$exception->getMessage()];
- }
- return [true, ''];
- }
- public function dailyPwOrderAdd($data,$user){
- list($status,$msg) = $this->dailyPwOrderRule($data, $user);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = new DailyPwOrder();
- $model->code = $this->generateBillNo([
- 'top_depart_id' => $user['top_depart_id'],
- 'type' => DailyPwOrder::Order_type,
- 'period' => date("Ym", $data['order_time'])
- ]);
- $model->order_time = $data['order_time'] ?? 0;
- $model->item_id = $data['item_id'] ?? 0;
- $model->crt_id = $user['id'];
- $model->top_depart_id = $data['top_depart_id'];
- $model->save();
- $this->saveDetailDaily($model->id, time(), $data);
- DB::commit();
- }catch (\Exception $exception){
- DB::rollBack();
- return [false,$exception->getMessage()];
- }
- return [true, ''];
- }
- private function saveDetailDaily($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_work_min' => $value['total_work_min'],
- 'crt_time' => $time,
- 'top_depart_id' => $value['top_depart_id'],
- 'order_time' => $data['order_time'] ?? 0,
- 'item_id' => $data['item_id'],
- ];
- }
- if(! empty($unit)) DailyPwOrderDetails::insert($unit);
- }
- }
- private function getDetailDaily($id){
- $data = DailyPwOrderDetails::where('del_time',0)
- ->where('main_id', $id)
- ->select('employee_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_work_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 dailyPwOrderDel($data){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- try {
- DB::beginTransaction();
- $time = time();
- DailyPwOrder::where('del_time',0)
- ->whereIn('id',$data['id'])
- ->update(['del_time' => $time]);
- DailyPwOrderDetails::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 dailyPwOrderDetail($data, $user){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- $customer = DailyPwOrder::where('del_time',0)
- ->where('id',$data['id'])
- ->first();
- if(empty($customer)) return [false,'人员日工时单不存在或已被删除'];
- $customer = $customer->toArray();
- $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']): '';
- $item = Item::where('id', $customer['item_id'])->first();
- $customer['item_title'] = $item->title;
- $customer['item_code'] = $item->code;
- $customer['order_time'] = $customer['order_time'] ? date("Y-m-d",$customer['order_time']): '';
- $details = $this->getDetailDaily($data['id']);
- $customer = array_merge($customer, $details);
- return [true, $customer];
- }
- public function dailyPwOrderCommon($data,$user, $field = []){
- if(empty($field)) $field = DailyPwOrder::$field;
- $model = DailyPwOrder::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['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]);
- }
- return $model;
- }
- public function dailyPwOrderList($data,$user){
- $model = $this->dailyPwOrderCommon($data, $user);
- $list = $this->limit($model,'',$data);
- $list = $this->fillDataDaily($list);
- return [true, $list];
- }
- public function dailyPwOrderRule(&$data, $user, $is_add = true){
- if(empty($data['order_time'])) return [false, '单据日期不能为空'];
- $data['order_time'] = $this->changeDateToDate($data['order_time']);
- $orderTime = $data['order_time'];
- $itemId = $data['item_id'] ?? 0;
- if(empty($itemId)) return [false, '项目不能为空'];
- $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
- if(!$bool) return [false, '项目不存在或已被删除'];
- $data['top_depart_id'] = $user['top_depart_id'];
- if(empty($data['details'])) return [false, '人员日工时单明细不能为空'];
- // --- 1. 批量预获取人员信息,用于报错提示 ---
- $allEmpIds = array_filter(array_unique(array_column($data['details'], 'employee_id')));
- // 如果需要工号+姓名,建议这样获取:
- $empDisplayMap = Employee::whereIn('id', $allEmpIds)
- ->get(['id', 'number', 'title'])
- ->mapWithKeys(function($item){
- return [$item->id => "[{$item->number}]{$item->title}"];
- })->toArray();
- // 2. 本次提交内部重叠记录器
- $internalOverlap = [];
- foreach ($data['details'] as $key => $value){
- $empId = $value['employee_id'] ?? 0;
- if(empty($empId)) return [false, '人员不能为空'];
- $empName = $empDisplayMap[$empId] ?? "ID:{$empId}";
- $res = $this->checkNumber($value['start_time_hour'], 0, 'non-negative');
- if(!$res['valid']) return [false, "人员{$empName}开始点:" . $res['error']];
- if($value['start_time_hour'] > 23) return [false, false, "人员{$empName}开始点不合法"];
- $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
- if(!$res['valid']) return [false, "人员{$empName}开始分:" . $res['error']];
- if($value['start_time_min'] > 60) return [false, false, "人员{$empName}开始点不合法"];
- $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
- if(!$res['valid']) return [false, "人员{$empName}结束点:" . $res['error']];
- if($value['end_time_hour'] > 24) return [false, false, "人员{$empName}结束点不合法"];
- $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
- if(!$res['valid']) return [false, "人员{$empName}结束分:" . $res['error']];
- if($value['end_time_min'] > 60) return [false, 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}:开始时间必须早于结束时间"];
- }
- // --- 3. 内部重叠校验(防止一次提交多行重复) ---
- 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];
- $query = DB::table('daily_pw_order_details as d')
- ->join('daily_pw_order as m', 'd.main_id', '=', 'm.id')
- ->where('m.top_depart_id', $data['top_depart_id'])
- ->where('m.order_time', $orderTime)
- ->where('m.item_id', $itemId)
- ->where('d.employee_id', $empId)
- ->where('m.del_time', 0)
- ->where('d.del_time', 0);
- if (!$is_add && !empty($data['id'])) {
- $query->where('m.id', '<>', $data['id']);
- }
- $existingPeriods = $query->select('d.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')->get();
- foreach ($existingPeriods as $p) {
- $exStart = $p->start_time_hour * 60 + $p->start_time_min;
- $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
- if ($currentStart < $exEnd && $exStart < $currentEnd) {
- return [false, "人员{$empName}在该项目该日已有其他工时单创建重叠的时间段数据"];
- }
- }
- $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
- }
- if(!$is_add){
- if(empty($data['id'])) return [false,'ID不能为空'];
- $bool = DailyPwOrder::where('top_depart_id', $data['top_depart_id'])
- ->where('id',$data['id'])
- ->where('del_time',0)
- ->exists();
- if(!$bool) return [false, '人员日工时单不存在或已被删除'];
- }
- return [true, ''];
- }
- public function fillDataDaily($data){
- if(empty($data['data'])) return $data;
- $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
- $item = (new ItemService())->getItemMap(array_unique(array_column($data['data'],'item_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']] ?? '';
- $item_tmp = $item[$value['item_id']] ?? [];
- $data['data'][$key]['item_title'] = $item_tmp['title'] ?? '';
- $data['data'][$key]['item_code'] = $item_tmp['code'] ?? '';
- }
- return $data;
- }
- public function fillDataForExportDaily($data, $column, &$return)
- {
- if (empty($data)) return;
- $mainIds = array_column($data, 'id');
- // 1. 获取详情及所有关联档案(项目、人员)的映射
- $detailsMap = $this->getDailyDetailsMap($mainIds, $data);
- 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)) {
- // 无明细时只导出一行主表信息
- $tempRow = [];
- foreach ($column as $col) {
- $tempRow[] = $mainInfo[$col] ?? '';
- }
- $return[] = $tempRow;
- } else {
- // 3. 平铺:将详情里的项目信息、人员信息与主表信息合并
- foreach ($details as $sub) {
- $fullRowData = array_merge($mainInfo, $sub);
- $tempRow = [];
- foreach ($column as $col) {
- $tempRow[] = $fullRowData[$col] ?? '';
- }
- $return[] = $tempRow;
- }
- }
- }
- }
- public function getDailyDetailsMap($mainIds, $mainData)
- {
- // 1. 获取所有子表记录
- $details = DB::table('daily_pw_order_details')
- ->where('del_time', 0)
- ->whereIn('main_id', $mainIds)
- ->get();
- // 2. 提取所有关联 ID
- $empIds = $details->pluck('employee_id')->unique();
- $itemIds = array_unique(array_column($mainData, 'item_id')); // 从主表数组提取项目ID
- // 3. 批量获取档案 Map
- $empMap = DB::table('employee')
- ->whereIn('id', $empIds)
- ->get(['id', 'title', 'number'])
- ->keyBy('id');
- $itemMap = DB::table('item')
- ->whereIn('id', $itemIds)
- ->get(['id', 'title', 'code'])
- ->keyBy('id');
- // 4. 将主表的项目信息预先挂载到主表 ID 下,方便后续合并
- $mainItemInfo = [];
- foreach ($mainData as $m) {
- $proj = $itemMap[$m['item_id']] ?? null;
- $mainItemInfo[$m['id']] = [
- 'item_code' => $proj ? $proj->code : '',
- 'item_title' => $proj ? $proj->title : '',
- ];
- }
- $res = [];
- if ($details->isEmpty()) {
- // 如果没有详情,把项目信息返回去,确保主表能导出行
- foreach ($mainItemInfo as $mId => $info) {
- $res[$mId] = [];
- }
- return $res;
- }
- foreach ($details as $item) {
- $emp = $empMap[$item->employee_id] ?? null;
- // 组装明细行数据
- $detailRow = [
- // 人员信息
- 'employee_number' => $emp ? $emp->number : '',
- 'employee_title' => $emp ? $emp->title : '',
- // 时间信息
- '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),
- // 将主表的项目信息也塞进每一行详情里实现平铺
- 'item_code' => $mainItemInfo[$item->main_id]['item_code'] ?? '',
- 'item_title' => $mainItemInfo[$item->main_id]['item_title'] ?? '',
- ];
- $res[$item->main_id][] = $detailRow;
- }
- return $res;
- }
- public function dailyPwOrderCreate($data, $user)
- {
- $topDepartId = $user['top_depart_id'];
- if (empty($data['month'])) return [false, '月份不能为空'];
- $monthStart = $this->changeDateToDate($data['month']);
- // --- 一开始就做的核心校验 ---
- // 1. 检查是否存在月度工时明细(如果没有,队列执行也是徒劳)
- $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
- ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
- ->where('m.month', $monthStart)
- ->where('m.top_depart_id', $topDepartId)
- ->where('m.del_time', 0)
- ->where('d.del_time', 0)
- ->exists();
- if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
- // 2. 检查是否配置了工作日历
- $hasCalendar = DB::table('calendar_details')
- ->where('month', $monthStart)
- ->where('del_time', 0)
- ->exists();
- if (!$hasCalendar) return [false, '该月份工作日历未配置'];
- // 3. 检查是否配置了项目比例规则
- $hasRules = DB::table('rule_set as r')
- ->where('r.month', $monthStart)
- ->where('r.top_depart_id', $topDepartId)
- ->where('r.del_time', 0)
- ->exists();
- if (!$hasRules) return [false, '未找到该月份的规则配置单'];
- $data['type'] = "p_work";
- ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
- return [true, '生成任务已提交,系统正在后台处理,请稍后查看'];
- }
- public function dailyPwOrderCreateMain($data, $user)
- {
- $topDepartId = $user['top_depart_id'];
- if (empty($data['month'])) return [false, '月份不能为空'];
- $monthStart = $this->changeDateToDate($data['month']);
- $monthEnd = strtotime('+1 month', $monthStart) - 1;
- $now = time();
- DB::beginTransaction();
- try {
- // --- 0. 清理旧数据 ---
- $oldOrderIds = DB::table('daily_pw_order')
- ->where('top_depart_id', $topDepartId)
- ->where('order_time', '>=', $monthStart)
- ->where('order_time', '<=', $monthEnd)
- ->where('is_create', 1)
- ->where('del_time', 0)
- ->pluck('id');
- if ($oldOrderIds->isNotEmpty()) {
- DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
- DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
- }
- // --- 1. 基础数据加载 ---
- $monthlyOrder = DB::table('monthly_pw_order_details as d')
- ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
- ->where('m.month', $monthStart)->where('m.top_depart_id', $topDepartId)
- ->where('m.del_time', 0)->where('d.del_time', 0)
- ->select('d.*')->get();
- if ($monthlyOrder->isEmpty()) return [false, '未找到月度工时明细'];
- $empIds = $monthlyOrder->pluck('employee_id')->unique()->toArray();
- $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
- $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
- $ruleSet = DB::table('rule_set_details as rd')->join('rule_set as r', 'r.id', '=', 'rd.main_id')
- ->where('r.month', $monthStart)->where('rd.type', RuleSetDetails::type_one)
- ->where('r.del_time', 0)->where('rd.del_time', 0)
- ->select('rd.*')->get()->groupBy('data_id');
- $allDays = DB::table('calendar_details')->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
- $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
- ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('m.del_time', 0)
- ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
- // --- 2. 核心分配逻辑:计算每天、每个项目、每个人的分钟数 ---
- $finalAlloc = [];
- foreach ($monthlyOrder as $mDetail) {
- $empId = $mDetail->employee_id;
- $empRules = $ruleSet->get($empId);
- if (!$empRules) continue;
- $empRemainingMin = (float)$mDetail->rd_total_hours * 60;
- if ($empRemainingMin <= 0) continue;
- foreach ($allDays as $dayInfo) {
- if ($empRemainingMin <= 0) break;
- $dayTs = $dayInfo->time;
- $isWorkDay = ($dayInfo->is_work == CalendarDetails::TYPE_ONE);
- $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
- $todayOvertimes = $todaySpecials->where('main_type', 2);
- if (!$isWorkDay && $todayOvertimes->isEmpty()) continue;
- // 计算当天可用总时长
- $dayAvailableMin = 0;
- if ($isWorkDay) {
- $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
- foreach ($baseRanges as $br) {
- $brS = $br->start_time_hour * 60 + $br->start_time_min;
- $brE = $br->end_time_hour * 60 + $br->end_time_min;
- $avail = (float)$br->total_work_min;
- foreach ($todaySpecials->where('main_type', 1) as $lv) {
- $overlap = min($brE, ($lv->end_time_hour * 60 + $lv->end_time_min)) - max($brS, ($lv->start_time_hour * 60 + $lv->start_time_min));
- if ($overlap > 0) $avail -= $overlap;
- }
- $dayAvailableMin += max(0, $avail);
- }
- }
- foreach ($todayOvertimes as $ot) $dayAvailableMin += (float)$ot->total_min;
- $canAllocToday = min($empRemainingMin, $dayAvailableMin);
- if ($canAllocToday <= 0) continue;
- foreach ($empRules as $rule) {
- $rate = (float)$rule->rate / 100;
- $projectMin = $canAllocToday * $rate;
- if ($projectMin > 0) {
- // 结果存入:[日期][项目][人员]
- $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
- }
- }
- $empRemainingMin -= $canAllocToday;
- }
- }
- // --- 3. 生成单据:解决时间重叠的核心逻辑 ---
- $newOrderIds = [];
- // 为了解决重叠,我们需要按 [日期][人员] 来追踪时间池的消耗进度
- $dailyEmpTimePools = [];
- foreach ($finalAlloc as $dayTs => $projects) {
- foreach ($projects as $itemId => $employees) {
- $mainId = DB::table('daily_pw_order')->insertGetId([
- 'code' => '', 'item_id' => $itemId, 'order_time' => $dayTs, 'top_depart_id' => $topDepartId,
- 'is_create' => 1, 'crt_id' => $user['id'], 'crt_time' => $now, 'upd_time' => $now,
- ]);
- $newOrderIds[] = ['id' => $mainId, 'time' => $dayTs];
- foreach ($employees as $empId => $toAllocMin) {
- // 如果该员工当天的池子还没构建,先构建一次
- if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
- $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
- }
- $tempRem = $toAllocMin;
- // 指向该员工当天的可用池引用,这样处理完项目A,池子里的时间会自动被“消耗”
- foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
- if ($tempRem <= 0) break;
- $pMax = $p['e'] - $p['s'];
- if ($pMax <= 0) continue;
- $take = min($tempRem, $pMax);
- $realStart = $p['s'];
- $realEnd = $p['s'] + $take;
- DB::table('daily_pw_order_details')->insert([
- 'main_id' => $mainId, 'employee_id' => $empId, 'top_depart_id' => $topDepartId,
- 'start_time_hour' => floor($realStart / 60), 'start_time_min' => $realStart % 60,
- 'end_time_hour' => floor($realEnd / 60), 'end_time_min' => $realEnd % 60,
- 'total_work_min' => $take, 'crt_time' => $now, 'upd_time' => $now,
- ]);
- $tempRem -= $take;
- // 重要:消耗掉这个时段的起始位置,确保下一个项目从这里开始
- $p['s'] = $realEnd;
- }
- }
- }
- }
- // --- 4. 回填单号 ---
- if (empty($newOrderIds)) return [false, '未生成数据'];
- foreach ($newOrderIds as $item) {
- $code = $this->generateBillNo(['top_depart_id' => $topDepartId, 'type' => DailyPwOrder::Order_type, 'period' => date("Ym", $item['time'])]);
- DB::table('daily_pw_order')->where('id', $item['id'])->update(['code' => $code]);
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
- }
- return [true, ''];
- }
- /**
- * 辅助函数:构建某人某天的初始可用时段池
- */
- private function buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData)
- {
- $dayInfo = $allDays->where('time', $dayTs)->first();
- $todaySpecials = data_get($leaveOverData, "$empId.$dayTs", collect());
- $pool = [];
- if ($dayInfo && $dayInfo->is_work == CalendarDetails::TYPE_ONE) {
- $baseRanges = $empWorkRanges->has($empId) ? $empWorkRanges->get($empId) : $standardWorkRanges;
- foreach ($baseRanges as $br) {
- $currentS = $br->start_time_hour * 60 + $br->start_time_min;
- $eMin = $br->end_time_hour * 60 + $br->end_time_min;
- $sortedLeaves = $todaySpecials->where('main_type', 1)->sortBy('start_time_hour');
- foreach ($sortedLeaves as $lv) {
- $lvS = $lv->start_time_hour * 60 + $lv->start_time_min;
- $lvE = $lv->end_time_hour * 60 + $lv->end_time_min;
- if ($lvS < $eMin && $lvE > $currentS) {
- if ($lvS > $currentS) $pool[] = ['s' => $currentS, 'e' => $lvS];
- $currentS = max($currentS, $lvE);
- }
- }
- if ($currentS < $eMin) $pool[] = ['s' => $currentS, 'e' => $eMin];
- }
- }
- foreach ($todaySpecials->where('main_type', 2) as $ot) {
- $otS = $ot->start_time_hour * 60 + $ot->start_time_min;
- $pool[] = ['s' => $otS, 'e' => $otS + (float)$ot->total_min];
- }
- return $pool;
- }
- public function dailyPwOrderPreview($data, $user)
- {
- $topDepartId = $user['top_depart_id'];
- if (empty($data['month'])) return [false, '月份不能为空'];
- // 1. 前置校验 (保留你之前的校验逻辑)
- $monthStart = $this->changeDateToDate($data['month']);
- // 1. 检查是否存在月度工时明细
- $hasMonthlyOrder = DB::table('monthly_pw_order_details as d')
- ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
- ->where('m.month', $monthStart)
- ->where('m.top_depart_id', $topDepartId)
- ->where('m.del_time', 0)
- ->where('d.del_time', 0)
- ->exists();
- if (!$hasMonthlyOrder) return [false, '未找到该月份的月度工时明细,请先生成人员月度工时单'];
- // 2. 检查是否配置了工作日历
- $hasCalendar = DB::table('calendar_details')
- ->where('month', $monthStart)
- ->where('del_time', 0)
- ->exists();
- if (!$hasCalendar) return [false, '该月份工作日历未配置'];
- // 3. 检查是否配置了项目比例规则
- $hasRules = DB::table('rule_set as r')
- ->where('r.month', $monthStart)
- ->where('r.top_depart_id', $topDepartId)
- ->where('r.del_time', 0)
- ->exists();
- if (!$hasRules) return [false, '未找到该月份的规则配置单'];
- // 2. 调用核心计算逻辑 (抽取出的私有方法)
- $result = $this->calculateDailyAllocation($monthStart, $topDepartId, $user);
- if (!$result['status']) return [false, $result['msg']];
- // 3. 将结果存入临时表或直接返回
- // 建议增加一个 batch_id,防止多人操作冲突
- $batchId = uniqid('batch_');
- $previewData = $result['data'];
- return [true, [
- 'batch_id' => $batchId,
- 'list' => $previewData // 返回给前端展示
- ]];
- }
- /**
- * 核心分配逻辑:计算预览数据(确保全整数分钟)
- * @param int $monthStart 月初时间戳
- * @param int $topDepartId 顶级部门ID
- * @param array $user 用户信息
- * @return array
- */
- private function calculateDailyAllocation($monthStart, $topDepartId, $user)
- {
- $monthEnd = strtotime('+1 month', $monthStart) - 1;
- $now = time();
- // --- 1. 基础数据加载 ---
- // 加载月度工时明细,并关联人员姓名
- $monthlyOrder = DB::table('monthly_pw_order_details as d')
- ->join('monthly_pw_order as m', 'm.id', '=', 'd.main_id')
- ->leftJoin('employee as e', 'e.id', '=', 'd.employee_id') // 关联人员表
- ->where('m.month', $monthStart)
- ->where('m.top_depart_id', $topDepartId)
- ->where('m.del_time', 0)
- ->where('d.del_time', 0)
- ->select('d.*', 'e.title as employee_title') // 获取人员姓名
- ->get();
- if ($monthlyOrder->isEmpty()) return ['status' => false, 'msg' => '未找到该月份的月度工时明细'];
- // 建立人员 ID -> 姓名的映射,方便后续取用
- $empNameMap = $monthlyOrder->pluck('employee_title', 'employee_id')->toArray();
- $empIds = array_keys($empNameMap);
- // 加载项目信息,用于获取项目名称
- // 假设项目表名为 items,请根据你实际的表名修改
- $itemIds = DB::table('rule_set_details as rd')
- ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
- ->where('r.month', $monthStart)
- ->where('r.top_depart_id', $topDepartId)
- ->pluck('rd.item_id')->unique()->toArray();
- $itemMap = DB::table('item')
- ->whereIn('id', $itemIds)
- ->pluck('title', 'id')
- ->toArray();
- // 加载分配规则
- $ruleSet = DB::table('rule_set_details as rd')
- ->join('rule_set as r', 'r.id', '=', 'rd.main_id')
- ->where('r.month', $monthStart)
- ->where('rd.type', 1)
- ->where('r.del_time', 0)
- ->where('rd.del_time', 0)
- ->select('rd.*')
- ->get()
- ->groupBy('data_id');
- // 加载员工/标准班次、日历、请假加班数据 (逻辑同前)
- $empWorkRanges = DB::table('employee_work_range')->whereIn('employee_id', $empIds)->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
- $standardWorkRanges = DB::table('work_range_details')->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
- $allDays = DB::table('calendar_details')->where('month', $monthStart)->where('del_time', 0)->orderBy('time', 'asc')->get();
- $leaveOverData = DB::table('p_leave_over_order_details as d')->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
- ->whereBetween('m.order_time', [$monthStart, $monthEnd])->where('m.del_time', 0)
- ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
- // --- 2. 阶段一:计算每个人每天在每个项目上应分配的整数分钟数 ---
- $finalAlloc = [];
- foreach ($monthlyOrder as $mDetail) {
- $empId = $mDetail->employee_id;
- $empRules = $ruleSet->get($empId);
- if (!$empRules) continue;
- $empRemainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
- if ($empRemainingMin <= 0) continue;
- foreach ($allDays as $dayInfo) {
- if ($empRemainingMin <= 0) break;
- $dayTs = $dayInfo->time;
- $tempPool = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
- $dayAvailableMin = 0;
- foreach ($tempPool as $p) { $dayAvailableMin += (int)($p['e'] - $p['s']); }
- if ($dayAvailableMin <= 0) continue;
- $canAllocToday = min($empRemainingMin, $dayAvailableMin);
- $allocatedInDay = 0;
- $ruleCount = count($empRules);
- foreach ($empRules as $index => $rule) {
- $rate = (float)$rule->rate / 100;
- if ($index === $ruleCount - 1) {
- $projectMin = $canAllocToday - $allocatedInDay;
- } else {
- $projectMin = (int)round($canAllocToday * $rate);
- }
- if ($projectMin > 0) {
- $finalAlloc[$dayTs][$rule->item_id][$empId] = $projectMin;
- $allocatedInDay += $projectMin;
- }
- }
- $empRemainingMin -= $canAllocToday;
- }
- }
- // --- 3. 阶段二:打散到具体时间点并生成预览行 ---
- $previewList = [];
- $dailyEmpTimePools = [];
- $tempMainIdCounter = 1;
- foreach ($finalAlloc as $dayTs => $projects) {
- foreach ($projects as $itemId => $employees) {
- $currentTempMainId = $tempMainIdCounter++;
- // 获取项目名称
- $itemTitle = $itemMap[$itemId] ?? '未知项目';
- foreach ($employees as $empId => $toAllocMin) {
- if (!isset($dailyEmpTimePools[$dayTs][$empId])) {
- $dailyEmpTimePools[$dayTs][$empId] = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
- }
- $tempRem = (int)$toAllocMin;
- foreach ($dailyEmpTimePools[$dayTs][$empId] as &$p) {
- if ($tempRem <= 0) break;
- $pMax = (int)($p['e'] - $p['s']);
- if ($pMax <= 0) continue;
- $take = min($tempRem, $pMax);
- $realStart = (int)$p['s'];
- $realEnd = $realStart + $take;
- // 写入带 Title 的结果
- $previewList[] = [
- 'temp_main_id' => $currentTempMainId,
- 'order_time' => date('Y-m-d', $dayTs),
- 'order_timestamp' => $dayTs,
- 'item_id' => $itemId,
- 'item_title' => $itemTitle, // 项目名称
- 'employee_id' => $empId,
- 'employee_title' => $empNameMap[$empId] ?? '未知人员', // 人员姓名
- 'start_time' => sprintf('%02d:%02d', floor($realStart / 60), $realStart % 60),
- 'end_time' => sprintf('%02d:%02d', floor($realEnd / 60), $realEnd % 60),
- 'start_hour' => (int)floor($realStart / 60),
- 'start_min' => (int)($realStart % 60),
- 'end_hour' => (int)floor($realEnd / 60),
- 'end_min' => (int)($realEnd % 60),
- 'total_work_min' => $take,
- ];
- $tempRem -= $take;
- $p['s'] = $realEnd;
- }
- }
- }
- }
- return ['status' => true, 'data' => $previewList];
- }
- public function dailyPwOrderSave($data, $user)
- {
- $list = $data['list'] ?? [];
- if (empty($list)) return [false, '没有可保存的数据'];
- $topDepartId = $user['top_depart_id'];
- $now = time();
- DB::beginTransaction();
- try {
- // 1. 清理旧数据 (严格按月份和部门清理,防止重复)
- $monthStart = $this->changeDateToDate($data['month']);
- $monthEnd = strtotime('+1 month', $monthStart) - 1;
- $oldOrderIds = DB::table('daily_pw_order')
- ->where('top_depart_id', $topDepartId)
- ->where('order_time', '>=', $monthStart)
- ->where('order_time', '<=', $monthEnd)
- ->where('is_create', 1)
- ->where('del_time', 0)
- ->pluck('id');
- if ($oldOrderIds->isNotEmpty()) {
- DB::table('daily_pw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
- DB::table('daily_pw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
- }
- // 2. 按 temp_main_id 分组写入
- $grouped = collect($list)->groupBy('temp_main_id');
- foreach ($grouped as $tempMainId => $details) {
- $first = $details->first();
- // 写入主表
- $mainId = DB::table('daily_pw_order')->insertGetId([
- 'code' => '',
- 'item_id' => $first['item_id'],
- 'order_time' => $first['order_timestamp'],
- 'top_depart_id' => $topDepartId,
- 'is_create' => 1,
- 'crt_id' => $user['id'],
- 'crt_time' => $now,
- ]);
- // 构造批量插入的明细数组
- $insertDetails = [];
- foreach ($details as $d) {
- $insertDetails[] = [
- 'main_id' => $mainId,
- 'employee_id' => $d['employee_id'],
- 'top_depart_id' => $topDepartId,
- // 直接使用预览时生成的字段,效率更高
- 'start_time_hour' => $d['start_hour'],
- 'start_time_min' => $d['start_min'],
- 'end_time_hour' => $d['end_hour'],
- 'end_time_min' => $d['end_min'],
- 'total_work_min' => $d['total_work_min'],
- 'crt_time' => $now,
- ];
- }
- // 批量写入明细
- DB::table('daily_pw_order_details')->insert($insertDetails);
- // 3. 生成并回填单号
- $code = $this->generateBillNo([
- 'top_depart_id' => $topDepartId,
- 'type' => DailyPwOrder::Order_type,
- 'period' => date("Ym", $first['order_timestamp'])
- ]);
- DB::table('daily_pw_order')->where('id', $mainId)->update(['code' => $code]);
- }
- DB::commit();
- return [true, ''];
- } catch (\Exception $e) {
- DB::rollBack();
- return [false, '保存失败: ' . $e->getMessage() . ' (Line: ' . $e->getLine() . ')'];
- }
- }
- }
|