| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254 |
- <?php
- namespace App\Service;
- use App\Jobs\ProcessDataJob;
- use App\Model\CalendarDetails;
- use App\Model\DailyDwOrder;
- use App\Model\DailyDwOrderDetails;
- use App\Model\DailyPwOrder;
- use App\Model\Device;
- use App\Model\Employee;
- use App\Model\Item;
- use App\Model\MonthlyDwOrder;
- use App\Model\MonthlyDwOrderDetails;
- use App\Model\RuleSetDetails;
- use Illuminate\Support\Facades\DB;
- class DeviceWorkService extends Service
- {
- //设备月工时单--------------------------------------------
- public function monthlyDwOrderEdit($data,$user){
- list($status,$msg) = $this->monthlyDwOrderRule($data, $user, false);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = MonthlyDwOrder::where('id',$data['id'])->first();
- // $model->month = $data['month'] ?? 0;
- // $model->save();
- $time = time();
- MonthlyDwOrderDetails::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 monthlyDwOrderAdd($data,$user){
- list($status,$msg) = $this->monthlyDwOrderRule($data, $user);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = new MonthlyDwOrder();
- $model->code = $this->generateBillNo([
- 'top_depart_id' => $user['top_depart_id'],
- 'type' => MonthlyDwOrder::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,
- 'device_id' => $value['device_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)) MonthlyDwOrderDetails::insert($unit);
- }
- }
- private function getDetail($id){
- $data = MonthlyDwOrderDetails::where('del_time',0)
- ->where('main_id', $id)
- ->select('device_id', 'total_days', 'rd_total_days', 'total_hours', 'rd_total_hours')
- ->get()->toArray();
- $id = array_column($data,'device_id');
- $map = Device::whereIn('id', $id)->select('title','id','code')->get()->toArray();
- $map = array_column($map,null,'id');
- foreach ($data as $key => $value){
- $tmp = $map[$value['device_id']] ?? [];
- $merge = [];
- $merge['device_title'] = $tmp['title'];
- $merge['device_code'] = $tmp['code'];
- $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 monthlyDwOrderDel($data){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- try {
- DB::beginTransaction();
- $time = time();
- MonthlyDwOrder::where('del_time',0)
- ->whereIn('id',$data['id'])
- ->update(['del_time' => $time]);
- MonthlyDwOrderDetails::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 monthlyDwOrderDetail($data, $user){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- $customer = MonthlyDwOrder::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 monthlyDwOrderCommon($data,$user, $field = []){
- if(empty($field)) $field = MonthlyDwOrder::$field;
- $model = MonthlyDwOrder::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 monthlyDwOrderList($data,$user){
- $model = $this->monthlyDwOrderCommon($data, $user);
- $list = $this->limit($model,'',$data);
- $list = $this->fillData($list);
- return [true, $list];
- }
- public function monthlyDwOrderRule(&$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, '设备月度工时单明细不能为空'];
- // --- 1. 批量获取设备档案信息 (用于展示 [编码]名称) ---
- $deviceIds = array_column($data['details'], 'device_id');
- $deviceMap = DB::table('device')
- ->whereIn('id', $deviceIds)
- ->where('top_depart_id', $data['top_depart_id'])
- ->get(['id', 'code', 'title'])
- ->mapWithKeys(fn($item) => [$item->id => "[{$item->code}]{$item->title}"])
- ->toArray();
- // --- 2. 获取设备考勤基准 ---
- list($status, $deviceStats) = (new DeviceService())->getDevicesMonthStats($deviceIds, $data['month'], $user);
- if (!$status) return [false, $deviceStats];
- // 字段中文映射,用于报错
- $fieldNames = [
- 'total_days' => '出勤总天数',
- 'rd_total_days' => '研发出勤天数',
- 'total_hours' => '出勤总工时',
- 'rd_total_hours'=> '研发总工时'
- ];
- // --- 3. 循环校验明细 ---
- foreach ($data['details'] as $key => $value) {
- $line = $key + 1; // 行号
- if (empty($value['device_id'])) return [false, "第{$line}行:设备ID不能为空"];
- $deviceId = $value['device_id'];
- $deviceDisplayName = $deviceMap[$deviceId] ?? "";
- if(empty($deviceDisplayName)) return [false, "第{$line}行:设备不存在或已被删除"];
- // 基础数字格式检查
- foreach ($fieldNames as $field => $cnName) {
- $precision = 2;
- $res = $this->checkNumber($value[$field], $precision, 'non-negative');
- if (!$res['valid']) {
- return [false, "第{$line}行:设备{$deviceDisplayName}的{$cnName}填写不规范({$res['error']})"];
- }
- }
- // --- 4. 业务逻辑校验 ---
- $sysData = $deviceStats[$deviceId] ?? null;
- if ($sysData) {
- // A. 内部逻辑:研发不能大于总额
- if ($value['rd_total_days'] > $value['total_days']) {
- return [false, "第{$line}行:设备{$deviceDisplayName}的研发出勤天数不能大于出勤总天数"];
- }
- if ($value['rd_total_hours'] > $value['total_hours']) {
- return [false, "第{$line}行:设备{$deviceDisplayName}的研发总工时不能大于出勤总工时"];
- }
- // B. 外部逻辑:不能超过系统根据日历算出的上限
- if ($value['total_days'] != $sysData['attendance_days']) {
- return [false, "第{$line}行:设备{$deviceDisplayName}的出勤总天数({$value['total_days']})不等于当月标准天数({$sysData['attendance_days']})"];
- }
- if ($value['total_hours'] != $sysData['final_work_hour']) {
- return [false, "第{$line}行:设备{$deviceDisplayName}的出勤总工时({$value['total_hours']})不等于当月标准工时({$sysData['final_work_hour']})"];
- }
- }
- $data['details'][$key]['top_depart_id'] = $data['top_depart_id'];
- }
- // --- 5. 查重与唯一性校验 ---
- list($status, $msg) = $this->checkArrayRepeat($data['details'], 'device_id', '设备');
- if (!$status) return [false, $msg];
- $query = MonthlyDwOrder::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 monthlyDwOrderRule1(&$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['device_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'],'device_id','设备');
- if(! $status) return [false, $msg];
- if($is_add){
- $bool = MonthlyDwOrder::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 = MonthlyDwOrder::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 = MonthlyDwOrderDetails::where('del_time', 0)
- ->whereIn('main_id', $main_ids)
- ->get();
- // 获取设备信息
- $empIds = $details->pluck('device_id')->unique();
- $empMap = Device::whereIn('id', $empIds)->get()->keyBy('id');
- $res = [];
- foreach ($details as $item) {
- $tmpEmp = $empMap[$item->device_id] ?? null;
- // 组装每一行详情需要展示的字段
- $res[$item->main_id][] = [
- 'device_code' => $tmpEmp ? $tmpEmp->code : '',
- 'device_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 dailyDwOrderEdit($data,$user){
- list($status,$msg) = $this->dailyDwOrderRule($data, $user, false);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = DailyDwOrder::where('id',$data['id'])->first();
- $model->item_id = $data['item_id'] ?? 0;
- $model->save();
- $time = time();
- DailyDwOrderDetails::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 dailyDwOrderAdd($data,$user){
- list($status,$msg) = $this->dailyDwOrderRule($data, $user);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = new DailyDwOrder();
- $model->code = $this->generateBillNo([
- 'top_depart_id' => $user['top_depart_id'],
- 'type' => DailyDwOrder::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,
- 'device_id' => $value['device_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)) DailyDwOrderDetails::insert($unit);
- }
- }
- private function getDetailDaily($id){
- $data = DailyDwOrderDetails::where('del_time',0)
- ->where('main_id', $id)
- ->select('device_id', 'start_time_hour', 'start_time_min', 'end_time_hour', 'end_time_min', 'total_work_min')
- ->get()->toArray();
- $id = array_column($data,'device_id');
- $map = Device::whereIn('id',$id)
- ->select('title','id','code')
- ->get()
- ->keyBy('id')
- ->toArray();
- foreach ($data as $key => $value){
- $tmp = $map[$value['device_id']] ?? [];
- $merge = [];
- $merge['device_title'] = $tmp['title'];
- $merge['device_code'] = $tmp['code'];
- $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 dailyDwOrderDel($data){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- try {
- DB::beginTransaction();
- $time = time();
- DailyDwOrder::where('del_time',0)
- ->whereIn('id',$data['id'])
- ->update(['del_time' => $time]);
- DailyDwOrderDetails::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 dailyDwOrderDetail($data, $user){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- $customer = DailyDwOrder::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 dailyDwOrderCommon($data,$user, $field = []){
- if(empty($field)) $field = DailyDwOrder::$field;
- $model = DailyDwOrder::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 dailyDwOrderList($data,$user){
- $model = $this->dailyDwOrderCommon($data, $user);
- $list = $this->limit($model,'',$data);
- $list = $this->fillDataDaily($list);
- return [true, $list];
- }
- public function dailyDwOrderRule(&$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'], 'device_id')));
- $empDisplayMap = Device::whereIn('id', $allEmpIds)
- ->get(['id', 'code', 'title'])
- ->mapWithKeys(function($item){
- return [$item->id => "[{$item->code}]{$item->title}"];
- })->toArray();
- // 2. 本次提交内部重叠记录
- $internalOverlap = [];
- foreach ($data['details'] as $key => $value){
- $empId = $value['device_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_dw_order_details as d')
- ->join('daily_dw_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.device_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 = DailyDwOrder::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->getDwDailyDetailsMap($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 getDwDailyDetailsMap($mainIds, $mainData)
- {
- // 1. 获取设备工时子表记录
- $details = DB::table('daily_dw_order_details')
- ->where('del_time', 0)
- ->whereIn('main_id', $mainIds)
- ->get();
- // 2. 提取关联 ID(设备 ID 和 项目 ID)
- $deviceIds = $details->pluck('device_id')->unique();
- $itemIds = array_unique(array_column($mainData, 'item_id'));
- // 3. 批量获取设备档案和项目档案
- $deviceMap = DB::table('device')
- ->whereIn('id', $deviceIds)
- ->get(['id', 'title', 'code'])
- ->keyBy('id');
- $itemMap = DB::table('item')
- ->whereIn('id', $itemIds)
- ->get(['id', 'title', 'code'])
- ->keyBy('id');
- // 4. 预挂载主表的项目信息(item_code, item_title)
- $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;
- }
- // 5. 循环子表,合并设备档案信息
- foreach ($details as $item) {
- $device = $deviceMap[$item->device_id] ?? null;
- $detailRow = [
- // 设备信息(对应 Excel 配置中的 key)
- 'device_code' => $device ? $device->code : '',
- 'device_title' => $device ? $device->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 dailyDwOrderCreate($data, $user)
- {
- $topDepartId = $user['top_depart_id'];
- if (empty($data['month'])) return [false, '月份不能为空'];
- $monthStart = $this->changeDateToDate($data['month']);
- // --- 前置核心校验 ---
- // 1. 校验设备月度明细是否存在
- $hasMonthly = DB::table('monthly_dw_order_details as d')
- ->join('monthly_dw_order as m', 'm.id', '=', 'd.main_id')
- ->where('m.month', $monthStart)
- ->where('m.top_depart_id', $topDepartId)
- ->where('m.del_time', 0)
- ->exists();
- if (!$hasMonthly) return [false, '未找到该月份的设备月度工时明细'];
- // 2. 校验设备项目分配规则
- $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, '未找到该月份的项目比例规则设置'];
- // 3. 校验工作日历
- $hasCalendar = DB::table('calendar_details')
- ->where('month', $monthStart)
- ->where('is_work', 1)
- ->where('del_time', 0)
- ->exists();
- if (!$hasCalendar) return [false, '该月份未配置工作日历'];
- $data['type'] = 'd_work';
- ProcessDataJob::dispatch($data, $user)->onQueue(DailyPwOrder::job);
- return [true, '设备工时生成任务已提交,请稍后查看结果'];
- }
- public function dailyDwOrderCreateMain($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_dw_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_dw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
- DB::table('daily_dw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
- }
- // --- 1. 基础数据预加载 ---
- // 月度设备工时明细
- $monthlyOrder = DB::table('monthly_dw_order_details as d')
- ->join('monthly_dw_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, '未找到设备月度工时明细'];
- // 设备项目分配比例 (与人员类似,但通常关联 device_id)
- $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_two) // 假设 type_two 是设备类型
- ->where('r.del_time', 0)->where('rd.del_time', 0)
- ->select('rd.*')->get()->groupBy('data_id');
- // 标准工作时段 (设备通常只走公司标准时段)
- $standardWorkRanges = DB::table('work_range_details')
- ->where('top_depart_id', $topDepartId)
- ->where('del_time', 0)
- ->get();
- // 工作日历
- $workDays = DB::table('calendar_details')
- ->where('month', $monthStart)
- ->where('is_work', CalendarDetails::TYPE_ONE)
- ->where('del_time', 0)
- ->orderBy('time', 'asc')
- ->get();
- if ($workDays->isEmpty()) return [false, '未配置工作日历,无法分配设备工时'];
- // --- 2. 核心分配逻辑 ---
- $finalAlloc = [];
- foreach ($monthlyOrder as $mDetail) {
- $deviceId = $mDetail->device_id;
- $deviceRules = $ruleSet->get($deviceId);
- if (!$deviceRules) continue;
- $remainingMin = (float)$mDetail->rd_total_hours * 60;
- if ($remainingMin <= 0) continue;
- foreach ($workDays as $dayInfo) {
- if ($remainingMin <= 0) break;
- // 计算当天设备最大可用分钟 (标准时段总和)
- $dayMaxAvail = $standardWorkRanges->sum('total_work_min');
- $canAllocToday = min($remainingMin, $dayMaxAvail);
- foreach ($deviceRules as $rule) {
- $rate = (float)$rule->rate / 100;
- $projectMin = $canAllocToday * $rate;
- if ($projectMin > 0) {
- $finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] = ($finalAlloc[$dayInfo->time][$rule->item_id][$deviceId] ?? 0) + $projectMin;
- }
- }
- $remainingMin -= $canAllocToday;
- }
- }
- // --- 3. 生成单据并填充时段 (防重叠) ---
- $newOrderIds = [];
- $dailyDevicePools = []; // 追踪每台设备每天的时间消耗情况
- foreach ($finalAlloc as $dayTs => $projects) {
- foreach ($projects as $itemId => $devices) {
- $mainId = DB::table('daily_dw_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 ($devices as $deviceId => $toAllocMin) {
- // 初始化该设备当天的时段池 (仅由标准时段构成)
- if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
- $pool = [];
- foreach ($standardWorkRanges as $swr) {
- $pool[] = [
- 's' => $swr->start_time_hour * 60 + $swr->start_time_min,
- 'e' => $swr->end_time_hour * 60 + $swr->end_time_min
- ];
- }
- $dailyDevicePools[$dayTs][$deviceId] = $pool;
- }
- $tempRem = $toAllocMin;
- foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
- if ($tempRem <= 0) break;
- $pMax = $p['e'] - $p['s'];
- if ($pMax <= 0) continue;
- $take = min($tempRem, $pMax);
- $start = $p['s'];
- $end = $p['s'] + $take;
- DB::table('daily_dw_order_details')->insert([
- 'main_id' => $mainId,
- 'device_id' => $deviceId,
- 'top_depart_id' => $topDepartId,
- 'start_time_hour' => floor($start / 60),
- 'start_time_min' => $start % 60,
- 'end_time_hour' => floor($end / 60),
- 'end_time_min' => $end % 60,
- 'total_work_min' => $take,
- 'crt_time' => $now,
- 'upd_time' => $now,
- ]);
- $tempRem -= $take;
- $p['s'] = $end; // 指针后移,防重叠
- }
- }
- }
- }
- // --- 4. 回填单号 ---
- if (empty($newOrderIds)) return [false, '未生成任何设备日工时单'];
- foreach ($newOrderIds as $item) {
- $code = $this->generateBillNo([
- 'top_depart_id' => $topDepartId,
- 'type' => DailyDwOrder::Order_type, // 确保模型中定义了此常量
- 'period' => date("Ym", $item['time'])
- ]);
- DB::table('daily_dw_order')->where('id', $item['id'])->update(['code' => $code]);
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- return [false, '错误: ' . $e->getMessage() . ' 行: ' . $e->getLine()];
- }
- return [true, ''];
- }
- public function dailyDwOrderPreview($data, $user)
- {
- $topDepartId = $user['top_depart_id'];
- if (empty($data['month'])) return [false, '月份不能为空'];
- $monthStart = $this->changeDateToDate($data['month']);
- // 调用核心计算逻辑
- $result = $this->calculateDailyDeviceAllocation($monthStart, $topDepartId, $user);
- if (!$result['status']) return [false, $result['msg']];
- return [true, [
- 'list' => $result['data'] // 返回给前端预览
- ]];
- }
- private function calculateDailyDeviceAllocation($monthStart, $topDepartId, $user)
- {
- // 加载月度设备明细
- $monthlyOrder = DB::table('monthly_dw_order_details as d')
- ->join('monthly_dw_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 ['status' => false, 'msg' => '未找到设备月度工时明细'];
- $usedDeviceIds = $monthlyOrder->pluck('device_id')->unique()->toArray();
- // 【优化点】按需查询设备名称
- $deviceMap = DB::table('device')
- ->whereIn('id', $usedDeviceIds)
- ->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', RuleSetDetails::type_two) // 设备类型
- ->where('r.del_time', 0)
- ->where('rd.del_time', 0)
- ->select('rd.*')
- ->get();
- // 【优化点】按需查询项目名称
- $usedItemIds = $ruleSet->pluck('item_id')->unique()->toArray();
- $itemMap = DB::table('item')
- ->whereIn('id', $usedItemIds)
- ->pluck('title', 'id')
- ->toArray();
- $ruleSetGrouped = $ruleSet->groupBy('data_id'); // 按 device_id 分组
- // 标准班次 & 日历 (逻辑同前)
- $standardWorkRanges = DB::table('work_range_details')
- ->where('top_depart_id', $topDepartId)->where('del_time', 0)->get();
- $dayMaxAvail = (int)$standardWorkRanges->sum('total_work_min');
- $workDays = DB::table('calendar_details')
- ->where('month', $monthStart)->where('is_work', 1)->where('del_time', 0)
- ->orderBy('time', 'asc')->get();
- if ($workDays->isEmpty()) return ['status' => false, 'msg' => '未配置工作日历'];
- // --- 2. 阶段一:计算每天每台设备分配的项目分钟数 ---
- $finalAlloc = [];
- foreach ($monthlyOrder as $mDetail) {
- $deviceId = $mDetail->device_id;
- $deviceRules = $ruleSetGrouped->get($deviceId);
- if (!$deviceRules) continue;
- $remainingMin = (int)round((float)$mDetail->rd_total_hours * 60);
- if ($remainingMin <= 0) continue;
- foreach ($workDays as $dayInfo) {
- if ($remainingMin <= 0) break;
- $canAllocToday = min($remainingMin, $dayMaxAvail);
- $allocatedInDay = 0;
- $ruleCount = count($deviceRules);
- foreach ($deviceRules 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[$dayInfo->time][$rule->item_id][$deviceId] = $projectMin;
- $allocatedInDay += $projectMin;
- }
- }
- $remainingMin -= $canAllocToday;
- }
- }
- // --- 3. 阶段二:生成预览行 ---
- $previewList = [];
- $dailyDevicePools = [];
- $tempMainIdCounter = 1;
- foreach ($finalAlloc as $dayTs => $projects) {
- foreach ($projects as $itemId => $devices) {
- $currentTempMainId = $tempMainIdCounter++;
- $itemTitle = $itemMap[$itemId] ?? '未知项目';
- foreach ($devices as $deviceId => $toAllocMin) {
- if (!isset($dailyDevicePools[$dayTs][$deviceId])) {
- $pool = [];
- foreach ($standardWorkRanges as $swr) {
- $pool[] = [
- 's' => (int)($swr->start_time_hour * 60 + $swr->start_time_min),
- 'e' => (int)($swr->end_time_hour * 60 + $swr->end_time_min)
- ];
- }
- $dailyDevicePools[$dayTs][$deviceId] = $pool;
- }
- $tempRem = (int)$toAllocMin;
- foreach ($dailyDevicePools[$dayTs][$deviceId] as &$p) {
- if ($tempRem <= 0) break;
- $pMax = $p['e'] - $p['s'];
- if ($pMax <= 0) continue;
- $take = min($tempRem, $pMax);
- $start = (int)$p['s'];
- $end = $start + $take;
- $previewList[] = [
- 'temp_main_id' => $currentTempMainId,
- 'order_time' => date('Y-m-d', $dayTs),
- 'order_timestamp' => $dayTs,
- 'item_id' => $itemId,
- 'item_title' => $itemTitle,
- 'device_id' => $deviceId,
- 'device_title' => $deviceMap[$deviceId] ?? '未知设备',
- 'start_time' => sprintf('%02d:%02d', floor($start / 60), $start % 60),
- 'end_time' => sprintf('%02d:%02d', floor($end / 60), $end % 60),
- 'start_hour' => (int)floor($start / 60),
- 'start_min' => (int)($start % 60),
- 'end_hour' => (int)floor($end / 60),
- 'end_min' => (int)($end % 60),
- 'total_work_min' => $take,
- ];
- $tempRem -= $take;
- $p['s'] = $end;
- }
- }
- }
- }
- return ['status' => true, 'data' => $previewList];
- }
- public function dailyDwOrderSave($data, $user)
- {
- $list = $data['list'] ?? [];
- if (empty($list)) return [false, '没有可保存的数据'];
- $topDepartId = $user['top_depart_id'];
- $now = time();
- DB::beginTransaction();
- try {
- // 清理旧数据
- $monthStart = $this->changeDateToDate($data['month']);
- $monthEnd = strtotime('+1 month', $monthStart) - 1;
- $oldOrderIds = DB::table('daily_dw_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_dw_order')->whereIn('id', $oldOrderIds)->update(['del_time' => $now]);
- DB::table('daily_dw_order_details')->whereIn('main_id', $oldOrderIds)->update(['del_time' => $now]);
- }
- // 按 temp_main_id 分组批量插入
- $grouped = collect($list)->groupBy('temp_main_id');
- foreach ($grouped as $tempMainId => $details) {
- $first = $details->first();
- $mainId = DB::table('daily_dw_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,
- 'upd_time' => $now,
- 'del_time' => 0
- ]);
- $insertData = [];
- foreach ($details as $d) {
- $insertData[] = [
- 'main_id' => $mainId,
- 'device_id' => $d['device_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,
- 'upd_time' => $now,
- 'del_time' => 0
- ];
- }
- DB::table('daily_dw_order_details')->insert($insertData);
- // 回填单号
- $code = $this->generateBillNo([
- 'top_depart_id' => $topDepartId,
- 'type' => DailyDwOrder::Order_type,
- 'period' => date("Ym", $first['order_timestamp'])
- ]);
- DB::table('daily_dw_order')->where('id', $mainId)->update(['code' => $code]);
- }
- DB::commit();
- return [true, ''];
- } catch (\Exception $e) {
- DB::rollBack();
- return [false, '保存失败: ' . $e->getMessage()];
- }
- }
- }
|