ruleSetRule($data, $user, false); if(!$status) return [$status,$msg]; try { DB::beginTransaction(); $model = RuleSet::where('id',$data['id'])->first(); // $model->code = $data['code'] ?? ''; // $model->month = $data['month'] ?? 0; // $model->save(); $time = time(); RuleSetDetails::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 ruleSetAdd($data,$user){ list($status,$msg) = $this->ruleSetRule($data, $user); if(!$status) return [$status,$msg]; try { DB::beginTransaction(); $model = new RuleSet(); $model->code = $this->generateBillNo([ 'top_depart_id' => $user['top_depart_id'], 'type' => RuleSet::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['man_list'])){ $unit = []; foreach ($data['man_list'] as $value){ $unit[] = [ 'main_id' => $id, 'item_id' => $value['item_id'], 'type' => $value['type'], 'data_id' => $value['data_id'], 'rate' => $value['rate'], 'crt_time' => $time, 'top_depart_id' => $value['top_depart_id'], ]; } if(! empty($unit)) RuleSetDetails::insert($unit); } if(! empty($data['device_list'])){ $receipt = []; foreach ($data['device_list'] as $value){ $receipt[] = [ 'main_id' => $id, 'item_id' => $value['item_id'], 'type' => $value['type'], 'data_id' => $value['data_id'], 'rate' => $value['rate'], 'crt_time' => $time, 'top_depart_id' => $value['top_depart_id'], ]; } if(! empty($receipt)) RuleSetDetails::insert($receipt); } } private function getDetail($id){ $data = RuleSetDetails::where('del_time',0) ->where('main_id', $id) ->get()->toArray(); $id = $id2 = $item_id = []; foreach ($data as $value){ if($value['type'] == RuleSetDetails::type_one) { $id[] = $value['data_id']; }else{ $id2[] = $value['data_id']; } if(! in_array($value['item_id'], $item_id)) $item_id[] = $value['item_id']; } $map = Employee::whereIn('id', $id)->select('title','id','number')->get()->toArray(); $map = array_column($map,null,'id'); $map2 = Device::whereIn('id', $id2)->select('code','id','title')->get()->toArray(); $map2 = array_column($map2,null,'id'); $map3 = Item::whereIn('id', $item_id)->select('title','id','code')->get()->toArray(); $map3 = array_column($map3,null,'id'); $unit = $receipt = []; foreach ($data as $value){ $item = $map3[$value['item_id']] ?? []; if($value['type'] == RuleSetDetails::type_one) { $tmp = $map[$value['data_id']] ?? []; $unit[] = [ 'type' => $value['type'], 'rate' => $value['rate'], 'data_id' => $value['data_id'], 'data_title' => $tmp['title'], 'data_code' => $tmp['number'], 'item_id' => $value['item_id'], 'item_title' => $item['title'] ?? "", 'item_code' => $item['code'] ?? "", ]; }else{ $tmp = $map2[$value['data_id']] ?? []; $receipt[] = [ 'type' => $value['type'], 'rate' => $value['rate'], 'data_id' => $value['data_id'], 'data_title' => $tmp['title'] ?? "", 'data_code' => $tmp['code'] ?? "", 'item_id' => $value['item_id'], 'item_title' => $item['title'] ?? "", 'item_code' => $item['code'] ?? "", ]; } } $detail = [ 'man_list' => $unit, 'device_list' => $receipt, ]; //foreach ($detail as $key => $value) { // if (empty($value)) { //$detail[$key] = (object)[]; // 转成 stdClass 对象 //} //} return $detail; } public function ruleSetDel($data){ if($this->isEmpty($data,'id')) return [false,'请选择数据!']; try { DB::beginTransaction(); $time = time(); RuleSet::where('del_time',0) ->whereIn('id',$data['id']) ->update(['del_time' => $time]); RuleSetDetails::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 ruleSetDetail($data, $user){ if($this->isEmpty($data,'id')) return [false,'请选择数据!']; $customer = RuleSet::where('del_time',0) ->where('id',$data['id']) ->first(); if(empty($customer)) return [false,'规则配置单不存在或已被删除']; $customer = $customer->toArray(); $customer['month'] = ! empty($customer['month']) ? date("Y-m", $customer['month']) : ""; $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']): ''; $details = $this->getDetail($data['id']); $customer = array_merge($customer, $details); return [true, $customer]; } public function ruleSetCommon($data,$user, $field = []){ if(empty($field)) $field = RuleSet::$field; $model = RuleSet::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]); } if(! empty($data['time'][0]) && ! empty($data['time'][1])) { $return = $this->changeDateToTimeStampAboutRange($data['time']); $model->where('month','>=',$return[0]); $model->where('month','<=',$return[1]); } return $model; } public function ruleSetList($data,$user){ $model = $this->ruleSetCommon($data, $user); $list = $this->limit($model,'',$data); $list = $this->fillData($list); return [true, $list]; } public function ruleSetRule(&$data, $user, $is_add = true) { $data['top_depart_id'] = $user['top_depart_id']; if (empty($data['month'])) return [false, '月份不能为空']; $data['month'] = $this->changeDateToDate($data['month']); // --- 0. 批量预加载档案用于错误提示 (核心优化点) --- $manIds = array_unique(array_column($data['man_list'] ?? [], 'data_id')); $devIds = array_unique(array_column($data['device_list'] ?? [], 'data_id')); $manMap = Employee::whereIn('id', $manIds)->get(['id', 'number', 'title']) ->mapWithKeys(fn($item) => [$item->id => "[{$item->number}]{$item->title}"]); $devMap = Device::whereIn('id', $devIds)->get(['id', 'code', 'title']) ->mapWithKeys(fn($item) => [$item->id => "[{$item->code}]{$item->title}"]); // --- 1. 人员列表校验 --- if (empty($data['man_list'])) return [false, '人员不能为空']; $manRates = []; foreach ($data['man_list'] as $key => $value) { if (empty($value['type'])) return [false, '类型不能为空']; if (empty($value['data_id'])) return [false, '人员不能为空']; if (empty($value['item_id'])) return [false, '项目不能为空']; $res = $this->checkNumber($value['rate'], 2, 'non-negative'); if (!$res['valid']) return [false, '人员工时分摊比例:' . $res['error']]; $data['man_list'][$key]['top_depart_id'] = $data['top_depart_id']; $manId = $value['data_id']; $manRates[$manId] = ($manRates[$manId] ?? 0) + $value['rate']; } // 校验人员比例 (错误提示加入人名) foreach ($manRates as $mId => $total) { if (abs($total - 100) > 0.0001) { $displayName = $manMap[$mId] ?? "ID:{$mId}"; return [false, "人员{$displayName}的分摊比例合计为{$total}%,必须等于100%"]; } } // --- 2. 设备列表校验 --- if (empty($data['device_list'])) return [false, '设备不能为空']; $deviceRates = []; foreach ($data['device_list'] as $key => $value) { if (empty($value['type'])) return [false, '类型不能为空']; if (empty($value['data_id'])) return [false, '设备ID不能为空']; if (empty($value['item_id'])) return [false, '项目不能为空']; $res = $this->checkNumber($value['rate'], 2, 'non-negative'); if (!$res['valid']) return [false, '设备工时分摊比例:' . $res['error']]; $data['device_list'][$key]['top_depart_id'] = $data['top_depart_id']; $devId = $value['data_id']; $deviceRates[$devId] = ($deviceRates[$devId] ?? 0) + $value['rate']; } // 校验设备比例 (错误提示加入设备名称) foreach ($deviceRates as $dId => $total) { if (abs($total - 100) > 0.0001) { $displayName = $devMap[$dId] ?? "ID:{$dId}"; return [false, "设备{$displayName}的分摊比例合计为{$total}%,必须等于100%"]; } } // --- 3. 重复单据校验 --- if ($is_add) { $bool = RuleSet::where('month', $data['month']) ->where('top_depart_id', $data['top_depart_id']) ->where('del_time', 0) ->exists(); } else { if (empty($data['id'])) return [false, 'ID不能为空']; $bool = RuleSet::where('month', $data['month']) ->where('top_depart_id', $data['top_depart_id']) ->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'); // 1. 获取详情映射 [main_id => [ [code_2=>..., title=>..., item_code=>...], ... ]] $detailsMap = $this->getDetailsMap($mainIds); foreach ($data as $main) { $mainId = $main['id']; $details = $detailsMap[$mainId] ?? []; // 2. 提取并格式化主表共有信息 $mainInfo = [ 'code' => $main['code'], 'month' => !empty($main['month']) ? date('Y-m', $main['month']) : '', ]; 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 = []; // 严格按照导出 Excel 的列顺序填充数据 foreach ($column as $col) { $tempRow[] = $fullRowData[$col] ?? ''; } $return[] = $tempRow; } } } } public function getDetailsMap($mainIds) { $details = RuleSetDetails::where('del_time', 0) ->whereIn('main_id', $mainIds) ->get(); if ($details->isEmpty()) return []; // 1. 提取所有需要关联的 ID $empIds = $details->where('type', RuleSetDetails::type_one)->pluck('data_id')->unique(); $devIds = $details->where('type', RuleSetDetails::type_two)->pluck('data_id')->unique(); $itemIds = $details->pluck('item_id')->unique(); // 2. 批量获取档案 Map $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id'); $devMap = Device::whereIn('id', $devIds)->get()->keyBy('id'); $itemMap = Item::whereIn('id', $itemIds)->get()->keyBy('id'); $typeNames = RuleSetDetails::$type_name; $res = []; foreach ($details as $item) { $detailRow = []; // 类型名称(明细类型列) $detailRow['type_title'] = $typeNames[$item->type] ?? ''; // 处理人员或设备的编码与名称(影子列) if ($item->type == RuleSetDetails::type_one) { $emp = $empMap[$item->data_id] ?? null; $detailRow['code_2'] = $emp ? $emp->number : ''; // 明细编码 $detailRow['title'] = $emp ? $emp->title : ''; // 明细名称 } else { $dev = $devMap[$item->data_id] ?? null; $detailRow['code_2'] = $dev ? $dev->code : ''; // 明细编码 $detailRow['title'] = $dev ? $dev->title : ''; // 明细名称 } // 处理项目编码与名称 $project = $itemMap[$item->item_id] ?? null; $detailRow['item_code'] = $project ? $project->code : ''; $detailRow['item_title'] = $project ? $project->title : ''; // 比例 $detailRow['rate'] = $item->rate; // 归档到对应的单据下 $res[$item->main_id][] = $detailRow; } return $res; } public function isSetMonthCalendar($data, $user){ $data['top_depart_id'] = $user['top_depart_id']; if(empty($data['month'])) return [false, '月份不能为空']; // 1. 月份初始化 $monthStart = $this->changeDateToDate($data['month']); $monthStr = date("Y-m", $monthStart); $endTime = strtotime("+1 month", $monthStart) - 1; // 2. 获取当月标准工作日天数 (基数) $standardWorkDays = DB::table('calendar_details') ->where('top_depart_id', $data['top_depart_id']) ->where('del_time', 0) ->where('time', '>=', $monthStart) ->where('time', '<=', $endTime) ->where('is_work', CalendarDetails::TYPE_ONE) ->count(); if ($standardWorkDays <= 0) return [false, $monthStr . '还未设置工作日']; return [true, '']; } public function ruleSetCreate($data, $user){ $data['top_depart_id'] = $user['top_depart_id']; if(empty($data['month'])) return [false, '月份不能为空']; $monthStart = $this->changeDateToDate($data['month']); $data['month'] = $monthStart; $monthEnd = strtotime('+1 month', $monthStart) - 1; // 1. 获取在该月份有效期内的项目及其信息 (ID, 标题, 编号) $itemsData = DB::table('item') ->where('top_depart_id', $data['top_depart_id']) ->where('del_time', 0) ->where('start_time', '<=', $monthEnd) ->where('end_time', '>=', $monthStart) ->get(['id', 'title', 'code']) // 获取项目 ID, 标题, 编号 ->keyBy('id') ->toArray(); if (empty($itemsData)) return [false, "该月份下无项目信息"]; $itemIds = array_keys($itemsData); // 2. 获取项目明细 $details = DB::table('item_details') ->whereIn('item_id', $itemIds) ->where('top_depart_id', $data['top_depart_id']) ->where('del_time', 0) ->get(); $manIds = []; $devIds = []; $manMap = []; $deviceMap = []; foreach ($details as $row) { if ($row->type == ItemDetails::type_one) { $manMap[$row->data_id][] = $row->item_id; $manIds[] = $row->data_id; } elseif ($row->type == ItemDetails::type_two) { $deviceMap[$row->data_id][] = $row->item_id; $devIds[] = $row->data_id; } } // 3. 批量获取人员和设备信息 (含编号) $manInfos = DB::table('employee') ->whereIn('id', array_unique($manIds)) ->get(['id', 'title', 'number']) // 这里的 number 是工号 ->keyBy('id')->toArray(); $devInfos = DB::table('device') ->whereIn('id', array_unique($devIds)) ->get(['id', 'title', 'code']) // 这里的 code 是资产编号 ->keyBy('id')->toArray(); // 4. 生成分配列表 $man_list = $this->distributeRates($manMap, RuleSetDetails::type_one, $manInfos, $itemsData); $device_list = $this->distributeRates($deviceMap, RuleSetDetails::type_two, $devInfos, $itemsData); return [true, [ 'month' => date('Y-m', $monthStart), 'man_list' => $man_list, 'device_list' => $device_list ]]; } private function distributeRates($map, $type, $infoMap, $itemsData) { $result = []; foreach ($map as $dataId => $items) { $count = count($items); $rates = []; // --- 随机分配逻辑 (保持不变) --- if ($count === 1) { $rates = [100]; } else { $sum = 0; $temp = []; for ($i = 0; $i < $count; $i++) { $rand = rand(10, 100); $temp[] = $rand; $sum += $rand; } $currentTotal = 0; foreach ($temp as $i => $weight) { if ($i === $count - 1) { $rates[] = 100 - $currentTotal; } else { $val = (int)round(($weight / $sum) * 100); $val = $val <= 0 ? 1 : $val; $rates[] = $val; $currentTotal += $val; } } } // --- 数据组装 --- foreach ($items as $index => $itemId) { $info = $infoMap[$dataId] ?? null; $itemInfo = $itemsData[$itemId] ?? null; $result[] = [ 'type' => $type, 'data_id' => $dataId, 'data_title' => $info->title ?? '', 'data_code' => ($type == RuleSetDetails::type_one) ? ($info->number ?? '') : ($info->code ?? ''), 'item_id' => $itemId, 'item_title' => $itemInfo->title ?? '', 'item_code' => $itemInfo->code ?? '', // 项目编号 'rate' => $rates[$index] ]; } } return $result; } }