ImportService.php 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515
  1. <?php
  2. namespace App\Service;
  3. use App\Exports\TableHeadExport;
  4. use App\Import\ImportAll;
  5. use App\Model\DailyDwOrder;
  6. use App\Model\DailyPwOrder;
  7. use App\Model\Depart;
  8. use App\Model\Device;
  9. use App\Model\Employee;
  10. use App\Model\EmployeeDepartPermission;
  11. use App\Model\ExpenseClaimsDetails;
  12. use App\Model\Fee;
  13. use App\Model\Item;
  14. use App\Model\ItemDetails;
  15. use App\Model\MonthlyDdOrder;
  16. use App\Model\MonthlyPsOrder;
  17. use App\Model\MonthlyPwOrder;
  18. use App\Model\PLeaveOverOrder;
  19. use App\Model\Tag;
  20. use App\Model\RuleSet;
  21. use App\Model\RuleSetDetails;
  22. use App\Model\Team;
  23. use App\Model\TeamDetails;
  24. use Illuminate\Support\Facades\DB;
  25. use Maatwebsite\Excel\Facades\Excel;
  26. use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F;
  27. use PhpOffice\PhpSpreadsheet\IOFactory;
  28. use PhpOffice\PhpSpreadsheet\Shared\Date;
  29. class ImportService extends Service
  30. {
  31. public static $type = [
  32. 'depart', // 部门
  33. 'employee', // 用户
  34. 'device', // 设备
  35. 'item', // 项目
  36. 'fee', // 费用
  37. 'monthPwOrder', // 人员月度研发工时单
  38. 'monthDwOrder', // 设备月度研发工时单
  39. 'monthPsOrder', // 人员月度工资单
  40. 'monthDdOrder', // 设备月度折旧单
  41. 'ruleSet', // 规则配置单
  42. 'dailyPwOrder', // 人员日工时单
  43. 'dailyDwOrder', // 设备日工时单
  44. 'leaveOrder', // 请假单
  45. 'overtimeOrder', // 加班单
  46. 'feeOrder', // 费用项目单
  47. 'RDOrder', // 研发支出辅助帐
  48. 'tag', // 标签管理
  49. 'team', // 团队
  50. ];
  51. public function getTableTitleXls($data,$user){
  52. if(empty($data['type'])) return [false,'缺少类型'];
  53. //获取配置文件
  54. // $fuc = $data['type'];
  55. // if (! method_exists(self::class, $fuc)) return [false, "导入文件方法获取不存在,请联系开发"];
  56. list($status,$return) = $this->title($data,$user);
  57. list($msg,$filename) = $return;
  58. if(! $status) return [false, $msg];
  59. $headers = array_column($msg,'value');
  60. $comments = $enums = [];
  61. foreach ($msg as $value){
  62. if(! empty($value['comments'])) $comments[$value['value']] = $value['comments'];
  63. if(! empty($value['enums'])) $enums[$value['value']] = $value['enums'];
  64. }
  65. Excel::store(new TableHeadExport([], $headers, $comments, $enums),"/public/export/{$filename}", null, 'Xlsx', []);
  66. return [true, ['file' => $filename]];
  67. }
  68. private function getTableConfig($type = ""){
  69. if(empty($type)) return [];
  70. //获取配置文件
  71. $config = "excel." . $type;
  72. return config($config) ?? [];
  73. }
  74. private function title($data,$user){
  75. $config = $this->getTableConfig($data['type']);
  76. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  77. $config_array = $config['array'] ?? [];
  78. //生成下载文件
  79. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  80. return [true, [$config_array, $filename]];
  81. }
  82. //导入入口
  83. public function importAll($data,$user){
  84. // //不超时
  85. // ini_set('max_execution_time', 0);
  86. // //内存设置
  87. // ini_set('memory_limit', -1);
  88. // $reader = IOFactory::createReader('Xlsx');
  89. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  90. // $spreadsheet = $reader->load($data['file']);
  91. // dd($spreadsheet);
  92. // // 创建一个Reader对象
  93. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  94. //
  95. //// 加载Excel文件
  96. // $spreadsheet = $reader->load($data['file']);
  97. //
  98. //// 获取第一个工作表
  99. // $worksheet = $spreadsheet->getActiveSheet();
  100. //
  101. //// 获取总行数
  102. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  103. if(empty($data['type'])) return [false,'缺少导入类型,导入失败'];
  104. if(! in_array($data['type'],self::$type)) return [false,'导入类型不存在,导入失败'];
  105. if(empty($data['file'])) return [false,'导入文件不能为空'];
  106. try {
  107. $import = new ImportAll();
  108. //设置导入人id
  109. $import->setCrt($user['id']);
  110. $import->setUser($user);
  111. $import->setType($data['type']);
  112. $other = $data;
  113. unset($other['file']);
  114. $import->setOtherParam($other);
  115. //导入
  116. \Maatwebsite\Excel\Facades\Excel::import($import,$data['file']);
  117. if($import->getMsg()) {
  118. $bool = $import->getIsLongText();
  119. if($bool) {
  120. return [0, $import->getMsg()];
  121. }else{
  122. return [false, $import->getMsg()];
  123. }
  124. }
  125. }catch (\Throwable $exception) {
  126. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  127. }
  128. return [true, ''];
  129. }
  130. // 人 -----------------------------------
  131. public function employeeImport($array, $user, $other_param)
  132. {
  133. $upload = $array[0];
  134. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  135. if (!$status) return [false, $msg];
  136. $table_config = $msg;
  137. unset($array[0]);
  138. if (empty($array)) return [false, '导入数据不能为空'];
  139. // 1. 公共校验 (必填、唯一性等)
  140. list($array, $error) = $this->checkCommon($array, $table_config);
  141. if (!empty($error)) return [0, $error];
  142. // 2. 业务详细校验 (获取更新映射及明细数据)
  143. list($error, $update_map, $detail_data_map) = $this->employeeCheck($array, $user, $table_config);
  144. if (!empty($error)) return [0, $error];
  145. $time = time();
  146. $insert_data = [];
  147. $update_data = [];
  148. $all_detail_insert = []; // 用于聚合所有部门权限
  149. $update_main_ids = [];
  150. // 获取工号在配置中的索引
  151. $keys = array_column($table_config, 'key');
  152. $codeIdx = array_search('number', $keys);
  153. // 3. 数据分拣与聚合
  154. foreach ($array as $key => $value) {
  155. $empNumber = trim((string)$value[$codeIdx]);
  156. if ($empNumber === '') continue;
  157. $main_tmp = [];
  158. foreach ($value as $k => $val) {
  159. // 只要 is_main 为 true,就记录到主表。
  160. // 配置单中 depart_code 为 false,会自动被此处跳过
  161. if (!empty($table_config[$k]['is_main'])) {
  162. $main_tmp[$table_config[$k]['key']] = $val;
  163. }
  164. }
  165. if (isset($update_map[$key])) {
  166. // 更新逻辑:以 ID 为键去重
  167. $empId = $update_map[$key];
  168. $update_main_ids[$empId] = $empId;
  169. $update_data[$empId] = array_merge($main_tmp, ['id' => $empId]);
  170. // 收集部门明细
  171. if (isset($detail_data_map[$key])) {
  172. foreach ($detail_data_map[$key] as $d) {
  173. // 使用 工号_部门ID 确保明细不重复
  174. $all_detail_insert[$empNumber . '_' . $d['depart_id']] = [
  175. 'employee_id' => $empId,
  176. 'depart_id' => $d['depart_id'],
  177. 'top_depart_id' => $user['top_depart_id']
  178. ];
  179. }
  180. }
  181. } else {
  182. // 新增逻辑:以工号为键去重
  183. if (!isset($insert_data[$empNumber])) {
  184. $main_tmp['account'] = $user['top_depart_code'] . "_" . $empNumber;
  185. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  186. $main_tmp['crt_id'] = $user['id'];
  187. $main_tmp['crt_time'] = $time;
  188. $insert_data[$empNumber] = $main_tmp;
  189. }
  190. // 收集部门明细 (待回填主表 ID)
  191. if (isset($detail_data_map[$key])) {
  192. foreach ($detail_data_map[$key] as $d) {
  193. $all_detail_insert[$empNumber . '_' . $d['depart_id']] = [
  194. '_number' => $empNumber, // 临时标记
  195. 'depart_id' => $d['depart_id'],
  196. 'top_depart_id' => $user['top_depart_id']
  197. ];
  198. }
  199. }
  200. }
  201. }
  202. DB::beginTransaction();
  203. try {
  204. // 4. 执行新增主表
  205. $new_item_maps = [];
  206. if (!empty($insert_data)) {
  207. // 使用 array_values 将关联数组转为索引数组
  208. foreach (array_chunk(array_values($insert_data), 500) as $chunk) {
  209. Employee::insert($chunk);
  210. }
  211. // 获取新插入数据的 ID 映射
  212. $new_item_maps = Employee::whereIn('number', array_keys($insert_data))
  213. ->where('del_time', 0)
  214. ->where('top_depart_id', $user['top_depart_id'])
  215. ->pluck('id', 'number')->toArray();
  216. }
  217. // 5. 执行更新主表 (分批更新)
  218. if (!empty($update_data)) {
  219. foreach ($update_data as $uItem) {
  220. $id = $uItem['id'];
  221. unset($uItem['id']);
  222. Employee::where('id', $id)->update($uItem);
  223. }
  224. }
  225. // 6. 处理明细表 (先删后插策略)
  226. // 注意:分行模式下,更新人员的所有旧权限都要先清空
  227. if (!empty($update_main_ids)) {
  228. EmployeeDepartPermission::whereIn('employee_id', array_values($update_main_ids))->delete();
  229. }
  230. // 组装最终插入的明细数组并回填 ID
  231. $final_detail_insert = [];
  232. foreach ($all_detail_insert as $di) {
  233. if (isset($di['_number'])) {
  234. $di['employee_id'] = $new_item_maps[$di['_number']] ?? 0;
  235. unset($di['_number']);
  236. }
  237. if ($di['employee_id'] > 0) {
  238. $final_detail_insert[] = $di;
  239. }
  240. }
  241. // 批量插入所有明细
  242. if (!empty($final_detail_insert)) {
  243. foreach (array_chunk($final_detail_insert, 500) as $chunk) {
  244. EmployeeDepartPermission::insert($chunk);
  245. }
  246. }
  247. DB::commit();
  248. } catch (\Exception $e) {
  249. DB::rollBack();
  250. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  251. }
  252. return [true, ''];
  253. }
  254. private function getEmployeeList($array, $user, $index){
  255. //查找设备
  256. $codes = array_unique(array_filter(array_column($array,$index)));
  257. return Employee::where('del_time', 0)
  258. ->where('top_depart_id', $user['top_depart_id'])
  259. ->whereIn('number', $codes)
  260. ->pluck('id','number')
  261. ->toArray();
  262. }
  263. private function employeeCheck(&$array, $user, $table_config)
  264. {
  265. $keys = array_column($table_config, 'key');
  266. $codeIdx = array_search('number', $keys);
  267. $sexIdx = array_search('sex', $keys);
  268. $eductionIdx = array_search('education', $keys);
  269. $stateIdx = array_search('state', $keys);
  270. $manIdx = array_search('man_type', $keys);
  271. $entrustIdx = array_search('entrust_type', $keys);
  272. $depIdx = array_search('depart_code', $keys);
  273. $employeeTypeIdx = array_search('employee_type', $keys);
  274. $code_map = $this->getEmployeeList($array, $user, $codeIdx);
  275. $dep_map = $this->getEDataList($array, $user, $depIdx);
  276. $errors = [];
  277. $update_mapping = [];
  278. $detail_storage = [];
  279. $mainDataConsistency = []; // 用于存放工号对应的主表数据备份
  280. $sex_map = array_flip(Employee::SEX_TYPE);
  281. $e_map = array_flip(Employee::Education);
  282. $state_map = array_flip(Employee::State_Type);
  283. $man_map = array_flip(Employee::Man_Type);
  284. $wt_map = array_flip(Employee::WT_Type);
  285. $employeeT_map = array_flip(Employee::E_State_Type);
  286. // 获取所有标记为 is_main 的列索引,用于一致性对比
  287. $mainColIndices = [];
  288. foreach ($table_config as $index => $conf) {
  289. if (!empty($conf['is_main'])) $mainColIndices[$index] = $conf['value'];
  290. }
  291. foreach ($array as $rowIndex => $rowValue) {
  292. $displayLine = $rowIndex + 1;
  293. $valCode = trim($rowValue[$codeIdx] ?? '');
  294. if ($valCode === '') continue;
  295. // --- 核心:一致性校验 ---
  296. if (!isset($mainDataConsistency[$valCode])) {
  297. // 第一次遇见该工号,记录其所有主表字段的值
  298. foreach ($mainColIndices as $idx => $label) {
  299. $mainDataConsistency[$valCode][$idx] = trim($rowValue[$idx] ?? '');
  300. }
  301. } else {
  302. // 再次遇见该工号,对比主表字段是否一致
  303. foreach ($mainColIndices as $idx => $label) {
  304. $currentVal = trim($rowValue[$idx] ?? '');
  305. if ($currentVal !== $mainDataConsistency[$valCode][$idx]) {
  306. $errors[] = "第{$displayLine}行:工号[{$valCode}]的主表数据[{$label}]与前文不一致";
  307. }
  308. }
  309. }
  310. // 1. 判定更新还是新增
  311. if (isset($code_map[$valCode])) {
  312. $update_mapping[$rowIndex] = $code_map[$valCode];
  313. }
  314. // 2. 校验(性别、学历、状态映射转换)
  315. // 性别
  316. $sex_text = trim($rowValue[$sexIdx] ?? '');
  317. if (!empty($sex_text)) {
  318. if (!isset($sex_map[$sex_text])) {
  319. $errors[] = "第{$displayLine}行:性别[{$sex_text}]无效";
  320. } else {
  321. $array[$rowIndex][$sexIdx] = $sex_map[$sex_text];
  322. }
  323. }
  324. // 学历
  325. $e_text = trim($rowValue[$eductionIdx] ?? '');
  326. if (!empty($e_text)) {
  327. if (!isset($e_map[$e_text])) {
  328. $errors[] = "第{$displayLine}行:学历[{$e_text}]无效";
  329. } else {
  330. $array[$rowIndex][$eductionIdx] = $e_map[$e_text];
  331. }
  332. }
  333. // 状态
  334. $state_text = trim($rowValue[$stateIdx] ?? '');
  335. if (!isset($state_map[$state_text])) {
  336. $errors[] = "第{$displayLine}行:状态[{$state_text}]无效";
  337. } else {
  338. $array[$rowIndex][$stateIdx] = $state_map[$state_text];
  339. }
  340. // 外聘类型
  341. $e_text = trim($rowValue[$employeeTypeIdx] ?? '');
  342. if (!isset($employeeT_map[$e_text])) {
  343. $errors[] = "第{$displayLine}行:外聘类型[{$e_text}]无效";
  344. } else {
  345. $array[$rowIndex][$employeeTypeIdx] = $employeeT_map[$e_text];
  346. }
  347. //人员类别
  348. $man_text = trim($rowValue[$manIdx] ?? '');
  349. if (!isset($man_map[$man_text])) {
  350. $errors[] = "第{$displayLine}行:人员类别[{$man_text}]无效";
  351. } else {
  352. $array[$rowIndex][$manIdx] = $man_map[$man_text];
  353. }
  354. //委托类型
  355. $wt_text = trim($rowValue[$entrustIdx] ?? '');
  356. if (!isset($wt_map[$wt_text])) {
  357. $errors[] = "第{$displayLine}行:委托方式[{$wt_text}]无效";
  358. } else {
  359. $array[$rowIndex][$entrustIdx] = $wt_map[$wt_text];
  360. }
  361. // 4. 解析部门 (分行模式)
  362. if ($depIdx !== false && !empty($rowValue[$depIdx])) {
  363. $mNum = trim($rowValue[$depIdx]);
  364. if (!isset($dep_map[$mNum])) {
  365. $errors[] = "第{$displayLine}行:部门编码[{$mNum}]不存在";
  366. } else {
  367. $detail_storage[$rowIndex][] = ['depart_id' => $dep_map[$mNum]];
  368. }
  369. }
  370. }
  371. $error_str = !empty($errors) ? implode('|', $errors) : "";
  372. return [$error_str, $update_mapping, $detail_storage];
  373. }
  374. private function getEDataList($array, $user, $index1)
  375. {
  376. $depNums = [];
  377. // 去重收集
  378. foreach ($array as $row) {
  379. if (!empty($row[$index1])) {
  380. foreach (explode(',', $row[$index1]) as $v) $depNums[trim($v)] = true;
  381. }
  382. }
  383. return Depart::where('del_time', 0)
  384. ->where('top_depart_id', $user['top_depart_id'])
  385. ->whereIn('code', array_keys($depNums))
  386. ->pluck('id', 'code')->toArray();
  387. }
  388. // 部门 ----------------------------------
  389. public function departImport($array, $user, $other_param)
  390. {
  391. $upload = $array[0];
  392. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  393. if (!$status) return [false, $msg];
  394. $table_config = $msg;
  395. unset($array[0]);
  396. if (empty($array)) return [false, '导入数据不能为空'];
  397. list($array, $error) = $this->checkCommon($array, $table_config);
  398. if (!empty($error)) return [0, $error];
  399. // 2. 详细校验
  400. list($error, $update_map, $parent_code_map) = $this->departCheck($array, $user, $table_config);
  401. if (!empty($error)) return [0, $error];
  402. $time = time();
  403. $insert = [];
  404. $update = [];
  405. $all_codes = [];
  406. $all_parent_codes = [];
  407. // --- 修正点 1: 必须确保索引提取准确 ---
  408. $keys = array_column($table_config, 'key');
  409. $codeIdx = array_search('code', $keys);
  410. // ------------------------------------
  411. $ignoreKeys = ['parent_id', 'parent_title'];
  412. foreach ($array as $key => $value) {
  413. $cCode = trim($value[$codeIdx] ?? '');
  414. if($cCode === '') continue;
  415. $all_codes[] = $cCode;
  416. if (isset($parent_code_map[$key])) {
  417. $all_parent_codes[] = $parent_code_map[$key];
  418. }
  419. $main_tmp = [];
  420. foreach ($value as $k => $val){
  421. if(!empty($table_config[$k]['is_main'])){
  422. if (!in_array($table_config[$k]['key'], $ignoreKeys)) {
  423. $main_tmp[$table_config[$k]['key']] = $val;
  424. }
  425. }
  426. }
  427. if (isset($update_map[$key])) {
  428. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  429. } else {
  430. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  431. $main_tmp['crt_time'] = $time;
  432. $main_tmp['parent_id'] = 0;
  433. $insert[] = $main_tmp;
  434. }
  435. }
  436. $searchCodes = array_unique(array_merge($all_codes, $all_parent_codes));
  437. DB::beginTransaction();
  438. try {
  439. if (!empty($insert)) {
  440. foreach (array_chunk($insert, 500) as $chunk) {
  441. Depart::insert($chunk);
  442. }
  443. }
  444. if (!empty($update)) {
  445. foreach ($update as $item) {
  446. $uId = $item['id']; unset($item['id']);
  447. Depart::where('id', $uId)->update($item);
  448. }
  449. }
  450. // --- 修正点 2: 核心回填逻辑 ---
  451. $newCodeToIdMap = Depart::where('del_time', 0)
  452. ->where('top_depart_id', $user['top_depart_id'])
  453. ->whereIn('code', $searchCodes)
  454. ->pluck('id', 'code')
  455. ->toArray();
  456. foreach ($parent_code_map as $rowIndex => $pCode) {
  457. // 这里必须通过 $rowIndex 从原始 $array 中精准获取当前行的编码
  458. $currentCode = isset($array[$rowIndex][$codeIdx]) ? trim($array[$rowIndex][$codeIdx]) : '';
  459. $pCode = trim($pCode);
  460. if ($currentCode === '' || $pCode === '') continue;
  461. $currentId = $newCodeToIdMap[$currentCode] ?? null;
  462. $parentId = $newCodeToIdMap[$pCode] ?? null;
  463. if($pCode == $user['top_depart_code']) $parentId = $user['top_depart_id'];
  464. // 严谨判断:只有当前记录存在,且上级记录也存在,且两者不是同一个 ID 时才更新
  465. if ($currentId && $parentId && $currentId != $parentId) {
  466. Depart::where('id', $currentId)->update(['parent_id' => $parentId]);
  467. }
  468. }
  469. DB::commit();
  470. } catch (\Exception $e) {
  471. DB::rollBack();
  472. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  473. }
  474. return [true, ''];
  475. }
  476. private function departCheck(&$array, $user, $table_config)
  477. {
  478. $keys = array_column($table_config, 'key');
  479. $codeIdx = array_search('code', $keys);
  480. $parentIdx = array_search('parent_id', $keys);
  481. // 1. 获取基础数据
  482. list($dbFeeMap, $excelCodesMap) = $this->getDepartList($array, $user, $codeIdx);
  483. $errors = [];
  484. $update = [];
  485. $parent_code_map = [];
  486. // 2. 建立 Excel 内部父子关系映射(用于环路追溯)
  487. $currentExcelMap = [];
  488. foreach ($array as $row) {
  489. $c = trim($row[$codeIdx] ?? '');
  490. $p = trim($row[$parentIdx] ?? '');
  491. if ($c !== '') $currentExcelMap[$c] = $p ?: $user['top_depart_code'] ;
  492. }
  493. // 3. 逐行校验
  494. foreach ($array as $rowIndex => $value) {
  495. $displayLine = $rowIndex + 1;
  496. $valCode = trim($value[$codeIdx] ?? '');
  497. $valParentCode = trim($value[$parentIdx] ?? '');
  498. if ($valCode === '') continue;
  499. // 更新状态记录
  500. if (isset($dbFeeMap[$valCode])) {
  501. $update[$rowIndex] = $dbFeeMap[$valCode]['id'];
  502. }
  503. if ($valParentCode !== '') {
  504. // --- A. 存在性校验 ---
  505. // 这里会检查 006 是否在数据库,或者是否在本次 Excel 的其他行中
  506. if (!isset($dbFeeMap[$valParentCode]) && !isset($excelCodesMap[$valParentCode])) {
  507. $errors[] = "第{$displayLine}行:上级编码[{$valParentCode}]在系统和文件中均不存在";
  508. continue;
  509. }
  510. // --- B. 自引用校验 ---
  511. if ($valCode === $valParentCode) {
  512. $errors[] = "第{$displayLine}行:上级编码不能是自身";
  513. continue;
  514. }
  515. // --- C. 环路追溯 ---
  516. $visited = [];
  517. $res = $this->findDLoopInAncestors($valParentCode, $valCode, $currentExcelMap, $dbFeeMap, $visited);
  518. if ($res !== false) {
  519. if ($res['type'] === 'LOOP_SELF') {
  520. $errors[] = "第{$displayLine}行:编码[{$valCode}]与上级[{$valParentCode}]存在循环引用";
  521. } else {
  522. $errors[] = "第{$displayLine}行:上级[{$valParentCode}]的溯源链条已成环";
  523. }
  524. continue;
  525. }
  526. // 记录有效的父级关系
  527. $parent_code_map[$rowIndex] = $valParentCode;
  528. }else{
  529. $parent_code_map[$rowIndex] = $user['top_depart_code'];
  530. }
  531. }
  532. $error_string = !empty($errors) ? implode('|', $errors) : "";
  533. return [$error_string, $update, $parent_code_map];
  534. }
  535. private function getDepartList($array, $user, $index)
  536. {
  537. // 关键:一定要把 Excel 里所有的 code 这一列全部拿出来,并去除空值
  538. $codesInExcel = [];
  539. foreach ($array as $row) {
  540. $c = trim($row[$index] ?? '');
  541. if ($c !== '') {
  542. $codesInExcel[$c] = true;
  543. }
  544. }
  545. $allFees = Depart::where('del_time', 0)
  546. ->where('top_depart_id', $user['top_depart_id'])
  547. ->select('id', 'code', 'parent_id')
  548. ->get();
  549. $dbFeeMap = [];
  550. foreach ($allFees as $fee) {
  551. $dbFeeMap[$fee->code] = [
  552. 'id' => $fee->id,
  553. 'code' => $fee->code,
  554. 'parent_id' => $fee->parent_id
  555. ];
  556. }
  557. // 返回数据库映射和 Excel 编码映射
  558. return [$dbFeeMap, $codesInExcel];
  559. }
  560. private function findDLoopInAncestors($startParentCode, $targetCode, $excelMap, $dbFeeMap, &$visited)
  561. {
  562. $current = $startParentCode;
  563. while ($current !== '' && $current !== 0) {
  564. if ($current === $targetCode) {
  565. return ['type' => 'LOOP_SELF', 'code' => $current];
  566. }
  567. if (isset($visited[$current])) {
  568. return ['type' => 'EXISTING_LOOP', 'code' => $current];
  569. }
  570. $visited[$current] = true;
  571. if (isset($excelMap[$current]) && $excelMap[$current] !== '') {
  572. $current = $excelMap[$current];
  573. } elseif (isset($dbFeeMap[$current])) {
  574. $parentId = $dbFeeMap[$current]['parent_id'];
  575. $parentCode = '';
  576. foreach ($dbFeeMap as $item) {
  577. if ($item['id'] == $parentId) {
  578. $parentCode = $item['code'];
  579. break;
  580. }
  581. }
  582. $current = $parentCode;
  583. } else {
  584. break;
  585. }
  586. }
  587. return false;
  588. }
  589. // 设备 ------------------------------------
  590. public function deviceImport($array, $user, $other_param){
  591. $upload = $array[0];
  592. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  593. if(!$status) return [false, $msg];
  594. $table_config = $msg;
  595. unset($array[0]);
  596. if(empty($array)) return [false, '导入数据不能为空'];
  597. // 公共校验
  598. list($array, $error) = $this->checkCommon($array, $table_config);
  599. if(!empty($error)) return [0, $error];
  600. // 详细校验 (这里 $array 传引用,内部会转换日期)
  601. list($error, $update_map) = $this->deviceCheck($array, $user, $table_config);
  602. if(!empty($error)) return [0, $error];
  603. $time = time();
  604. $insert = [];
  605. $update = [];
  606. foreach ($array as $key => $value){
  607. $main_tmp = [];
  608. foreach ($value as $k => $val){
  609. if(!empty($table_config[$k]['is_main'])){
  610. $main_tmp[$table_config[$k]['key']] = $val;
  611. }
  612. }
  613. if(isset($update_map[$key])){
  614. // 存入待更新数组
  615. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  616. } else {
  617. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  618. $main_tmp['crt_id'] = $user['id'];
  619. $main_tmp['crt_time'] = $time;
  620. $insert[] = $main_tmp;
  621. }
  622. }
  623. DB::beginTransaction();
  624. try {
  625. // 1. 批量新增
  626. if(!empty($insert)){
  627. foreach(array_chunk($insert, 500) as $chunkInsert){
  628. Device::insert($chunkInsert);
  629. }
  630. }
  631. // 批量更新
  632. foreach (array_chunk($update, 100) as $chunk) {
  633. foreach ($chunk as $item) {
  634. $id = $item['id'];
  635. unset($item['id']);
  636. Device::where('id', $id)->update($item);
  637. }
  638. }
  639. DB::commit();
  640. } catch (\Exception $e) {
  641. DB::rollBack();
  642. return [false, "错误:" . $e->getMessage() . " 行:" . $e->getLine()];
  643. }
  644. return [true, ''];
  645. }
  646. private function deviceCheck(&$array, $user, $table_config)
  647. {
  648. // 动态获取关键列的索引
  649. $codeIdx = array_search('code', array_column($table_config, 'key'));
  650. $dateIdx = array_search('in_time', array_column($table_config, 'key'));
  651. $typeIdx = array_search('type', array_column($table_config, 'key'));
  652. $deviceTypeIdx = array_search('device_type', array_column($table_config, 'key'));
  653. $type2Idx = array_search('is_use', array_column($table_config, 'key'));
  654. $code_map = $this->getDeviceList($array, $user, $codeIdx);
  655. $errors = [];
  656. $update = [];
  657. $map_type = array_flip(Device::$type);
  658. $map_type_2 = array_flip(Device::Use);
  659. $map_type_3 = array_flip(Device::$device_type);
  660. foreach ($array as $rowIndex => $value) {
  661. $displayLine = $rowIndex + 1;
  662. $valCode = $value[$codeIdx] ?? '';
  663. // 记录更新 ID
  664. if(isset($code_map[$valCode])){
  665. $update[$rowIndex] = $code_map[$valCode];
  666. }
  667. if(empty($map_type[$value[$typeIdx]])){
  668. $errors[] = "第{$displayLine}行固定资产类型错误";
  669. }else{
  670. $array[$rowIndex][$typeIdx] = $map_type[$value[$typeIdx]];
  671. }
  672. if(empty($map_type_3[$value[$deviceTypeIdx]])){
  673. $errors[] = "第{$displayLine}行设备标签错误";
  674. }else{
  675. $array[$rowIndex][$typeIdx] = $map_type_3[$value[$deviceTypeIdx]];
  676. }
  677. if(empty($map_type_2[$value[$type2Idx]])){
  678. $errors[] = "第{$displayLine}行是否启用错误";
  679. }else{
  680. $array[$rowIndex][$type2Idx] = $map_type_2[$value[$type2Idx]];
  681. }
  682. // 日期处理
  683. if($dateIdx !== false && !empty($value[$dateIdx])){
  684. list($status, $msg) = $this->convertExcelCellToDate($value[$dateIdx]);
  685. if(!$status) {
  686. $errors[] = "第{$displayLine}行日期格式错误";
  687. } else {
  688. $array[$rowIndex][$dateIdx] = $msg;
  689. }
  690. }
  691. }
  692. $error_string = "";
  693. if(! empty($errors)) $error_string = implode('|', $errors);
  694. return [$error_string, $update];
  695. }
  696. private function getDeviceList($array, $user, $index){
  697. //查找设备
  698. $codes = array_unique(array_filter(array_column($array,$index)));
  699. return Device::where('del_time', 0)
  700. ->where('top_depart_id', $user['top_depart_id'])
  701. ->whereIn('code', $codes)
  702. ->pluck('id','code')
  703. ->toArray();
  704. }
  705. // 项目 -----------------------------------
  706. private function getItemList($array, $user, $index){
  707. //查找设备
  708. $codes = array_unique(array_filter(array_column($array,$index)));
  709. return Item::where('del_time', 0)
  710. ->where('top_depart_id', $user['top_depart_id'])
  711. ->whereIn('code', $codes)
  712. ->pluck('id','code')
  713. ->toArray();
  714. }
  715. public function itemImport($array, $user, $other_param)
  716. {
  717. $upload = $array[0];
  718. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  719. if (!$status) return [false, $msg];
  720. $table_config = $msg;
  721. unset($array[0]);
  722. if (empty($array)) return [false, '导入数据不能为空'];
  723. // 1. 公共校验 (必填、唯一性等)
  724. list($array, $error) = $this->checkCommon($array, $table_config);
  725. if (!empty($error)) return [0, $error];
  726. // 2. 业务详细校验 (包含一致性校验、明细解析)
  727. list($error, $update_map, $detail_data_map) = $this->itemCheck($array, $user, $table_config);
  728. if (!empty($error)) return [0, $error];
  729. $time = time();
  730. $insert_data = [];
  731. $update_data = [];
  732. $all_detail_insert = [];
  733. $update_main_ids = [];
  734. $keys = array_column($table_config, 'key');
  735. $codeIdx = array_search('code', $keys);
  736. // 3. 数据分拣(聚合平铺数据)
  737. foreach ($array as $key => $value) {
  738. $itemCode = trim($value[$codeIdx]);
  739. $main_tmp = [];
  740. foreach ($value as $k => $val) {
  741. if (!empty($table_config[$k]['is_main'])) {
  742. if ($table_config[$k]['key'] == 'employee_title') continue;
  743. $main_tmp[$table_config[$k]['key']] = $val;
  744. }
  745. }
  746. if (isset($update_map[$key])) {
  747. // 更新逻辑:以 ID 为键去重
  748. $itemId = $update_map[$key];
  749. $update_main_ids[$itemId] = $itemId;
  750. $update_data[$itemId] = array_merge($main_tmp, ['id' => $itemId]);
  751. if (isset($detail_data_map[$key])) {
  752. foreach ($detail_data_map[$key] as $d) {
  753. $all_detail_insert[] = array_merge($d, [
  754. 'item_id' => $itemId,
  755. 'crt_time' => $time,
  756. 'top_depart_id' => $user['top_depart_id']
  757. ]);
  758. }
  759. }
  760. } else {
  761. // 新增逻辑:以项目编码为键去重
  762. if (!isset($insert_data[$itemCode])) {
  763. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  764. $main_tmp['crt_id'] = $user['id'];
  765. $main_tmp['crt_time'] = $time;
  766. $insert_data[$itemCode] = $main_tmp;
  767. }
  768. if (isset($detail_data_map[$key])) {
  769. foreach ($detail_data_map[$key] as $d) {
  770. $all_detail_insert[] = array_merge($d, [
  771. '_code' => $itemCode,
  772. 'crt_time' => $time,
  773. 'top_depart_id' => $user['top_depart_id']
  774. ]);
  775. }
  776. }
  777. }
  778. }
  779. DB::beginTransaction();
  780. try {
  781. // 4. 执行新增主表
  782. $new_item_maps = [];
  783. if (!empty($insert_data)) {
  784. foreach (array_chunk(array_values($insert_data), 500) as $chunk) {
  785. Item::insert($chunk);
  786. }
  787. $new_item_maps = Item::whereIn('code', array_keys($insert_data))
  788. ->where('del_time', 0)
  789. ->where('top_depart_id', $user['top_depart_id'])
  790. ->pluck('id', 'code')->toArray();
  791. }
  792. // 5. 执行更新主表
  793. if (!empty($update_data)) {
  794. foreach ($update_data as $id => $uItem) {
  795. unset($uItem['id']);
  796. Item::where('id', $id)->update($uItem);
  797. }
  798. }
  799. // 6. 处理明细表 (先全删后插)
  800. if (!empty($update_main_ids)) {
  801. ItemDetails::whereIn('item_id', array_values($update_main_ids))
  802. ->where('del_time', 0)
  803. ->update(['del_time' => $time]);
  804. }
  805. foreach ($all_detail_insert as &$di) {
  806. if (isset($di['_code'])) {
  807. $di['item_id'] = $new_item_maps[$di['_code']] ?? 0;
  808. unset($di['_code']);
  809. }
  810. }
  811. unset($di);
  812. if (!empty($all_detail_insert)) {
  813. foreach (array_chunk($all_detail_insert, 500) as $chunk) {
  814. ItemDetails::insert($chunk);
  815. }
  816. }
  817. DB::commit();
  818. } catch (\Exception $e) {
  819. DB::rollBack();
  820. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  821. }
  822. return [true, ''];
  823. }
  824. private function itemCheck(&$array, $user, $table_config)
  825. {
  826. $keys = array_column($table_config, 'key');
  827. $codeIdx = array_search('code', $keys);
  828. $stateIdx = array_search('state', $keys);
  829. $attrIdx = array_search('item_attribute', $keys);
  830. $budgetIdx = array_search('budget', $keys);
  831. $typeIdx = array_search('type', $keys); // 明细类型列
  832. $code2Idx = array_search('code_2', $keys); // 资产/工号列
  833. $dateIdx = array_search('start_time', $keys);
  834. $date2Idx = array_search('end_time', $keys);
  835. $empIdx = array_search('charge_id', $keys);
  836. $allEmpNumbers = array_filter(array_unique(array_column($array, $empIdx)));
  837. $dbEmps = Employee::where('del_time', 0)
  838. ->whereIn('number', $allEmpNumbers)
  839. ->where('top_depart_id', $user['top_depart_id'])
  840. ->pluck('id', 'number')->toArray();
  841. $code_map = $this->getItemList($array, $user, $codeIdx);
  842. // 这里的 getDataList 需要适配平铺后的 code_2 列
  843. list($man_map, $device_map) = $this->getFlatDataList($array, $user, $typeIdx, $code2Idx);
  844. $errors = [];
  845. $update_mapping = [];
  846. $detail_storage = [];
  847. $mainDataConsistency = []; // 一致性校验
  848. $state_type_map = array_flip(Item::State_Type);
  849. $attr_map = array_flip(Item::Item_Attribute);
  850. $detail_type_map = array_flip(ItemDetails::$type_name);
  851. // 识别主表字段列索引
  852. $mainColIndices = [];
  853. foreach ($table_config as $index => $conf) {
  854. if (!empty($conf['is_main'])) $mainColIndices[$index] = $conf['value'];
  855. }
  856. foreach ($array as $rowIndex => $rowValue) {
  857. $displayLine = $rowIndex + 1;
  858. $valCode = trim($rowValue[$codeIdx] ?? '');
  859. $valEmp = trim($rowValue[$empIdx] ?? '');
  860. if ($valCode === '') continue;
  861. // --- A. 主表一致性校验 ---
  862. if (!isset($mainDataConsistency[$valCode])) {
  863. $mainDataConsistency[$valCode] = array_intersect_key($rowValue, $mainColIndices);
  864. } else {
  865. foreach ($mainColIndices as $idx => $label) {
  866. if (trim($rowValue[$idx] ?? '') != trim($mainDataConsistency[$valCode][$idx] ?? '')) {
  867. $errors[] = "第{$displayLine}行:项目[{$valCode}]的主表信息[{$label}]与前文不一致";
  868. }
  869. }
  870. }
  871. // --- B. 基础校验 ---
  872. if (isset($code_map[$valCode])) {
  873. $update_mapping[$rowIndex] = $code_map[$valCode];
  874. }
  875. // 状态
  876. $state_text = $rowValue[$stateIdx] ?? '';
  877. if (!isset($state_type_map[$state_text])) {
  878. $errors[] = "第{$displayLine}行:状态[{$state_text}]无效";
  879. } else {
  880. $array[$rowIndex][$stateIdx] = $state_type_map[$state_text];
  881. }
  882. $attr_text = $rowValue[$attrIdx] ?? '';
  883. if (!isset($attr_map[$attr_text])) {
  884. $errors[] = "第{$displayLine}行:项目属性[{$attr_text}]无效";
  885. } else {
  886. $array[$rowIndex][$attrIdx] = $attr_map[$attr_text];
  887. }
  888. $budget_text = $rowValue[$budgetIdx] ?? 0;
  889. if(! empty($budget_text)){
  890. $res = $this->checkNumber($budget_text, 2, 'non-negative');
  891. if (!$res['valid']) $errors[] = "第{$displayLine}行预算:" . $res['error'];
  892. }
  893. // D. 人员校验
  894. if(! empty($valEmp)){
  895. if (!isset($dbEmps[$valEmp])) {
  896. $errors[] = "第{$displayLine}行:人员工号[{$valEmp}]不存在";
  897. } else {
  898. $array[$rowIndex][$empIdx] = $dbEmps[$valEmp];
  899. }
  900. }
  901. // 日期转换
  902. foreach ([$dateIdx, $date2Idx] as $dIdx) {
  903. if ($dIdx !== false && !empty($rowValue[$dIdx])) {
  904. list($s, $m) = $this->convertExcelCellToDate($rowValue[$dIdx]);
  905. if (!$s) $errors[] = "第{$displayLine}行:日期格式非法";
  906. else $array[$rowIndex][$dIdx] = $m;
  907. }
  908. }
  909. // --- C. 解析明细 (一行一个明细) ---
  910. $typeName = trim($rowValue[$typeIdx] ?? '');
  911. $subCode = trim($rowValue[$code2Idx] ?? '');
  912. if ($typeName !== '' && $subCode !== '') {
  913. $typeVal = $detail_type_map[$typeName] ?? 0;
  914. if (!$typeVal) {
  915. $errors[] = "第{$displayLine}行:明细类型[{$typeName}]无效";
  916. } else {
  917. if ($typeVal == ItemDetails::type_one) {
  918. if (!isset($man_map[$subCode])) {
  919. $errors[] = "第{$displayLine}行:人员工号[{$subCode}]不存在";
  920. } else {
  921. $detail_storage[$rowIndex][] = ['type' => $typeVal, 'data_id' => $man_map[$subCode]];
  922. }
  923. } else {
  924. if (!isset($device_map[$subCode])) {
  925. $errors[] = "第{$displayLine}行:设备编码[{$subCode}]不存在";
  926. } else {
  927. $detail_storage[$rowIndex][] = ['type' => $typeVal, 'data_id' => $device_map[$subCode]];
  928. }
  929. }
  930. }
  931. }
  932. }
  933. $error_str = !empty($errors) ? implode('|', $errors) : "";
  934. return [$error_str, $update_mapping, $detail_storage];
  935. }
  936. private function getFlatDataList($array, $user, $typeIdx, $code2Idx)
  937. {
  938. $manNums = [];
  939. $devCodes = [];
  940. $detail_type_map = array_flip(ItemDetails::$type_name);
  941. foreach ($array as $row) {
  942. $typeName = trim($row[$typeIdx] ?? '');
  943. $val = trim($row[$code2Idx] ?? '');
  944. if ($val === '') continue;
  945. $typeVal = $detail_type_map[$typeName] ?? 0;
  946. if ($typeVal == ItemDetails::type_one) {
  947. $manNums[$val] = true;
  948. } elseif ($typeVal == ItemDetails::type_two) {
  949. $devCodes[$val] = true;
  950. }
  951. }
  952. $manMap = Employee::where('del_time', 0)
  953. ->where('top_depart_id', $user['top_depart_id'])
  954. ->whereIn('number', array_keys($manNums))
  955. ->pluck('id', 'number')->toArray();
  956. $devMap = Device::where('del_time', 0)
  957. ->where('top_depart_id', $user['top_depart_id'])
  958. ->whereIn('code', array_keys($devCodes))
  959. ->pluck('id', 'code')->toArray();
  960. return [$manMap, $devMap];
  961. }
  962. // 费用 ----------------------------------
  963. public function feeImport($array, $user, $other_param)
  964. {
  965. $upload = $array[0];
  966. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  967. if (!$status) return [false, $msg];
  968. $table_config = $msg;
  969. unset($array[0]);
  970. if (empty($array)) return [false, '导入数据不能为空'];
  971. list($array, $error) = $this->checkCommon($array, $table_config);
  972. if (!empty($error)) return [0, $error];
  973. // 2. 详细校验
  974. list($error, $update_map, $parent_code_map) = $this->feeCheck($array, $user, $table_config);
  975. if (!empty($error)) return [0, $error];
  976. $time = time();
  977. $insert = [];
  978. $update = [];
  979. $all_codes = [];
  980. // --- 修正点 1: 必须确保索引提取准确 ---
  981. $keys = array_column($table_config, 'key');
  982. $codeIdx = array_search('code', $keys);
  983. // ------------------------------------
  984. $ignoreKeys = ['parent_id', 'parent_title'];
  985. foreach ($array as $key => $value) {
  986. $cCode = trim($value[$codeIdx] ?? '');
  987. if($cCode === '') continue;
  988. $all_codes[] = $cCode;
  989. $main_tmp = [];
  990. foreach ($value as $k => $val){
  991. if(!empty($table_config[$k]['is_main'])){
  992. if (!in_array($table_config[$k]['key'], $ignoreKeys)) {
  993. $main_tmp[$table_config[$k]['key']] = $val;
  994. }
  995. }
  996. }
  997. if (isset($update_map[$key])) {
  998. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  999. } else {
  1000. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  1001. $main_tmp['crt_time'] = $time;
  1002. $main_tmp['parent_id'] = 0;
  1003. $insert[] = $main_tmp;
  1004. }
  1005. }
  1006. $all_parent_codes = array_values($parent_code_map);
  1007. $searchCodes = array_unique(array_merge($all_codes, $all_parent_codes));
  1008. DB::beginTransaction();
  1009. try {
  1010. if (!empty($insert)) {
  1011. foreach (array_chunk($insert, 500) as $chunk) {
  1012. Fee::insert($chunk);
  1013. }
  1014. }
  1015. if (!empty($update)) {
  1016. foreach ($update as $item) {
  1017. $uId = $item['id']; unset($item['id']);
  1018. Fee::where('id', $uId)->update($item);
  1019. }
  1020. }
  1021. // --- 修正点 2: 核心回填逻辑 ---
  1022. $newCodeToIdMap = Fee::where('del_time', 0)
  1023. ->where('top_depart_id', $user['top_depart_id'])
  1024. ->whereIn('code', $searchCodes)
  1025. ->pluck('id', 'code')
  1026. ->toArray();
  1027. foreach ($parent_code_map as $rowIndex => $pCode) {
  1028. // 这里必须通过 $rowIndex 从原始 $array 中精准获取当前行的编码
  1029. $currentCode = isset($array[$rowIndex][$codeIdx]) ? trim($array[$rowIndex][$codeIdx]) : '';
  1030. $pCode = trim($pCode);
  1031. if ($currentCode === '' || $pCode === '') continue;
  1032. $currentId = $newCodeToIdMap[$currentCode] ?? null;
  1033. $parentId = $newCodeToIdMap[$pCode] ?? null;
  1034. // 严谨判断:只有当前记录存在,且上级记录也存在,且两者不是同一个 ID 时才更新
  1035. if ($currentId && $parentId && $currentId != $parentId) {
  1036. Fee::where('id', $currentId)->update(['parent_id' => $parentId]);
  1037. }
  1038. }
  1039. // ================== 【新增需求:导入时的子集联动更新】 ==================
  1040. // 1. 重新去数据库捞一下本次导入/更新涉及到的所有【顶级父节点】
  1041. $topParents = Fee::where('del_time', 0)
  1042. ->where('top_depart_id', $user['top_depart_id'])
  1043. ->whereIn('code', $all_codes)
  1044. ->where('parent_id', 0) // 只找顶级
  1045. ->select('id', 'is_other', 'is_direct')
  1046. ->get();
  1047. // 2. 统一对这些顶级节点的子集进行刷洗
  1048. $service = new FeeService();
  1049. foreach ($topParents as $parent) {
  1050. $service->syncChildrenAttributes($parent->id, $parent->is_other, $parent->is_direct);
  1051. }
  1052. DB::commit();
  1053. } catch (\Exception $e) {
  1054. DB::rollBack();
  1055. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1056. }
  1057. return [true, ''];
  1058. }
  1059. private function feeCheck(&$array, $user, $table_config)
  1060. {
  1061. $keys = array_column($table_config, 'key');
  1062. $codeIdx = array_search('code', $keys);
  1063. $parentIdx = array_search('parent_id', $keys);
  1064. $isOtherIdx = array_search('is_other', $keys);
  1065. $isDirectIdx = array_search('is_direct', $keys);
  1066. $sortIdx = array_search('sort', $keys);
  1067. // 1. 获取基础数据
  1068. list($dbFeeMap, $excelCodesMap) = $this->getFeeList($array, $user, $codeIdx);
  1069. $errors = [];
  1070. $update = [];
  1071. $parent_code_map = [];
  1072. $is_other_map = array_flip(Fee::IS_OTHER);
  1073. $is_direct_map = array_flip(Fee::IS_DIRECT);
  1074. // 2. 建立 Excel 内部父子关系映射(用于环路追溯)
  1075. $currentExcelMap = [];
  1076. foreach ($array as $row) {
  1077. $c = trim($row[$codeIdx] ?? '');
  1078. $p = trim($row[$parentIdx] ?? '');
  1079. if ($c !== '') $currentExcelMap[$c] = $p;
  1080. }
  1081. // 3. 逐行校验
  1082. foreach ($array as $rowIndex => $value) {
  1083. $displayLine = $rowIndex + 1;
  1084. $valCode = trim($value[$codeIdx] ?? '');
  1085. $valParentCode = trim($value[$parentIdx] ?? '');
  1086. if ($valCode === '') continue;
  1087. // 更新状态记录
  1088. if (isset($dbFeeMap[$valCode])) {
  1089. $update[$rowIndex] = $dbFeeMap[$valCode]['id'];
  1090. }
  1091. // 其他费用
  1092. $is_other_text = $value[$isOtherIdx] ?? '';
  1093. if (!isset($is_other_map[$is_other_text])) {
  1094. $errors[] = "第{$displayLine}行:是否其他费用[{$is_other_text}]无效";
  1095. } else {
  1096. $array[$rowIndex][$isOtherIdx] = $is_other_map[$is_other_text];
  1097. }
  1098. $is_direct_text = $value[$isDirectIdx] ?? '';
  1099. if (!isset($is_direct_map[$is_direct_text])) {
  1100. $errors[] = "第{$displayLine}行:是否直接投入费用[{$is_direct_text}]无效";
  1101. } else {
  1102. $array[$rowIndex][$isDirectIdx] = $is_direct_map[$is_direct_text];
  1103. }
  1104. if($is_other_text && $is_direct_text) $errors[] = "第{$displayLine}行:是否其他费用与是否直接投入费用不能同时开启";
  1105. $sort_v = trim($value[$sortIdx] ?? 0);
  1106. if(! is_numeric($sort_v)) $errors[] = "第{$displayLine}行:排序请填写数字";
  1107. if ($valParentCode !== '') {
  1108. // --- A. 存在性校验 ---
  1109. // 这里会检查 006 是否在数据库,或者是否在本次 Excel 的其他行中
  1110. if (!isset($dbFeeMap[$valParentCode]) && !isset($excelCodesMap[$valParentCode])) {
  1111. $errors[] = "第{$displayLine}行:上级编码[{$valParentCode}]在系统和文件中均不存在";
  1112. continue;
  1113. }
  1114. // --- B. 自引用校验 ---
  1115. if ($valCode === $valParentCode) {
  1116. $errors[] = "第{$displayLine}行:上级编码不能是自身";
  1117. continue;
  1118. }
  1119. // --- C. 环路追溯 ---
  1120. $visited = [];
  1121. $res = $this->findLoopInAncestors($valParentCode, $valCode, $currentExcelMap, $dbFeeMap, $visited);
  1122. if ($res !== false) {
  1123. if ($res['type'] === 'LOOP_SELF') {
  1124. $errors[] = "第{$displayLine}行:编码[{$valCode}]与上级[{$valParentCode}]存在循环引用";
  1125. } else {
  1126. $errors[] = "第{$displayLine}行:上级[{$valParentCode}]的溯源链条已成环";
  1127. }
  1128. continue;
  1129. }
  1130. // 记录有效的父级关系
  1131. $parent_code_map[$rowIndex] = $valParentCode;
  1132. }
  1133. }
  1134. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1135. return [$error_string, $update, $parent_code_map];
  1136. }
  1137. private function getFeeList($array, $user, $index)
  1138. {
  1139. // 关键:一定要把 Excel 里所有的 code 这一列全部拿出来,并去除空值
  1140. $codesInExcel = [];
  1141. foreach ($array as $row) {
  1142. $c = trim($row[$index] ?? '');
  1143. if ($c !== '') {
  1144. $codesInExcel[$c] = true;
  1145. }
  1146. }
  1147. $allFees = Fee::where('del_time', 0)
  1148. ->where('top_depart_id', $user['top_depart_id'])
  1149. ->select('id', 'code', 'parent_id')
  1150. ->get();
  1151. $dbFeeMap = [];
  1152. foreach ($allFees as $fee) {
  1153. $dbFeeMap[$fee->code] = [
  1154. 'id' => $fee->id,
  1155. 'code' => $fee->code,
  1156. 'parent_id' => $fee->parent_id
  1157. ];
  1158. }
  1159. // 返回数据库映射和 Excel 编码映射
  1160. return [$dbFeeMap, $codesInExcel];
  1161. }
  1162. private function findLoopInAncestors($startParentCode, $targetCode, $excelMap, $dbFeeMap, &$visited)
  1163. {
  1164. $current = $startParentCode;
  1165. while ($current !== '' && $current !== 0) {
  1166. if ($current === $targetCode) {
  1167. return ['type' => 'LOOP_SELF', 'code' => $current];
  1168. }
  1169. if (isset($visited[$current])) {
  1170. return ['type' => 'EXISTING_LOOP', 'code' => $current];
  1171. }
  1172. $visited[$current] = true;
  1173. if (isset($excelMap[$current]) && $excelMap[$current] !== '') {
  1174. $current = $excelMap[$current];
  1175. } elseif (isset($dbFeeMap[$current])) {
  1176. $parentId = $dbFeeMap[$current]['parent_id'];
  1177. $parentCode = '';
  1178. foreach ($dbFeeMap as $item) {
  1179. if ($item['id'] == $parentId) {
  1180. $parentCode = $item['code'];
  1181. break;
  1182. }
  1183. }
  1184. $current = $parentCode;
  1185. } else {
  1186. break;
  1187. }
  1188. }
  1189. return false;
  1190. }
  1191. // 人员月度工时单 ------------------------------
  1192. public function monthPwOrderImport($array, $user, $other_param)
  1193. {
  1194. $upload = $array[0];
  1195. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1196. if (!$status) return [false, $msg];
  1197. $table_config = $msg;
  1198. unset($array[0]);
  1199. if (empty($array)) return [false, '导入数据不能为空'];
  1200. list($array, $error) = $this->checkCommon($array, $table_config);
  1201. if (!empty($error)) return [0, $error];
  1202. // 2. 详细校验 (这里会返回 update_map 和 dbEmps 映射)
  1203. list($error, $update_map, $dbEmps) = $this->monthPwOrderCheck($array, $user, $table_config);
  1204. if (!empty($error)) return [0, $error];
  1205. $keys = array_column($table_config, 'key');
  1206. $codeIdx = array_search('code', $keys);
  1207. $monthIdx = array_search('month', $keys);
  1208. $empIdx = array_search('employee_id', $keys);
  1209. // --- 步骤 1: 数据聚合分组 ---
  1210. // 将 Excel 数据按“单据”维度归类
  1211. $groups = [];
  1212. foreach ($array as $rowIndex => $row) {
  1213. $cCode = trim($row[$codeIdx] ?? '');
  1214. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1215. // 聚合 Key:有编码用编码,没编码用月份标记
  1216. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1217. if (!isset($groups[$aggKey])) {
  1218. $groups[$aggKey] = [
  1219. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1220. 'code' => $cCode,
  1221. 'month' => $cMonthTs,
  1222. 'details' => []
  1223. ];
  1224. }
  1225. // 准备详情行数据
  1226. $detailTmp = [];
  1227. foreach ($table_config as $k => $conf) {
  1228. if (!$conf['is_main']) {
  1229. $fieldKey = $conf['key'];
  1230. if ($fieldKey == 'employee_title') continue;
  1231. $fieldVal = $row[$k];
  1232. // 如果是人员,转换为 ID
  1233. if ($fieldKey == 'employee_id') {
  1234. $fieldVal = $dbEmps[$fieldVal] ?? 0;
  1235. }
  1236. $detailTmp[$fieldKey] = $fieldVal;
  1237. }
  1238. }
  1239. $groups[$aggKey]['details'][] = $detailTmp;
  1240. }
  1241. // --- 步骤 2: 开启事务写入 ---
  1242. DB::beginTransaction();
  1243. try {
  1244. $time = time();
  1245. foreach ($groups as $aggKey => $group) {
  1246. $mainId = $group['main_id'];
  1247. if ($mainId > 0) {
  1248. // 删除旧详情
  1249. DB::table('monthly_pw_order_details')->where('del_time',0)
  1250. ->where('main_id', $mainId)
  1251. ->update(['del_time' => $time]);
  1252. } else {
  1253. // B. 新增逻辑
  1254. $newCode = $this->generateBillNo([
  1255. 'top_depart_id' => $user['top_depart_id'],
  1256. 'type' => MonthlyPwOrder::Order_type,
  1257. 'period' => date("Ym", $group['month'])
  1258. ]);
  1259. $mainId = DB::table('monthly_pw_order')->insertGetId([
  1260. 'code' => $newCode,
  1261. 'month' => $group['month'],
  1262. 'top_depart_id' => $user['top_depart_id'],
  1263. 'crt_id' => $user['id'],
  1264. 'crt_time' => $time,
  1265. 'upd_time' => $time,
  1266. 'del_time' => 0
  1267. ]);
  1268. }
  1269. // C. 批量插入详情
  1270. $insertDetails = [];
  1271. foreach ($group['details'] as $detail) {
  1272. $detail['main_id'] = $mainId;
  1273. $detail['top_depart_id']= $user['top_depart_id'];
  1274. $detail['crt_time'] = $time;
  1275. $detail['del_time'] = 0;
  1276. $insertDetails[] = $detail;
  1277. }
  1278. if (!empty($insertDetails)) {
  1279. DB::table('monthly_pw_order_details')->insert($insertDetails);
  1280. }
  1281. }
  1282. DB::commit();
  1283. } catch (\Exception $e) {
  1284. DB::rollBack();
  1285. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1286. }
  1287. return [true, ''];
  1288. }
  1289. private function monthPwOrderCheck(&$array, $user, $table_config)
  1290. {
  1291. $keys = array_column($table_config, 'key');
  1292. $codeIdx = array_search('code', $keys);
  1293. $monthIdx = array_search('month', $keys);
  1294. $empIdx = array_search('employee_id', $keys);
  1295. $numIdx = array_search('total_days', $keys);
  1296. $num2Idx = array_search('rd_total_days', $keys);
  1297. $num3Idx = array_search('total_hours', $keys);
  1298. $num4Idx = array_search('rd_total_hours', $keys);
  1299. $topDepartId = $user['top_depart_id'];
  1300. $errors = [];
  1301. // --- 1. 预处理月份与工号 ---
  1302. $allEmpNumbers = [];
  1303. $allMonthsTs = [];
  1304. foreach ($array as $rowIndex => $row) {
  1305. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1306. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1307. if (!$mStatus) {
  1308. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误";
  1309. continue;
  1310. }
  1311. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1312. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1313. $allMonthsTs[] = $valMonthTs;
  1314. if (!empty($row[$empIdx])) $allEmpNumbers[] = trim($row[$empIdx]);
  1315. }
  1316. if (!empty($errors)) return [implode('|', $errors), [], []];
  1317. $allMonthsTs = array_unique($allMonthsTs);
  1318. $allEmpNumbers = array_unique($allEmpNumbers);
  1319. //归档
  1320. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1321. if(! $status) return [$msg, [], []];
  1322. // --- 2. 批量预加载 ---
  1323. // A. 人员档案
  1324. $empModels = Employee::where('del_time', 0)->whereIn('number', $allEmpNumbers)
  1325. ->where('top_depart_id', $topDepartId)->get(['id', 'number', 'title'])->keyBy('number');
  1326. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  1327. // B. 系统考勤基准 (按月获取)
  1328. $systemStatsMap = [];
  1329. $service = new EmployeeService();
  1330. foreach ($allMonthsTs as $ts) {
  1331. list($sStatus, $stats) = $service->getEmployeesMonthStats(array_values($dbEmps), $ts, $user);
  1332. if (!$sStatus) {
  1333. $errors[] = "月份[" . date('Y-m', $ts) . "]:" . $stats;
  1334. continue;
  1335. }
  1336. $systemStatsMap[$ts] = $stats;
  1337. }
  1338. if (!empty($errors)) return [implode('|', $errors), [], []];
  1339. // C. 核心修正:单据查重(建立 月份 -> 单号 的映射,避免循环内查询)
  1340. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1341. // 1) 所有的 Excel 涉及月份在数据库中已有的单据映射
  1342. $existingMonthsMap = DB::table('monthly_pw_order')
  1343. ->where('top_depart_id', $topDepartId)
  1344. ->where('del_time', 0)
  1345. ->whereIn('month', $allMonthsTs)
  1346. ->pluck('code', 'month') // 注意:这里直接查出 month => code
  1347. ->toArray();
  1348. // 2) 用户填写的单据号对应的数据库记录
  1349. $dbOrdersByCode = DB::table('monthly_pw_order')
  1350. ->whereIn('code', $allCodes)
  1351. ->where('top_depart_id', $topDepartId)
  1352. ->where('del_time', 0)
  1353. ->get()
  1354. ->keyBy('code');
  1355. // --- 3. 业务逻辑全量检查 ---
  1356. $excelAggregator = [];
  1357. $update_map = [];
  1358. foreach ($array as $rowIndex => $row) {
  1359. $line = $rowIndex + 1;
  1360. $valCode = trim($row[$codeIdx] ?? '');
  1361. $valMonthTs = $row[$monthIdx];
  1362. $valEmpNum = trim($row[$empIdx] ?? '');
  1363. $monthStr = date('Y-m', $valMonthTs);
  1364. if (!isset($empModels[$valEmpNum])) {
  1365. $errors[] = "第{$line}行:工号[{$valEmpNum}]不存在";
  1366. continue;
  1367. }
  1368. $empId = $empModels[$valEmpNum]->id;
  1369. $empTitle = "[{$valEmpNum}]" . $empModels[$valEmpNum]->title;
  1370. // --- 核心修正:单据单号提示逻辑 ---
  1371. if ($valCode !== '') {
  1372. if (isset($dbOrdersByCode[$valCode])) {
  1373. if ($dbOrdersByCode[$valCode]->month != $valMonthTs) {
  1374. $errors[] = "第{$line}行:单据[{$valCode}]月份应为" . date('Y-m', $dbOrdersByCode[$valCode]->month) . ",请核实";
  1375. }
  1376. $update_map[$rowIndex] = $dbOrdersByCode[$valCode]->id;
  1377. } else {
  1378. $errors[] = "第{$line}行:填写的单据编号[{$valCode}]在系统中不存在";
  1379. }
  1380. } else {
  1381. // 如果没填单号,但该月已存在单据,从预加载的 existingMonthsMap 中获取正确单号
  1382. if (isset($existingMonthsMap[$valMonthTs])) {
  1383. $correctCode = $existingMonthsMap[$valMonthTs];
  1384. $errors[] = "第{$line}行:月份[{$monthStr}]已存在研发单,单号为:[{$correctCode}],请填写该单号进行编辑";
  1385. }
  1386. }
  1387. // --- 考勤上限校验 ---
  1388. $sysEmpData = $systemStatsMap[$valMonthTs][$empId] ?? null;
  1389. if ($sysEmpData) {
  1390. $inTotalDays = (float)($row[$numIdx] ?? 0);
  1391. $inRdDays = (float)($row[$num2Idx] ?? 0);
  1392. $inTotalHours= (float)($row[$num3Idx] ?? 0);
  1393. $inRdHours = (float)($row[$num4Idx] ?? 0);
  1394. // 使用误差范围比较,避免浮点数精度问题
  1395. if (abs($inTotalDays - $sysEmpData['attendance_days']) > 0.01) {
  1396. $errors[] = "第{$line}行:{$empTitle}出勤总天数({$inTotalDays})与核算({$sysEmpData['attendance_days']})不符";
  1397. }
  1398. if (abs($inTotalHours - $sysEmpData['final_work_hour']) > 0.01) {
  1399. $errors[] = "第{$line}行:{$empTitle}出勤总工时({$inTotalHours})与核算({$sysEmpData['final_work_hour']})不符";
  1400. }
  1401. if ($inRdDays > $inTotalDays + 0.01) $errors[] = "第{$line}行:{$empTitle}研发天数超过总天数";
  1402. if ($inRdHours > $inTotalHours + 0.01) $errors[] = "第{$line}行:{$empTitle}研发工时超过总工时";
  1403. }
  1404. if (isset($excelAggregator[$valCode ?: $valMonthTs]['emps'][$valEmpNum])) {
  1405. $errors[] = "第{$line}行:人员在同单据内重复";
  1406. }
  1407. $excelAggregator[$valCode ?: $valMonthTs]['emps'][$valEmpNum] = true;
  1408. }
  1409. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $dbEmps];
  1410. }
  1411. // 设备月度工时单
  1412. public function monthDwOrderImport($array, $user, $other_param)
  1413. {
  1414. $upload = $array[0];
  1415. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1416. if (!$status) return [false, $msg];
  1417. $table_config = $msg;
  1418. unset($array[0]);
  1419. if (empty($array)) return [false, '导入数据不能为空'];
  1420. list($array, $error) = $this->checkCommon($array, $table_config);
  1421. if (!empty($error)) return [0, $error];
  1422. // 2. 详细校验 (这里会返回 update_map 和 dbDevs 映射)
  1423. list($error, $update_map, $dbDevs) = $this->monthDwOrderCheck($array, $user, $table_config);
  1424. if (!empty($error)) return [0, $error];
  1425. $keys = array_column($table_config, 'key');
  1426. $codeIdx = array_search('code', $keys);
  1427. $monthIdx = array_search('month', $keys);
  1428. $empIdx = array_search('device_id', $keys);
  1429. // --- 步骤 1: 数据聚合分组 ---
  1430. // 将 Excel 数据按“单据”维度归类
  1431. $groups = [];
  1432. foreach ($array as $rowIndex => $row) {
  1433. $cCode = trim($row[$codeIdx] ?? '');
  1434. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1435. // 聚合 Key:有编码用编码,没编码用月份标记
  1436. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1437. if (!isset($groups[$aggKey])) {
  1438. $groups[$aggKey] = [
  1439. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1440. 'code' => $cCode,
  1441. 'month' => $cMonthTs,
  1442. 'details' => []
  1443. ];
  1444. }
  1445. // 准备详情行数据
  1446. $detailTmp = [];
  1447. foreach ($table_config as $k => $conf) {
  1448. if (!$conf['is_main']) {
  1449. $fieldKey = $conf['key'];
  1450. if ($fieldKey == 'device_title') continue;
  1451. $fieldVal = $row[$k];
  1452. // 如果是人员,转换为 ID
  1453. if ($fieldKey == 'device_id') {
  1454. $fieldVal = $dbDevs[$fieldVal] ?? 0;
  1455. }
  1456. $detailTmp[$fieldKey] = $fieldVal;
  1457. }
  1458. }
  1459. $groups[$aggKey]['details'][] = $detailTmp;
  1460. }
  1461. // --- 步骤 2: 开启事务写入 ---
  1462. DB::beginTransaction();
  1463. try {
  1464. $time = time();
  1465. foreach ($groups as $aggKey => $group) {
  1466. $mainId = $group['main_id'];
  1467. if ($mainId > 0) {
  1468. // 删除旧详情
  1469. DB::table('monthly_dw_order_details')->where('del_time',0)
  1470. ->where('main_id', $mainId)
  1471. ->update(['del_time' => $time]);
  1472. } else {
  1473. // B. 新增逻辑
  1474. $newCode = $this->generateBillNo([
  1475. 'top_depart_id' => $user['top_depart_id'],
  1476. 'type' => MonthlyPwOrder::Order_type,
  1477. 'period' => date("Ym", $group['month'])
  1478. ]);
  1479. $mainId = DB::table('monthly_dw_order')->insertGetId([
  1480. 'code' => $newCode,
  1481. 'month' => $group['month'],
  1482. 'top_depart_id' => $user['top_depart_id'],
  1483. 'crt_id' => $user['id'],
  1484. 'crt_time' => $time,
  1485. 'upd_time' => $time,
  1486. 'del_time' => 0
  1487. ]);
  1488. }
  1489. // C. 批量插入详情
  1490. $insertDetails = [];
  1491. foreach ($group['details'] as $detail) {
  1492. $detail['main_id'] = $mainId;
  1493. $detail['top_depart_id']= $user['top_depart_id'];
  1494. $detail['crt_time'] = $time;
  1495. $detail['del_time'] = 0;
  1496. $insertDetails[] = $detail;
  1497. }
  1498. if (!empty($insertDetails)) {
  1499. DB::table('monthly_dw_order_details')->insert($insertDetails);
  1500. }
  1501. }
  1502. DB::commit();
  1503. } catch (\Exception $e) {
  1504. DB::rollBack();
  1505. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1506. }
  1507. return [true, ''];
  1508. }
  1509. private function monthDwOrderCheck(&$array, $user, $table_config)
  1510. {
  1511. $keys = array_column($table_config, 'key');
  1512. $codeIdx = array_search('code', $keys);
  1513. $monthIdx = array_search('month', $keys);
  1514. $devIdx = array_search('device_id', $keys);
  1515. $numIdx = array_search('total_days', $keys);
  1516. $num2Idx = array_search('rd_total_days', $keys);
  1517. $num3Idx = array_search('total_hours', $keys);
  1518. $num4Idx = array_search('rd_total_hours', $keys);
  1519. $topDepartId = $user['top_depart_id'];
  1520. $errors = [];
  1521. // --- 1. 提取月份和资产编码 ---
  1522. $allDevCodes = [];
  1523. $allMonthsTs = [];
  1524. foreach ($array as $rowIndex => $row) {
  1525. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($row[$monthIdx] ?? '');
  1526. if (!$mStatus) {
  1527. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误";
  1528. continue;
  1529. }
  1530. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1531. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1532. $allMonthsTs[] = $valMonthTs;
  1533. if (!empty($row[$devIdx])) $allDevCodes[] = trim($row[$devIdx]);
  1534. }
  1535. if (!empty($errors)) return [implode('|', $errors), [], []];
  1536. $allMonthsTs = array_unique($allMonthsTs);
  1537. //归档
  1538. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1539. if(! $status) return [$msg, [], []];
  1540. // --- 2. 预加载档案与基准 ---
  1541. $devModels = Device::where('del_time', 0)
  1542. ->whereIn('code', $allDevCodes)
  1543. ->where('top_depart_id', $topDepartId)
  1544. ->get(['id', 'code', 'title'])
  1545. ->keyBy('code');
  1546. $dbDevs = $devModels->pluck('id', 'code')->toArray();
  1547. $systemStatsMap = [];
  1548. $allDeviceIds = array_values($dbDevs);
  1549. $service = new DeviceService();
  1550. foreach ($allMonthsTs as $ts) {
  1551. list($sStatus, $stats) = $service->getDevicesMonthStats($allDeviceIds, $ts, $user);
  1552. if (!$sStatus) {
  1553. $errors[] = "月份[" . date('Y-m', $ts) . "]解析失败:{$stats}";
  1554. $systemStatsMap[$ts] = null;
  1555. } else {
  1556. $systemStatsMap[$ts] = $stats;
  1557. }
  1558. }
  1559. // 如果基准获取有误(如日历未设),直接返回错误,不执行后续逻辑
  1560. if (!empty($errors)) return [implode('|', $errors), [], []];
  1561. // --- 3. 核心修正:单据查重与单号映射 (避免循环内查询) ---
  1562. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1563. // 获取该租户相关月份已存在的单据映射 (Month => Code)
  1564. $existingMonthsMap = DB::table('monthly_dw_order')
  1565. ->where('top_depart_id', $topDepartId)
  1566. ->where('del_time', 0)
  1567. ->whereIn('month', $allMonthsTs)
  1568. ->pluck('code', 'month')
  1569. ->toArray();
  1570. // 获取 Excel 中填写的单号对应的数据库记录 (Code => Object)
  1571. $dbOrdersByCode = DB::table('monthly_dw_order')
  1572. ->whereIn('code', $allCodes)
  1573. ->where('top_depart_id', $topDepartId)
  1574. ->where('del_time', 0)
  1575. ->get()
  1576. ->keyBy('code');
  1577. $excelAggregator = [];
  1578. $update_map = [];
  1579. // --- 4. 循环校验 ---
  1580. foreach ($array as $rowIndex => $row) {
  1581. $line = $rowIndex + 1;
  1582. $valMonthTs = $row[$monthIdx];
  1583. $monthStr = date('Y-m', $valMonthTs);
  1584. $valDevCode = trim($row[$devIdx] ?? '');
  1585. $valCode = trim($row[$codeIdx] ?? '');
  1586. // A. 设备档案检查
  1587. if (!isset($devModels[$valDevCode])) {
  1588. $errors[] = "第{$line}行:设备编码[{$valDevCode}]不存在";
  1589. continue;
  1590. }
  1591. $deviceId = $devModels[$valDevCode]->id;
  1592. $devTitle = "[{$valDevCode}]" . $devModels[$valDevCode]->title;
  1593. // B. 单据号存在性与意图校验
  1594. if ($valCode !== '') {
  1595. // 意图:编辑已存在的单据
  1596. if (isset($dbOrdersByCode[$valCode])) {
  1597. $dbOrder = $dbOrdersByCode[$valCode];
  1598. if ($dbOrder->month != $valMonthTs) {
  1599. $errors[] = "第{$line}行:单据[{$valCode}]所属月份为" . date('Y-m', $dbOrder->month) . ",与当前月份不符";
  1600. }
  1601. $update_map[$rowIndex] = $dbOrder->id;
  1602. } else {
  1603. // 填了单号但库里没有
  1604. $errors[] = "第{$line}行:单据编号[{$valCode}]无效或不存在";
  1605. }
  1606. } else {
  1607. // 意图:新增。校验是否该月已有单据
  1608. if (isset($existingMonthsMap[$valMonthTs])) {
  1609. $correctCode = $existingMonthsMap[$valMonthTs];
  1610. $errors[] = "第{$line}行:月份[{$monthStr}]已存在研发单,单号为:[{$correctCode}],请填写该单号进行更新";
  1611. }
  1612. }
  1613. // C. 考勤基准对比
  1614. $sysData = $systemStatsMap[$valMonthTs][$deviceId] ?? null;
  1615. if ($sysData) {
  1616. $inTotalDays = (float)($row[$numIdx] ?? 0);
  1617. $inRdDays = (float)($row[$num2Idx] ?? 0);
  1618. $inTotalHours= (float)($row[$num3Idx] ?? 0);
  1619. $inRdHours = (float)($row[$num4Idx] ?? 0);
  1620. // 1. 内部逻辑:研发 <= 总额
  1621. if ($inRdDays > $inTotalDays + 0.01) $errors[] = "第{$line}行:{$devTitle}研发天数大于总天数";
  1622. if ($inRdHours > $inTotalHours + 0.01) $errors[] = "第{$line}行:{$devTitle}研发工时大于总工时";
  1623. // 2. 外部逻辑:总额 == 系统核算
  1624. if (abs($inTotalDays - $sysData['attendance_days']) > 0.01) {
  1625. $errors[] = "第{$line}行:{$devTitle}总天数({$inTotalDays})不等于系统核算({$sysData['attendance_days']})";
  1626. }
  1627. if (abs($inTotalHours - $sysData['final_work_hour']) > 0.01) {
  1628. $errors[] = "第{$line}行:{$devTitle}总工时({$inTotalHours})不等于系统核算({$sysData['final_work_hour']})";
  1629. }
  1630. }
  1631. // D. 组内查重 (单号或月份作为聚合维度)
  1632. $aggKey = $valCode ?: "NEW_" . $valMonthTs;
  1633. if (isset($excelAggregator[$aggKey]['devs'][$valDevCode])) {
  1634. $errors[] = "第{$line}行:资产编码[{$valDevCode}]在同单据中重复";
  1635. }
  1636. $excelAggregator[$aggKey]['devs'][$valDevCode] = true;
  1637. }
  1638. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1639. return [$error_string, $update_map, $dbDevs];
  1640. }
  1641. // 人员月度工资单
  1642. public function monthPsOrderImport($array, $user, $other_param)
  1643. {
  1644. $upload = $array[0];
  1645. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1646. if (!$status) return [false, $msg];
  1647. $table_config = $msg;
  1648. unset($array[0]);
  1649. if (empty($array)) return [false, '导入数据不能为空'];
  1650. list($array, $error) = $this->checkCommon($array, $table_config);
  1651. if (!empty($error)) return [0, $error];
  1652. // 2. 详细校验 (这里会返回 update_map 和 dbEmps 映射)
  1653. list($error, $update_map, $dbEmps) = $this->monthPsOrderCheck($array, $user, $table_config);
  1654. if (!empty($error)) return [0, $error];
  1655. $keys = array_column($table_config, 'key');
  1656. $codeIdx = array_search('code', $keys);
  1657. $monthIdx = array_search('month', $keys);
  1658. $empIdx = array_search('employee_id', $keys);
  1659. // --- 步骤 1: 数据聚合分组 ---
  1660. // 将 Excel 数据按“单据”维度归类
  1661. $groups = [];
  1662. foreach ($array as $rowIndex => $row) {
  1663. $cCode = trim($row[$codeIdx] ?? '');
  1664. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1665. // 聚合 Key:有编码用编码,没编码用月份标记
  1666. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1667. if (!isset($groups[$aggKey])) {
  1668. $groups[$aggKey] = [
  1669. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1670. 'code' => $cCode,
  1671. 'month' => $cMonthTs,
  1672. 'details' => []
  1673. ];
  1674. }
  1675. // 准备详情行数据
  1676. $detailTmp = [];
  1677. foreach ($table_config as $k => $conf) {
  1678. if (!$conf['is_main']) {
  1679. $fieldKey = $conf['key'];
  1680. if ($fieldKey == 'employee_title') continue;
  1681. $fieldVal = $row[$k];
  1682. // 如果是人员,转换为 ID
  1683. if ($fieldKey == 'employee_id') {
  1684. $fieldVal = $dbEmps[$fieldVal] ?? 0;
  1685. }
  1686. $detailTmp[$fieldKey] = $fieldVal;
  1687. }
  1688. }
  1689. $groups[$aggKey]['details'][] = $detailTmp;
  1690. }
  1691. // --- 步骤 2: 开启事务写入 ---
  1692. DB::beginTransaction();
  1693. try {
  1694. $time = time();
  1695. foreach ($groups as $aggKey => $group) {
  1696. $mainId = $group['main_id'];
  1697. if ($mainId > 0) {
  1698. // 删除旧详情
  1699. DB::table('monthly_ps_order_details')->where('del_time',0)
  1700. ->where('main_id', $mainId)
  1701. ->update(['del_time' => $time]);
  1702. } else {
  1703. // B. 新增逻辑
  1704. $newCode = $this->generateBillNo([
  1705. 'top_depart_id' => $user['top_depart_id'],
  1706. 'type' => MonthlyPsOrder::Order_type,
  1707. 'period' => date("Ym", $group['month'])
  1708. ]);
  1709. $mainId = DB::table('monthly_ps_order')->insertGetId([
  1710. 'code' => $newCode,
  1711. 'month' => $group['month'],
  1712. 'top_depart_id' => $user['top_depart_id'],
  1713. 'crt_id' => $user['id'],
  1714. 'crt_time' => $time,
  1715. 'upd_time' => $time,
  1716. 'del_time' => 0
  1717. ]);
  1718. }
  1719. // C. 批量插入详情
  1720. $insertDetails = [];
  1721. foreach ($group['details'] as $detail) {
  1722. $detail['main_id'] = $mainId;
  1723. $detail['top_depart_id']= $user['top_depart_id'];
  1724. $detail['crt_time'] = $time;
  1725. $detail['del_time'] = 0;
  1726. $insertDetails[] = $detail;
  1727. }
  1728. if (!empty($insertDetails)) {
  1729. DB::table('monthly_ps_order_details')->insert($insertDetails);
  1730. }
  1731. }
  1732. DB::commit();
  1733. } catch (\Exception $e) {
  1734. DB::rollBack();
  1735. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1736. }
  1737. return [true, ''];
  1738. }
  1739. private function monthPsOrderCheck(&$array, $user, $table_config)
  1740. {
  1741. $keys = array_column($table_config, 'key');
  1742. $codeIdx = array_search('code', $keys);
  1743. $monthIdx = array_search('month', $keys);
  1744. $empIdx = array_search('employee_id', $keys);
  1745. $numIdx = array_search('base_salary', $keys);
  1746. $num2Idx = array_search('social_insurance', $keys);
  1747. $num3Idx = array_search('public_housing_fund', $keys);
  1748. $num4Idx = array_search('performance_salary', $keys);
  1749. $num5Idx = array_search('bonus', $keys);
  1750. $num6Idx = array_search('other', $keys);
  1751. // 1. 预加载基础数据
  1752. $allEmpNumbers = array_filter(array_unique(array_column($array, $empIdx)));
  1753. $dbEmps = Employee::where('del_time', 0)
  1754. ->whereIn('number', $allEmpNumbers)
  1755. ->where('top_depart_id', $user['top_depart_id'])
  1756. ->pluck('id', 'number')->toArray();
  1757. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1758. $dbOrders = DB::table('monthly_ps_order')
  1759. ->whereIn('code', $allCodes)
  1760. ->where('top_depart_id', $user['top_depart_id'])
  1761. ->where('del_time', 0) // 必须确保没删除
  1762. ->get()->keyBy('code');
  1763. $errors = [];
  1764. $uniqueMonths = [];
  1765. // --- 步骤 1:月份标准化预处理 ---
  1766. foreach ($array as $rowIndex => $row) {
  1767. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1768. if ($valMonthRaw === '') continue;
  1769. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1770. if (!$mStatus) {
  1771. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  1772. continue;
  1773. }
  1774. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1775. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1776. $uniqueMonths[] = $valMonthTs;
  1777. }
  1778. if (!empty($errors)) return [implode('|', $errors), [], []];
  1779. $allMonthsTs = array_unique($uniqueMonths);
  1780. //归档
  1781. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1782. if(! $status) return [$msg, [], []];
  1783. // 查询数据库中已存在的月份单据
  1784. $existingMonths = DB::table('monthly_ps_order')
  1785. ->where('top_depart_id', $user['top_depart_id'])
  1786. ->where('del_time', 0)
  1787. ->whereIn('month', $allMonthsTs)
  1788. ->pluck('month')
  1789. ->toArray();
  1790. $existingMonthsMap = array_fill_keys($existingMonths, true);
  1791. $excelAggregator = [];
  1792. $update_map = [];
  1793. $monthToKeyMap = []; // 校验 Excel 内部月份是否冲突
  1794. // --- 步骤 2:全量业务校验 ---
  1795. foreach ($array as $rowIndex => $row) {
  1796. $displayLine = $rowIndex + 1;
  1797. $valCode = trim($row[$codeIdx] ?? '');
  1798. $valMonthTs = $row[$monthIdx] ?? '';
  1799. $valEmp = trim($row[$empIdx] ?? '');
  1800. if (!is_numeric($valMonthTs)) continue;
  1801. // 确定单据组 AggKey
  1802. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  1803. // A. 校验单据存在性 & 匹配 ID
  1804. if ($valCode) {
  1805. if (isset($dbOrders[$valCode])) {
  1806. $dbOrder = $dbOrders[$valCode];
  1807. if ($dbOrder->month != $valMonthTs) {
  1808. $errors[] = "第{$displayLine}行:单据编码[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入月份不符";
  1809. }
  1810. $update_map[$rowIndex] = $dbOrder->id;
  1811. }
  1812. // 乱填编码的情况,不会进 update_map,将由下方的查重逻辑拦截
  1813. }
  1814. // B. 【核心修正】月份唯一单据校验
  1815. // 如果系统最终认为这行是“新增”,则必须检查该月份是否已有数据
  1816. if (!isset($update_map[$rowIndex])) {
  1817. if (isset($existingMonthsMap[$valMonthTs])) {
  1818. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]已存在单据,请填写正确的单据编码进行编辑";
  1819. }
  1820. }
  1821. // C. Excel 内部逻辑一致性
  1822. if (!isset($monthToKeyMap[$valMonthTs])) {
  1823. $monthToKeyMap[$valMonthTs] = $aggKey;
  1824. } elseif ($monthToKeyMap[$valMonthTs] !== $aggKey) {
  1825. $errors[] = "第{$displayLine}行:同一个月份[" . date('Y-m', $valMonthTs) . "]在 Excel 中指向了不同的单据组";
  1826. }
  1827. // D. 人员校验与单据内查重
  1828. if (!isset($dbEmps[$valEmp])) {
  1829. $errors[] = "第{$displayLine}行:人员工号[{$valEmp}]不存在";
  1830. } else {
  1831. if (isset($excelAggregator[$aggKey]['emps'][$valEmp])) {
  1832. $errors[] = "第{$displayLine}行:人员[{$valEmp}]在同一单据中重复";
  1833. }
  1834. $excelAggregator[$aggKey]['emps'][$valEmp] = true;
  1835. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  1836. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  1837. }
  1838. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  1839. }
  1840. // E. 数字格式校验
  1841. $numChecks = [
  1842. $numIdx => '基本工资',
  1843. $num2Idx => '社保',
  1844. $num3Idx => '公积金',
  1845. $num4Idx => '绩效工资',
  1846. $num5Idx => '奖金',
  1847. $num6Idx => '其他',
  1848. ];
  1849. foreach ($numChecks as $idx => $label) {
  1850. $res = $this->checkNumber($row[$idx] ?? 0, 2, 'non-negative');
  1851. if (!$res['valid']) $errors[] = "第{$displayLine}行{$label}:" . $res['error'];
  1852. }
  1853. }
  1854. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1855. return [$error_string, $update_map, $dbEmps];
  1856. }
  1857. // 设备月度折旧单
  1858. public function monthDdOrderImport($array, $user, $other_param)
  1859. {
  1860. $upload = $array[0];
  1861. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1862. if (!$status) return [false, $msg];
  1863. $table_config = $msg;
  1864. unset($array[0]);
  1865. if (empty($array)) return [false, '导入数据不能为空'];
  1866. list($array, $error) = $this->checkCommon($array, $table_config);
  1867. if (!empty($error)) return [0, $error];
  1868. // 2. 详细校验 (这里会返回 update_map 和 dbDevs 映射)
  1869. list($error, $update_map, $dbDevs) = $this->monthDdOrderCheck($array, $user, $table_config);
  1870. if (!empty($error)) return [0, $error];
  1871. $keys = array_column($table_config, 'key');
  1872. $codeIdx = array_search('code', $keys);
  1873. $monthIdx = array_search('month', $keys);
  1874. $empIdx = array_search('device_id', $keys);
  1875. // --- 步骤 1: 数据聚合分组 ---
  1876. // 将 Excel 数据按“单据”维度归类
  1877. $groups = [];
  1878. foreach ($array as $rowIndex => $row) {
  1879. $cCode = trim($row[$codeIdx] ?? '');
  1880. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1881. // 聚合 Key:有编码用编码,没编码用月份标记
  1882. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1883. if (!isset($groups[$aggKey])) {
  1884. $groups[$aggKey] = [
  1885. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1886. 'code' => $cCode,
  1887. 'month' => $cMonthTs,
  1888. 'details' => []
  1889. ];
  1890. }
  1891. // 准备详情行数据
  1892. $detailTmp = [];
  1893. foreach ($table_config as $k => $conf) {
  1894. if (!$conf['is_main']) {
  1895. $fieldKey = $conf['key'];
  1896. if ($fieldKey == 'device_title') continue;
  1897. $fieldVal = $row[$k];
  1898. // 如果是人员,转换为 ID
  1899. if ($fieldKey == 'device_id') {
  1900. $fieldVal = $dbDevs[$fieldVal] ?? 0;
  1901. }
  1902. $detailTmp[$fieldKey] = $fieldVal;
  1903. }
  1904. }
  1905. $groups[$aggKey]['details'][] = $detailTmp;
  1906. }
  1907. // --- 步骤 2: 开启事务写入 ---
  1908. DB::beginTransaction();
  1909. try {
  1910. $time = time();
  1911. $id = [];
  1912. foreach ($groups as $aggKey => $group) {
  1913. $mainId = $group['main_id'];
  1914. if ($mainId > 0) {
  1915. // 删除旧详情
  1916. DB::table('monthly_dd_order_details')->where('del_time',0)
  1917. ->where('main_id', $mainId)
  1918. ->update(['del_time' => $time]);
  1919. } else {
  1920. // B. 新增逻辑
  1921. $newCode = $this->generateBillNo([
  1922. 'top_depart_id' => $user['top_depart_id'],
  1923. 'type' => MonthlyDdOrder::Order_type,
  1924. 'period' => date("Ym", $group['month'])
  1925. ]);
  1926. $mainId = DB::table('monthly_dd_order')->insertGetId([
  1927. 'code' => $newCode,
  1928. 'month' => $group['month'],
  1929. 'top_depart_id' => $user['top_depart_id'],
  1930. 'crt_id' => $user['id'],
  1931. 'crt_time' => $time,
  1932. 'upd_time' => $time,
  1933. 'del_time' => 0
  1934. ]);
  1935. }
  1936. // C. 批量插入详情
  1937. $insertDetails = [];
  1938. foreach ($group['details'] as $detail) {
  1939. $detail['main_id'] = $mainId;
  1940. $detail['top_depart_id']= $user['top_depart_id'];
  1941. $detail['crt_time'] = $time;
  1942. $detail['del_time'] = 0;
  1943. $insertDetails[] = $detail;
  1944. }
  1945. if(! in_array($mainId, $id)) $id[] = $mainId;
  1946. if (!empty($insertDetails)) {
  1947. DB::table('monthly_dd_order_details')->insert($insertDetails);
  1948. }
  1949. }
  1950. DB::commit();
  1951. //触发折旧计算
  1952. (new DeviceDepreciationService())->triggerJob($id);
  1953. } catch (\Exception $e) {
  1954. DB::rollBack();
  1955. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1956. }
  1957. return [true, ''];
  1958. }
  1959. private function monthDdOrderCheck(&$array, $user, $table_config)
  1960. {
  1961. $keys = array_column($table_config, 'key');
  1962. $codeIdx = array_search('code', $keys);
  1963. $monthIdx = array_search('month', $keys);
  1964. $devIdx = array_search('device_id', $keys);
  1965. $numIdx = array_search('depreciation_amount', $keys);
  1966. // 1. 预加载基础数据
  1967. $allDevNumbers = array_filter(array_unique(array_column($array, $devIdx)));
  1968. $dbDevs = Device::where('del_time', 0)
  1969. ->whereIn('code', $allDevNumbers)
  1970. ->where('top_depart_id', $user['top_depart_id'])
  1971. ->pluck('id', 'code')->toArray();
  1972. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1973. $dbOrders = DB::table('monthly_dd_order')
  1974. ->whereIn('code', $allCodes)
  1975. ->where('top_depart_id', $user['top_depart_id'])
  1976. ->where('del_time', 0)
  1977. ->get()->keyBy('code');
  1978. $errors = [];
  1979. $uniqueMonths = [];
  1980. // --- 步骤 1:月份标准化 ---
  1981. foreach ($array as $rowIndex => $row) {
  1982. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1983. if ($valMonthRaw === '') continue;
  1984. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1985. if (!$mStatus) {
  1986. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  1987. continue;
  1988. }
  1989. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1990. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1991. $uniqueMonths[] = $valMonthTs;
  1992. }
  1993. if (!empty($errors)) return [implode('|', $errors), [], []];
  1994. $allMonthsTs = array_unique($uniqueMonths);
  1995. //归档
  1996. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1997. if(! $status) return [$msg, [], []];
  1998. // 预查数据库已存在的月份
  1999. $existingMonths = DB::table('monthly_dd_order')
  2000. ->where('top_depart_id', $user['top_depart_id'])
  2001. ->where('del_time', 0)
  2002. ->whereIn('month', $allMonthsTs)
  2003. ->pluck('month')
  2004. ->toArray();
  2005. $existingMonthsMap = array_fill_keys($existingMonths, true);
  2006. $excelAggregator = [];
  2007. $update_map = [];
  2008. $monthToKeyMap = []; // 校验同一月份在 Excel 内部是否产生了多个单据组
  2009. // --- 步骤 2:全量校验 ---
  2010. foreach ($array as $rowIndex => $row) {
  2011. $displayLine = $rowIndex + 1;
  2012. $valCode = trim($row[$codeIdx] ?? '');
  2013. $valMonthTs = $row[$monthIdx] ?? '';
  2014. $valDev = trim($row[$devIdx] ?? '');
  2015. $valNumRaw = $row[$numIdx] ?? 0;
  2016. if (!is_numeric($valMonthTs)) continue;
  2017. // 确定单据聚合 Key
  2018. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  2019. // A. 匹配更新 ID
  2020. if ($valCode) {
  2021. if (isset($dbOrders[$valCode])) {
  2022. $dbOrder = $dbOrders[$valCode];
  2023. if ($dbOrder->month != $valMonthTs) {
  2024. $errors[] = "第{$displayLine}行:单据[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入不符";
  2025. }
  2026. $update_map[$rowIndex] = $dbOrder->id;
  2027. }
  2028. // 乱填编码的情况不进 update_map,将被视为“新增”由下方逻辑拦截
  2029. }
  2030. // B. 【核心修正】月份唯一性拦截
  2031. // 只要不是更新已有单据,且月份已存在,就报错
  2032. if (!isset($update_map[$rowIndex])) {
  2033. if (isset($existingMonthsMap[$valMonthTs])) {
  2034. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]已存在折旧单,请填正确编码编辑";
  2035. }
  2036. }
  2037. // C. Excel 内部逻辑一致性
  2038. if (!isset($monthToKeyMap[$valMonthTs])) {
  2039. $monthToKeyMap[$valMonthTs] = $aggKey;
  2040. } elseif ($monthToKeyMap[$valMonthTs] !== $aggKey) {
  2041. $errors[] = "第{$displayLine}行:同月份[" . date('Y-m', $valMonthTs) . "]存在多组单据定义";
  2042. }
  2043. // D. 设备校验
  2044. if (!isset($dbDevs[$valDev])) {
  2045. $errors[] = "第{$displayLine}行:资产编码[{$valDev}]不存在";
  2046. } else {
  2047. if (isset($excelAggregator[$aggKey]['devs'][$valDev])) {
  2048. $errors[] = "第{$displayLine}行:资产编码[{$valDev}]在同单据中重复";
  2049. }
  2050. $excelAggregator[$aggKey]['devs'][$valDev] = true;
  2051. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  2052. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  2053. }
  2054. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  2055. }
  2056. // E. 数字校验
  2057. $res = $this->checkNumber($valNumRaw, 2, 'non-negative');
  2058. if (!$res['valid']) {
  2059. $errors[] = "第{$displayLine}行月折旧额:" . $res['error'];
  2060. }
  2061. }
  2062. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2063. return [$error_string, $update_map, $dbDevs];
  2064. }
  2065. // 规则配置单
  2066. public function ruleSetImport($array, $user, $other_param){
  2067. $upload = $array[0];
  2068. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2069. if (!$status) return [false, $msg];
  2070. $table_config = $msg;
  2071. unset($array[0]);
  2072. if (empty($array)) return [false, '导入数据不能为空'];
  2073. list($array, $error) = $this->checkCommon($array, $table_config);
  2074. if (!empty($error)) return [0, $error];
  2075. // 2. 详细校验
  2076. list($error, $update_map, $dbDevs) = $this->ruleSetCheck($array, $user, $table_config);
  2077. if (!empty($error)) return [0, $error];
  2078. $keys = array_column($table_config, 'key');
  2079. $codeIdx = array_search('code', $keys);
  2080. $monthIdx = array_search('month', $keys);
  2081. $rateIdx = array_search('rate', $keys);
  2082. $groups = [];
  2083. foreach ($array as $rowIndex => $row) {
  2084. $mCode = trim($row[$codeIdx] ?? '');
  2085. $month = $row[$monthIdx];
  2086. $aggKey = $mCode ?: "NEW_" . $month;
  2087. if (!isset($groups[$aggKey])) {
  2088. $groups[$aggKey] = [
  2089. 'id' => $update_map[$rowIndex] ?? 0,
  2090. 'month' => $month,
  2091. 'details' => []
  2092. ];
  2093. }
  2094. $groups[$aggKey]['details'][] = [
  2095. 'item_id' => $row['parsed_item_id'],
  2096. 'data_id' => $row['parsed_data_id'],
  2097. 'type' => $row['parsed_type'],
  2098. 'rate' => $row[$rateIdx],
  2099. ];
  2100. }
  2101. $time = time();
  2102. DB::beginTransaction();
  2103. try {
  2104. foreach ($groups as $group) {
  2105. $mainId = $group['id'];
  2106. if ($mainId) {
  2107. DB::table('rule_set_details')
  2108. ->where('del_time',0)
  2109. ->where('main_id', $mainId)->update(['del_time' => $time]);
  2110. } else {
  2111. $newCode = $this->generateBillNo([
  2112. 'top_depart_id' => $user['top_depart_id'],
  2113. 'type' => RuleSet::Order_type,
  2114. 'period' => date("Ym", $group['month'])
  2115. ]);
  2116. $mainId = DB::table('rule_set')->insertGetId([
  2117. 'code' => $newCode,
  2118. 'month' => $group['month'],
  2119. 'top_depart_id' => $user['top_depart_id'],
  2120. 'crt_id' => $user['id'],
  2121. 'crt_time' => $time
  2122. ]);
  2123. }
  2124. foreach ($group['details'] as &$d) {
  2125. $d['main_id'] = $mainId;
  2126. $d['top_depart_id'] = $user['top_depart_id'];
  2127. $d['crt_time'] = $time;
  2128. }
  2129. DB::table('rule_set_details')->insert($group['details']);
  2130. }
  2131. DB::commit();
  2132. } catch (\Exception $e) {
  2133. DB::rollBack();
  2134. return [false, "失败: " . $e->getMessage()];
  2135. }
  2136. return [true, ''];
  2137. }
  2138. private function ruleSetCheck(&$array, $user, $table_config)
  2139. {
  2140. $keys = array_column($table_config, 'key');
  2141. // 1. 索引提取
  2142. $mCodeIdx = array_search('code', $keys);
  2143. $monthIdx = array_search('month', $keys);
  2144. $typeIdx = array_search('type', $keys);
  2145. $dCodeIdx = array_search('code_2', $keys);
  2146. $itemIdIdx = array_search('item_id', $keys);
  2147. $rateIdx = array_search('rate', $keys);
  2148. $uniqueMonths = [];
  2149. $empCodes = [];
  2150. $devCodes = [];
  2151. $itemCodes = [];
  2152. $type_map = array_flip(RuleSetDetails::$type_name);
  2153. // --- 步骤 1: 预处理扫描 ---
  2154. foreach ($array as $rowIndex => $row) {
  2155. $valMonthRaw = trim($row[$monthIdx] ?? '');
  2156. if ($valMonthRaw === '') continue;
  2157. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  2158. if (!$mStatus) {
  2159. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  2160. continue;
  2161. }
  2162. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  2163. $array[$rowIndex][$monthIdx] = $valMonthTs;
  2164. $uniqueMonths[] = $valMonthTs;
  2165. $type = $type_map[$row[$typeIdx] ?? ''] ?? 0;
  2166. $dCode = trim($row[$dCodeIdx] ?? '');
  2167. $iCode = trim($row[$itemIdIdx] ?? '');
  2168. if ($type == RuleSetDetails::type_one && $dCode !== '') $empCodes[] = $dCode;
  2169. if ($type == RuleSetDetails::type_two && $dCode !== '') $devCodes[] = $dCode;
  2170. if ($iCode !== '') $itemCodes[] = $iCode;
  2171. }
  2172. if (!empty($errors)) return [implode('|', $errors), [], []];
  2173. $allMonthsTs = array_unique($uniqueMonths);
  2174. //归档
  2175. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  2176. if(! $status) return [$msg, [], []];
  2177. // --- 步骤 2: 批量预加载 ---
  2178. $dbEmps = Employee::where('del_time', 0)->where('top_depart_id', $user['top_depart_id'])
  2179. ->whereIn('number', array_unique($empCodes))->pluck('id', 'number')->toArray();
  2180. $dbDevs = Device::where('del_time', 0)->where('top_depart_id', $user['top_depart_id'])
  2181. ->whereIn('code', array_unique($devCodes))->pluck('id', 'code')->toArray();
  2182. $dbItems = Item::where('del_time', 0)->where('top_depart_id', $user['top_depart_id'])
  2183. ->whereIn('code', array_unique($itemCodes))->pluck('id', 'code')->toArray();
  2184. $allMCodes = array_filter(array_unique(array_column($array, $mCodeIdx)));
  2185. $dbOrders = DB::table('rule_set')->where('top_depart_id', $user['top_depart_id'])
  2186. ->where('del_time', 0)->whereIn('code', $allMCodes)->get()->keyBy('code');
  2187. $existingMonthsMap = DB::table('rule_set')->where('top_depart_id', $user['top_depart_id'])
  2188. ->where('del_time', 0)->whereIn('month', array_unique($uniqueMonths))->pluck('id', 'month')->toArray();
  2189. $errors = [];
  2190. $update_map = [];
  2191. $aggregator = [];
  2192. $uniqueCheck = [];
  2193. $monthToKeyMap = []; // 校验 Excel 内部月份与单号组的唯一性
  2194. // --- 步骤 3: 详细校验循环 ---
  2195. foreach ($array as $rowIndex => $row) {
  2196. $displayLine = $rowIndex + 1;
  2197. $valMCode = trim($row[$mCodeIdx] ?? '');
  2198. $valMonthTs = $row[$monthIdx] ?? '';
  2199. $typeTitle = trim($row[$typeIdx] ?? '');
  2200. $type = $type_map[$typeTitle] ?? 0;
  2201. $valDCode = trim($row[$dCodeIdx] ?? '');
  2202. $valICode = trim($row[$itemIdIdx] ?? '');
  2203. $valRate = $row[$rateIdx] ?? 0;
  2204. // A. 编辑/新增逻辑判定 (核心修正)
  2205. if ($valMCode !== '' && isset($dbOrders[$valMCode])) {
  2206. $dbOrder = $dbOrders[$valMCode];
  2207. if ($dbOrder->month != $valMonthTs) {
  2208. $errors[] = "第{$displayLine}行:单号[{$valMCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],不允许修改";
  2209. }
  2210. $update_map[$rowIndex] = $dbOrder->id;
  2211. }
  2212. // 月份唯一性拦截:只要没进入 update_map (无论是乱填单号还是没填),就查重
  2213. if (!isset($update_map[$rowIndex])) {
  2214. if (isset($existingMonthsMap[$valMonthTs])) {
  2215. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]已存在单据,请填写正确的单号编辑";
  2216. }
  2217. }
  2218. // B. Excel 内部一致性拦截
  2219. $aggKey = $valMCode ?: "NEW_ORDER_" . $valMonthTs;
  2220. if (!isset($monthToKeyMap[$valMonthTs])) {
  2221. $monthToKeyMap[$valMonthTs] = $aggKey;
  2222. } elseif ($monthToKeyMap[$valMonthTs] !== $aggKey) {
  2223. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]在表格中对应了不同的单据编号,请确保同一月份的单号一致";
  2224. }
  2225. // C. 人员/设备/项目存在性校验
  2226. $dataId = 0;
  2227. if ($type == RuleSetDetails::type_one) {
  2228. $dataId = $dbEmps[$valDCode] ?? 0;
  2229. if (!$dataId) $errors[] = "第{$displayLine}行:工号[{$valDCode}]不存在";
  2230. } elseif ($type == RuleSetDetails::type_two) {
  2231. $dataId = $dbDevs[$valDCode] ?? 0;
  2232. if (!$dataId) $errors[] = "第{$displayLine}行:资产编码[{$valDCode}]不存在";
  2233. } else {
  2234. $errors[] = "第{$displayLine}行:明细类型[{$typeTitle}]非法";
  2235. }
  2236. $itemId = $dbItems[$valICode] ?? 0;
  2237. if (!$itemId) $errors[] = "第{$displayLine}行:项目编码[{$valICode}]不存在";
  2238. // D. 比例与唯一性聚合
  2239. if ($dataId && $itemId) {
  2240. // 同一单据+项目内 人/设备唯一
  2241. $rowUniqueKey = $aggKey . '_' . $itemId . '_' . $type . '_' . $dataId;
  2242. if (isset($uniqueCheck[$rowUniqueKey])) {
  2243. $errors[] = "第{$displayLine}行:项目[{$valICode}]下[{$valDCode}]重复录入";
  2244. }
  2245. $uniqueCheck[$rowUniqueKey] = true;
  2246. // 比例和校验聚合
  2247. $totalRateKey = $aggKey . '_' . $type . '_' . $dataId;
  2248. $aggregator[$totalRateKey]['total_rate'] = ($aggregator[$totalRateKey]['total_rate'] ?? 0) + $valRate;
  2249. $aggregator[$totalRateKey]['title'] = $valDCode;
  2250. $aggregator[$totalRateKey]['type_name'] = $typeTitle;
  2251. $aggregator[$totalRateKey]['month_str'] = date('Y-m', $valMonthTs);
  2252. }
  2253. $array[$rowIndex]['parsed_data_id'] = $dataId;
  2254. $array[$rowIndex]['parsed_item_id'] = $itemId;
  2255. $array[$rowIndex]['parsed_type'] = $type;
  2256. }
  2257. // --- 步骤 4: 比例汇总校验 ---
  2258. foreach ($aggregator as $key => $info) {
  2259. if (abs($info['total_rate'] - 100) > 0.0001) {
  2260. $errors[] = "汇总错误:月份[{$info['month_str']}]下,{$info['type_name']}[{$info['title']}]的总分摊比例为 {$info['total_rate']}%,不等于 100%";
  2261. }
  2262. }
  2263. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2264. return [$error_string, $update_map, $dbItems];
  2265. }
  2266. // 人员日工时单 ------------------------------
  2267. public function dailyPwOrderImport($array, $user, $other_param)
  2268. {
  2269. $upload = $array[0];
  2270. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2271. if (!$status) return [false, $msg];
  2272. $table_config = $msg;
  2273. unset($array[0]);
  2274. if (empty($array)) return [false, '导入数据不能为空'];
  2275. // 1. 基础格式检查
  2276. list($array, $error) = $this->checkCommon($array, $table_config);
  2277. if (!empty($error)) return [0, $error];
  2278. // 2. 详细业务校验 (返回 update_map, 人员映射, 项目映射)
  2279. list($error, $update_map, $dbEmps, $dbItems) = $this->dailyPwOrderCheck($array, $user, $table_config);
  2280. if (!empty($error)) return [0, $error];
  2281. $keys = array_column($table_config, 'key');
  2282. $codeIdx = array_search('code', $keys);
  2283. $timeIdx = array_search('order_time', $keys);
  2284. $itemIdx = array_search('item_id', $keys);
  2285. $empIdx = array_search('employee_id', $keys);
  2286. $startIdx = array_search('start_time', $keys);
  2287. $endIdx = array_search('end_time', $keys);
  2288. // 3. 数据聚合分组
  2289. $groups = [];
  2290. foreach ($array as $rowIndex => $row) {
  2291. $cCode = trim($row[$codeIdx] ?? '');
  2292. $cTimeTs = $row[$timeIdx];
  2293. $cItemCode = trim($row[$itemIdx] ?? '');
  2294. $cItemId = $dbItems[$cItemCode] ?? 0;
  2295. // 聚合 Key:如果是更新则按主表ID聚类;如果是新增则按 日期+项目 聚类
  2296. $aggKey = ($update_map[$rowIndex] ?? 0) > 0
  2297. ? "UPDATE_" . $update_map[$rowIndex]
  2298. : "NEW_" . $cTimeTs . "_" . $cItemId;
  2299. if (!isset($groups[$aggKey])) {
  2300. $groups[$aggKey] = [
  2301. 'main_id' => $update_map[$rowIndex] ?? 0,
  2302. 'code' => $cCode,
  2303. 'order_time' => $cTimeTs,
  2304. 'item_id' => $cItemId,
  2305. 'details' => []
  2306. ];
  2307. }
  2308. // 解析时间
  2309. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2310. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2311. $groups[$aggKey]['details'][] = [
  2312. 'employee_id' => $dbEmps[trim($row[$empIdx])] ?? 0,
  2313. 'start_time_hour' => $sH,
  2314. 'start_time_min' => $sM,
  2315. 'end_time_hour' => $eH,
  2316. 'end_time_min' => $eM,
  2317. 'total_work_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM), // 计算分钟差
  2318. ];
  2319. }
  2320. // 4. 执行写入
  2321. DB::beginTransaction();
  2322. try {
  2323. $time = time();
  2324. foreach ($groups as $group) {
  2325. $mainId = $group['main_id'];
  2326. if ($mainId > 0) {
  2327. // 编辑:更新主表(允许改项目)
  2328. DB::table('daily_pw_order')->where('id', $mainId)->update([
  2329. 'item_id' => $group['item_id'],
  2330. 'upd_time' => $time
  2331. ]);
  2332. // 逻辑删除旧明细
  2333. DB::table('daily_pw_order_details')->where('main_id', $mainId)
  2334. ->where('del_time', 0)
  2335. ->update(['del_time' => $time]);
  2336. } else {
  2337. // 新增:自动生成单号
  2338. $newCode = $this->generateBillNo([
  2339. 'top_depart_id' => $user['top_depart_id'],
  2340. 'type' => DailyPwOrder::Order_type,
  2341. 'period' => date("Ym", $group['order_time'])
  2342. ]);
  2343. $mainId = DB::table('daily_pw_order')->insertGetId([
  2344. 'code' => $newCode,
  2345. 'order_time' => $group['order_time'],
  2346. 'item_id' => $group['item_id'],
  2347. 'top_depart_id' => $user['top_depart_id'],
  2348. 'crt_id' => $user['id'],
  2349. 'crt_time' => $time,
  2350. ]);
  2351. }
  2352. // 批量插入明细
  2353. $insertDetails = [];
  2354. foreach ($group['details'] as $detail) {
  2355. $detail['main_id'] = $mainId;
  2356. $detail['top_depart_id'] = $user['top_depart_id'];
  2357. $detail['crt_time'] = $time;
  2358. $detail['crt_id'] = $user['id'];
  2359. $insertDetails[] = $detail;
  2360. }
  2361. if (!empty($insertDetails)) {
  2362. DB::table('daily_pw_order_details')->insert($insertDetails);
  2363. }
  2364. }
  2365. DB::commit();
  2366. } catch (\Exception $e) {
  2367. DB::rollBack();
  2368. return [false, "失败:" . $e->getMessage()];
  2369. }
  2370. return [true, ''];
  2371. }
  2372. private function dailyPwOrderCheck(&$array, $user, $table_config)
  2373. {
  2374. $keys = array_column($table_config, 'key');
  2375. $codeIdx = array_search('code', $keys);
  2376. $timeIdx = array_search('order_time', $keys);
  2377. $itemIdx = array_search('item_id', $keys);
  2378. $empIdx = array_search('employee_id', $keys);
  2379. $startIdx = array_search('start_time', $keys);
  2380. $endIdx = array_search('end_time', $keys);
  2381. $topDepartId = $user['top_depart_id'];
  2382. // 1. 批量预加载基础档案
  2383. $empCodes = array_filter(array_unique(array_column($array, $empIdx)));
  2384. $empModels = Employee::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2385. ->whereIn('number', $empCodes)->get(['id', 'number', 'title']);
  2386. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  2387. $empDisplayMap = $empModels->mapWithKeys(function($item){
  2388. return [$item->id => "[{$item->number}]{$item->title}"];
  2389. })->toArray();
  2390. $itemCodes = array_filter(array_unique(array_column($array, $itemIdx)));
  2391. $dbItems = Item::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2392. ->whereIn('code', $itemCodes)->pluck('id', 'code')->toArray();
  2393. // 2. 预加载已有单据
  2394. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  2395. $dbOrders = DB::table('daily_pw_order')->where('top_depart_id', $topDepartId)
  2396. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  2397. // --- 跨单据预查:提前解析日期并检索库内已存在的工时区间 ---
  2398. $allDates = [];
  2399. foreach ($array as $rowIndex => $row) {
  2400. $valMonthRaw = $row[$timeIdx] ?? '';
  2401. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  2402. if(! $status) {
  2403. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  2404. continue;
  2405. }
  2406. $d = strtotime(date('Y-m-d', $ts));
  2407. $array[$rowIndex][$timeIdx] = $d;
  2408. $allDates[] = $d;
  2409. }
  2410. if (!empty($errors)) return [implode('|', $errors), [], [], []];
  2411. $allDates = array_unique($allDates);
  2412. //归档
  2413. list($status, $msg) = ArchiveService::isArchive($allDates, $user);
  2414. if(! $status) return [$msg, [], [], []];
  2415. // 查询数据库:同公司、同日期、同项目、同人员的已有工时 (排除本次 Excel 涉及到的单号)
  2416. $dbExistingWork = DB::table('daily_pw_order_details as d')
  2417. ->join('daily_pw_order as m', 'd.main_id', '=', 'm.id')
  2418. ->where('m.top_depart_id', $topDepartId) // 核心:公司数据隔离
  2419. ->whereIn('m.order_time', $allDates)
  2420. ->whereIn('m.item_id', array_values($dbItems))
  2421. ->whereIn('d.employee_id', array_values($dbEmps))
  2422. ->where('m.del_time', 0)
  2423. ->where('d.del_time', 0)
  2424. ->whereNotIn('m.code', $allCodes) // 排除掉当前正在编辑的单据本身,避免自冲突
  2425. ->select('m.order_time', 'm.item_id', 'd.employee_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')
  2426. ->get()
  2427. ->groupBy(function($item) {
  2428. return $item->order_time . '_' . $item->item_id . '_' . $item->employee_id;
  2429. });
  2430. $errors = [];
  2431. $update_map = [];
  2432. $excelBillMap = [];
  2433. $timeOverlapMap = []; // 内部记录器:$date_$item_$emp => [ ['s'=>min, 'e'=>min], ... ]
  2434. // 3. 全量循环检查
  2435. foreach ($array as $rowIndex => $row) {
  2436. $displayLine = $rowIndex + 1;
  2437. $ts = $row[$timeIdx];
  2438. $valCode = trim($row[$codeIdx] ?? '');
  2439. $valItemCode = trim($row[$itemIdx] ?? '');
  2440. $itemId = $dbItems[$valItemCode] ?? 0;
  2441. $valEmpCode = trim($row[$empIdx] ?? '');
  2442. $empId = $dbEmps[$valEmpCode] ?? 0;
  2443. $empName = $empDisplayMap[$empId] ?? "工号:{$valEmpCode}";
  2444. // B. 基础档案存在性校验
  2445. if (!$itemId) $errors[] = "第{$displayLine}行:项目编号[{$valItemCode}]不存在";
  2446. if (!$empId) $errors[] = "第{$displayLine}行:人员工号[{$valEmpCode}]不存在";
  2447. if (!$itemId || !$empId) continue;
  2448. // C. 单号与编辑逻辑判定
  2449. if ($valCode !== '') {
  2450. if (isset($dbOrders[$valCode])) {
  2451. $dbOrder = $dbOrders[$valCode];
  2452. if ($dbOrder->order_time != $ts) {
  2453. $errors[] = "第{$displayLine}行:单据[{$valCode}]原日期为[" . date('Y-m-d', $dbOrder->order_time) . "],不允许跨日期编辑";
  2454. }
  2455. $update_map[$rowIndex] = $dbOrder->id;
  2456. } else {
  2457. $errors[] = "第{$displayLine}行:单据编号[{$valCode}]不存在,若要新增请清空该列";
  2458. }
  2459. }
  2460. // D. 时间合法性校验
  2461. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  2462. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  2463. if ($sH === null || $sM === null || $eH === null || $eM === null) {
  2464. $errors[] = "第{$displayLine}行:时间格式非法或超出00:00-23:59范围";
  2465. continue;
  2466. }
  2467. $currentStart = $sH * 60 + $sM;
  2468. $currentEnd = $eH * 60 + $eM;
  2469. if ($currentStart >= $currentEnd) {
  2470. $errors[] = "第{$displayLine}行:人员{$empName}的开始时间需早于结束时间";
  2471. continue;
  2472. }
  2473. // --- E. 三位一体冲突校验 ---
  2474. $checkKey = $ts . "_" . $itemId . "_" . $empId;
  2475. // 1. 校验:数据库已有记录 (跨单据)
  2476. if (isset($dbExistingWork[$checkKey])) {
  2477. foreach ($dbExistingWork[$checkKey] as $p) {
  2478. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  2479. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  2480. // 重叠判定公式: (StartA < EndB) && (StartB < EndA)
  2481. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  2482. $errors[] = "第{$displayLine}行:人员{$empName}与已存在该时间重叠的工时单";
  2483. break;
  2484. }
  2485. }
  2486. }
  2487. // 2. 校验:Excel内上方行记录 (内部重叠)
  2488. if (isset($timeOverlapMap[$checkKey])) {
  2489. foreach ($timeOverlapMap[$checkKey] as $period) {
  2490. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  2491. $errors[] = "第{$displayLine}行:人员{$empName}与表格内其他行时间重叠";
  2492. break;
  2493. }
  2494. }
  2495. }
  2496. // 3. 校验通过,记录到内部记录器
  2497. $timeOverlapMap[$checkKey][] = ['s' => $currentStart, 'e' => $currentEnd];
  2498. }
  2499. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2500. return [$error_string, $update_map, $dbEmps, $dbItems];
  2501. }
  2502. // 设备日工时单 ------------------------------
  2503. public function dailyDwOrderImport($array, $user, $other_param)
  2504. {
  2505. $upload = $array[0];
  2506. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2507. if (!$status) return [false, $msg];
  2508. $table_config = $msg;
  2509. unset($array[0]);
  2510. if (empty($array)) return [false, '导入数据不能为空'];
  2511. // 1. 基础格式检查
  2512. list($array, $error) = $this->checkCommon($array, $table_config);
  2513. if (!empty($error)) return [0, $error];
  2514. // 2. 详细业务校验 (改为设备校验)
  2515. list($error, $update_map, $dbDevices, $dbItems) = $this->dailyDwOrderCheck($array, $user, $table_config);
  2516. if (!empty($error)) return [0, $error];
  2517. $keys = array_column($table_config, 'key');
  2518. $codeIdx = array_search('code', $keys);
  2519. $timeIdx = array_search('order_time', $keys);
  2520. $itemIdx = array_search('item_id', $keys);
  2521. $devIdx = array_search('device_id', $keys); // 对应配置中的 device_id
  2522. $startIdx = array_search('start_time', $keys);
  2523. $endIdx = array_search('end_time', $keys);
  2524. // 3. 数据聚合分组
  2525. $groups = [];
  2526. foreach ($array as $rowIndex => $row) {
  2527. $cCode = trim($row[$codeIdx] ?? '');
  2528. $cTimeTs = $row[$timeIdx];
  2529. $cItemCode = trim($row[$itemIdx] ?? '');
  2530. $cItemId = $dbItems[$cItemCode] ?? 0;
  2531. $aggKey = ($update_map[$rowIndex] ?? 0) > 0
  2532. ? "UPDATE_" . $update_map[$rowIndex]
  2533. : "NEW_" . $cTimeTs . "_" . $cItemId;
  2534. if (!isset($groups[$aggKey])) {
  2535. $groups[$aggKey] = [
  2536. 'main_id' => $update_map[$rowIndex] ?? 0,
  2537. 'code' => $cCode,
  2538. 'order_time' => $cTimeTs,
  2539. 'item_id' => $cItemId,
  2540. 'details' => []
  2541. ];
  2542. }
  2543. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2544. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2545. $groups[$aggKey]['details'][] = [
  2546. 'device_id' => $dbDevices[trim($row[$devIdx])] ?? 0, // 改为设备ID
  2547. 'start_time_hour' => $sH,
  2548. 'start_time_min' => $sM,
  2549. 'end_time_hour' => $eH,
  2550. 'end_time_min' => $eM,
  2551. 'total_work_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM),
  2552. ];
  2553. }
  2554. // 4. 执行写入
  2555. DB::beginTransaction();
  2556. try {
  2557. $time = time();
  2558. foreach ($groups as $group) {
  2559. $mainId = $group['main_id'];
  2560. if ($mainId > 0) {
  2561. // 编辑:更新设备工时主表
  2562. DB::table('daily_dw_order')->where('id', $mainId)->update([
  2563. 'item_id' => $group['item_id'],
  2564. 'upd_time' => $time
  2565. ]);
  2566. DB::table('daily_dw_order_details')->where('main_id', $mainId)
  2567. ->where('del_time', 0)
  2568. ->update(['del_time' => $time]);
  2569. } else {
  2570. // 新增
  2571. $newCode = $this->generateBillNo([
  2572. 'top_depart_id' => $user['top_depart_id'],
  2573. 'type' => DailyDwOrder::Order_type,
  2574. 'period' => date("Ym", $group['order_time'])
  2575. ]);
  2576. $mainId = DB::table('daily_dw_order')->insertGetId([
  2577. 'code' => $newCode,
  2578. 'order_time' => $group['order_time'],
  2579. 'item_id' => $group['item_id'],
  2580. 'top_depart_id' => $user['top_depart_id'],
  2581. 'crt_id' => $user['id'],
  2582. 'crt_time' => $time,
  2583. ]);
  2584. }
  2585. $insertDetails = [];
  2586. foreach ($group['details'] as $detail) {
  2587. $detail['main_id'] = $mainId;
  2588. $detail['top_depart_id'] = $user['top_depart_id'];
  2589. $detail['crt_time'] = $time;
  2590. $detail['crt_id'] = $user['id'];
  2591. $insertDetails[] = $detail;
  2592. }
  2593. if (!empty($insertDetails)) {
  2594. DB::table('daily_dw_order_details')->insert($insertDetails);
  2595. }
  2596. }
  2597. DB::commit();
  2598. } catch (\Exception $e) {
  2599. DB::rollBack();
  2600. return [false, "失败:" . $e->getMessage()];
  2601. }
  2602. return [true, ''];
  2603. }
  2604. private function dailyDwOrderCheck(&$array, $user, $table_config)
  2605. {
  2606. $keys = array_column($table_config, 'key');
  2607. $codeIdx = array_search('code', $keys);
  2608. $timeIdx = array_search('order_time', $keys);
  2609. $itemIdx = array_search('item_id', $keys);
  2610. $devIdx = array_search('device_id', $keys); // 设备编码索引
  2611. $startIdx = array_search('start_time', $keys);
  2612. $endIdx = array_search('end_time', $keys);
  2613. $topDepartId = $user['top_depart_id'];
  2614. // 1. 批量预加载设备档案 (替换原本的人员逻辑)
  2615. $devCodes = array_filter(array_unique(array_column($array, $devIdx)));
  2616. $devModels = Device::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2617. ->whereIn('code', $devCodes)->get(['id', 'code', 'title']);
  2618. $dbDevices = $devModels->pluck('id', 'code')->toArray(); // 以编号为Key查找ID
  2619. $devDisplayMap = $devModels->mapWithKeys(function($item){
  2620. return [$item->id => "[{$item->code}]{$item->title}"];
  2621. })->toArray();
  2622. $itemCodes = array_filter(array_unique(array_column($array, $itemIdx)));
  2623. $dbItems = Item::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2624. ->whereIn('code', $itemCodes)->pluck('id', 'code')->toArray();
  2625. // 2. 预加载设备已有单据
  2626. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  2627. $dbOrders = DB::table('daily_dw_order')->where('top_depart_id', $topDepartId)
  2628. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  2629. // 3. 跨单据预查
  2630. $allDates = [];
  2631. foreach ($array as $rowIndex => $row) {
  2632. $valMonthRaw = $row[$timeIdx] ?? '';
  2633. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  2634. if(! $status) {
  2635. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  2636. continue;
  2637. }
  2638. $d = strtotime(date('Y-m-d', $ts));
  2639. $array[$rowIndex][$timeIdx] = $d;
  2640. $allDates[] = $d;
  2641. }
  2642. if (!empty($errors)) return [implode('|', $errors), [], [], []];
  2643. $allDates = array_unique($allDates);
  2644. //归档
  2645. list($status, $msg) = ArchiveService::isArchive($allDates, $user);
  2646. if(! $status) return [$msg, [], [], []];
  2647. $dbExistingWork = DB::table('daily_dw_order_details as d')
  2648. ->join('daily_dw_order as m', 'd.main_id', '=', 'm.id')
  2649. ->where('m.top_depart_id', $topDepartId)
  2650. ->whereIn('m.order_time', $allDates)
  2651. ->whereIn('m.item_id', array_values($dbItems))
  2652. ->whereIn('d.device_id', array_values($dbDevices)) // 改为 device_id
  2653. ->where('m.del_time', 0)
  2654. ->where('d.del_time', 0)
  2655. ->whereNotIn('m.code', $allCodes)
  2656. ->select('m.order_time', 'm.item_id', 'd.device_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')
  2657. ->get()
  2658. ->groupBy(function($item) {
  2659. return $item->order_time . '_' . $item->item_id . '_' . $item->device_id;
  2660. });
  2661. $errors = [];
  2662. $update_map = [];
  2663. $timeOverlapMap = [];
  2664. // 4. 全量循环检查
  2665. foreach ($array as $rowIndex => $row) {
  2666. $displayLine = $rowIndex + 1;
  2667. $ts = $row[$timeIdx];
  2668. $valCode = trim($row[$codeIdx] ?? '');
  2669. $valItemCode = trim($row[$itemIdx] ?? '');
  2670. $itemId = $dbItems[$valItemCode] ?? 0;
  2671. $valDevCode = trim($row[$devIdx] ?? '');
  2672. $devId = $dbDevices[$valDevCode] ?? 0;
  2673. $devName = $devDisplayMap[$devId] ?? "设备编号:{$valDevCode}";
  2674. if (!$itemId) $errors[] = "第{$displayLine}行:项目编号[{$valItemCode}]不存在";
  2675. if (!$devId) $errors[] = "第{$displayLine}行:设备编码[{$valDevCode}]不存在";
  2676. if (!$itemId || !$devId) continue;
  2677. if ($valCode !== '') {
  2678. if (isset($dbOrders[$valCode])) {
  2679. $dbOrder = $dbOrders[$valCode];
  2680. if ($dbOrder->order_time != $ts) {
  2681. $errors[] = "第{$displayLine}行:单据[{$valCode}]原日期不符,编辑模式不允许修改日期";
  2682. }
  2683. $update_map[$rowIndex] = $dbOrder->id;
  2684. } else {
  2685. $errors[] = "第{$displayLine}行:单据编号[{$valCode}]不存在";
  2686. }
  2687. }
  2688. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  2689. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  2690. if ($sH === null || $sM === null || $eH === null || $eM === null) {
  2691. $errors[] = "第{$displayLine}行:时间段格式非法";
  2692. continue;
  2693. }
  2694. $currentStart = $sH * 60 + $sM;
  2695. $currentEnd = $eH * 60 + $eM;
  2696. if ($currentStart >= $currentEnd) {
  2697. $errors[] = "第{$displayLine}行:设备{$devName}开始时间需早于结束时间";
  2698. continue;
  2699. }
  2700. $checkKey = $ts . "_" . $itemId . "_" . $devId;
  2701. // 跨单据检查
  2702. if (isset($dbExistingWork[$checkKey])) {
  2703. foreach ($dbExistingWork[$checkKey] as $p) {
  2704. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  2705. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  2706. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  2707. $errors[] = "第{$displayLine}行:设备{$devName}在该项目当日已有记录重叠";
  2708. break;
  2709. }
  2710. }
  2711. }
  2712. // Excel内部检查
  2713. if (isset($timeOverlapMap[$checkKey])) {
  2714. foreach ($timeOverlapMap[$checkKey] as $period) {
  2715. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  2716. $errors[] = "第{$displayLine}行:设备{$devName}与表格内其他行重叠";
  2717. break;
  2718. }
  2719. }
  2720. }
  2721. $timeOverlapMap[$checkKey][] = ['s' => $currentStart, 'e' => $currentEnd];
  2722. }
  2723. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2724. return [$error_string, $update_map, $dbDevices, $dbItems];
  2725. }
  2726. // 人员请假单 --------------------------------
  2727. public function leaveOrderImport($array, $user, $other_param)
  2728. {
  2729. $upload = $array[0];
  2730. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2731. if (!$status) return [false, $msg];
  2732. $table_config = $msg;
  2733. unset($array[0]);
  2734. if (empty($array)) return [false, '导入数据不能为空'];
  2735. // 1. 基础格式检查
  2736. list($array, $error) = $this->checkCommon($array, $table_config);
  2737. if (!empty($error)) return [0, $error];
  2738. // 2. 详细业务校验 (固定为请假单校验)
  2739. list($error, $update_map, $dbEmps) = $this->leaveOrderCheck($array, $user, $table_config);
  2740. if (!empty($error)) return [0, $error];
  2741. $keys = array_column($table_config, 'key');
  2742. $codeIdx = array_search('code', $keys);
  2743. $timeIdx = array_search('order_time', $keys);
  2744. $empIdx = array_search('employee_id', $keys);
  2745. $startIdx = array_search('start_time', $keys);
  2746. $endIdx = array_search('end_time', $keys);
  2747. // 3. 数据聚合分组 (按日期聚合)
  2748. $groups = [];
  2749. foreach ($array as $rowIndex => $row) {
  2750. $cTimeTs = $row[$timeIdx];
  2751. $mainId = $update_map[$rowIndex] ?? 0;
  2752. // 聚合Key:如果是更新则按主表ID;如果是新增则按日期
  2753. $aggKey = $mainId > 0 ? "ID_" . $mainId : "DATE_" . $cTimeTs;
  2754. if (!isset($groups[$aggKey])) {
  2755. $groups[$aggKey] = [
  2756. 'main_id' => $mainId,
  2757. 'order_time' => $cTimeTs,
  2758. 'details' => []
  2759. ];
  2760. }
  2761. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2762. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2763. $groups[$aggKey]['details'][] = [
  2764. 'employee_id' => $dbEmps[trim($row[$empIdx])] ?? 0,
  2765. 'start_time_hour' => $sH,
  2766. 'start_time_min' => $sM,
  2767. 'end_time_hour' => $eH,
  2768. 'end_time_min' => $eM,
  2769. 'total_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM),
  2770. 'type' => PLeaveOverOrder::TYPE_ONE, // 固定请假类型
  2771. ];
  2772. }
  2773. // 4. 执行写入
  2774. DB::beginTransaction();
  2775. try {
  2776. $time = time();
  2777. foreach ($groups as $group) {
  2778. if ($group['main_id'] > 0) {
  2779. $mainId = $group['main_id'];
  2780. // 删除旧明细准备覆盖
  2781. DB::table('p_leave_over_order_details')->where('main_id', $mainId)->update(['del_time' => $time]);
  2782. } else {
  2783. // 生成请假单号
  2784. $newCode = $this->generateBillNo([
  2785. 'top_depart_id' => $user['top_depart_id'],
  2786. 'type' => PLeaveOverOrder::Order_type,
  2787. 'period' => date("Ym", $group['order_time'])
  2788. ]);
  2789. $mainId = DB::table('p_leave_over_order')->insertGetId([
  2790. 'code' => $newCode,
  2791. 'order_time' => $group['order_time'],
  2792. 'type' => PLeaveOverOrder::TYPE_ONE,
  2793. 'top_depart_id' => $user['top_depart_id'],
  2794. 'crt_id' => $user['id'],
  2795. 'crt_time' => $time,
  2796. ]);
  2797. }
  2798. foreach ($group['details'] as &$d) {
  2799. $d['main_id'] = $mainId;
  2800. $d['top_depart_id'] = $user['top_depart_id'];
  2801. $d['crt_time'] = $time;
  2802. }
  2803. DB::table('p_leave_over_order_details')->insert($group['details']);
  2804. }
  2805. DB::commit();
  2806. } catch (\Exception $e) {
  2807. DB::rollBack();
  2808. return [false, "失败:" . $e->getMessage()];
  2809. }
  2810. return [true, ''];
  2811. }
  2812. private function leaveOrderCheck(&$array, $user, $table_config)
  2813. {
  2814. $keys = array_column($table_config, 'key');
  2815. $codeIdx = array_search('code', $keys);
  2816. $timeIdx = array_search('order_time', $keys);
  2817. $empIdx = array_search('employee_id', $keys);
  2818. $startIdx = array_search('start_time', $keys);
  2819. $endIdx = array_search('end_time', $keys);
  2820. $topDepartId = $user['top_depart_id'];
  2821. $errors = [];
  2822. $update_map = [];
  2823. // --- 1. 基础档案预加载 (代码省略,保持原样) ---
  2824. $empCodes = array_filter(array_unique(array_column($array, $empIdx)));
  2825. $empModels = Employee::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2826. ->whereIn('number', $empCodes)->get(['id', 'number', 'title']);
  2827. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  2828. $empDisplayMap = $empModels->mapWithKeys(fn($item) => [$item->id => "[{$item->number}]{$item->title}"])->toArray();
  2829. // --- 2. 日历 & 主表预查 (代码省略,保持原样) ---
  2830. $allDateTs = [];
  2831. foreach ($array as $rowIndex => $row) {
  2832. $valMonthRaw = $row[$timeIdx] ?? '';
  2833. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  2834. if(! $status) {
  2835. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  2836. continue;
  2837. }
  2838. $d = strtotime(date('Y-m-d', $ts));
  2839. $array[$rowIndex][$timeIdx] = $d;
  2840. $allDateTs[] = $d;
  2841. }
  2842. if (!empty($errors)) return [implode('|', $errors), [], []];
  2843. $allDateTs = array_unique($allDateTs);
  2844. //归档
  2845. list($status, $msg) = ArchiveService::isArchive($allDateTs, $user);
  2846. if(! $status) return [$msg, [], []];
  2847. $calendarMap = DB::table('calendar_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  2848. ->whereIn('time', $allDateTs)->pluck('is_work', 'time')->toArray();
  2849. $existMainOrders = DB::table('p_leave_over_order')
  2850. ->where('top_depart_id', $topDepartId)
  2851. ->whereIn('order_time', $allDateTs)
  2852. ->where('type', PLeaveOverOrder::TYPE_ONE)
  2853. ->where('del_time', 0)->get()->keyBy('order_time');
  2854. // --- 3. 工时设置 (代码省略,保持原样) ---
  2855. $specialWorkMap = DB::table('employee_work_range')->whereIn('employee_id', array_values($dbEmps))
  2856. ->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  2857. $commonWorkRanges = DB::table('work_range_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)->get();
  2858. $commonPeriods = [];
  2859. foreach ($commonWorkRanges as $wr) {
  2860. $commonPeriods[] = ['s' => $wr->start_time_hour * 60 + $wr->start_time_min, 'e' => $wr->end_time_hour * 60 + $wr->end_time_min];
  2861. }
  2862. // --- 4. 库内明细校验数据 (代码省略,保持原样) ---
  2863. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  2864. $dbExistingWork = DB::table('p_leave_over_order_details as d')
  2865. ->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  2866. ->where('m.top_depart_id', $topDepartId)
  2867. ->whereIn('m.order_time', $allDateTs)
  2868. ->where('m.type', PLeaveOverOrder::TYPE_ONE)
  2869. ->where('m.del_time', 0)->where('d.del_time', 0)
  2870. ->whereNotIn('m.code', $allCodes)
  2871. ->select('m.order_time', 'd.employee_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')
  2872. ->get()->groupBy(fn($item) => $item->order_time . '_' . $item->employee_id);
  2873. $dbOrders = DB::table('p_leave_over_order')->where('top_depart_id', $topDepartId)
  2874. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  2875. $internalOverlapMap = [];
  2876. // --- 5. 循环校验 (全量提示版) ---
  2877. foreach ($array as $rowIndex => $row) {
  2878. $line = $rowIndex + 1;
  2879. $rowErrors = []; // 临时收集本行的所有错误
  2880. $ts = $row[$timeIdx];
  2881. // 1. 单据与编辑逻辑检查
  2882. $valCode = trim($row[$codeIdx] ?? '');
  2883. if ($valCode === '') {
  2884. if (isset($existMainOrders[$ts])) {
  2885. $rowErrors[] = date('Y-m-d', $ts) . "已存在请假单[{$existMainOrders[$ts]->code}],请填写单号进行编辑";
  2886. }
  2887. } else {
  2888. if (isset($dbOrders[$valCode])) {
  2889. if ($dbOrders[$valCode]->order_time != $ts) {
  2890. $rowErrors[] = "单据[{$valCode}]原日期不符,不允许跨日期编辑";
  2891. }
  2892. $update_map[$rowIndex] = $dbOrders[$valCode]->id;
  2893. } else {
  2894. $rowErrors[] = "单据号[{$valCode}]不存在";
  2895. }
  2896. }
  2897. // 2. 日历检查
  2898. if (!isset($calendarMap[$ts]) || (int)$calendarMap[$ts] !== 1) {
  2899. $rowErrors[] = "该日期非工作日,无需请假";
  2900. }
  2901. // 3. 人员检查
  2902. $empId = $dbEmps[trim($row[$empIdx])] ?? 0;
  2903. $empName = $empDisplayMap[$empId] ?? "工号:".$row[$empIdx];
  2904. if (!$empId) {
  2905. $rowErrors[] = "人员不存在";
  2906. // 如果人都不存在,后面的时间校验没意义,报错合并
  2907. $errors[] = "第{$line}行:" . implode(';', $rowErrors);
  2908. continue;
  2909. }
  2910. // 4. 时间段合法性检查
  2911. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  2912. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  2913. $curS = $sH * 60 + $sM; $curE = $eH * 60 + $eM;
  2914. if ($curS >= $curE) {
  2915. $rowErrors[] = "结束时间需晚于开始时间";
  2916. } else {
  2917. // 只有在时间段本身合法的情况下,才检查范围和重叠
  2918. // A. 工作范围检查
  2919. $empPeriods = isset($specialWorkMap[$empId]) ? [] : $commonPeriods;
  2920. if (isset($specialWorkMap[$empId])) {
  2921. foreach ($specialWorkMap[$empId] as $sw) {
  2922. $empPeriods[] = ['s' => $sw->start_time_hour * 60 + $sw->start_time_min, 'e' => $sw->end_time_hour * 60 + $sw->end_time_min];
  2923. }
  2924. }
  2925. $inRange = false;
  2926. foreach ($empPeriods as $p) { if ($curS >= $p['s'] && $curE <= $p['e']) { $inRange = true; break; } }
  2927. if (!$inRange) {
  2928. $rowErrors[] = "请假需在规定的工作时间内";
  2929. }
  2930. // B. 重叠检查 (不再 continue,两个都查)
  2931. $checkKey = $ts . "_" . $empId;
  2932. // 表内
  2933. if (isset($internalOverlapMap[$checkKey])) {
  2934. foreach ($internalOverlapMap[$checkKey] as $p) {
  2935. if ($curS < $p['e'] && $p['s'] < $curE) {
  2936. $rowErrors[] = "在表内存在时间重叠";
  2937. break; // 同一行的“表内重叠”只提示一次
  2938. }
  2939. }
  2940. }
  2941. // 库内
  2942. if (isset($dbExistingWork[$checkKey])) {
  2943. foreach ($dbExistingWork[$checkKey] as $p) {
  2944. $exS = $p->start_time_hour * 60 + $p->start_time_min;
  2945. $exE = $p->end_time_hour * 60 + $p->end_time_min;
  2946. if ($curS < $exE && $exS < $curE) {
  2947. $rowErrors[] = "与已有的请假单时间重叠";
  2948. break; // 同一行的“库内重叠”只提示一次
  2949. }
  2950. }
  2951. }
  2952. }
  2953. // 收集汇总错误
  2954. if (!empty($rowErrors)) {
  2955. $errors[] = "第{$line}行:{$empName}" . implode(',', $rowErrors);
  2956. } else {
  2957. // 只有完全没错误的数据,才放入 internalOverlapMap 供后续行比对
  2958. // 这样可以防止第2行报错了,第3行又提示跟第2行重叠,造成提示混乱
  2959. $checkKey = $ts . "_" . $empId;
  2960. $internalOverlapMap[$checkKey][] = ['s' => $curS, 'e' => $curE];
  2961. }
  2962. }
  2963. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $dbEmps];
  2964. }
  2965. // 人员加班单
  2966. public function overtimeOrderImport($array, $user, $other_param)
  2967. {
  2968. $upload = $array[0];
  2969. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2970. if (!$status) return [false, $msg];
  2971. $table_config = $msg;
  2972. unset($array[0]);
  2973. if (empty($array)) return [false, '导入数据不能为空'];
  2974. // 1. 基础格式检查
  2975. list($array, $error) = $this->checkCommon($array, $table_config);
  2976. if (!empty($error)) return [0, $error];
  2977. // 2. 业务逻辑校验 (专用于加班)
  2978. list($error, $update_map, $dbEmps) = $this->overtimeOrderCheck($array, $user, $table_config);
  2979. if (!empty($error)) return [0, $error];
  2980. $keys = array_column($table_config, 'key');
  2981. $codeIdx = array_search('code', $keys);
  2982. $timeIdx = array_search('order_time', $keys);
  2983. $empIdx = array_search('employee_id', $keys);
  2984. $startIdx = array_search('start_time', $keys);
  2985. $endIdx = array_search('end_time', $keys);
  2986. // 3. 数据聚合分组 (按日期聚合)
  2987. $groups = [];
  2988. foreach ($array as $rowIndex => $row) {
  2989. $cTimeTs = $row[$timeIdx];
  2990. $mainId = $update_map[$rowIndex] ?? 0;
  2991. $aggKey = $mainId > 0 ? "ID_" . $mainId : "DATE_" . $cTimeTs;
  2992. if (!isset($groups[$aggKey])) {
  2993. $groups[$aggKey] = [
  2994. 'main_id' => $mainId,
  2995. 'order_time' => $cTimeTs,
  2996. 'details' => []
  2997. ];
  2998. }
  2999. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  3000. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  3001. $groups[$aggKey]['details'][] = [
  3002. 'employee_id' => $dbEmps[trim($row[$empIdx])] ?? 0,
  3003. 'start_time_hour' => $sH,
  3004. 'start_time_min' => $sM,
  3005. 'end_time_hour' => $eH,
  3006. 'end_time_min' => $eM,
  3007. 'total_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM),
  3008. 'type' => PLeaveOverOrder::TYPE_TWO, // 加班类型
  3009. ];
  3010. }
  3011. // 4. 执行写入
  3012. DB::beginTransaction();
  3013. try {
  3014. $time = time();
  3015. foreach ($groups as $group) {
  3016. if ($group['main_id'] > 0) {
  3017. $mainId = $group['main_id'];
  3018. DB::table('p_leave_over_order_details')->where('main_id', $mainId)->update(['del_time' => $time]);
  3019. } else {
  3020. $newCode = $this->generateBillNo([
  3021. 'top_depart_id' => $user['top_depart_id'],
  3022. 'type' => PLeaveOverOrder::Order_type,
  3023. 'period' => date("Ym", $group['order_time'])
  3024. ]);
  3025. $mainId = DB::table('p_leave_over_order')->insertGetId([
  3026. 'code' => $newCode,
  3027. 'order_time' => $group['order_time'],
  3028. 'type' => PLeaveOverOrder::TYPE_TWO,
  3029. 'top_depart_id' => $user['top_depart_id'],
  3030. 'crt_id' => $user['id'],
  3031. 'crt_time' => $time,
  3032. ]);
  3033. }
  3034. foreach ($group['details'] as &$d) {
  3035. $d['main_id'] = $mainId;
  3036. $d['top_depart_id'] = $user['top_depart_id'];
  3037. $d['crt_time'] = $time;
  3038. }
  3039. DB::table('p_leave_over_order_details')->insert($group['details']);
  3040. }
  3041. DB::commit();
  3042. } catch (\Exception $e) {
  3043. DB::rollBack();
  3044. return [false, "失败:" . $e->getMessage()];
  3045. }
  3046. return [true, ''];
  3047. }
  3048. private function overtimeOrderCheck(&$array, $user, $table_config)
  3049. {
  3050. $keys = array_column($table_config, 'key');
  3051. $codeIdx = array_search('code', $keys);
  3052. $timeIdx = array_search('order_time', $keys);
  3053. $empIdx = array_search('employee_id', $keys);
  3054. $startIdx = array_search('start_time', $keys);
  3055. $endIdx = array_search('end_time', $keys);
  3056. $topDepartId = $user['top_depart_id'];
  3057. $errors = [];
  3058. $update_map = [];
  3059. // 1. 档案预加载
  3060. $empCodes = array_filter(array_unique(array_column($array, $empIdx)));
  3061. $empModels = Employee::where('del_time', 0)->where('top_depart_id', $topDepartId)
  3062. ->whereIn('number', $empCodes)->get(['id', 'number', 'title']);
  3063. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  3064. $empDisplayMap = $empModels->mapWithKeys(fn($item) => [$item->id => "[{$item->number}]{$item->title}"])->toArray();
  3065. // 2. 日期、日历、主表预查
  3066. $allDateTs = [];
  3067. foreach ($array as $rowIndex => $row) {
  3068. $valMonthRaw = $row[$timeIdx] ?? '';
  3069. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  3070. if(! $status) {
  3071. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  3072. continue;
  3073. }
  3074. $d = strtotime(date('Y-m-d', $ts));
  3075. $array[$rowIndex][$timeIdx] = $d;
  3076. $allDateTs[] = $d;
  3077. }
  3078. if (!empty($errors)) return [implode('|', $errors), [], []];
  3079. $allDateTs = array_unique($allDateTs);
  3080. //归档
  3081. list($status, $msg) = ArchiveService::isArchive($allDateTs, $user);
  3082. if(! $status) return [$msg, [], []];
  3083. $calendarMap = DB::table('calendar_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3084. ->whereIn('time', $allDateTs)->pluck('is_work', 'time')->toArray();
  3085. $existMainOrders = DB::table('p_leave_over_order')
  3086. ->where('top_depart_id', $topDepartId)
  3087. ->whereIn('order_time', $allDateTs)
  3088. ->where('type', PLeaveOverOrder::TYPE_TWO)
  3089. ->where('del_time', 0)->get()->keyBy('order_time');
  3090. // 3. 工时设置预加载
  3091. $specialWorkMap = DB::table('employee_work_range')->whereIn('employee_id', array_values($dbEmps))
  3092. ->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  3093. $commonWorkRanges = DB::table('work_range_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)->get();
  3094. $commonPeriods = [];
  3095. foreach ($commonWorkRanges as $wr) {
  3096. $commonPeriods[] = ['s' => $wr->start_time_hour * 60 + $wr->start_time_min, 'e' => $wr->end_time_hour * 60 + $wr->end_time_min];
  3097. }
  3098. // 4. 库内明细预查 (跨单重叠校验)
  3099. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  3100. $dbExistingWork = DB::table('p_leave_over_order_details as d')
  3101. ->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  3102. ->where('m.top_depart_id', $topDepartId)
  3103. ->whereIn('m.order_time', $allDateTs)
  3104. ->where('m.type', PLeaveOverOrder::TYPE_TWO)
  3105. ->where('m.del_time', 0)->where('d.del_time', 0)
  3106. ->whereNotIn('m.code', $allCodes)
  3107. ->select('m.order_time', 'd.employee_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')
  3108. ->get()->groupBy(fn($item) => $item->order_time . '_' . $item->employee_id);
  3109. $dbOrders = DB::table('p_leave_over_order')->where('top_depart_id', $topDepartId)
  3110. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  3111. $internalOverlapMap = [];
  3112. // 5. 全量循环检查
  3113. foreach ($array as $rowIndex => $row) {
  3114. $line = $rowIndex + 1;
  3115. $rowErrors = [];
  3116. $ts = $row[$timeIdx];
  3117. // A. 单据存在性逻辑
  3118. $valCode = trim($row[$codeIdx] ?? '');
  3119. if ($valCode === '') {
  3120. if (isset($existMainOrders[$ts])) {
  3121. $rowErrors[] = date('Y-m-d', $ts) . "已存在加班单[{$existMainOrders[$ts]->code}],请填写单号进行编辑";
  3122. }
  3123. } else {
  3124. if (isset($dbOrders[$valCode])) {
  3125. if ($dbOrders[$valCode]->order_time != $ts) $rowErrors[] = "单据[{$valCode}]原日期不符";
  3126. $update_map[$rowIndex] = $dbOrders[$valCode]->id;
  3127. } else { $rowErrors[] = "单据号[{$valCode}]不存在"; }
  3128. }
  3129. // B. 人员校验
  3130. $empId = $dbEmps[trim($row[$empIdx])] ?? 0;
  3131. $empName = $empDisplayMap[$empId] ?? "工号:".$row[$empIdx];
  3132. if (!$empId) {
  3133. $errors[] = "第{$line}行:人员不存在"; continue;
  3134. }
  3135. // C. 时间格式校验
  3136. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  3137. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  3138. $curS = $sH * 60 + $sM; $curE = $eH * 60 + $eM;
  3139. if ($curS >= $curE) {
  3140. $rowErrors[] = "结束时间需晚于开始时间";
  3141. } else {
  3142. // D. 加班规则校验 (核心逻辑)
  3143. $isWorkDay = (int)($calendarMap[$ts] ?? 0) === 1;
  3144. if ($isWorkDay) {
  3145. // 如果是工作日,加班不能在工作时间内
  3146. $empPeriods = isset($specialWorkMap[$empId]) ? [] : $commonPeriods;
  3147. if (isset($specialWorkMap[$empId])) {
  3148. foreach ($specialWorkMap[$empId] as $sw) {
  3149. $empPeriods[] = ['s' => $sw->start_time_hour * 60 + $sw->start_time_min, 'e' => $sw->end_time_hour * 60 + $sw->end_time_min];
  3150. }
  3151. }
  3152. foreach ($empPeriods as $p) {
  3153. if ($curS < $p['e'] && $p['s'] < $curE) {
  3154. $rowErrors[] = "加班时间不能与正常工作时间重叠";
  3155. break;
  3156. }
  3157. }
  3158. }
  3159. // E. 重叠校验
  3160. $checkKey = $ts . "_" . $empId;
  3161. // 表内重叠
  3162. if (isset($internalOverlapMap[$checkKey])) {
  3163. foreach ($internalOverlapMap[$checkKey] as $p) {
  3164. if ($curS < $p['e'] && $p['s'] < $curE) { $rowErrors[] = "在表内存在时间重叠"; break; }
  3165. }
  3166. }
  3167. // 库内重叠
  3168. if (isset($dbExistingWork[$checkKey])) {
  3169. foreach ($dbExistingWork[$checkKey] as $p) {
  3170. $exS = $p->start_time_hour * 60 + $p->start_time_min; $exE = $p->end_time_hour * 60 + $p->end_time_min;
  3171. if ($curS < $exE && $exS < $curE) { $rowErrors[] = "与已有的加班单时间重叠"; break; }
  3172. }
  3173. }
  3174. }
  3175. if (!empty($rowErrors)) {
  3176. $errors[] = "第{$line}行:{$empName} " . implode(',', $rowErrors);
  3177. } else {
  3178. $internalOverlapMap[$ts . "_" . $empId][] = ['s' => $curS, 'e' => $curE];
  3179. }
  3180. }
  3181. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $dbEmps];
  3182. }
  3183. // 费用项目单月度导入 ------------------------------
  3184. public function feeOrderImport($array, $user, $other_param)
  3185. {
  3186. $upload = $array[0];
  3187. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  3188. if (!$status) return [false, $msg];
  3189. $table_config = $msg;
  3190. unset($array[0]);
  3191. if (empty($array)) return [false, '导入数据不能为空'];
  3192. // 1. 基础校验(格式、必填项等)
  3193. list($array, $error) = $this->checkCommon($array, $table_config);
  3194. if (!empty($error)) return [0, $error];
  3195. // 2. 业务详细校验 (获取 update_map 和 基础档案映射)
  3196. // 此时 claim_date 会在 check 方法内部被转换为时间戳并校验月份归属
  3197. list($error, $update_map, $maps) = $this->feeOrderCheck($array, $user, $table_config);
  3198. if (!empty($error)) return [0, $error];
  3199. $keys = array_column($table_config, 'key');
  3200. $codeIdx = array_search('code', $keys);
  3201. $monthIdx = array_search('month', $keys);
  3202. // --- 步骤 1: 数据聚合分组 ---
  3203. $groups = [];
  3204. foreach ($array as $rowIndex => $row) {
  3205. $cCode = trim($row[$codeIdx] ?? '');
  3206. $cMonthTs = $row[$monthIdx];
  3207. // 聚合 Key:有编码用编码,没编码用月份
  3208. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  3209. if (!isset($groups[$aggKey])) {
  3210. $groups[$aggKey] = [
  3211. 'main_id' => $update_map[$rowIndex] ?? 0,
  3212. 'code' => $cCode,
  3213. 'month' => $cMonthTs,
  3214. 'details' => []
  3215. ];
  3216. }
  3217. // 准备详情行数据
  3218. $detailTmp = [];
  3219. foreach ($table_config as $k => $conf) {
  3220. if (!$conf['is_main']) {
  3221. $fieldKey = $conf['key'];
  3222. // 跳过仅用于展示的名称字段
  3223. if (in_array($fieldKey, ['employee_title', 'item_title', 'fee_title'])) continue;
  3224. $fieldVal = $row[$k];
  3225. // 转换编号为 ID
  3226. if ($fieldKey == 'employee_id') $fieldVal = $maps['emps'][$fieldVal] ?? 0;
  3227. if ($fieldKey == 'item_id') $fieldVal = $maps['items'][$fieldVal] ?? 0;
  3228. if ($fieldKey == 'fee_id') $fieldVal = $maps['fees'][$fieldVal] ?? 0;
  3229. // 转换枚举值(委托方式、是否定位到人)
  3230. // if ($fieldKey == 'entrust_type') {
  3231. // $fieldVal = array_search($fieldVal, \App\Model\ExpenseClaimsDetails::State_Type) ?: 0;
  3232. // }
  3233. // if ($fieldKey == 'expense_type') {
  3234. // $fieldVal = array_search($fieldVal, \App\Model\ExpenseClaimsDetails::State_Type_2) ?: 0;
  3235. // }
  3236. // 注意:claim_date 已经在 check 方法里转成了时间戳,这里直接赋值即可
  3237. $detailTmp[$fieldKey] = $fieldVal;
  3238. }
  3239. }
  3240. $groups[$aggKey]['details'][] = $detailTmp;
  3241. }
  3242. // --- 步骤 2: 事务写入 ---
  3243. DB::beginTransaction();
  3244. try {
  3245. $time = time();
  3246. foreach ($groups as $group) {
  3247. $mainId = $group['main_id'];
  3248. if ($mainId > 0) {
  3249. // 编辑:逻辑删除旧明细
  3250. DB::table('expense_claims_details')->where('del_time', 0)
  3251. ->where('expense_claims_id', $mainId)
  3252. ->update(['del_time' => $time]);
  3253. // 更新主表更新时间
  3254. DB::table('expense_claims')->where('id', $mainId)->update(['upd_time' => $time]);
  3255. } else {
  3256. // 新增:生成单号
  3257. $newCode = $this->generateBillNo([
  3258. 'top_depart_id' => $user['top_depart_id'],
  3259. 'type' => \App\Model\ExpenseClaims::Order_type,
  3260. 'period' => date("Ym", $group['month'])
  3261. ]);
  3262. $mainId = DB::table('expense_claims')->insertGetId([
  3263. 'code' => $newCode,
  3264. 'month' => $group['month'],
  3265. 'top_depart_id' => $user['top_depart_id'],
  3266. 'crt_id' => $user['id'],
  3267. 'crt_time' => $time,
  3268. 'upd_time' => $time,
  3269. 'del_time' => 0
  3270. ]);
  3271. }
  3272. // 批量插入详情
  3273. $insertDetails = [];
  3274. foreach ($group['details'] as $detail) {
  3275. $detail['expense_claims_id'] = $mainId;
  3276. $detail['top_depart_id'] = $user['top_depart_id'];
  3277. $detail['crt_id'] = $user['id'];
  3278. $detail['crt_time'] = $time;
  3279. $detail['upd_time'] = $time;
  3280. $detail['del_time'] = 0;
  3281. $insertDetails[] = $detail;
  3282. }
  3283. if (!empty($insertDetails)) {
  3284. DB::table('expense_claims_details')->insert($insertDetails);
  3285. }
  3286. }
  3287. DB::commit();
  3288. } catch (\Exception $e) {
  3289. DB::rollBack();
  3290. return [false, "写入失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  3291. }
  3292. return [true, ''];
  3293. }
  3294. private function feeOrderCheck(&$array, $user, $table_config)
  3295. {
  3296. $keys = array_column($table_config, 'key');
  3297. $codeIdx = array_search('code', $keys);
  3298. $monthIdx = array_search('month', $keys);
  3299. $empIdx = array_search('employee_id', $keys);
  3300. $itemIdx = array_search('item_id', $keys);
  3301. $feeIdx = array_search('fee_id', $keys);
  3302. $claimDateIdx = array_search('claim_date', $keys);
  3303. $amountIdx = array_search('amount', $keys);
  3304. $eAmountIdx = array_search('entrust1_amount', $keys);
  3305. $e2AmountIdx = array_search('entrust2_amount', $keys);
  3306. $eTypeIdx = array_search('entrust_type', $keys);
  3307. $exTypeIdx = array_search('expense_type', $keys);
  3308. $state_map = array_flip(ExpenseClaimsDetails::State_Type);
  3309. $ex_map = array_flip(ExpenseClaimsDetails::State_Type_2);
  3310. $topDepartId = $user['top_depart_id'];
  3311. $errors = [];
  3312. $allEmpNos = []; $allItemCodes = []; $allFeeCodes = []; $allMonthsTs = []; $allCodes = [];
  3313. // --- 1. 预处理:日期转换与基础编号提取 ---
  3314. foreach ($array as $rowIndex => $row) {
  3315. $line = $rowIndex + 1;
  3316. // A. 报销主月份处理
  3317. $valMonthRaw = trim($row[$monthIdx] ?? '');
  3318. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  3319. if (!$mStatus) {
  3320. $errors[] = "第{$line}行:月份格式错误";
  3321. continue;
  3322. }
  3323. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  3324. $array[$rowIndex][$monthIdx] = $valMonthTs; // 回写转换后的时间戳
  3325. $allMonthsTs[] = $valMonthTs;
  3326. // B. 费用产生日期校验 (claim_date)
  3327. $valClaimDateRaw = trim($row[$claimDateIdx] ?? '');
  3328. if (empty($valClaimDateRaw)) {
  3329. $errors[] = "第{$line}行:费用产生日期不能为空";
  3330. } else {
  3331. list($dStatus, $dTs) = $this->convertExcelCellToDate($valClaimDateRaw);
  3332. if (!$dStatus) {
  3333. $errors[] = "第{$line}行:费用产生日期格式错误";
  3334. } else {
  3335. // 核心逻辑:判断产生日期是否在主月份内
  3336. $monthStr = date('Y-m', $valMonthTs);
  3337. $claimMonthStr = date('Y-m', $dTs);
  3338. if ($monthStr !== $claimMonthStr) {
  3339. $errors[] = "第{$line}行:产生日期[{$claimMonthStr}]与报销月份[{$monthStr}]不符";
  3340. }
  3341. $array[$rowIndex][$claimDateIdx] = $dTs; // 回写转换后的时间戳
  3342. }
  3343. }
  3344. // C. 提取其他编号
  3345. if (!empty($row[$empIdx])) $allEmpNos[] = trim($row[$empIdx]);
  3346. if (!empty($row[$itemIdx])) $allItemCodes[] = trim($row[$itemIdx]);
  3347. if (!empty($row[$feeIdx])) $allFeeCodes[] = trim($row[$feeIdx]);
  3348. if (!empty($row[$codeIdx])) $allCodes[] = trim($row[$codeIdx]);
  3349. }
  3350. if (!empty($errors)) return [implode('|', $errors), [], []];
  3351. $allMonthsTs = array_unique($allMonthsTs);
  3352. //归档
  3353. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  3354. if(! $status) return [$msg, [], []];
  3355. // --- 2. 批量预加载档案映射 ---
  3356. $dbEmps = DB::table('employee')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3357. ->whereIn('number', array_unique($allEmpNos))->pluck('id', 'number')->toArray();
  3358. $dbItems = DB::table('item')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3359. ->whereIn('code', array_unique($allItemCodes))->pluck('id', 'code')->toArray();
  3360. $dbFees = DB::table('fee')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3361. ->whereIn('code', array_unique($allFeeCodes))->pluck('id', 'code')->toArray();
  3362. $existingMonthsMap = DB::table('expense_claims')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3363. ->whereIn('month', $allMonthsTs)->pluck('code', 'month')->toArray();
  3364. $dbOrdersByCode = DB::table('expense_claims')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3365. ->whereIn('code', array_unique($allCodes))->get()->keyBy('code');
  3366. // --- 3. 逐行校验档案存在性与单据逻辑 ---
  3367. $update_map = [];
  3368. foreach ($array as $rowIndex => $row) {
  3369. $line = $rowIndex + 1;
  3370. $valCode = trim($row[$codeIdx] ?? '');
  3371. $valMonthTs = $row[$monthIdx];
  3372. if (!empty($row[$empIdx]) && !isset($dbEmps[trim($row[$empIdx])])) {
  3373. $errors[] = "第{$line}行:工号[{$row[$empIdx]}]不存在";
  3374. }
  3375. if (!isset($dbItems[trim($row[$itemIdx])])) {
  3376. $errors[] = "第{$line}行:项目编号[{$row[$itemIdx]}]不存在";
  3377. }
  3378. if (!isset($dbFees[trim($row[$feeIdx])])) {
  3379. $errors[] = "第{$line}行:费用类型编号[{$row[$feeIdx]}]不存在";
  3380. }
  3381. if ($valCode !== '') {
  3382. if (isset($dbOrdersByCode[$valCode])) {
  3383. if ($dbOrdersByCode[$valCode]->month != $valMonthTs) {
  3384. $errors[] = "第{$line}行:单据[{$valCode}]对应月份为" . date('Y-m', $dbOrdersByCode[$valCode]->month) . ",Excel中月份不符";
  3385. }
  3386. $update_map[$rowIndex] = $dbOrdersByCode[$valCode]->id;
  3387. } else {
  3388. $errors[] = "第{$line}行:填写的单据编码[{$valCode}]系统中不存在";
  3389. }
  3390. } else {
  3391. if (isset($existingMonthsMap[$valMonthTs])) {
  3392. $errors[] = "第{$line}行:月份[" . date('Y-m', $valMonthTs) . "]已存在单据[{$existingMonthsMap[$valMonthTs]}],请填写该单号进行编辑";
  3393. }
  3394. }
  3395. // 数字格式校验
  3396. $amount = $row[$amountIdx];
  3397. $res = $this->checkNumber($amount, 2, 'non-negative');
  3398. if (!$res['valid']) $errors[] = "第{$line}行费用金额:" . $res['error'];
  3399. // 委托方式
  3400. $e_text = $row[$eTypeIdx] ?? '';
  3401. if (!isset($state_map[$e_text])) {
  3402. $errors[] = "第{$line}行:委托方式[{$e_text}]无效";
  3403. } else {
  3404. $v_tmp = $state_map[$e_text];
  3405. $array[$rowIndex][$eTypeIdx] = $v_tmp;
  3406. }
  3407. $e1_text = $row[$eAmountIdx];
  3408. $res = $this->checkNumber($e1_text, 2, 'non-negative');
  3409. if (!$res['valid']) {
  3410. $errors[] = "第{$line}行:境内委托金额" . $res['error'];
  3411. }
  3412. $e2_text = $row[$e2AmountIdx];
  3413. $res = $this->checkNumber($e2_text, 2, 'non-negative');
  3414. if (!$res['valid']) {
  3415. $errors[] = "第{$line}行:境外委托金额" . $res['error'];
  3416. }
  3417. $tmp = bcadd($e1_text, $e2_text,2);
  3418. if(floatval($tmp) > $amount) return [false, "第{$line}行委托金额总和不能超过费用金额"];
  3419. //是否定位到人
  3420. $ex_text = $row[$exTypeIdx] ?? '';
  3421. if (!isset($ex_map[$ex_text])) {
  3422. $errors[] = "第{$line}行:是否定位到人[{$ex_text}]无效";
  3423. } else {
  3424. $v_tmp = $ex_map[$ex_text];
  3425. $array[$rowIndex][$exTypeIdx] = $v_tmp;
  3426. }
  3427. }
  3428. $maps = ['emps' => $dbEmps, 'items' => $dbItems, 'fees' => $dbFees];
  3429. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $maps];
  3430. }
  3431. // 标签管理
  3432. public function tagImport($array, $user, $other_param)
  3433. {
  3434. $upload = $array[0];
  3435. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  3436. if (!$status) return [false, $msg];
  3437. $table_config = $msg;
  3438. unset($array[0]);
  3439. if (empty($array)) return [false, '导入数据不能为空'];
  3440. // 基础格式校验
  3441. list($array, $error) = $this->checkCommon($array, $table_config);
  3442. if (!empty($error)) return [0, $error];
  3443. // 2. 业务逻辑校验
  3444. list($error, $update_map) = $this->tagCheck($array, $user, $table_config);
  3445. if (!empty($error)) return [0, $error];
  3446. $time = time();
  3447. $insert = [];
  3448. $update = [];
  3449. foreach ($array as $key => $value) {
  3450. $main_tmp = [];
  3451. foreach ($value as $k => $val){
  3452. if(!empty($table_config[$k]['is_main'])){
  3453. $main_tmp[$table_config[$k]['key']] = $val;
  3454. }
  3455. }
  3456. if (isset($update_map[$key])) {
  3457. // 更新逻辑
  3458. $update[] = array_merge($main_tmp, [
  3459. 'id' => $update_map[$key],
  3460. ]);
  3461. } else {
  3462. // 新增逻辑
  3463. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  3464. $main_tmp['crt_time'] = $time;
  3465. $insert[] = $main_tmp;
  3466. }
  3467. }
  3468. DB::beginTransaction();
  3469. try {
  3470. if (!empty($insert)) {
  3471. foreach (array_chunk($insert, 500) as $chunk) {
  3472. Tag::insert($chunk);
  3473. }
  3474. }
  3475. if (!empty($update)) {
  3476. foreach ($update as $item) {
  3477. $uId = $item['id'];
  3478. unset($item['id']);
  3479. Tag::where('id', $uId)->update($item);
  3480. }
  3481. }
  3482. DB::commit();
  3483. } catch (\Exception $e) {
  3484. DB::rollBack();
  3485. return [false, "导入失败:" . $e->getMessage()];
  3486. }
  3487. return [true, ''];
  3488. }
  3489. private function tagCheck(&$array, $user, $table_config)
  3490. {
  3491. $keys = array_column($table_config, 'key');
  3492. $codeIdx = array_search('code', $keys);
  3493. $sortIdx = array_search('sort', $keys);
  3494. $typeIdx = array_search('type', $keys);
  3495. $isUseIdx = array_search('is_use', $keys);
  3496. $type_map = array_flip(Tag::TYPE_TITLE);
  3497. $isUse_map = array_flip(Tag::IS_USE);
  3498. // 获取当前企业下已存在的标签,用于判断是新增还是更新
  3499. $dbMap = Tag::where('del_time', 0)
  3500. ->where('top_depart_id', $user['top_depart_id'])
  3501. ->get()
  3502. ->keyBy('code')
  3503. ->toArray();
  3504. $errors = [];
  3505. $update = [];
  3506. $excelCodes = [];
  3507. foreach ($array as $rowIndex => $value) {
  3508. $displayLine = $rowIndex + 1;
  3509. $valCode = trim($value[$codeIdx] ?? '');
  3510. if ($valCode === '') {
  3511. $errors[] = "第{$displayLine}行:编码不能为空";
  3512. continue;
  3513. }
  3514. // 校验 Excel 内部是否重复
  3515. if (isset($excelCodes[$valCode])) {
  3516. $errors[] = "第{$displayLine}行:编码[{$valCode}]在文件中重复出现";
  3517. continue;
  3518. }
  3519. $excelCodes[$valCode] = true;
  3520. // 类型
  3521. $e_text = $value[$typeIdx] ?? '';
  3522. if (!isset($type_map[$e_text])) {
  3523. $errors[] = "第{$displayLine}行:类型[{$e_text}]无效";
  3524. } else {
  3525. $array[$rowIndex][$typeIdx] = $type_map[$e_text];
  3526. }
  3527. // 是否启用
  3528. $e_text = $value[$isUseIdx] ?? '';
  3529. if (!isset($isUse_map[$e_text])) {
  3530. $errors[] = "第{$displayLine}行:是否启用[{$e_text}]无效";
  3531. } else {
  3532. $array[$rowIndex][$isUseIdx] = $isUse_map[$e_text];
  3533. }
  3534. // 数字格式校验
  3535. $sort = $value[$sortIdx];
  3536. if (filter_var($sort, FILTER_VALIDATE_INT) === false) return [false, "第{$displayLine}行排序字段排序字段必须是整数且不能含有小数点"];
  3537. // 如果数据库已存在,记录为更新操作
  3538. if (isset($dbMap[$valCode])) {
  3539. $update[$rowIndex] = $dbMap[$valCode]['id'];
  3540. }
  3541. }
  3542. $error_string = !empty($errors) ? implode('|', $errors) : "";
  3543. return [$error_string, $update];
  3544. }
  3545. // 团队 -----------------------------------
  3546. private function getTeamList($array, $user, $index){
  3547. $codes = array_unique(array_filter(array_column($array,$index)));
  3548. return Team::where('del_time', 0)
  3549. ->where('top_depart_id', $user['top_depart_id'])
  3550. ->whereIn('code', $codes)
  3551. ->pluck('id','code')
  3552. ->toArray();
  3553. }
  3554. public function teamImport($array, $user, $other_param)
  3555. {
  3556. $upload = $array[0];
  3557. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  3558. if (!$status) return [false, $msg];
  3559. $table_config = $msg;
  3560. unset($array[0]);
  3561. if (empty($array)) return [false, '导入数据不能为空'];
  3562. // 1. 公共校验 (必填、唯一性等)
  3563. list($array, $error) = $this->checkCommon($array, $table_config);
  3564. if (!empty($error)) return [0, $error];
  3565. // 2. 业务详细校验 (包含一致性校验、明细解析)
  3566. list($error, $update_map, $detail_data_map) = $this->teamCheck($array, $user, $table_config);
  3567. if (!empty($error)) return [0, $error];
  3568. $time = time();
  3569. $insert_data = [];
  3570. $update_data = [];
  3571. $all_detail_insert = [];
  3572. $update_main_ids = [];
  3573. $keys = array_column($table_config, 'key');
  3574. $codeIdx = array_search('code', $keys);
  3575. // 3. 数据分拣(聚合平铺数据)
  3576. foreach ($array as $key => $value) {
  3577. $itemCode = trim($value[$codeIdx]);
  3578. $main_tmp = [];
  3579. foreach ($value as $k => $val) {
  3580. if (!empty($table_config[$k]['is_main'])) {
  3581. if ($table_config[$k]['key'] == 'employee_title') continue;
  3582. $main_tmp[$table_config[$k]['key']] = $val;
  3583. }
  3584. }
  3585. if (isset($update_map[$key])) {
  3586. // 更新逻辑:以 ID 为键去重
  3587. $itemId = $update_map[$key];
  3588. $update_main_ids[$itemId] = $itemId;
  3589. $update_data[$itemId] = array_merge($main_tmp, ['id' => $itemId]);
  3590. if (isset($detail_data_map[$key])) {
  3591. foreach ($detail_data_map[$key] as $d) {
  3592. $all_detail_insert[] = array_merge($d, [
  3593. 'team_id' => $itemId,
  3594. 'crt_time' => $time,
  3595. 'top_depart_id' => $user['top_depart_id']
  3596. ]);
  3597. }
  3598. }
  3599. } else {
  3600. // 新增逻辑:以项目编码为键去重
  3601. if (!isset($insert_data[$itemCode])) {
  3602. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  3603. $main_tmp['crt_id'] = $user['id'];
  3604. $main_tmp['crt_time'] = $time;
  3605. $insert_data[$itemCode] = $main_tmp;
  3606. }
  3607. if (isset($detail_data_map[$key])) {
  3608. foreach ($detail_data_map[$key] as $d) {
  3609. $all_detail_insert[] = array_merge($d, [
  3610. '_code' => $itemCode,
  3611. 'crt_time' => $time,
  3612. 'top_depart_id' => $user['top_depart_id']
  3613. ]);
  3614. }
  3615. }
  3616. }
  3617. }
  3618. DB::beginTransaction();
  3619. try {
  3620. // 4. 执行新增主表
  3621. $new_item_maps = [];
  3622. if (!empty($insert_data)) {
  3623. foreach (array_chunk(array_values($insert_data), 500) as $chunk) {
  3624. Team::insert($chunk);
  3625. }
  3626. $new_item_maps = Team::whereIn('code', array_keys($insert_data))
  3627. ->where('del_time', 0)
  3628. ->where('top_depart_id', $user['top_depart_id'])
  3629. ->pluck('id', 'code')->toArray();
  3630. }
  3631. // 5. 执行更新主表
  3632. if (!empty($update_data)) {
  3633. foreach ($update_data as $id => $uItem) {
  3634. unset($uItem['id']);
  3635. Team::where('id', $id)->update($uItem);
  3636. }
  3637. }
  3638. // 6. 处理明细表 (先全删后插)
  3639. if (!empty($update_main_ids)) {
  3640. TeamDetails::whereIn('team_id', array_values($update_main_ids))
  3641. ->where('del_time', 0)
  3642. ->update(['del_time' => $time]);
  3643. }
  3644. foreach ($all_detail_insert as &$di) {
  3645. if (isset($di['_code'])) {
  3646. $di['item_id'] = $new_item_maps[$di['_code']] ?? 0;
  3647. unset($di['_code']);
  3648. }
  3649. }
  3650. unset($di);
  3651. if (!empty($all_detail_insert)) {
  3652. foreach (array_chunk($all_detail_insert, 500) as $chunk) {
  3653. TeamDetails::insert($chunk);
  3654. }
  3655. }
  3656. DB::commit();
  3657. } catch (\Exception $e) {
  3658. DB::rollBack();
  3659. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  3660. }
  3661. return [true, ''];
  3662. }
  3663. private function teamCheck(&$array, $user, $table_config)
  3664. {
  3665. $keys = array_column($table_config, 'key');
  3666. $codeIdx = array_search('code', $keys);
  3667. $stateIdx = array_search('state', $keys);
  3668. $code2Idx = array_search('code_2', $keys); // 工号列
  3669. $empIdx = array_search('charge_id', $keys);
  3670. // 假设 $array 是你的数据集
  3671. $allEmpNumbers = array_values(array_filter(array_unique([
  3672. array_column($array, $empIdx),
  3673. array_column($array, $code2Idx)
  3674. ])));
  3675. $dbEmps = Employee::where('del_time', 0)
  3676. ->whereIn('number', $allEmpNumbers)
  3677. ->where('top_depart_id', $user['top_depart_id'])
  3678. ->pluck('id', 'number')->toArray();
  3679. $code_map = $this->getTeamList($array, $user, $codeIdx);
  3680. $man_map = $this->getFlatDataList2($array, $user, $code2Idx);
  3681. $errors = [];
  3682. $update_mapping = [];
  3683. $detail_storage = [];
  3684. $mainDataConsistency = []; // 一致性校验
  3685. $state_type_map = array_flip(Team::State_Type);
  3686. // 识别主表字段列索引
  3687. $mainColIndices = [];
  3688. foreach ($table_config as $index => $conf) {
  3689. if (!empty($conf['is_main'])) $mainColIndices[$index] = $conf['value'];
  3690. }
  3691. foreach ($array as $rowIndex => $rowValue) {
  3692. $displayLine = $rowIndex + 1;
  3693. $valCode = trim($rowValue[$codeIdx] ?? '');
  3694. $valEmp = trim($rowValue[$empIdx] ?? '');
  3695. if ($valCode === '') continue;
  3696. // --- A. 主表一致性校验 ---
  3697. if (!isset($mainDataConsistency[$valCode])) {
  3698. $mainDataConsistency[$valCode] = array_intersect_key($rowValue, $mainColIndices);
  3699. } else {
  3700. foreach ($mainColIndices as $idx => $label) {
  3701. if (trim($rowValue[$idx] ?? '') != trim($mainDataConsistency[$valCode][$idx] ?? '')) {
  3702. $errors[] = "第{$displayLine}行:团队[{$valCode}]的主表信息[{$label}]与前文不一致";
  3703. }
  3704. }
  3705. }
  3706. // --- B. 基础校验 ---
  3707. if (isset($code_map[$valCode])) {
  3708. $update_mapping[$rowIndex] = $code_map[$valCode];
  3709. }
  3710. // 状态
  3711. $state_text = $rowValue[$stateIdx] ?? '';
  3712. if (!isset($state_type_map[$state_text])) {
  3713. $errors[] = "第{$displayLine}行:状态[{$state_text}]无效";
  3714. } else {
  3715. $array[$rowIndex][$stateIdx] = $state_type_map[$state_text];
  3716. }
  3717. // D. 人员校验
  3718. if(! empty($valEmp)){
  3719. if (!isset($dbEmps[$valEmp])) {
  3720. $errors[] = "第{$displayLine}行:负责人工号[{$valEmp}]不存在";
  3721. } else {
  3722. $array[$rowIndex][$empIdx] = $dbEmps[$valEmp];
  3723. }
  3724. }
  3725. $subCode = trim($rowValue[$code2Idx] ?? '');
  3726. if ($subCode !== '') {
  3727. if (!isset($man_map[$subCode])) {
  3728. $errors[] = "第{$displayLine}行:人员工号[{$subCode}]不存在";
  3729. } else {
  3730. $detail_storage[$rowIndex][] = ['data_id' => $man_map[$subCode]];
  3731. }
  3732. }
  3733. }
  3734. $error_str = !empty($errors) ? implode('|', $errors) : "";
  3735. return [$error_str, $update_mapping, $detail_storage];
  3736. }
  3737. private function getFlatDataList2($array, $user, $code2Idx)
  3738. {
  3739. $codes = array_unique(array_filter(array_column($array, $code2Idx)));
  3740. return Employee::where('del_time', 0)
  3741. ->where('top_depart_id', $user['top_depart_id'])
  3742. ->whereIn('number', $codes)
  3743. ->pluck('id', 'number')
  3744. ->toArray();
  3745. }
  3746. /**
  3747. * 解析并校验时间
  3748. */
  3749. private function parseTimeHourMin($val)
  3750. {
  3751. $h = -1; $m = -1;
  3752. if (strpos($val, ':') !== false) {
  3753. $parts = explode(':', $val);
  3754. $h = isset($parts[0]) ? (int)$parts[0] : -1;
  3755. $m = isset($parts[1]) ? (int)$parts[1] : -1;
  3756. } elseif (is_numeric($val)) {
  3757. $totalMinutes = (int)round($val * 1440);
  3758. $h = (int)floor($totalMinutes / 60);
  3759. $m = (int)($totalMinutes % 60);
  3760. }
  3761. if ($h < 0 || $h > 23 || $m < 0 || $m > 59) {
  3762. return [null, null];
  3763. }
  3764. return [$h, $m];
  3765. }
  3766. //公共校验 -----------------------------------------
  3767. private function checkCommon($array, $table_config) {
  3768. $error = [];
  3769. $uniqueCheck = [];
  3770. foreach ($array as $line => $row) {
  3771. // 如果整行都是空的(包括 null),直接剔除
  3772. if (empty(array_filter($row))) {
  3773. unset($array[$line]);
  3774. continue;
  3775. }
  3776. // --- 核心修正点:遍历配置,而不是遍历原始行数据 ---
  3777. // 这样即便 Excel 有 100 列,我们也只校验配置里的那 4 列
  3778. $newRow = [];
  3779. foreach ($table_config as $colIndex => $config) {
  3780. $value = isset($row[$colIndex]) ? trim($row[$colIndex]) : '';
  3781. $fieldName = $config['value'];
  3782. // 1. 必填校验
  3783. if (!empty($config['required']) && $value === '') {
  3784. $error[] = "第{$line}行:[{$fieldName}] 必填";
  3785. }
  3786. // 2. 默认值填充
  3787. if ($value === '' && isset($config['default'])) {
  3788. $value = $config['default'];
  3789. }
  3790. // 3. 唯一性校验
  3791. if (!empty($config['unique']) && $value !== '') {
  3792. if (isset($uniqueCheck[$colIndex][$value])) {
  3793. $prevLine = $uniqueCheck[$colIndex][$value];
  3794. $error[] = "第{$line}行:[{$fieldName}] 与第{$prevLine}行重复,重复值:{$value}";
  3795. } else {
  3796. $uniqueCheck[$colIndex][$value] = $line;
  3797. }
  3798. }
  3799. $newRow[$colIndex] = $value;
  3800. }
  3801. // 只保留校验过的数据列,多余的列(第4列之后)被自动丢弃
  3802. $array[$line] = $newRow;
  3803. }
  3804. $error_string = !empty($error) ? implode('|', $error) : "";
  3805. return [$array, $error_string];
  3806. }
  3807. //模板校验 -----------------------------------------
  3808. private function compareTableAndReturn($upload, $param){
  3809. if(empty($upload)) return [false, '表头不能为空'];
  3810. $config = $this->getTableConfig($param['type']);
  3811. $config_array = $config['array'];
  3812. if(empty($config_array)) return [false, '导入配置表头文件不存在'];
  3813. foreach ($config_array as $key => $value){
  3814. $key_position = $key + 1;
  3815. if(! isset($upload[$key])) return [false, "第" . $key_position . "列表头缺失"];
  3816. $tmp_v = trim($upload[$key]);
  3817. if($tmp_v != $value['value']) return [false, "第" . $key_position . "列表头与模板不符合,请重新下载模板"];
  3818. }
  3819. return [true, $config_array];
  3820. }
  3821. //转换日期 ------------------------------------------
  3822. function convertExcelCellToDate($cellValue) {
  3823. // 尝试将单元格值转换为浮点数(Excel 日期序列号)
  3824. $excelTimestamp = filter_var($cellValue, FILTER_VALIDATE_FLOAT);
  3825. if ($excelTimestamp !== false && $excelTimestamp > 0) {
  3826. // 如果成功转换并且值大于0,则认为是Excel日期序列号
  3827. try {
  3828. $dateTimeObject = Date::excelToDateTimeObject($cellValue);
  3829. // if ($dateTimeObject->format('H:i:s') === '00:00:00') {
  3830. // // 如果是,则将时间设置为 '23:59:00'
  3831. // $dateTimeObject->setTime(23, 59);
  3832. // }
  3833. // 现在你可以格式化这个日期了
  3834. $formattedDate = $dateTimeObject->format('Y-m-d');
  3835. if(! strtotime($formattedDate)) return [false, ''];
  3836. return [true, strtotime($formattedDate)];
  3837. } catch (\Exception $e) {
  3838. // 处理转换失败的情况
  3839. return [false, '单元格日期格式转换时间戳失败'];
  3840. }
  3841. }
  3842. // 如果不是有效的浮点数,则尝试按照多种日期格式解析
  3843. if(! strtotime($cellValue)) return [false, '单元格文本格式转换时间戳失败'];
  3844. return [true, strtotime($cellValue)];
  3845. }
  3846. }