| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217 |
- <?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, $user){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- try {
- DB::beginTransaction();
- $time = time();
- $month = MonthlyPwOrder::where('del_time',0)
- ->whereIn('id',$data['id'])
- ->pluck('month')
- ->toArray();
- //归档
- list($status, $msg) = ArchiveService::isArchive($month, $user);
- if(! $status) return [false, $msg];
- 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']): '';
- $map = ArchiveService::fillIsArchive($customer['month'], $user);
- $customer['is_archive'] = $map[$customer['month']] ?? false;
- $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['time'][0]) && ! empty($data['time'][1])) {
- $return = $this->changeDateToTimeStampAboutRange($data['time']);
- $model->where('month','>=',$return[0]);
- $model->where('month','<=',$return[1]);
- }
- 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, $user);
- 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'];
- //归档
- list($status, $msg) = ArchiveService::isArchive($data['month'], $user);
- if(! $status) return [false, $msg];
- 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]; // 如果日历未设置,直接拦截
- // 字段中文映射,用于报错
- $fieldNames = [
- 'total_days' => '出勤总天数',
- 'rd_total_days' => '研发出勤总天数',
- 'total_hours' => '出勤总工时',
- 'rd_total_hours'=> '研发总工时'
- ];
- foreach ($data['details'] as $key => $value) {
- $lineTitle = "第" . ($key + 1) . "行:";
- if (empty($value['employee_id'])) return [false, '人员不能为空'];
- $empId = $value['employee_id'];
- // 基础数字格式检查
- foreach ($fieldNames as $field => $title) {
- if(! isset($value[$field])) return [false, $lineTitle . $title . "不存在"];
- $precision = 2;
- $res = $this->checkNumber($value[$field], $precision, 'non-negative');
- if (!$res['valid']) return [false, $lineTitle . $value['employee_title'] . "的" . $title . ":" . $res['error']];
- }
- // --- 业务逻辑校验:出勤天数与工时合法性 ---
- $sysData = $systemStats[$empId] ?? null;
- if ($sysData) {
- // 1. 研发天数不能大于出勤总天数
- if ($value['rd_total_days'] > $value['total_days']) {
- return [false, $lineTitle . "研发出勤天数不能大于出勤总天数"];
- }
- // 2. 研发工时不能大于出勤总工时
- if ($value['rd_total_hours'] > $value['total_hours']) {
- return [false, $lineTitle . "研发总工时不能大于出勤总工时"];
- }
- // 4. 校验出勤总天数是否超过了系统计算的上限
- if ($value['total_days'] != $sysData['attendance_days']) {
- return [false, $lineTitle . "人员[{$empId}]填写的出勤总天数({$value['total_days']})不等于系统核算的天数({$sysData['attendance_days']})"];
- }
- //校验出勤总工时是否超过了系统计算的上限
- if ($value['total_hours'] != $sysData['final_work_hour']) {
- return [false, $lineTitle . "人员[{$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 fillData($data, $user){
- if(empty($data['data'])) return $data;
- $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
- $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'month')), $user);
- 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']] ?? '';
- $data['data'][$key]['is_archive'] = $map[$value['month']] ?? false;
- }
- 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, $user);
- 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, $user);
- DB::commit();
- }catch (\Exception $exception){
- DB::rollBack();
- return [false,$exception->getMessage()];
- }
- return [true, ''];
- }
- private function saveDetailDaily($id, $time, $data, $user){
- 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'],
- 'crt_id' => $user['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, $user){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- try {
- DB::beginTransaction();
- $time = time();
- $month = DailyPwOrder::where('del_time',0)
- ->whereIn('id',$data['id'])
- ->pluck('order_time')
- ->toArray();
- //归档
- list($status, $msg) = ArchiveService::isArchive($month, $user);
- if(! $status) return [false, $msg];
- 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 ?? '';
- $map = ArchiveService::fillIsArchive($customer['order_time'], $user);
- $customer['is_archive'] = $map[$customer['order_time']] ?? false;
- $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['time'][0]) && ! empty($data['time'][1])) {
- $return = $this->changeDateToTimeStampAboutRange($data['time']);
- $model->where('order_time','>=',$return[0]);
- $model->where('order_time','<=',$return[1]);
- }
- 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['item_title'])) {
- $models = Item::TopClear($user,$data);
- $id = $models->where('del_time',0)
- ->where('title', 'LIKE', '%'.$data['item_title'].'%')
- ->pluck('id')
- ->all();
- $model->whereIn('item_id', $id);
- }
- return $model;
- }
- public function dailyPwOrderList($data,$user){
- $model = $this->dailyPwOrderCommon($data, $user);
- $list = $this->limit($model,'',$data);
- $list = $this->fillDataDaily($list, $user);
- return [true, $list];
- }
- public function dailyPwOrderRule(&$data, $user, $is_add = true){
- $data['top_depart_id'] = $user['top_depart_id'];
- if(empty($data['order_time'])) return [false, '单据日期不能为空'];
- $data['order_time'] = $this->changeDateToDate($data['order_time']);
- $orderTime = $data['order_time'];
- $itemId = $data['item_id'] ?? 0;
- // 使用日期范围限制
- list($status, $msg) = MiddleGroundService::checkTimestampInRange($data['order_time'], $data['top_depart_id']);
- if(! $status) return [false, $msg];
- //归档
- list($status, $msg) = ArchiveService::isArchive($data['order_time'], $user);
- if(! $status) return [false, $msg];
- if(empty($itemId)) return [false, '项目不能为空'];
- $bool = Item::where('del_time',0)->where('id', $itemId)->exists();
- if(!$bool) return [false, '项目不存在或已被删除'];
- 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){
- $line = $key + 1;
- $t = "第" . $line . "行";
- $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, $t . "人员{$empName}开始点:" . $res['error']];
- if($value['start_time_hour'] > 23) return [false, false, $t . "人员{$empName}开始点不合法"];
- $res = $this->checkNumber($value['start_time_min'], 0, 'non-negative');
- if(!$res['valid']) return [false, $t . "人员{$empName}开始分:" . $res['error']];
- if($value['start_time_min'] > 60) return [false, false, $t . "人员{$empName}开始点不合法"];
- $res = $this->checkNumber($value['end_time_hour'], 0, 'non-negative');
- if(!$res['valid']) return [false, $t . "人员{$empName}结束点:" . $res['error']];
- if($value['end_time_hour'] > 24) return [false, false, $t . "人员{$empName}结束点不合法"];
- $res = $this->checkNumber($value['end_time_min'], 0, 'non-negative');
- if(!$res['valid']) return [false, $t . "人员{$empName}结束分:" . $res['error']];
- if($value['end_time_min'] > 60) return [false, false, $t . "人员{$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, $t . "人员{$empName}:开始时间必须早于结束时间"];
- }
- // --- 新增:总分钟数校验 ---
- $calculatedTotal = $currentEnd - $currentStart;
- if (!isset($value['total_work_min']) || intval($value['total_work_min']) !== $calculatedTotal) {
- return [false, $t . "人员{$empName}:总工时计算有误,应为 {$calculatedTotal} 分钟"];
- }
- // --- 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, $user){
- 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')));
- $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'order_time')), $user);
- 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'] ?? '';
- $data['data'][$key]['is_archive'] = $map[$value['order_time']] ?? false;
- }
- 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'] ?? '',
- 'total_work_min' => $item->total_work_min,
- ];
- $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']);
- //归档
- list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
- if(! $status) return [false, $msg];
- // 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'];
- // $total = 0;
- // foreach ($previewData as $value){
- // if($value['employee_id'] == 142 && $value['item_id'] == 122) $total += $value['total_work_min'];
- // }dd($total);
- return [true, [
- 'batch_id' => $batchId,
- 'list' => $previewData // 返回给前端展示
- ]];
- }
- /**
- * 核心分配逻辑:计算预览数据(确保全整数分钟)
- * @param int $monthStart 月初时间戳
- * @param int $topDepartId 顶级部门ID
- * @param array $user 用户信息
- * @return array
- */
- private function calculateDailyAllocation1($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('top_depart_id', $topDepartId)
- ->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('d.top_depart_id', $topDepartId)
- ->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];
- }
- private function calculateDailyAllocation($monthStart, $topDepartId, $user)
- {
- $monthEnd = strtotime('+1 month', $monthStart) - 1;
- $step = 5; // 尽量 5 分钟对齐;明细允许个别非整 5
- // --- 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' => '未找到明细'];
- $empNameMap = $monthlyOrder->pluck('employee_title', 'employee_id')->toArray();
- $empIds = array_keys($empNameMap);
- $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('top_depart_id', $topDepartId)->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('d.top_depart_id', $topDepartId)->where('m.del_time', 0)
- ->select('d.*', 'm.order_time', 'm.type as main_type')->get()->groupBy(['employee_id', 'order_time']);
- // --- 2. 阶段一:先锁定「每人每项目月目标」= 最大余数法(月总×比例),再往工作日摊 ---
- // 5 分钟对齐产生的零头,只加回「同一个人 + 同一个项目」的明细,不甩给别的项目
- $finalAlloc = [];
- $empProjectTargets = []; // [empId][itemId] => 月目标分钟
- $dayBalance = [];
- foreach ($monthlyOrder as $mDetail) {
- $empId = $mDetail->employee_id;
- $empRules = $ruleSet->get($empId);
- if (!$empRules || $empRules->isEmpty()) continue;
- $empTotalMin = (int)round((float)$mDetail->rd_total_hours * 60);
- if ($empTotalMin <= 0) continue;
- // 2.1 按比例拆月目标(最大余数法,保证加总=月总,且最接近「月总×比例」)
- $projTarget = $this->buildProjectMonthTargetsByRate($empRules, $empTotalMin);
- if (empty($projTarget)) continue;
- $empProjectTargets[$empId] = $projTarget;
- $projRem = $projTarget;
- $empRemainingMin = $empTotalMin;
- // 2.2 预计算有容量的工作日
- $dayCaps = [];
- foreach ($allDays as $dayInfo) {
- $dayTs = $dayInfo->time;
- $tempPool = $this->buildAvailablePool($empId, $dayTs, $allDays, $empWorkRanges, $standardWorkRanges, $leaveOverData);
- $dayCapacity = 0;
- foreach ($tempPool as $p) {
- $dayCapacity += (int)($p['e'] - $p['s']);
- }
- if ($dayCapacity > 0) {
- $dayCaps[$dayTs] = $dayCapacity;
- }
- }
- if (empty($dayCaps)) continue;
- $dayTsList = array_keys($dayCaps);
- $dayIndex = 0;
- $dayCount = count($dayTsList);
- foreach ($dayTsList as $dayTs) {
- if ($empRemainingMin <= 0) break;
- if (array_sum($projRem) <= 0) break;
- $dayCapacity = $dayCaps[$dayTs];
- $theoryAlloc = min($empRemainingMin, $dayCapacity);
- $isLastDay = ($dayIndex === $dayCount - 1) || ($theoryAlloc >= $empRemainingMin);
- if (!$isLastDay) {
- $currentWithBalance = $theoryAlloc + ($dayBalance[$empId] ?? 0);
- $roundedAlloc = (int)round($currentWithBalance / $step) * $step;
- $canAllocToday = min($roundedAlloc, $dayCapacity, $empRemainingMin);
- if ($canAllocToday <= 0 && $theoryAlloc > 0) {
- $canAllocToday = min($theoryAlloc, $empRemainingMin);
- }
- $dayBalance[$empId] = $currentWithBalance - $canAllocToday;
- } else {
- $canAllocToday = min($empRemainingMin, $dayCapacity);
- $dayBalance[$empId] = 0;
- }
- if ($canAllocToday <= 0) {
- $dayIndex++;
- continue;
- }
- $dayParts = $this->splitMinutesByRemaining($canAllocToday, $projRem, $step, $isLastDay);
- foreach ($dayParts as $itemId => $projectMin) {
- if ($projectMin <= 0) continue;
- $finalAlloc[$dayTs][$itemId][$empId] = ($finalAlloc[$dayTs][$itemId][$empId] ?? 0) + $projectMin;
- $projRem[$itemId] = max(0, ($projRem[$itemId] ?? 0) - $projectMin);
- }
- $empRemainingMin -= $canAllocToday;
- $dayIndex++;
- }
- // 2.3 仍有项目剩余则塞进尚有空闲的天(仍归原项目)
- $stuck = array_sum($projRem);
- if ($stuck > 0) {
- foreach ($dayCaps as $dayTs => $dayCapacity) {
- if ($stuck <= 0) break;
- $used = 0;
- if (!empty($finalAlloc[$dayTs])) {
- foreach ($finalAlloc[$dayTs] as $emps) {
- $used += (int)($emps[$empId] ?? 0);
- }
- }
- $free = $dayCapacity - $used;
- if ($free <= 0) continue;
- foreach ($projRem as $itemId => $rem) {
- if ($rem <= 0 || $free <= 0) continue;
- $take = min($rem, $free);
- $finalAlloc[$dayTs][$itemId][$empId] = ($finalAlloc[$dayTs][$itemId][$empId] ?? 0) + $take;
- $projRem[$itemId] -= $take;
- $free -= $take;
- $stuck -= $take;
- }
- }
- }
- }
- // --- 3. 阶段二:打散到时间点;尽量 5 对齐,零头加回同一人同一项目的某条明细 ---
- $previewList = [];
- $dailyEmpTimePools = [];
- $tempMainIdCounter = 1;
- foreach ($finalAlloc as $dayTs => $projects) {
- foreach ($projects as $itemId => $employees) {
- $itemTitle = $itemMap[$itemId] ?? '未知项目';
- foreach ($employees as $empId => $toAllocMin) {
- $currentTempMainId = $tempMainIdCounter++;
- 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;
- $rawStart = (int)$p['s'];
- $alignedStart = (int)ceil($rawStart / $step) * $step;
- if ($alignedStart < $p['e'] && ($p['e'] - $alignedStart) >= min($tempRem, 1)) {
- $realStart = $alignedStart;
- } else {
- $realStart = $rawStart;
- }
- if ($realStart >= $p['e']) continue;
- $pMax = (int)($p['e'] - $realStart);
- $take = min($tempRem, $pMax);
- // 先尽量按 5 切开;零头必须加到「后面有空档」的同人同项目明细上,避免保存时时间冲突
- if ($take >= $step && $tempRem > $step) {
- $alignedTake = (int)floor($take / $step) * $step;
- if ($take >= $tempRem) {
- $blocks = (int)floor($tempRem / $step) * $step;
- $odd = $tempRem - $blocks;
- $take = $blocks > 0 ? $blocks : $tempRem;
- if ($blocks > 0 && $odd > 0) {
- $realEnd = $realStart + $take;
- // 零头只能加在当前池子剩余空间内,且不与已有明细冲突
- $roomInPool = (int)$p['e'] - $realEnd;
- $oddToAdd = min($odd, max(0, $roomInPool));
- $previewList[] = $this->makePreviewRow(
- $currentTempMainId, $dayTs, $itemId, $itemTitle, $empId,
- $empNameMap[$empId] ?? '未知人员', $realStart, $realEnd, $take
- );
- $rowIdx = count($previewList) - 1;
- $tempRem -= $take;
- $p['s'] = $realEnd;
- if ($oddToAdd > 0 && $this->safeBumpPreviewRowMinutes($previewList, $rowIdx, $oddToAdd)) {
- $tempRem -= $oddToAdd;
- $p['s'] = $realEnd + $oddToAdd;
- }
- // 加不进去的 odd 留给后面 safe 回填
- continue;
- }
- } elseif ($alignedTake > 0) {
- $take = $alignedTake;
- }
- }
- $realEnd = $realStart + $take;
- $previewList[] = $this->makePreviewRow(
- $currentTempMainId, $dayTs, $itemId, $itemTitle, $empId,
- $empNameMap[$empId] ?? '未知人员', $realStart, $realEnd, $take
- );
- $tempRem -= $take;
- $p['s'] = $realEnd;
- }
- unset($p);
- // 剩余分钟:找同人同项目、延长后不冲突的明细往后加
- if ($tempRem > 0) {
- $left = $this->safeBumpMinutesOntoEmpItem(
- $previewList,
- (int)$empId,
- (int)$itemId,
- $tempRem,
- date('Y-m-d', $dayTs)
- );
- if ($left > 0) {
- // 当天加不下,再在其它日期的同人同项目明细上找空档
- $left = $this->safeBumpMinutesOntoEmpItem(
- $previewList,
- (int)$empId,
- (int)$itemId,
- $left,
- null
- );
- }
- // 仍剩:在当天找同人空档新开一条短明细(仍属本项目)
- if ($left > 0) {
- $placed = $this->insertRemainderRowInFreeGap(
- $previewList,
- $currentTempMainId,
- $dayTs,
- $itemId,
- $itemTitle,
- $empId,
- $empNameMap[$empId] ?? '未知人员',
- $left
- );
- if ($placed) {
- $left = 0;
- }
- }
- $tempRem = $left;
- }
- }
- }
- }
- // 3.1 最终校验:每人每项目合计必须等于月目标;差额安全加回(不制造重叠)
- $previewList = $this->reconcilePreviewToProjectTargets($previewList, $empProjectTargets);
- return ['status' => true, 'data' => $previewList];
- }
- /**
- * 按分摊比例生成每人各项目月目标分钟(最大余数法)
- * 保证:sum(项目) = 月总;各项目尽可能等于 round/最接近 月总×比例
- */
- private function buildProjectMonthTargetsByRate($empRules, $empTotalMin)
- {
- $rateByItem = [];
- foreach ($empRules as $rule) {
- $itemId = (int)$rule->item_id;
- $rateByItem[$itemId] = ($rateByItem[$itemId] ?? 0) + (float)$rule->rate;
- }
- if (empty($rateByItem) || $empTotalMin <= 0) {
- return [];
- }
- $rateSum = array_sum($rateByItem);
- if ($rateSum <= 0) {
- return [];
- }
- $targets = [];
- $parts = [];
- $used = 0;
- foreach ($rateByItem as $itemId => $rate) {
- $ideal = $empTotalMin * ($rate / $rateSum);
- $floor = (int)floor($ideal + 1e-8);
- $targets[$itemId] = $floor;
- $used += $floor;
- $parts[] = [
- 'item_id' => $itemId,
- 'frac' => $ideal - $floor,
- 'rate' => $rate,
- ];
- }
- $left = $empTotalMin - $used;
- usort($parts, function ($a, $b) {
- if ($a['frac'] == $b['frac']) {
- return $b['rate'] <=> $a['rate'];
- }
- return $b['frac'] <=> $a['frac'];
- });
- foreach ($parts as $row) {
- if ($left <= 0) break;
- $targets[$row['item_id']]++;
- $left--;
- }
- return $targets;
- }
- private function makePreviewRow($tempMainId, $dayTs, $itemId, $itemTitle, $empId, $empTitle, $realStart, $realEnd, $take)
- {
- return [
- 'temp_main_id' => $tempMainId,
- 'order_time' => date('Y-m-d', $dayTs),
- 'order_timestamp' => $dayTs,
- 'item_id' => $itemId,
- 'item_title' => $itemTitle,
- 'employee_id' => $empId,
- 'employee_title' => $empTitle,
- '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,
- ];
- }
- private function rowStartMin(array $row)
- {
- return ((int)$row['start_hour']) * 60 + (int)$row['start_min'];
- }
- private function rowEndMin(array $row)
- {
- return ((int)$row['end_hour']) * 60 + (int)$row['end_min'];
- }
- /**
- * 指定下标延长 end,不校验冲突(调用方需先确保安全)
- */
- private function bumpPreviewRowMinutes(array &$previewList, $index, $addMin)
- {
- if ($addMin == 0 || !isset($previewList[$index])) {
- return;
- }
- $row = &$previewList[$index];
- $end = $this->rowEndMin($row) + (int)$addMin;
- if ($end < $this->rowStartMin($row)) {
- $end = $this->rowStartMin($row);
- }
- $row['end_hour'] = (int)floor($end / 60);
- $row['end_min'] = (int)($end % 60);
- $row['end_time'] = sprintf('%02d:%02d', $row['end_hour'], $row['end_min']);
- $row['total_work_min'] = max(0, $end - $this->rowStartMin($row));
- unset($row);
- }
- /**
- * 判断把 index 行结束时间延长 addMin 后,是否与同人同日其它明细冲突
- */
- private function canBumpRowWithoutOverlap(array $previewList, $index, $addMin)
- {
- if ($addMin <= 0 || !isset($previewList[$index])) {
- return false;
- }
- $row = $previewList[$index];
- $empId = (int)$row['employee_id'];
- $dateStr = $row['order_time'];
- $newS = $this->rowStartMin($row);
- $newE = $this->rowEndMin($row) + (int)$addMin;
- if ($newE <= $newS) {
- return false;
- }
- foreach ($previewList as $i => $other) {
- if ($i === $index) {
- continue;
- }
- if ((int)$other['employee_id'] !== $empId) {
- continue;
- }
- if ($other['order_time'] !== $dateStr) {
- continue;
- }
- $os = $this->rowStartMin($other);
- $oe = $this->rowEndMin($other);
- if ($newS < $oe && $newE > $os) {
- return false;
- }
- }
- return true;
- }
- /**
- * 安全延长指定行(通过冲突检查才改)
- */
- private function safeBumpPreviewRowMinutes(array &$previewList, $index, $addMin)
- {
- if (!$this->canBumpRowWithoutOverlap($previewList, $index, $addMin)) {
- return false;
- }
- $this->bumpPreviewRowMinutes($previewList, $index, $addMin);
- return true;
- }
- /**
- * 把分钟安全加到「同人 + 同项目」某条明细后面(优先指定日期)
- * @return int 未能加上的剩余分钟
- */
- private function safeBumpMinutesOntoEmpItem(array &$previewList, $empId, $itemId, $addMin, $preferDate = null)
- {
- $addMin = (int)$addMin;
- if ($addMin <= 0) {
- return 0;
- }
- // 候选:同人同项目,按「结束后空档大小」优先;同日优先
- $candidates = [];
- foreach ($previewList as $i => $row) {
- if ((int)$row['employee_id'] !== (int)$empId) {
- continue;
- }
- if ((int)$row['item_id'] !== (int)$itemId) {
- continue;
- }
- if ($preferDate !== null && $row['order_time'] !== $preferDate) {
- continue;
- }
- $gap = $this->gapAfterRow($previewList, $i);
- if ($gap <= 0) {
- continue;
- }
- $candidates[] = [
- 'index' => $i,
- 'gap' => $gap,
- 'end' => $this->rowEndMin($row),
- 'same_day' => 1,
- ];
- }
- // 指定日没有空档时,扩大到其它日期
- if (empty($candidates) && $preferDate !== null) {
- return $this->safeBumpMinutesOntoEmpItem($previewList, $empId, $itemId, $addMin, null);
- }
- usort($candidates, function ($a, $b) {
- if ($a['gap'] == $b['gap']) {
- return $b['end'] <=> $a['end'];
- }
- return $b['gap'] <=> $a['gap'];
- });
- $left = $addMin;
- foreach ($candidates as $c) {
- if ($left <= 0) {
- break;
- }
- $give = min($left, $c['gap']);
- // 再确认一次(可能前面已经 bump 过改变了空隙)
- $gapNow = $this->gapAfterRow($previewList, $c['index']);
- $give = min($give, $gapNow);
- if ($give <= 0) {
- continue;
- }
- if ($this->safeBumpPreviewRowMinutes($previewList, $c['index'], $give)) {
- $left -= $give;
- }
- }
- return max(0, $left);
- }
- /**
- * 某条明细结束后,到同人同日下一段开始之间的空档分钟数
- */
- private function gapAfterRow(array $previewList, $index)
- {
- if (!isset($previewList[$index])) {
- return 0;
- }
- $row = $previewList[$index];
- $empId = (int)$row['employee_id'];
- $dateStr = $row['order_time'];
- $end = $this->rowEndMin($row);
- $nextStart = null;
- foreach ($previewList as $i => $other) {
- if ($i === $index) {
- continue;
- }
- if ((int)$other['employee_id'] !== $empId) {
- continue;
- }
- if ($other['order_time'] !== $dateStr) {
- continue;
- }
- $os = $this->rowStartMin($other);
- if ($os >= $end) {
- if ($nextStart === null || $os < $nextStart) {
- $nextStart = $os;
- }
- }
- }
- // 没有下一段:最多延到当天 24:00,避免无限延长
- if ($nextStart === null) {
- $nextStart = 24 * 60;
- }
- return max(0, $nextStart - $end);
- }
- /**
- * 在同人当天已有时间线的空隙中,插入一条余数明细(仍属本项目)
- */
- private function insertRemainderRowInFreeGap(
- array &$previewList,
- $tempMainId,
- $dayTs,
- $itemId,
- $itemTitle,
- $empId,
- $empTitle,
- $needMin
- ) {
- $needMin = (int)$needMin;
- if ($needMin <= 0) {
- return false;
- }
- $dateStr = date('Y-m-d', $dayTs);
- // 收集当天该人所有区间
- $intervals = [];
- foreach ($previewList as $row) {
- if ((int)$row['employee_id'] !== (int)$empId) {
- continue;
- }
- if ($row['order_time'] !== $dateStr) {
- continue;
- }
- $intervals[] = ['s' => $this->rowStartMin($row), 'e' => $this->rowEndMin($row)];
- }
- usort($intervals, function ($a, $b) {
- return $a['s'] <=> $b['s'];
- });
- // 合并后找空隙
- $cursor = 0;
- $dayEnd = 24 * 60;
- foreach ($intervals as $iv) {
- if ($iv['s'] > $cursor) {
- $gap = $iv['s'] - $cursor;
- if ($gap >= $needMin) {
- $previewList[] = $this->makePreviewRow(
- $tempMainId, $dayTs, $itemId, $itemTitle, $empId, $empTitle,
- $cursor, $cursor + $needMin, $needMin
- );
- return true;
- }
- }
- $cursor = max($cursor, $iv['e']);
- }
- if ($dayEnd - $cursor >= $needMin) {
- $previewList[] = $this->makePreviewRow(
- $tempMainId, $dayTs, $itemId, $itemTitle, $empId, $empTitle,
- $cursor, $cursor + $needMin, $needMin
- );
- return true;
- }
- return false;
- }
- /**
- * 最终对齐:每人每项目明细合计必须等于月目标;差额安全加回(不制造重叠)
- */
- private function reconcilePreviewToProjectTargets(array $previewList, array $empProjectTargets)
- {
- if (empty($empProjectTargets) || empty($previewList)) {
- return $previewList;
- }
- $actual = [];
- foreach ($previewList as $row) {
- $empId = (int)$row['employee_id'];
- $itemId = (int)$row['item_id'];
- $actual[$empId][$itemId] = ($actual[$empId][$itemId] ?? 0) + (int)$row['total_work_min'];
- }
- foreach ($empProjectTargets as $empId => $items) {
- foreach ($items as $itemId => $target) {
- $got = (int)($actual[$empId][$itemId] ?? 0);
- $diff = (int)$target - $got;
- if ($diff === 0) {
- continue;
- }
- if ($diff > 0) {
- $left = $this->safeBumpMinutesOntoEmpItem($previewList, $empId, $itemId, $diff, null);
- // 仍缺:按天找空档插入
- if ($left > 0) {
- $dates = [];
- foreach ($previewList as $row) {
- if ((int)$row['employee_id'] === (int)$empId) {
- $dates[$row['order_time']] = $row['order_timestamp'] ?? strtotime($row['order_time']);
- }
- }
- foreach ($dates as $dateStr => $ts) {
- if ($left <= 0) {
- break;
- }
- $itemTitle = '';
- foreach ($previewList as $row) {
- if ((int)$row['employee_id'] === (int)$empId && (int)$row['item_id'] === (int)$itemId) {
- $itemTitle = $row['item_title'];
- break;
- }
- }
- $empTitle = '';
- foreach ($previewList as $row) {
- if ((int)$row['employee_id'] === (int)$empId) {
- $empTitle = $row['employee_title'];
- break;
- }
- }
- $before = $left;
- if ($this->insertRemainderRowInFreeGap(
- $previewList,
- 'reconcile_' . $empId . '_' . $itemId,
- (int)$ts,
- $itemId,
- $itemTitle ?: '未知项目',
- $empId,
- $empTitle ?: '未知人员',
- $left
- )) {
- $left = 0;
- }
- // 插不进整天 needMin,尝试拆小:逐分钟插太慢;改为能插多少插多少
- if ($left > 0) {
- for ($n = $left; $n >= 1; $n--) {
- if ($this->insertRemainderRowInFreeGap(
- $previewList,
- 'reconcile_' . $empId . '_' . $itemId,
- (int)$ts,
- $itemId,
- $itemTitle ?: '未知项目',
- $empId,
- $empTitle ?: '未知人员',
- $n
- )) {
- $left -= $n;
- break;
- }
- }
- }
- unset($before);
- }
- }
- } elseif ($diff < 0) {
- // 多了:从有空可缩的明细尾部扣(不制造 start>=end)
- $needCut = -$diff;
- for ($i = count($previewList) - 1; $i >= 0 && $needCut > 0; $i--) {
- $row = $previewList[$i];
- if ((int)$row['employee_id'] !== (int)$empId) {
- continue;
- }
- if ((int)$row['item_id'] !== (int)$itemId) {
- continue;
- }
- $len = (int)$row['total_work_min'];
- if ($len <= 1) {
- continue;
- }
- $cut = min($needCut, $len - 1);
- $this->bumpPreviewRowMinutes($previewList, $i, -$cut);
- $needCut -= $cut;
- }
- }
- }
- }
- return $previewList;
- }
- /**
- * 按各项目剩余月目标,把当天额度拆开(最大余数法)
- * - 非最后一天:尽量按 5 分钟块分配
- * - 当天 1~4 分钟零头:补给「仍有剩余目标」的项目自身
- *
- * @param int $dayBudget 当天可分配总分钟
- * @param array $projRem [item_id => 剩余目标分钟]
- * @param int $step
- * @param bool $forceExact 是否强制精确分完(最后一天)
- * @return array [item_id => 当天分配分钟]
- */
- private function splitMinutesByRemaining($dayBudget, array $projRem, $step = 5, $forceExact = false)
- {
- $active = [];
- foreach ($projRem as $itemId => $rem) {
- if ($rem > 0) {
- $active[(int)$itemId] = (int)$rem;
- }
- }
- if (empty($active) || $dayBudget <= 0) {
- return [];
- }
- $totalRem = array_sum($active);
- $dayBudget = min($dayBudget, $totalRem);
- $result = array_fill_keys(array_keys($active), 0);
- if ($forceExact || $dayBudget < $step) {
- $order = [];
- $used = 0;
- foreach ($active as $itemId => $rem) {
- $ideal = $dayBudget * $rem / $totalRem;
- $base = (int)floor($ideal);
- $base = min($base, $rem);
- $result[$itemId] = $base;
- $used += $base;
- $order[] = [
- 'item_id' => $itemId,
- 'frac' => $ideal - $base,
- 'rem' => $rem - $base,
- ];
- }
- usort($order, function ($a, $b) {
- if ($a['frac'] == $b['frac']) {
- return $b['rem'] <=> $a['rem'];
- }
- return $b['frac'] <=> $a['frac'];
- });
- $left = $dayBudget - $used;
- foreach ($order as $row) {
- if ($left <= 0) break;
- if ($row['rem'] <= 0) continue;
- $give = min($left, $row['rem']);
- $result[$row['item_id']] += $give;
- $left -= $give;
- }
- return array_filter($result);
- }
- $blockBudget = (int)floor($dayBudget / $step) * $step;
- if ($blockBudget <= 0) {
- return $this->splitMinutesByRemaining($dayBudget, $active, $step, true);
- }
- $blocks = (int)($blockBudget / $step);
- $order = [];
- $usedBlocks = 0;
- foreach ($active as $itemId => $rem) {
- $maxBlocks = (int)floor($rem / $step);
- $idealBlocks = $blocks * $rem / $totalRem;
- $base = (int)floor($idealBlocks);
- $base = min($base, $maxBlocks);
- $result[$itemId] = $base * $step;
- $usedBlocks += $base;
- $order[] = [
- 'item_id' => $itemId,
- 'frac' => $idealBlocks - $base,
- 'rem_blocks' => $maxBlocks - $base,
- 'rem' => $rem,
- ];
- }
- usort($order, function ($a, $b) {
- if ($a['frac'] == $b['frac']) {
- return $b['rem_blocks'] <=> $a['rem_blocks'];
- }
- return $b['frac'] <=> $a['frac'];
- });
- $leftBlocks = $blocks - $usedBlocks;
- foreach ($order as $row) {
- if ($leftBlocks <= 0) break;
- if ($row['rem_blocks'] <= 0) continue;
- $result[$row['item_id']] += $step;
- $leftBlocks--;
- }
- // 当天 1~4 分钟零头:按剩余目标最大余数补给对应项目(该人该项目自己的零头)
- $odd = $dayBudget - $blockBudget;
- if ($odd > 0) {
- $oddParts = $this->splitMinutesByRemaining($odd, $active, $step, true);
- foreach ($oddParts as $itemId => $mins) {
- $already = $result[$itemId] ?? 0;
- $cap = $active[$itemId] - $already;
- if ($cap <= 0) continue;
- $result[$itemId] = $already + min($mins, $cap);
- }
- }
- return array_filter($result);
- }
- public function dailyPwOrderSave($data, $user)
- {
- $list = $data['list'] ?? [];
- if (empty($list)) return [false, '没有可保存的数据'];
- $topDepartId = $user['top_depart_id'];
- $month = $data['month'];
- $monthStart = $this->changeDateToDate($month);
- //归档
- list($status, $msg) = ArchiveService::isArchive($monthStart, $user);
- if(! $status) return [false, $msg];
- $now = time();
- // 1. 预加载员工名称映射 (使用 title 字段)
- $empIds = collect($list)->pluck('employee_id')->unique()->toArray();
- $empMap = DB::table('employee')->whereIn('id', $empIds)->pluck('title', 'id')->toArray();
- // --- 2. 重新分组并记录行号 ---
- $groupedByOrder = [];
- foreach ($list as $index => $item) {
- $item['_line'] = $index + 1; // 记录原始行号(从1开始)
- // 以日期字符串和项目ID作为分组 Key
- $groupKey = $item['order_time'] . '_' . $item['item_id'];
- $groupedByOrder[$groupKey][] = $item;
- }
- // 冲突校验器容器:记录 [员工ID][日期字符串] 下已占用的时间段
- $empTimeline = [];
- DB::beginTransaction();
- try {
- // A. 清理该月份旧数据
- $monthEnd = strtotime('+1 month', $monthStart) - 1;
- $oldOrderIds = DB::table('daily_pw_order')
- ->where('top_depart_id', $topDepartId)
- ->whereBetween('order_time', [$monthStart, $monthEnd])
- ->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]);
- }
- // B. 遍历重组后的分组写入
- foreach ($groupedByOrder as $details) {
- $first = $details[0];
- // 【修正】统一将前端日期字符串转为时间戳入库
- $orderTimestamp = strtotime($first['order_time']);
- $itemId = $first['item_id'];
- // 写入主表
- $mainId = DB::table('daily_pw_order')->insertGetId([
- 'code' => '',
- 'item_id' => $itemId,
- 'order_time' => $orderTimestamp,
- 'top_depart_id' => $topDepartId,
- 'is_create' => 1,
- 'crt_id' => $user['id'],
- 'crt_time' => $now,
- ]);
- $insertDetails = [];
- foreach ($details as $d) {
- $rowNum = $d['_line'];
- $empId = $d['employee_id'];
- $empName = $empMap[$empId] ?? "人员(ID:{$empId})";
- // --- 新增:月份一致性校验 ---
- // 校验这行数据的日期是否属于当前保存的月份
- if (date("Y-m", strtotime($d['order_time'])) !== $month) {
- return [false, "第 {$rowNum} 行:人员[{$empName}]的日期[{$d['order_time']}]不属于保存月份[{$month}]"];
- }
- // 【修正】强制由后端计算分钟数
- $s = (int)$d['start_hour'] * 60 + (int)$d['start_min'];
- $e = (int)$d['end_hour'] * 60 + (int)$d['end_min'];
- $calcTotalMin = $e - $s;
- // 校验1:逻辑合法性
- if ($calcTotalMin <= 0) {
- return [false, "第 {$rowNum} 行:人员[{$empName}]在[{$d['order_time']}]的时间段无效:结束时间必须晚于开始时间"];
- }
- // 校验2:跨单据时间重叠校验
- $dateStr = $d['order_time'];
- if (isset($empTimeline[$empId][$dateStr])) {
- foreach ($empTimeline[$empId][$dateStr] as $exist) {
- if ($s < $exist['e'] && $e > $exist['s']) {
- return [false, "第 {$rowNum} 行:人员[{$empName}]在[{$dateStr}]存在时间冲突({$d['start_time']}-{$d['end_time']}),请检查!"];
- }
- }
- }
- $empTimeline[$empId][$dateStr][] = ['s' => $s, 'e' => $e];
- $insertDetails[] = [
- 'main_id' => $mainId,
- 'employee_id' => $empId,
- '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' => $calcTotalMin,
- 'crt_time' => $now,
- 'item_id' => $itemId,
- 'order_time' => $orderTimestamp,
- 'crt_id' => $user['id'],
- ];
- }
- // 批量写入明细
- DB::table('daily_pw_order_details')->insert($insertDetails);
- // C. 回填单号
- $code = $this->generateBillNo([
- 'top_depart_id' => $topDepartId,
- 'type' => DailyPwOrder::Order_type,
- 'period' => date("Ym", $orderTimestamp)
- ]);
- DB::table('daily_pw_order')->where('id', $mainId)->update(['code' => $code]);
- }
- DB::commit();
- return [true, ''];
- } catch (\Exception $e) {
- DB::rollBack();
- return [false, "保存失败:" . $e->getMessage()];
- }
- }
- }
|