ImportService.php 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485
  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. DB::commit();
  1040. } catch (\Exception $e) {
  1041. DB::rollBack();
  1042. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1043. }
  1044. return [true, ''];
  1045. }
  1046. private function feeCheck(&$array, $user, $table_config)
  1047. {
  1048. $keys = array_column($table_config, 'key');
  1049. $codeIdx = array_search('code', $keys);
  1050. $parentIdx = array_search('parent_id', $keys);
  1051. $isOtherIdx = array_search('is_other', $keys);
  1052. // 1. 获取基础数据
  1053. list($dbFeeMap, $excelCodesMap) = $this->getFeeList($array, $user, $codeIdx);
  1054. $errors = [];
  1055. $update = [];
  1056. $parent_code_map = [];
  1057. $is_other_map = array_flip(Fee::IS_OTHER);
  1058. // 2. 建立 Excel 内部父子关系映射(用于环路追溯)
  1059. $currentExcelMap = [];
  1060. foreach ($array as $row) {
  1061. $c = trim($row[$codeIdx] ?? '');
  1062. $p = trim($row[$parentIdx] ?? '');
  1063. if ($c !== '') $currentExcelMap[$c] = $p;
  1064. }
  1065. // 3. 逐行校验
  1066. foreach ($array as $rowIndex => $value) {
  1067. $displayLine = $rowIndex + 1;
  1068. $valCode = trim($value[$codeIdx] ?? '');
  1069. $valParentCode = trim($value[$parentIdx] ?? '');
  1070. if ($valCode === '') continue;
  1071. // 更新状态记录
  1072. if (isset($dbFeeMap[$valCode])) {
  1073. $update[$rowIndex] = $dbFeeMap[$valCode]['id'];
  1074. }
  1075. // 其他费用
  1076. $is_other_text = $value[$isOtherIdx] ?? '';
  1077. if (!isset($is_other_map[$is_other_text])) {
  1078. $errors[] = "第{$displayLine}行:是否其他费用[{$is_other_text}]无效";
  1079. } else {
  1080. $array[$rowIndex][$isOtherIdx] = $is_other_map[$is_other_text];
  1081. }
  1082. if ($valParentCode !== '') {
  1083. // --- A. 存在性校验 ---
  1084. // 这里会检查 006 是否在数据库,或者是否在本次 Excel 的其他行中
  1085. if (!isset($dbFeeMap[$valParentCode]) && !isset($excelCodesMap[$valParentCode])) {
  1086. $errors[] = "第{$displayLine}行:上级编码[{$valParentCode}]在系统和文件中均不存在";
  1087. continue;
  1088. }
  1089. // --- B. 自引用校验 ---
  1090. if ($valCode === $valParentCode) {
  1091. $errors[] = "第{$displayLine}行:上级编码不能是自身";
  1092. continue;
  1093. }
  1094. // --- C. 环路追溯 ---
  1095. $visited = [];
  1096. $res = $this->findLoopInAncestors($valParentCode, $valCode, $currentExcelMap, $dbFeeMap, $visited);
  1097. if ($res !== false) {
  1098. if ($res['type'] === 'LOOP_SELF') {
  1099. $errors[] = "第{$displayLine}行:编码[{$valCode}]与上级[{$valParentCode}]存在循环引用";
  1100. } else {
  1101. $errors[] = "第{$displayLine}行:上级[{$valParentCode}]的溯源链条已成环";
  1102. }
  1103. continue;
  1104. }
  1105. // 记录有效的父级关系
  1106. $parent_code_map[$rowIndex] = $valParentCode;
  1107. }
  1108. }
  1109. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1110. return [$error_string, $update, $parent_code_map];
  1111. }
  1112. private function getFeeList($array, $user, $index)
  1113. {
  1114. // 关键:一定要把 Excel 里所有的 code 这一列全部拿出来,并去除空值
  1115. $codesInExcel = [];
  1116. foreach ($array as $row) {
  1117. $c = trim($row[$index] ?? '');
  1118. if ($c !== '') {
  1119. $codesInExcel[$c] = true;
  1120. }
  1121. }
  1122. $allFees = Fee::where('del_time', 0)
  1123. ->where('top_depart_id', $user['top_depart_id'])
  1124. ->select('id', 'code', 'parent_id')
  1125. ->get();
  1126. $dbFeeMap = [];
  1127. foreach ($allFees as $fee) {
  1128. $dbFeeMap[$fee->code] = [
  1129. 'id' => $fee->id,
  1130. 'code' => $fee->code,
  1131. 'parent_id' => $fee->parent_id
  1132. ];
  1133. }
  1134. // 返回数据库映射和 Excel 编码映射
  1135. return [$dbFeeMap, $codesInExcel];
  1136. }
  1137. private function findLoopInAncestors($startParentCode, $targetCode, $excelMap, $dbFeeMap, &$visited)
  1138. {
  1139. $current = $startParentCode;
  1140. while ($current !== '' && $current !== 0) {
  1141. if ($current === $targetCode) {
  1142. return ['type' => 'LOOP_SELF', 'code' => $current];
  1143. }
  1144. if (isset($visited[$current])) {
  1145. return ['type' => 'EXISTING_LOOP', 'code' => $current];
  1146. }
  1147. $visited[$current] = true;
  1148. if (isset($excelMap[$current]) && $excelMap[$current] !== '') {
  1149. $current = $excelMap[$current];
  1150. } elseif (isset($dbFeeMap[$current])) {
  1151. $parentId = $dbFeeMap[$current]['parent_id'];
  1152. $parentCode = '';
  1153. foreach ($dbFeeMap as $item) {
  1154. if ($item['id'] == $parentId) {
  1155. $parentCode = $item['code'];
  1156. break;
  1157. }
  1158. }
  1159. $current = $parentCode;
  1160. } else {
  1161. break;
  1162. }
  1163. }
  1164. return false;
  1165. }
  1166. // 人员月度工时单 ------------------------------
  1167. public function monthPwOrderImport($array, $user, $other_param)
  1168. {
  1169. $upload = $array[0];
  1170. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1171. if (!$status) return [false, $msg];
  1172. $table_config = $msg;
  1173. unset($array[0]);
  1174. if (empty($array)) return [false, '导入数据不能为空'];
  1175. list($array, $error) = $this->checkCommon($array, $table_config);
  1176. if (!empty($error)) return [0, $error];
  1177. // 2. 详细校验 (这里会返回 update_map 和 dbEmps 映射)
  1178. list($error, $update_map, $dbEmps) = $this->monthPwOrderCheck($array, $user, $table_config);
  1179. if (!empty($error)) return [0, $error];
  1180. $keys = array_column($table_config, 'key');
  1181. $codeIdx = array_search('code', $keys);
  1182. $monthIdx = array_search('month', $keys);
  1183. $empIdx = array_search('employee_id', $keys);
  1184. // --- 步骤 1: 数据聚合分组 ---
  1185. // 将 Excel 数据按“单据”维度归类
  1186. $groups = [];
  1187. foreach ($array as $rowIndex => $row) {
  1188. $cCode = trim($row[$codeIdx] ?? '');
  1189. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1190. // 聚合 Key:有编码用编码,没编码用月份标记
  1191. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1192. if (!isset($groups[$aggKey])) {
  1193. $groups[$aggKey] = [
  1194. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1195. 'code' => $cCode,
  1196. 'month' => $cMonthTs,
  1197. 'details' => []
  1198. ];
  1199. }
  1200. // 准备详情行数据
  1201. $detailTmp = [];
  1202. foreach ($table_config as $k => $conf) {
  1203. if (!$conf['is_main']) {
  1204. $fieldKey = $conf['key'];
  1205. if ($fieldKey == 'employee_title') continue;
  1206. $fieldVal = $row[$k];
  1207. // 如果是人员,转换为 ID
  1208. if ($fieldKey == 'employee_id') {
  1209. $fieldVal = $dbEmps[$fieldVal] ?? 0;
  1210. }
  1211. $detailTmp[$fieldKey] = $fieldVal;
  1212. }
  1213. }
  1214. $groups[$aggKey]['details'][] = $detailTmp;
  1215. }
  1216. // --- 步骤 2: 开启事务写入 ---
  1217. DB::beginTransaction();
  1218. try {
  1219. $time = time();
  1220. foreach ($groups as $aggKey => $group) {
  1221. $mainId = $group['main_id'];
  1222. if ($mainId > 0) {
  1223. // 删除旧详情
  1224. DB::table('monthly_pw_order_details')->where('del_time',0)
  1225. ->where('main_id', $mainId)
  1226. ->update(['del_time' => $time]);
  1227. } else {
  1228. // B. 新增逻辑
  1229. $newCode = $this->generateBillNo([
  1230. 'top_depart_id' => $user['top_depart_id'],
  1231. 'type' => MonthlyPwOrder::Order_type,
  1232. 'period' => date("Ym", $group['month'])
  1233. ]);
  1234. $mainId = DB::table('monthly_pw_order')->insertGetId([
  1235. 'code' => $newCode,
  1236. 'month' => $group['month'],
  1237. 'top_depart_id' => $user['top_depart_id'],
  1238. 'crt_id' => $user['id'],
  1239. 'crt_time' => $time,
  1240. 'upd_time' => $time,
  1241. 'del_time' => 0
  1242. ]);
  1243. }
  1244. // C. 批量插入详情
  1245. $insertDetails = [];
  1246. foreach ($group['details'] as $detail) {
  1247. $detail['main_id'] = $mainId;
  1248. $detail['top_depart_id']= $user['top_depart_id'];
  1249. $detail['crt_time'] = $time;
  1250. $detail['del_time'] = 0;
  1251. $insertDetails[] = $detail;
  1252. }
  1253. if (!empty($insertDetails)) {
  1254. DB::table('monthly_pw_order_details')->insert($insertDetails);
  1255. }
  1256. }
  1257. DB::commit();
  1258. } catch (\Exception $e) {
  1259. DB::rollBack();
  1260. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1261. }
  1262. return [true, ''];
  1263. }
  1264. private function monthPwOrderCheck(&$array, $user, $table_config)
  1265. {
  1266. $keys = array_column($table_config, 'key');
  1267. $codeIdx = array_search('code', $keys);
  1268. $monthIdx = array_search('month', $keys);
  1269. $empIdx = array_search('employee_id', $keys);
  1270. $numIdx = array_search('total_days', $keys);
  1271. $num2Idx = array_search('rd_total_days', $keys);
  1272. $num3Idx = array_search('total_hours', $keys);
  1273. $num4Idx = array_search('rd_total_hours', $keys);
  1274. $topDepartId = $user['top_depart_id'];
  1275. $errors = [];
  1276. // --- 1. 预处理月份与工号 ---
  1277. $allEmpNumbers = [];
  1278. $allMonthsTs = [];
  1279. foreach ($array as $rowIndex => $row) {
  1280. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1281. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1282. if (!$mStatus) {
  1283. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误";
  1284. continue;
  1285. }
  1286. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1287. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1288. $allMonthsTs[] = $valMonthTs;
  1289. if (!empty($row[$empIdx])) $allEmpNumbers[] = trim($row[$empIdx]);
  1290. }
  1291. if (!empty($errors)) return [implode('|', $errors), [], []];
  1292. $allMonthsTs = array_unique($allMonthsTs);
  1293. $allEmpNumbers = array_unique($allEmpNumbers);
  1294. //归档
  1295. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1296. if(! $status) return [$msg, [], []];
  1297. // --- 2. 批量预加载 ---
  1298. // A. 人员档案
  1299. $empModels = Employee::where('del_time', 0)->whereIn('number', $allEmpNumbers)
  1300. ->where('top_depart_id', $topDepartId)->get(['id', 'number', 'title'])->keyBy('number');
  1301. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  1302. // B. 系统考勤基准 (按月获取)
  1303. $systemStatsMap = [];
  1304. $service = new EmployeeService();
  1305. foreach ($allMonthsTs as $ts) {
  1306. list($sStatus, $stats) = $service->getEmployeesMonthStats(array_values($dbEmps), $ts, $user);
  1307. if (!$sStatus) {
  1308. $errors[] = "月份[" . date('Y-m', $ts) . "]:" . $stats;
  1309. continue;
  1310. }
  1311. $systemStatsMap[$ts] = $stats;
  1312. }
  1313. if (!empty($errors)) return [implode('|', $errors), [], []];
  1314. // C. 核心修正:单据查重(建立 月份 -> 单号 的映射,避免循环内查询)
  1315. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1316. // 1) 所有的 Excel 涉及月份在数据库中已有的单据映射
  1317. $existingMonthsMap = DB::table('monthly_pw_order')
  1318. ->where('top_depart_id', $topDepartId)
  1319. ->where('del_time', 0)
  1320. ->whereIn('month', $allMonthsTs)
  1321. ->pluck('code', 'month') // 注意:这里直接查出 month => code
  1322. ->toArray();
  1323. // 2) 用户填写的单据号对应的数据库记录
  1324. $dbOrdersByCode = DB::table('monthly_pw_order')
  1325. ->whereIn('code', $allCodes)
  1326. ->where('top_depart_id', $topDepartId)
  1327. ->where('del_time', 0)
  1328. ->get()
  1329. ->keyBy('code');
  1330. // --- 3. 业务逻辑全量检查 ---
  1331. $excelAggregator = [];
  1332. $update_map = [];
  1333. foreach ($array as $rowIndex => $row) {
  1334. $line = $rowIndex + 1;
  1335. $valCode = trim($row[$codeIdx] ?? '');
  1336. $valMonthTs = $row[$monthIdx];
  1337. $valEmpNum = trim($row[$empIdx] ?? '');
  1338. $monthStr = date('Y-m', $valMonthTs);
  1339. if (!isset($empModels[$valEmpNum])) {
  1340. $errors[] = "第{$line}行:工号[{$valEmpNum}]不存在";
  1341. continue;
  1342. }
  1343. $empId = $empModels[$valEmpNum]->id;
  1344. $empTitle = "[{$valEmpNum}]" . $empModels[$valEmpNum]->title;
  1345. // --- 核心修正:单据单号提示逻辑 ---
  1346. if ($valCode !== '') {
  1347. if (isset($dbOrdersByCode[$valCode])) {
  1348. if ($dbOrdersByCode[$valCode]->month != $valMonthTs) {
  1349. $errors[] = "第{$line}行:单据[{$valCode}]月份应为" . date('Y-m', $dbOrdersByCode[$valCode]->month) . ",请核实";
  1350. }
  1351. $update_map[$rowIndex] = $dbOrdersByCode[$valCode]->id;
  1352. } else {
  1353. $errors[] = "第{$line}行:填写的单据编号[{$valCode}]在系统中不存在";
  1354. }
  1355. } else {
  1356. // 如果没填单号,但该月已存在单据,从预加载的 existingMonthsMap 中获取正确单号
  1357. if (isset($existingMonthsMap[$valMonthTs])) {
  1358. $correctCode = $existingMonthsMap[$valMonthTs];
  1359. $errors[] = "第{$line}行:月份[{$monthStr}]已存在研发单,单号为:[{$correctCode}],请填写该单号进行编辑";
  1360. }
  1361. }
  1362. // --- 考勤上限校验 ---
  1363. $sysEmpData = $systemStatsMap[$valMonthTs][$empId] ?? null;
  1364. if ($sysEmpData) {
  1365. $inTotalDays = (float)($row[$numIdx] ?? 0);
  1366. $inRdDays = (float)($row[$num2Idx] ?? 0);
  1367. $inTotalHours= (float)($row[$num3Idx] ?? 0);
  1368. $inRdHours = (float)($row[$num4Idx] ?? 0);
  1369. // 使用误差范围比较,避免浮点数精度问题
  1370. if (abs($inTotalDays - $sysEmpData['attendance_days']) > 0.01) {
  1371. $errors[] = "第{$line}行:{$empTitle}出勤总天数({$inTotalDays})与核算({$sysEmpData['attendance_days']})不符";
  1372. }
  1373. if (abs($inTotalHours - $sysEmpData['final_work_hour']) > 0.01) {
  1374. $errors[] = "第{$line}行:{$empTitle}出勤总工时({$inTotalHours})与核算({$sysEmpData['final_work_hour']})不符";
  1375. }
  1376. if ($inRdDays > $inTotalDays + 0.01) $errors[] = "第{$line}行:{$empTitle}研发天数超过总天数";
  1377. if ($inRdHours > $inTotalHours + 0.01) $errors[] = "第{$line}行:{$empTitle}研发工时超过总工时";
  1378. }
  1379. if (isset($excelAggregator[$valCode ?: $valMonthTs]['emps'][$valEmpNum])) {
  1380. $errors[] = "第{$line}行:人员在同单据内重复";
  1381. }
  1382. $excelAggregator[$valCode ?: $valMonthTs]['emps'][$valEmpNum] = true;
  1383. }
  1384. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $dbEmps];
  1385. }
  1386. // 设备月度工时单
  1387. public function monthDwOrderImport($array, $user, $other_param)
  1388. {
  1389. $upload = $array[0];
  1390. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1391. if (!$status) return [false, $msg];
  1392. $table_config = $msg;
  1393. unset($array[0]);
  1394. if (empty($array)) return [false, '导入数据不能为空'];
  1395. list($array, $error) = $this->checkCommon($array, $table_config);
  1396. if (!empty($error)) return [0, $error];
  1397. // 2. 详细校验 (这里会返回 update_map 和 dbDevs 映射)
  1398. list($error, $update_map, $dbDevs) = $this->monthDwOrderCheck($array, $user, $table_config);
  1399. if (!empty($error)) return [0, $error];
  1400. $keys = array_column($table_config, 'key');
  1401. $codeIdx = array_search('code', $keys);
  1402. $monthIdx = array_search('month', $keys);
  1403. $empIdx = array_search('device_id', $keys);
  1404. // --- 步骤 1: 数据聚合分组 ---
  1405. // 将 Excel 数据按“单据”维度归类
  1406. $groups = [];
  1407. foreach ($array as $rowIndex => $row) {
  1408. $cCode = trim($row[$codeIdx] ?? '');
  1409. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1410. // 聚合 Key:有编码用编码,没编码用月份标记
  1411. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1412. if (!isset($groups[$aggKey])) {
  1413. $groups[$aggKey] = [
  1414. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1415. 'code' => $cCode,
  1416. 'month' => $cMonthTs,
  1417. 'details' => []
  1418. ];
  1419. }
  1420. // 准备详情行数据
  1421. $detailTmp = [];
  1422. foreach ($table_config as $k => $conf) {
  1423. if (!$conf['is_main']) {
  1424. $fieldKey = $conf['key'];
  1425. if ($fieldKey == 'device_title') continue;
  1426. $fieldVal = $row[$k];
  1427. // 如果是人员,转换为 ID
  1428. if ($fieldKey == 'device_id') {
  1429. $fieldVal = $dbDevs[$fieldVal] ?? 0;
  1430. }
  1431. $detailTmp[$fieldKey] = $fieldVal;
  1432. }
  1433. }
  1434. $groups[$aggKey]['details'][] = $detailTmp;
  1435. }
  1436. // --- 步骤 2: 开启事务写入 ---
  1437. DB::beginTransaction();
  1438. try {
  1439. $time = time();
  1440. foreach ($groups as $aggKey => $group) {
  1441. $mainId = $group['main_id'];
  1442. if ($mainId > 0) {
  1443. // 删除旧详情
  1444. DB::table('monthly_dw_order_details')->where('del_time',0)
  1445. ->where('main_id', $mainId)
  1446. ->update(['del_time' => $time]);
  1447. } else {
  1448. // B. 新增逻辑
  1449. $newCode = $this->generateBillNo([
  1450. 'top_depart_id' => $user['top_depart_id'],
  1451. 'type' => MonthlyPwOrder::Order_type,
  1452. 'period' => date("Ym", $group['month'])
  1453. ]);
  1454. $mainId = DB::table('monthly_dw_order')->insertGetId([
  1455. 'code' => $newCode,
  1456. 'month' => $group['month'],
  1457. 'top_depart_id' => $user['top_depart_id'],
  1458. 'crt_id' => $user['id'],
  1459. 'crt_time' => $time,
  1460. 'upd_time' => $time,
  1461. 'del_time' => 0
  1462. ]);
  1463. }
  1464. // C. 批量插入详情
  1465. $insertDetails = [];
  1466. foreach ($group['details'] as $detail) {
  1467. $detail['main_id'] = $mainId;
  1468. $detail['top_depart_id']= $user['top_depart_id'];
  1469. $detail['crt_time'] = $time;
  1470. $detail['del_time'] = 0;
  1471. $insertDetails[] = $detail;
  1472. }
  1473. if (!empty($insertDetails)) {
  1474. DB::table('monthly_dw_order_details')->insert($insertDetails);
  1475. }
  1476. }
  1477. DB::commit();
  1478. } catch (\Exception $e) {
  1479. DB::rollBack();
  1480. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1481. }
  1482. return [true, ''];
  1483. }
  1484. private function monthDwOrderCheck(&$array, $user, $table_config)
  1485. {
  1486. $keys = array_column($table_config, 'key');
  1487. $codeIdx = array_search('code', $keys);
  1488. $monthIdx = array_search('month', $keys);
  1489. $devIdx = array_search('device_id', $keys);
  1490. $numIdx = array_search('total_days', $keys);
  1491. $num2Idx = array_search('rd_total_days', $keys);
  1492. $num3Idx = array_search('total_hours', $keys);
  1493. $num4Idx = array_search('rd_total_hours', $keys);
  1494. $topDepartId = $user['top_depart_id'];
  1495. $errors = [];
  1496. // --- 1. 提取月份和资产编码 ---
  1497. $allDevCodes = [];
  1498. $allMonthsTs = [];
  1499. foreach ($array as $rowIndex => $row) {
  1500. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($row[$monthIdx] ?? '');
  1501. if (!$mStatus) {
  1502. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误";
  1503. continue;
  1504. }
  1505. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1506. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1507. $allMonthsTs[] = $valMonthTs;
  1508. if (!empty($row[$devIdx])) $allDevCodes[] = trim($row[$devIdx]);
  1509. }
  1510. if (!empty($errors)) return [implode('|', $errors), [], []];
  1511. $allMonthsTs = array_unique($allMonthsTs);
  1512. //归档
  1513. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1514. if(! $status) return [$msg, [], []];
  1515. // --- 2. 预加载档案与基准 ---
  1516. $devModels = Device::where('del_time', 0)
  1517. ->whereIn('code', $allDevCodes)
  1518. ->where('top_depart_id', $topDepartId)
  1519. ->get(['id', 'code', 'title'])
  1520. ->keyBy('code');
  1521. $dbDevs = $devModels->pluck('id', 'code')->toArray();
  1522. $systemStatsMap = [];
  1523. $allDeviceIds = array_values($dbDevs);
  1524. $service = new DeviceService();
  1525. foreach ($allMonthsTs as $ts) {
  1526. list($sStatus, $stats) = $service->getDevicesMonthStats($allDeviceIds, $ts, $user);
  1527. if (!$sStatus) {
  1528. $errors[] = "月份[" . date('Y-m', $ts) . "]解析失败:{$stats}";
  1529. $systemStatsMap[$ts] = null;
  1530. } else {
  1531. $systemStatsMap[$ts] = $stats;
  1532. }
  1533. }
  1534. // 如果基准获取有误(如日历未设),直接返回错误,不执行后续逻辑
  1535. if (!empty($errors)) return [implode('|', $errors), [], []];
  1536. // --- 3. 核心修正:单据查重与单号映射 (避免循环内查询) ---
  1537. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1538. // 获取该租户相关月份已存在的单据映射 (Month => Code)
  1539. $existingMonthsMap = DB::table('monthly_dw_order')
  1540. ->where('top_depart_id', $topDepartId)
  1541. ->where('del_time', 0)
  1542. ->whereIn('month', $allMonthsTs)
  1543. ->pluck('code', 'month')
  1544. ->toArray();
  1545. // 获取 Excel 中填写的单号对应的数据库记录 (Code => Object)
  1546. $dbOrdersByCode = DB::table('monthly_dw_order')
  1547. ->whereIn('code', $allCodes)
  1548. ->where('top_depart_id', $topDepartId)
  1549. ->where('del_time', 0)
  1550. ->get()
  1551. ->keyBy('code');
  1552. $excelAggregator = [];
  1553. $update_map = [];
  1554. // --- 4. 循环校验 ---
  1555. foreach ($array as $rowIndex => $row) {
  1556. $line = $rowIndex + 1;
  1557. $valMonthTs = $row[$monthIdx];
  1558. $monthStr = date('Y-m', $valMonthTs);
  1559. $valDevCode = trim($row[$devIdx] ?? '');
  1560. $valCode = trim($row[$codeIdx] ?? '');
  1561. // A. 设备档案检查
  1562. if (!isset($devModels[$valDevCode])) {
  1563. $errors[] = "第{$line}行:设备编码[{$valDevCode}]不存在";
  1564. continue;
  1565. }
  1566. $deviceId = $devModels[$valDevCode]->id;
  1567. $devTitle = "[{$valDevCode}]" . $devModels[$valDevCode]->title;
  1568. // B. 单据号存在性与意图校验
  1569. if ($valCode !== '') {
  1570. // 意图:编辑已存在的单据
  1571. if (isset($dbOrdersByCode[$valCode])) {
  1572. $dbOrder = $dbOrdersByCode[$valCode];
  1573. if ($dbOrder->month != $valMonthTs) {
  1574. $errors[] = "第{$line}行:单据[{$valCode}]所属月份为" . date('Y-m', $dbOrder->month) . ",与当前月份不符";
  1575. }
  1576. $update_map[$rowIndex] = $dbOrder->id;
  1577. } else {
  1578. // 填了单号但库里没有
  1579. $errors[] = "第{$line}行:单据编号[{$valCode}]无效或不存在";
  1580. }
  1581. } else {
  1582. // 意图:新增。校验是否该月已有单据
  1583. if (isset($existingMonthsMap[$valMonthTs])) {
  1584. $correctCode = $existingMonthsMap[$valMonthTs];
  1585. $errors[] = "第{$line}行:月份[{$monthStr}]已存在研发单,单号为:[{$correctCode}],请填写该单号进行更新";
  1586. }
  1587. }
  1588. // C. 考勤基准对比
  1589. $sysData = $systemStatsMap[$valMonthTs][$deviceId] ?? null;
  1590. if ($sysData) {
  1591. $inTotalDays = (float)($row[$numIdx] ?? 0);
  1592. $inRdDays = (float)($row[$num2Idx] ?? 0);
  1593. $inTotalHours= (float)($row[$num3Idx] ?? 0);
  1594. $inRdHours = (float)($row[$num4Idx] ?? 0);
  1595. // 1. 内部逻辑:研发 <= 总额
  1596. if ($inRdDays > $inTotalDays + 0.01) $errors[] = "第{$line}行:{$devTitle}研发天数大于总天数";
  1597. if ($inRdHours > $inTotalHours + 0.01) $errors[] = "第{$line}行:{$devTitle}研发工时大于总工时";
  1598. // 2. 外部逻辑:总额 == 系统核算
  1599. if (abs($inTotalDays - $sysData['attendance_days']) > 0.01) {
  1600. $errors[] = "第{$line}行:{$devTitle}总天数({$inTotalDays})不等于系统核算({$sysData['attendance_days']})";
  1601. }
  1602. if (abs($inTotalHours - $sysData['final_work_hour']) > 0.01) {
  1603. $errors[] = "第{$line}行:{$devTitle}总工时({$inTotalHours})不等于系统核算({$sysData['final_work_hour']})";
  1604. }
  1605. }
  1606. // D. 组内查重 (单号或月份作为聚合维度)
  1607. $aggKey = $valCode ?: "NEW_" . $valMonthTs;
  1608. if (isset($excelAggregator[$aggKey]['devs'][$valDevCode])) {
  1609. $errors[] = "第{$line}行:资产编码[{$valDevCode}]在同单据中重复";
  1610. }
  1611. $excelAggregator[$aggKey]['devs'][$valDevCode] = true;
  1612. }
  1613. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1614. return [$error_string, $update_map, $dbDevs];
  1615. }
  1616. // 人员月度工资单
  1617. public function monthPsOrderImport($array, $user, $other_param)
  1618. {
  1619. $upload = $array[0];
  1620. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1621. if (!$status) return [false, $msg];
  1622. $table_config = $msg;
  1623. unset($array[0]);
  1624. if (empty($array)) return [false, '导入数据不能为空'];
  1625. list($array, $error) = $this->checkCommon($array, $table_config);
  1626. if (!empty($error)) return [0, $error];
  1627. // 2. 详细校验 (这里会返回 update_map 和 dbEmps 映射)
  1628. list($error, $update_map, $dbEmps) = $this->monthPsOrderCheck($array, $user, $table_config);
  1629. if (!empty($error)) return [0, $error];
  1630. $keys = array_column($table_config, 'key');
  1631. $codeIdx = array_search('code', $keys);
  1632. $monthIdx = array_search('month', $keys);
  1633. $empIdx = array_search('employee_id', $keys);
  1634. // --- 步骤 1: 数据聚合分组 ---
  1635. // 将 Excel 数据按“单据”维度归类
  1636. $groups = [];
  1637. foreach ($array as $rowIndex => $row) {
  1638. $cCode = trim($row[$codeIdx] ?? '');
  1639. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1640. // 聚合 Key:有编码用编码,没编码用月份标记
  1641. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1642. if (!isset($groups[$aggKey])) {
  1643. $groups[$aggKey] = [
  1644. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1645. 'code' => $cCode,
  1646. 'month' => $cMonthTs,
  1647. 'details' => []
  1648. ];
  1649. }
  1650. // 准备详情行数据
  1651. $detailTmp = [];
  1652. foreach ($table_config as $k => $conf) {
  1653. if (!$conf['is_main']) {
  1654. $fieldKey = $conf['key'];
  1655. if ($fieldKey == 'employee_title') continue;
  1656. $fieldVal = $row[$k];
  1657. // 如果是人员,转换为 ID
  1658. if ($fieldKey == 'employee_id') {
  1659. $fieldVal = $dbEmps[$fieldVal] ?? 0;
  1660. }
  1661. $detailTmp[$fieldKey] = $fieldVal;
  1662. }
  1663. }
  1664. $groups[$aggKey]['details'][] = $detailTmp;
  1665. }
  1666. // --- 步骤 2: 开启事务写入 ---
  1667. DB::beginTransaction();
  1668. try {
  1669. $time = time();
  1670. foreach ($groups as $aggKey => $group) {
  1671. $mainId = $group['main_id'];
  1672. if ($mainId > 0) {
  1673. // 删除旧详情
  1674. DB::table('monthly_ps_order_details')->where('del_time',0)
  1675. ->where('main_id', $mainId)
  1676. ->update(['del_time' => $time]);
  1677. } else {
  1678. // B. 新增逻辑
  1679. $newCode = $this->generateBillNo([
  1680. 'top_depart_id' => $user['top_depart_id'],
  1681. 'type' => MonthlyPsOrder::Order_type,
  1682. 'period' => date("Ym", $group['month'])
  1683. ]);
  1684. $mainId = DB::table('monthly_ps_order')->insertGetId([
  1685. 'code' => $newCode,
  1686. 'month' => $group['month'],
  1687. 'top_depart_id' => $user['top_depart_id'],
  1688. 'crt_id' => $user['id'],
  1689. 'crt_time' => $time,
  1690. 'upd_time' => $time,
  1691. 'del_time' => 0
  1692. ]);
  1693. }
  1694. // C. 批量插入详情
  1695. $insertDetails = [];
  1696. foreach ($group['details'] as $detail) {
  1697. $detail['main_id'] = $mainId;
  1698. $detail['top_depart_id']= $user['top_depart_id'];
  1699. $detail['crt_time'] = $time;
  1700. $detail['del_time'] = 0;
  1701. $insertDetails[] = $detail;
  1702. }
  1703. if (!empty($insertDetails)) {
  1704. DB::table('monthly_ps_order_details')->insert($insertDetails);
  1705. }
  1706. }
  1707. DB::commit();
  1708. } catch (\Exception $e) {
  1709. DB::rollBack();
  1710. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1711. }
  1712. return [true, ''];
  1713. }
  1714. private function monthPsOrderCheck(&$array, $user, $table_config)
  1715. {
  1716. $keys = array_column($table_config, 'key');
  1717. $codeIdx = array_search('code', $keys);
  1718. $monthIdx = array_search('month', $keys);
  1719. $empIdx = array_search('employee_id', $keys);
  1720. $numIdx = array_search('base_salary', $keys);
  1721. $num2Idx = array_search('social_insurance', $keys);
  1722. $num3Idx = array_search('public_housing_fund', $keys);
  1723. $num4Idx = array_search('performance_salary', $keys);
  1724. $num5Idx = array_search('bonus', $keys);
  1725. $num6Idx = array_search('other', $keys);
  1726. // 1. 预加载基础数据
  1727. $allEmpNumbers = array_filter(array_unique(array_column($array, $empIdx)));
  1728. $dbEmps = Employee::where('del_time', 0)
  1729. ->whereIn('number', $allEmpNumbers)
  1730. ->where('top_depart_id', $user['top_depart_id'])
  1731. ->pluck('id', 'number')->toArray();
  1732. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1733. $dbOrders = DB::table('monthly_ps_order')
  1734. ->whereIn('code', $allCodes)
  1735. ->where('top_depart_id', $user['top_depart_id'])
  1736. ->where('del_time', 0) // 必须确保没删除
  1737. ->get()->keyBy('code');
  1738. $errors = [];
  1739. $uniqueMonths = [];
  1740. // --- 步骤 1:月份标准化预处理 ---
  1741. foreach ($array as $rowIndex => $row) {
  1742. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1743. if ($valMonthRaw === '') continue;
  1744. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1745. if (!$mStatus) {
  1746. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  1747. continue;
  1748. }
  1749. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1750. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1751. $uniqueMonths[] = $valMonthTs;
  1752. }
  1753. if (!empty($errors)) return [implode('|', $errors), [], []];
  1754. $allMonthsTs = array_unique($uniqueMonths);
  1755. //归档
  1756. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1757. if(! $status) return [$msg, [], []];
  1758. // 查询数据库中已存在的月份单据
  1759. $existingMonths = DB::table('monthly_ps_order')
  1760. ->where('top_depart_id', $user['top_depart_id'])
  1761. ->where('del_time', 0)
  1762. ->whereIn('month', $allMonthsTs)
  1763. ->pluck('month')
  1764. ->toArray();
  1765. $existingMonthsMap = array_fill_keys($existingMonths, true);
  1766. $excelAggregator = [];
  1767. $update_map = [];
  1768. $monthToKeyMap = []; // 校验 Excel 内部月份是否冲突
  1769. // --- 步骤 2:全量业务校验 ---
  1770. foreach ($array as $rowIndex => $row) {
  1771. $displayLine = $rowIndex + 1;
  1772. $valCode = trim($row[$codeIdx] ?? '');
  1773. $valMonthTs = $row[$monthIdx] ?? '';
  1774. $valEmp = trim($row[$empIdx] ?? '');
  1775. if (!is_numeric($valMonthTs)) continue;
  1776. // 确定单据组 AggKey
  1777. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  1778. // A. 校验单据存在性 & 匹配 ID
  1779. if ($valCode) {
  1780. if (isset($dbOrders[$valCode])) {
  1781. $dbOrder = $dbOrders[$valCode];
  1782. if ($dbOrder->month != $valMonthTs) {
  1783. $errors[] = "第{$displayLine}行:单据编码[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入月份不符";
  1784. }
  1785. $update_map[$rowIndex] = $dbOrder->id;
  1786. }
  1787. // 乱填编码的情况,不会进 update_map,将由下方的查重逻辑拦截
  1788. }
  1789. // B. 【核心修正】月份唯一单据校验
  1790. // 如果系统最终认为这行是“新增”,则必须检查该月份是否已有数据
  1791. if (!isset($update_map[$rowIndex])) {
  1792. if (isset($existingMonthsMap[$valMonthTs])) {
  1793. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]已存在单据,请填写正确的单据编码进行编辑";
  1794. }
  1795. }
  1796. // C. Excel 内部逻辑一致性
  1797. if (!isset($monthToKeyMap[$valMonthTs])) {
  1798. $monthToKeyMap[$valMonthTs] = $aggKey;
  1799. } elseif ($monthToKeyMap[$valMonthTs] !== $aggKey) {
  1800. $errors[] = "第{$displayLine}行:同一个月份[" . date('Y-m', $valMonthTs) . "]在 Excel 中指向了不同的单据组";
  1801. }
  1802. // D. 人员校验与单据内查重
  1803. if (!isset($dbEmps[$valEmp])) {
  1804. $errors[] = "第{$displayLine}行:人员工号[{$valEmp}]不存在";
  1805. } else {
  1806. if (isset($excelAggregator[$aggKey]['emps'][$valEmp])) {
  1807. $errors[] = "第{$displayLine}行:人员[{$valEmp}]在同一单据中重复";
  1808. }
  1809. $excelAggregator[$aggKey]['emps'][$valEmp] = true;
  1810. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  1811. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  1812. }
  1813. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  1814. }
  1815. // E. 数字格式校验
  1816. $numChecks = [
  1817. $numIdx => '基本工资',
  1818. $num2Idx => '社保',
  1819. $num3Idx => '公积金',
  1820. $num4Idx => '绩效工资',
  1821. $num5Idx => '奖金',
  1822. $num6Idx => '其他',
  1823. ];
  1824. foreach ($numChecks as $idx => $label) {
  1825. $res = $this->checkNumber($row[$idx] ?? 0, 2, 'non-negative');
  1826. if (!$res['valid']) $errors[] = "第{$displayLine}行{$label}:" . $res['error'];
  1827. }
  1828. }
  1829. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1830. return [$error_string, $update_map, $dbEmps];
  1831. }
  1832. // 设备月度折旧单
  1833. public function monthDdOrderImport($array, $user, $other_param)
  1834. {
  1835. $upload = $array[0];
  1836. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1837. if (!$status) return [false, $msg];
  1838. $table_config = $msg;
  1839. unset($array[0]);
  1840. if (empty($array)) return [false, '导入数据不能为空'];
  1841. list($array, $error) = $this->checkCommon($array, $table_config);
  1842. if (!empty($error)) return [0, $error];
  1843. // 2. 详细校验 (这里会返回 update_map 和 dbDevs 映射)
  1844. list($error, $update_map, $dbDevs) = $this->monthDdOrderCheck($array, $user, $table_config);
  1845. if (!empty($error)) return [0, $error];
  1846. $keys = array_column($table_config, 'key');
  1847. $codeIdx = array_search('code', $keys);
  1848. $monthIdx = array_search('month', $keys);
  1849. $empIdx = array_search('device_id', $keys);
  1850. // --- 步骤 1: 数据聚合分组 ---
  1851. // 将 Excel 数据按“单据”维度归类
  1852. $groups = [];
  1853. foreach ($array as $rowIndex => $row) {
  1854. $cCode = trim($row[$codeIdx] ?? '');
  1855. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1856. // 聚合 Key:有编码用编码,没编码用月份标记
  1857. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1858. if (!isset($groups[$aggKey])) {
  1859. $groups[$aggKey] = [
  1860. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1861. 'code' => $cCode,
  1862. 'month' => $cMonthTs,
  1863. 'details' => []
  1864. ];
  1865. }
  1866. // 准备详情行数据
  1867. $detailTmp = [];
  1868. foreach ($table_config as $k => $conf) {
  1869. if (!$conf['is_main']) {
  1870. $fieldKey = $conf['key'];
  1871. if ($fieldKey == 'device_title') continue;
  1872. $fieldVal = $row[$k];
  1873. // 如果是人员,转换为 ID
  1874. if ($fieldKey == 'device_id') {
  1875. $fieldVal = $dbDevs[$fieldVal] ?? 0;
  1876. }
  1877. $detailTmp[$fieldKey] = $fieldVal;
  1878. }
  1879. }
  1880. $groups[$aggKey]['details'][] = $detailTmp;
  1881. }
  1882. // --- 步骤 2: 开启事务写入 ---
  1883. DB::beginTransaction();
  1884. try {
  1885. $time = time();
  1886. $id = [];
  1887. foreach ($groups as $aggKey => $group) {
  1888. $mainId = $group['main_id'];
  1889. if ($mainId > 0) {
  1890. // 删除旧详情
  1891. DB::table('monthly_dd_order_details')->where('del_time',0)
  1892. ->where('main_id', $mainId)
  1893. ->update(['del_time' => $time]);
  1894. } else {
  1895. // B. 新增逻辑
  1896. $newCode = $this->generateBillNo([
  1897. 'top_depart_id' => $user['top_depart_id'],
  1898. 'type' => MonthlyDdOrder::Order_type,
  1899. 'period' => date("Ym", $group['month'])
  1900. ]);
  1901. $mainId = DB::table('monthly_dd_order')->insertGetId([
  1902. 'code' => $newCode,
  1903. 'month' => $group['month'],
  1904. 'top_depart_id' => $user['top_depart_id'],
  1905. 'crt_id' => $user['id'],
  1906. 'crt_time' => $time,
  1907. 'upd_time' => $time,
  1908. 'del_time' => 0
  1909. ]);
  1910. }
  1911. // C. 批量插入详情
  1912. $insertDetails = [];
  1913. foreach ($group['details'] as $detail) {
  1914. $detail['main_id'] = $mainId;
  1915. $detail['top_depart_id']= $user['top_depart_id'];
  1916. $detail['crt_time'] = $time;
  1917. $detail['del_time'] = 0;
  1918. $insertDetails[] = $detail;
  1919. }
  1920. if(! in_array($mainId, $id)) $id[] = $mainId;
  1921. if (!empty($insertDetails)) {
  1922. DB::table('monthly_dd_order_details')->insert($insertDetails);
  1923. }
  1924. }
  1925. DB::commit();
  1926. //触发折旧计算
  1927. (new DeviceDepreciationService())->triggerJob($id);
  1928. } catch (\Exception $e) {
  1929. DB::rollBack();
  1930. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1931. }
  1932. return [true, ''];
  1933. }
  1934. private function monthDdOrderCheck(&$array, $user, $table_config)
  1935. {
  1936. $keys = array_column($table_config, 'key');
  1937. $codeIdx = array_search('code', $keys);
  1938. $monthIdx = array_search('month', $keys);
  1939. $devIdx = array_search('device_id', $keys);
  1940. $numIdx = array_search('depreciation_amount', $keys);
  1941. // 1. 预加载基础数据
  1942. $allDevNumbers = array_filter(array_unique(array_column($array, $devIdx)));
  1943. $dbDevs = Device::where('del_time', 0)
  1944. ->whereIn('code', $allDevNumbers)
  1945. ->where('top_depart_id', $user['top_depart_id'])
  1946. ->pluck('id', 'code')->toArray();
  1947. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1948. $dbOrders = DB::table('monthly_dd_order')
  1949. ->whereIn('code', $allCodes)
  1950. ->where('top_depart_id', $user['top_depart_id'])
  1951. ->where('del_time', 0)
  1952. ->get()->keyBy('code');
  1953. $errors = [];
  1954. $uniqueMonths = [];
  1955. // --- 步骤 1:月份标准化 ---
  1956. foreach ($array as $rowIndex => $row) {
  1957. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1958. if ($valMonthRaw === '') continue;
  1959. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1960. if (!$mStatus) {
  1961. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  1962. continue;
  1963. }
  1964. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1965. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1966. $uniqueMonths[] = $valMonthTs;
  1967. }
  1968. if (!empty($errors)) return [implode('|', $errors), [], []];
  1969. $allMonthsTs = array_unique($uniqueMonths);
  1970. //归档
  1971. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  1972. if(! $status) return [$msg, [], []];
  1973. // 预查数据库已存在的月份
  1974. $existingMonths = DB::table('monthly_dd_order')
  1975. ->where('top_depart_id', $user['top_depart_id'])
  1976. ->where('del_time', 0)
  1977. ->whereIn('month', $allMonthsTs)
  1978. ->pluck('month')
  1979. ->toArray();
  1980. $existingMonthsMap = array_fill_keys($existingMonths, true);
  1981. $excelAggregator = [];
  1982. $update_map = [];
  1983. $monthToKeyMap = []; // 校验同一月份在 Excel 内部是否产生了多个单据组
  1984. // --- 步骤 2:全量校验 ---
  1985. foreach ($array as $rowIndex => $row) {
  1986. $displayLine = $rowIndex + 1;
  1987. $valCode = trim($row[$codeIdx] ?? '');
  1988. $valMonthTs = $row[$monthIdx] ?? '';
  1989. $valDev = trim($row[$devIdx] ?? '');
  1990. $valNumRaw = $row[$numIdx] ?? 0;
  1991. if (!is_numeric($valMonthTs)) continue;
  1992. // 确定单据聚合 Key
  1993. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  1994. // A. 匹配更新 ID
  1995. if ($valCode) {
  1996. if (isset($dbOrders[$valCode])) {
  1997. $dbOrder = $dbOrders[$valCode];
  1998. if ($dbOrder->month != $valMonthTs) {
  1999. $errors[] = "第{$displayLine}行:单据[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入不符";
  2000. }
  2001. $update_map[$rowIndex] = $dbOrder->id;
  2002. }
  2003. // 乱填编码的情况不进 update_map,将被视为“新增”由下方逻辑拦截
  2004. }
  2005. // B. 【核心修正】月份唯一性拦截
  2006. // 只要不是更新已有单据,且月份已存在,就报错
  2007. if (!isset($update_map[$rowIndex])) {
  2008. if (isset($existingMonthsMap[$valMonthTs])) {
  2009. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]已存在折旧单,请填正确编码编辑";
  2010. }
  2011. }
  2012. // C. Excel 内部逻辑一致性
  2013. if (!isset($monthToKeyMap[$valMonthTs])) {
  2014. $monthToKeyMap[$valMonthTs] = $aggKey;
  2015. } elseif ($monthToKeyMap[$valMonthTs] !== $aggKey) {
  2016. $errors[] = "第{$displayLine}行:同月份[" . date('Y-m', $valMonthTs) . "]存在多组单据定义";
  2017. }
  2018. // D. 设备校验
  2019. if (!isset($dbDevs[$valDev])) {
  2020. $errors[] = "第{$displayLine}行:资产编码[{$valDev}]不存在";
  2021. } else {
  2022. if (isset($excelAggregator[$aggKey]['devs'][$valDev])) {
  2023. $errors[] = "第{$displayLine}行:资产编码[{$valDev}]在同单据中重复";
  2024. }
  2025. $excelAggregator[$aggKey]['devs'][$valDev] = true;
  2026. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  2027. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  2028. }
  2029. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  2030. }
  2031. // E. 数字校验
  2032. $res = $this->checkNumber($valNumRaw, 2, 'non-negative');
  2033. if (!$res['valid']) {
  2034. $errors[] = "第{$displayLine}行月折旧额:" . $res['error'];
  2035. }
  2036. }
  2037. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2038. return [$error_string, $update_map, $dbDevs];
  2039. }
  2040. // 规则配置单
  2041. public function ruleSetImport($array, $user, $other_param){
  2042. $upload = $array[0];
  2043. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2044. if (!$status) return [false, $msg];
  2045. $table_config = $msg;
  2046. unset($array[0]);
  2047. if (empty($array)) return [false, '导入数据不能为空'];
  2048. list($array, $error) = $this->checkCommon($array, $table_config);
  2049. if (!empty($error)) return [0, $error];
  2050. // 2. 详细校验
  2051. list($error, $update_map, $dbDevs) = $this->ruleSetCheck($array, $user, $table_config);
  2052. if (!empty($error)) return [0, $error];
  2053. $keys = array_column($table_config, 'key');
  2054. $codeIdx = array_search('code', $keys);
  2055. $monthIdx = array_search('month', $keys);
  2056. $rateIdx = array_search('rate', $keys);
  2057. $groups = [];
  2058. foreach ($array as $rowIndex => $row) {
  2059. $mCode = trim($row[$codeIdx] ?? '');
  2060. $month = $row[$monthIdx];
  2061. $aggKey = $mCode ?: "NEW_" . $month;
  2062. if (!isset($groups[$aggKey])) {
  2063. $groups[$aggKey] = [
  2064. 'id' => $update_map[$rowIndex] ?? 0,
  2065. 'month' => $month,
  2066. 'details' => []
  2067. ];
  2068. }
  2069. $groups[$aggKey]['details'][] = [
  2070. 'item_id' => $row['parsed_item_id'],
  2071. 'data_id' => $row['parsed_data_id'],
  2072. 'type' => $row['parsed_type'],
  2073. 'rate' => $row[$rateIdx],
  2074. ];
  2075. }
  2076. $time = time();
  2077. DB::beginTransaction();
  2078. try {
  2079. foreach ($groups as $group) {
  2080. $mainId = $group['id'];
  2081. if ($mainId) {
  2082. DB::table('rule_set_details')
  2083. ->where('del_time',0)
  2084. ->where('main_id', $mainId)->update(['del_time' => $time]);
  2085. } else {
  2086. $newCode = $this->generateBillNo([
  2087. 'top_depart_id' => $user['top_depart_id'],
  2088. 'type' => RuleSet::Order_type,
  2089. 'period' => date("Ym", $group['month'])
  2090. ]);
  2091. $mainId = DB::table('rule_set')->insertGetId([
  2092. 'code' => $newCode,
  2093. 'month' => $group['month'],
  2094. 'top_depart_id' => $user['top_depart_id'],
  2095. 'crt_id' => $user['id'],
  2096. 'crt_time' => $time
  2097. ]);
  2098. }
  2099. foreach ($group['details'] as &$d) {
  2100. $d['main_id'] = $mainId;
  2101. $d['top_depart_id'] = $user['top_depart_id'];
  2102. $d['crt_time'] = $time;
  2103. }
  2104. DB::table('rule_set_details')->insert($group['details']);
  2105. }
  2106. DB::commit();
  2107. } catch (\Exception $e) {
  2108. DB::rollBack();
  2109. return [false, "失败: " . $e->getMessage()];
  2110. }
  2111. return [true, ''];
  2112. }
  2113. private function ruleSetCheck(&$array, $user, $table_config)
  2114. {
  2115. $keys = array_column($table_config, 'key');
  2116. // 1. 索引提取
  2117. $mCodeIdx = array_search('code', $keys);
  2118. $monthIdx = array_search('month', $keys);
  2119. $typeIdx = array_search('type', $keys);
  2120. $dCodeIdx = array_search('code_2', $keys);
  2121. $itemIdIdx = array_search('item_id', $keys);
  2122. $rateIdx = array_search('rate', $keys);
  2123. $uniqueMonths = [];
  2124. $empCodes = [];
  2125. $devCodes = [];
  2126. $itemCodes = [];
  2127. $type_map = array_flip(RuleSetDetails::$type_name);
  2128. // --- 步骤 1: 预处理扫描 ---
  2129. foreach ($array as $rowIndex => $row) {
  2130. $valMonthRaw = trim($row[$monthIdx] ?? '');
  2131. if ($valMonthRaw === '') continue;
  2132. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  2133. if (!$mStatus) {
  2134. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  2135. continue;
  2136. }
  2137. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  2138. $array[$rowIndex][$monthIdx] = $valMonthTs;
  2139. $uniqueMonths[] = $valMonthTs;
  2140. $type = $type_map[$row[$typeIdx] ?? ''] ?? 0;
  2141. $dCode = trim($row[$dCodeIdx] ?? '');
  2142. $iCode = trim($row[$itemIdIdx] ?? '');
  2143. if ($type == RuleSetDetails::type_one && $dCode !== '') $empCodes[] = $dCode;
  2144. if ($type == RuleSetDetails::type_two && $dCode !== '') $devCodes[] = $dCode;
  2145. if ($iCode !== '') $itemCodes[] = $iCode;
  2146. }
  2147. if (!empty($errors)) return [implode('|', $errors), [], []];
  2148. $allMonthsTs = array_unique($uniqueMonths);
  2149. //归档
  2150. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  2151. if(! $status) return [$msg, [], []];
  2152. // --- 步骤 2: 批量预加载 ---
  2153. $dbEmps = Employee::where('del_time', 0)->where('top_depart_id', $user['top_depart_id'])
  2154. ->whereIn('number', array_unique($empCodes))->pluck('id', 'number')->toArray();
  2155. $dbDevs = Device::where('del_time', 0)->where('top_depart_id', $user['top_depart_id'])
  2156. ->whereIn('code', array_unique($devCodes))->pluck('id', 'code')->toArray();
  2157. $dbItems = Item::where('del_time', 0)->where('top_depart_id', $user['top_depart_id'])
  2158. ->whereIn('code', array_unique($itemCodes))->pluck('id', 'code')->toArray();
  2159. $allMCodes = array_filter(array_unique(array_column($array, $mCodeIdx)));
  2160. $dbOrders = DB::table('rule_set')->where('top_depart_id', $user['top_depart_id'])
  2161. ->where('del_time', 0)->whereIn('code', $allMCodes)->get()->keyBy('code');
  2162. $existingMonthsMap = DB::table('rule_set')->where('top_depart_id', $user['top_depart_id'])
  2163. ->where('del_time', 0)->whereIn('month', array_unique($uniqueMonths))->pluck('id', 'month')->toArray();
  2164. $errors = [];
  2165. $update_map = [];
  2166. $aggregator = [];
  2167. $uniqueCheck = [];
  2168. $monthToKeyMap = []; // 校验 Excel 内部月份与单号组的唯一性
  2169. // --- 步骤 3: 详细校验循环 ---
  2170. foreach ($array as $rowIndex => $row) {
  2171. $displayLine = $rowIndex + 1;
  2172. $valMCode = trim($row[$mCodeIdx] ?? '');
  2173. $valMonthTs = $row[$monthIdx] ?? '';
  2174. $typeTitle = trim($row[$typeIdx] ?? '');
  2175. $type = $type_map[$typeTitle] ?? 0;
  2176. $valDCode = trim($row[$dCodeIdx] ?? '');
  2177. $valICode = trim($row[$itemIdIdx] ?? '');
  2178. $valRate = $row[$rateIdx] ?? 0;
  2179. // A. 编辑/新增逻辑判定 (核心修正)
  2180. if ($valMCode !== '' && isset($dbOrders[$valMCode])) {
  2181. $dbOrder = $dbOrders[$valMCode];
  2182. if ($dbOrder->month != $valMonthTs) {
  2183. $errors[] = "第{$displayLine}行:单号[{$valMCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],不允许修改";
  2184. }
  2185. $update_map[$rowIndex] = $dbOrder->id;
  2186. }
  2187. // 月份唯一性拦截:只要没进入 update_map (无论是乱填单号还是没填),就查重
  2188. if (!isset($update_map[$rowIndex])) {
  2189. if (isset($existingMonthsMap[$valMonthTs])) {
  2190. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]已存在单据,请填写正确的单号编辑";
  2191. }
  2192. }
  2193. // B. Excel 内部一致性拦截
  2194. $aggKey = $valMCode ?: "NEW_ORDER_" . $valMonthTs;
  2195. if (!isset($monthToKeyMap[$valMonthTs])) {
  2196. $monthToKeyMap[$valMonthTs] = $aggKey;
  2197. } elseif ($monthToKeyMap[$valMonthTs] !== $aggKey) {
  2198. $errors[] = "第{$displayLine}行:月份[" . date('Y-m', $valMonthTs) . "]在表格中对应了不同的单据编号,请确保同一月份的单号一致";
  2199. }
  2200. // C. 人员/设备/项目存在性校验
  2201. $dataId = 0;
  2202. if ($type == RuleSetDetails::type_one) {
  2203. $dataId = $dbEmps[$valDCode] ?? 0;
  2204. if (!$dataId) $errors[] = "第{$displayLine}行:工号[{$valDCode}]不存在";
  2205. } elseif ($type == RuleSetDetails::type_two) {
  2206. $dataId = $dbDevs[$valDCode] ?? 0;
  2207. if (!$dataId) $errors[] = "第{$displayLine}行:资产编码[{$valDCode}]不存在";
  2208. } else {
  2209. $errors[] = "第{$displayLine}行:明细类型[{$typeTitle}]非法";
  2210. }
  2211. $itemId = $dbItems[$valICode] ?? 0;
  2212. if (!$itemId) $errors[] = "第{$displayLine}行:项目编码[{$valICode}]不存在";
  2213. // D. 比例与唯一性聚合
  2214. if ($dataId && $itemId) {
  2215. // 同一单据+项目内 人/设备唯一
  2216. $rowUniqueKey = $aggKey . '_' . $itemId . '_' . $type . '_' . $dataId;
  2217. if (isset($uniqueCheck[$rowUniqueKey])) {
  2218. $errors[] = "第{$displayLine}行:项目[{$valICode}]下[{$valDCode}]重复录入";
  2219. }
  2220. $uniqueCheck[$rowUniqueKey] = true;
  2221. // 比例和校验聚合
  2222. $totalRateKey = $aggKey . '_' . $type . '_' . $dataId;
  2223. $aggregator[$totalRateKey]['total_rate'] = ($aggregator[$totalRateKey]['total_rate'] ?? 0) + $valRate;
  2224. $aggregator[$totalRateKey]['title'] = $valDCode;
  2225. $aggregator[$totalRateKey]['type_name'] = $typeTitle;
  2226. $aggregator[$totalRateKey]['month_str'] = date('Y-m', $valMonthTs);
  2227. }
  2228. $array[$rowIndex]['parsed_data_id'] = $dataId;
  2229. $array[$rowIndex]['parsed_item_id'] = $itemId;
  2230. $array[$rowIndex]['parsed_type'] = $type;
  2231. }
  2232. // --- 步骤 4: 比例汇总校验 ---
  2233. foreach ($aggregator as $key => $info) {
  2234. if (abs($info['total_rate'] - 100) > 0.0001) {
  2235. $errors[] = "汇总错误:月份[{$info['month_str']}]下,{$info['type_name']}[{$info['title']}]的总分摊比例为 {$info['total_rate']}%,不等于 100%";
  2236. }
  2237. }
  2238. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2239. return [$error_string, $update_map, $dbItems];
  2240. }
  2241. // 人员日工时单 ------------------------------
  2242. public function dailyPwOrderImport($array, $user, $other_param)
  2243. {
  2244. $upload = $array[0];
  2245. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2246. if (!$status) return [false, $msg];
  2247. $table_config = $msg;
  2248. unset($array[0]);
  2249. if (empty($array)) return [false, '导入数据不能为空'];
  2250. // 1. 基础格式检查
  2251. list($array, $error) = $this->checkCommon($array, $table_config);
  2252. if (!empty($error)) return [0, $error];
  2253. // 2. 详细业务校验 (返回 update_map, 人员映射, 项目映射)
  2254. list($error, $update_map, $dbEmps, $dbItems) = $this->dailyPwOrderCheck($array, $user, $table_config);
  2255. if (!empty($error)) return [0, $error];
  2256. $keys = array_column($table_config, 'key');
  2257. $codeIdx = array_search('code', $keys);
  2258. $timeIdx = array_search('order_time', $keys);
  2259. $itemIdx = array_search('item_id', $keys);
  2260. $empIdx = array_search('employee_id', $keys);
  2261. $startIdx = array_search('start_time', $keys);
  2262. $endIdx = array_search('end_time', $keys);
  2263. // 3. 数据聚合分组
  2264. $groups = [];
  2265. foreach ($array as $rowIndex => $row) {
  2266. $cCode = trim($row[$codeIdx] ?? '');
  2267. $cTimeTs = $row[$timeIdx];
  2268. $cItemCode = trim($row[$itemIdx] ?? '');
  2269. $cItemId = $dbItems[$cItemCode] ?? 0;
  2270. // 聚合 Key:如果是更新则按主表ID聚类;如果是新增则按 日期+项目 聚类
  2271. $aggKey = ($update_map[$rowIndex] ?? 0) > 0
  2272. ? "UPDATE_" . $update_map[$rowIndex]
  2273. : "NEW_" . $cTimeTs . "_" . $cItemId;
  2274. if (!isset($groups[$aggKey])) {
  2275. $groups[$aggKey] = [
  2276. 'main_id' => $update_map[$rowIndex] ?? 0,
  2277. 'code' => $cCode,
  2278. 'order_time' => $cTimeTs,
  2279. 'item_id' => $cItemId,
  2280. 'details' => []
  2281. ];
  2282. }
  2283. // 解析时间
  2284. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2285. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2286. $groups[$aggKey]['details'][] = [
  2287. 'employee_id' => $dbEmps[trim($row[$empIdx])] ?? 0,
  2288. 'start_time_hour' => $sH,
  2289. 'start_time_min' => $sM,
  2290. 'end_time_hour' => $eH,
  2291. 'end_time_min' => $eM,
  2292. 'total_work_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM), // 计算分钟差
  2293. ];
  2294. }
  2295. // 4. 执行写入
  2296. DB::beginTransaction();
  2297. try {
  2298. $time = time();
  2299. foreach ($groups as $group) {
  2300. $mainId = $group['main_id'];
  2301. if ($mainId > 0) {
  2302. // 编辑:更新主表(允许改项目)
  2303. DB::table('daily_pw_order')->where('id', $mainId)->update([
  2304. 'item_id' => $group['item_id'],
  2305. 'upd_time' => $time
  2306. ]);
  2307. // 逻辑删除旧明细
  2308. DB::table('daily_pw_order_details')->where('main_id', $mainId)
  2309. ->where('del_time', 0)
  2310. ->update(['del_time' => $time]);
  2311. } else {
  2312. // 新增:自动生成单号
  2313. $newCode = $this->generateBillNo([
  2314. 'top_depart_id' => $user['top_depart_id'],
  2315. 'type' => DailyPwOrder::Order_type,
  2316. 'period' => date("Ym", $group['order_time'])
  2317. ]);
  2318. $mainId = DB::table('daily_pw_order')->insertGetId([
  2319. 'code' => $newCode,
  2320. 'order_time' => $group['order_time'],
  2321. 'item_id' => $group['item_id'],
  2322. 'top_depart_id' => $user['top_depart_id'],
  2323. 'crt_id' => $user['id'],
  2324. 'crt_time' => $time,
  2325. ]);
  2326. }
  2327. // 批量插入明细
  2328. $insertDetails = [];
  2329. foreach ($group['details'] as $detail) {
  2330. $detail['main_id'] = $mainId;
  2331. $detail['top_depart_id'] = $user['top_depart_id'];
  2332. $detail['crt_time'] = $time;
  2333. $detail['crt_id'] = $user['id'];
  2334. $insertDetails[] = $detail;
  2335. }
  2336. if (!empty($insertDetails)) {
  2337. DB::table('daily_pw_order_details')->insert($insertDetails);
  2338. }
  2339. }
  2340. DB::commit();
  2341. } catch (\Exception $e) {
  2342. DB::rollBack();
  2343. return [false, "失败:" . $e->getMessage()];
  2344. }
  2345. return [true, ''];
  2346. }
  2347. private function dailyPwOrderCheck(&$array, $user, $table_config)
  2348. {
  2349. $keys = array_column($table_config, 'key');
  2350. $codeIdx = array_search('code', $keys);
  2351. $timeIdx = array_search('order_time', $keys);
  2352. $itemIdx = array_search('item_id', $keys);
  2353. $empIdx = array_search('employee_id', $keys);
  2354. $startIdx = array_search('start_time', $keys);
  2355. $endIdx = array_search('end_time', $keys);
  2356. $topDepartId = $user['top_depart_id'];
  2357. // 1. 批量预加载基础档案
  2358. $empCodes = array_filter(array_unique(array_column($array, $empIdx)));
  2359. $empModels = Employee::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2360. ->whereIn('number', $empCodes)->get(['id', 'number', 'title']);
  2361. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  2362. $empDisplayMap = $empModels->mapWithKeys(function($item){
  2363. return [$item->id => "[{$item->number}]{$item->title}"];
  2364. })->toArray();
  2365. $itemCodes = array_filter(array_unique(array_column($array, $itemIdx)));
  2366. $dbItems = Item::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2367. ->whereIn('code', $itemCodes)->pluck('id', 'code')->toArray();
  2368. // 2. 预加载已有单据
  2369. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  2370. $dbOrders = DB::table('daily_pw_order')->where('top_depart_id', $topDepartId)
  2371. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  2372. // --- 跨单据预查:提前解析日期并检索库内已存在的工时区间 ---
  2373. $allDates = [];
  2374. foreach ($array as $rowIndex => $row) {
  2375. $valMonthRaw = $row[$timeIdx] ?? '';
  2376. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  2377. if(! $status) {
  2378. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  2379. continue;
  2380. }
  2381. $d = strtotime(date('Y-m-d', $ts));
  2382. $array[$rowIndex][$timeIdx] = $d;
  2383. $allDates[] = $d;
  2384. }
  2385. if (!empty($errors)) return [implode('|', $errors), [], [], []];
  2386. $allDates = array_unique($allDates);
  2387. //归档
  2388. list($status, $msg) = ArchiveService::isArchive($allDates, $user);
  2389. if(! $status) return [$msg, [], [], []];
  2390. // 查询数据库:同公司、同日期、同项目、同人员的已有工时 (排除本次 Excel 涉及到的单号)
  2391. $dbExistingWork = DB::table('daily_pw_order_details as d')
  2392. ->join('daily_pw_order as m', 'd.main_id', '=', 'm.id')
  2393. ->where('m.top_depart_id', $topDepartId) // 核心:公司数据隔离
  2394. ->whereIn('m.order_time', $allDates)
  2395. ->whereIn('m.item_id', array_values($dbItems))
  2396. ->whereIn('d.employee_id', array_values($dbEmps))
  2397. ->where('m.del_time', 0)
  2398. ->where('d.del_time', 0)
  2399. ->whereNotIn('m.code', $allCodes) // 排除掉当前正在编辑的单据本身,避免自冲突
  2400. ->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')
  2401. ->get()
  2402. ->groupBy(function($item) {
  2403. return $item->order_time . '_' . $item->item_id . '_' . $item->employee_id;
  2404. });
  2405. $errors = [];
  2406. $update_map = [];
  2407. $excelBillMap = [];
  2408. $timeOverlapMap = []; // 内部记录器:$date_$item_$emp => [ ['s'=>min, 'e'=>min], ... ]
  2409. // 3. 全量循环检查
  2410. foreach ($array as $rowIndex => $row) {
  2411. $displayLine = $rowIndex + 1;
  2412. $ts = $row[$timeIdx];
  2413. $valCode = trim($row[$codeIdx] ?? '');
  2414. $valItemCode = trim($row[$itemIdx] ?? '');
  2415. $itemId = $dbItems[$valItemCode] ?? 0;
  2416. $valEmpCode = trim($row[$empIdx] ?? '');
  2417. $empId = $dbEmps[$valEmpCode] ?? 0;
  2418. $empName = $empDisplayMap[$empId] ?? "工号:{$valEmpCode}";
  2419. // B. 基础档案存在性校验
  2420. if (!$itemId) $errors[] = "第{$displayLine}行:项目编号[{$valItemCode}]不存在";
  2421. if (!$empId) $errors[] = "第{$displayLine}行:人员工号[{$valEmpCode}]不存在";
  2422. if (!$itemId || !$empId) continue;
  2423. // C. 单号与编辑逻辑判定
  2424. if ($valCode !== '') {
  2425. if (isset($dbOrders[$valCode])) {
  2426. $dbOrder = $dbOrders[$valCode];
  2427. if ($dbOrder->order_time != $ts) {
  2428. $errors[] = "第{$displayLine}行:单据[{$valCode}]原日期为[" . date('Y-m-d', $dbOrder->order_time) . "],不允许跨日期编辑";
  2429. }
  2430. $update_map[$rowIndex] = $dbOrder->id;
  2431. } else {
  2432. $errors[] = "第{$displayLine}行:单据编号[{$valCode}]不存在,若要新增请清空该列";
  2433. }
  2434. }
  2435. // D. 时间合法性校验
  2436. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  2437. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  2438. if ($sH === null || $sM === null || $eH === null || $eM === null) {
  2439. $errors[] = "第{$displayLine}行:时间格式非法或超出00:00-23:59范围";
  2440. continue;
  2441. }
  2442. $currentStart = $sH * 60 + $sM;
  2443. $currentEnd = $eH * 60 + $eM;
  2444. if ($currentStart >= $currentEnd) {
  2445. $errors[] = "第{$displayLine}行:人员{$empName}的开始时间需早于结束时间";
  2446. continue;
  2447. }
  2448. // --- E. 三位一体冲突校验 ---
  2449. $checkKey = $ts . "_" . $itemId . "_" . $empId;
  2450. // 1. 校验:数据库已有记录 (跨单据)
  2451. if (isset($dbExistingWork[$checkKey])) {
  2452. foreach ($dbExistingWork[$checkKey] as $p) {
  2453. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  2454. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  2455. // 重叠判定公式: (StartA < EndB) && (StartB < EndA)
  2456. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  2457. $errors[] = "第{$displayLine}行:人员{$empName}与已存在该时间重叠的工时单";
  2458. break;
  2459. }
  2460. }
  2461. }
  2462. // 2. 校验:Excel内上方行记录 (内部重叠)
  2463. if (isset($timeOverlapMap[$checkKey])) {
  2464. foreach ($timeOverlapMap[$checkKey] as $period) {
  2465. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  2466. $errors[] = "第{$displayLine}行:人员{$empName}与表格内其他行时间重叠";
  2467. break;
  2468. }
  2469. }
  2470. }
  2471. // 3. 校验通过,记录到内部记录器
  2472. $timeOverlapMap[$checkKey][] = ['s' => $currentStart, 'e' => $currentEnd];
  2473. }
  2474. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2475. return [$error_string, $update_map, $dbEmps, $dbItems];
  2476. }
  2477. // 设备日工时单 ------------------------------
  2478. public function dailyDwOrderImport($array, $user, $other_param)
  2479. {
  2480. $upload = $array[0];
  2481. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2482. if (!$status) return [false, $msg];
  2483. $table_config = $msg;
  2484. unset($array[0]);
  2485. if (empty($array)) return [false, '导入数据不能为空'];
  2486. // 1. 基础格式检查
  2487. list($array, $error) = $this->checkCommon($array, $table_config);
  2488. if (!empty($error)) return [0, $error];
  2489. // 2. 详细业务校验 (改为设备校验)
  2490. list($error, $update_map, $dbDevices, $dbItems) = $this->dailyDwOrderCheck($array, $user, $table_config);
  2491. if (!empty($error)) return [0, $error];
  2492. $keys = array_column($table_config, 'key');
  2493. $codeIdx = array_search('code', $keys);
  2494. $timeIdx = array_search('order_time', $keys);
  2495. $itemIdx = array_search('item_id', $keys);
  2496. $devIdx = array_search('device_id', $keys); // 对应配置中的 device_id
  2497. $startIdx = array_search('start_time', $keys);
  2498. $endIdx = array_search('end_time', $keys);
  2499. // 3. 数据聚合分组
  2500. $groups = [];
  2501. foreach ($array as $rowIndex => $row) {
  2502. $cCode = trim($row[$codeIdx] ?? '');
  2503. $cTimeTs = $row[$timeIdx];
  2504. $cItemCode = trim($row[$itemIdx] ?? '');
  2505. $cItemId = $dbItems[$cItemCode] ?? 0;
  2506. $aggKey = ($update_map[$rowIndex] ?? 0) > 0
  2507. ? "UPDATE_" . $update_map[$rowIndex]
  2508. : "NEW_" . $cTimeTs . "_" . $cItemId;
  2509. if (!isset($groups[$aggKey])) {
  2510. $groups[$aggKey] = [
  2511. 'main_id' => $update_map[$rowIndex] ?? 0,
  2512. 'code' => $cCode,
  2513. 'order_time' => $cTimeTs,
  2514. 'item_id' => $cItemId,
  2515. 'details' => []
  2516. ];
  2517. }
  2518. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2519. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2520. $groups[$aggKey]['details'][] = [
  2521. 'device_id' => $dbDevices[trim($row[$devIdx])] ?? 0, // 改为设备ID
  2522. 'start_time_hour' => $sH,
  2523. 'start_time_min' => $sM,
  2524. 'end_time_hour' => $eH,
  2525. 'end_time_min' => $eM,
  2526. 'total_work_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM),
  2527. ];
  2528. }
  2529. // 4. 执行写入
  2530. DB::beginTransaction();
  2531. try {
  2532. $time = time();
  2533. foreach ($groups as $group) {
  2534. $mainId = $group['main_id'];
  2535. if ($mainId > 0) {
  2536. // 编辑:更新设备工时主表
  2537. DB::table('daily_dw_order')->where('id', $mainId)->update([
  2538. 'item_id' => $group['item_id'],
  2539. 'upd_time' => $time
  2540. ]);
  2541. DB::table('daily_dw_order_details')->where('main_id', $mainId)
  2542. ->where('del_time', 0)
  2543. ->update(['del_time' => $time]);
  2544. } else {
  2545. // 新增
  2546. $newCode = $this->generateBillNo([
  2547. 'top_depart_id' => $user['top_depart_id'],
  2548. 'type' => DailyDwOrder::Order_type,
  2549. 'period' => date("Ym", $group['order_time'])
  2550. ]);
  2551. $mainId = DB::table('daily_dw_order')->insertGetId([
  2552. 'code' => $newCode,
  2553. 'order_time' => $group['order_time'],
  2554. 'item_id' => $group['item_id'],
  2555. 'top_depart_id' => $user['top_depart_id'],
  2556. 'crt_id' => $user['id'],
  2557. 'crt_time' => $time,
  2558. ]);
  2559. }
  2560. $insertDetails = [];
  2561. foreach ($group['details'] as $detail) {
  2562. $detail['main_id'] = $mainId;
  2563. $detail['top_depart_id'] = $user['top_depart_id'];
  2564. $detail['crt_time'] = $time;
  2565. $detail['crt_id'] = $user['id'];
  2566. $insertDetails[] = $detail;
  2567. }
  2568. if (!empty($insertDetails)) {
  2569. DB::table('daily_dw_order_details')->insert($insertDetails);
  2570. }
  2571. }
  2572. DB::commit();
  2573. } catch (\Exception $e) {
  2574. DB::rollBack();
  2575. return [false, "失败:" . $e->getMessage()];
  2576. }
  2577. return [true, ''];
  2578. }
  2579. private function dailyDwOrderCheck(&$array, $user, $table_config)
  2580. {
  2581. $keys = array_column($table_config, 'key');
  2582. $codeIdx = array_search('code', $keys);
  2583. $timeIdx = array_search('order_time', $keys);
  2584. $itemIdx = array_search('item_id', $keys);
  2585. $devIdx = array_search('device_id', $keys); // 设备编码索引
  2586. $startIdx = array_search('start_time', $keys);
  2587. $endIdx = array_search('end_time', $keys);
  2588. $topDepartId = $user['top_depart_id'];
  2589. // 1. 批量预加载设备档案 (替换原本的人员逻辑)
  2590. $devCodes = array_filter(array_unique(array_column($array, $devIdx)));
  2591. $devModels = Device::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2592. ->whereIn('code', $devCodes)->get(['id', 'code', 'title']);
  2593. $dbDevices = $devModels->pluck('id', 'code')->toArray(); // 以编号为Key查找ID
  2594. $devDisplayMap = $devModels->mapWithKeys(function($item){
  2595. return [$item->id => "[{$item->code}]{$item->title}"];
  2596. })->toArray();
  2597. $itemCodes = array_filter(array_unique(array_column($array, $itemIdx)));
  2598. $dbItems = Item::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2599. ->whereIn('code', $itemCodes)->pluck('id', 'code')->toArray();
  2600. // 2. 预加载设备已有单据
  2601. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  2602. $dbOrders = DB::table('daily_dw_order')->where('top_depart_id', $topDepartId)
  2603. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  2604. // 3. 跨单据预查
  2605. $allDates = [];
  2606. foreach ($array as $rowIndex => $row) {
  2607. $valMonthRaw = $row[$timeIdx] ?? '';
  2608. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  2609. if(! $status) {
  2610. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  2611. continue;
  2612. }
  2613. $d = strtotime(date('Y-m-d', $ts));
  2614. $array[$rowIndex][$timeIdx] = $d;
  2615. $allDates[] = $d;
  2616. }
  2617. if (!empty($errors)) return [implode('|', $errors), [], [], []];
  2618. $allDates = array_unique($allDates);
  2619. //归档
  2620. list($status, $msg) = ArchiveService::isArchive($allDates, $user);
  2621. if(! $status) return [$msg, [], [], []];
  2622. $dbExistingWork = DB::table('daily_dw_order_details as d')
  2623. ->join('daily_dw_order as m', 'd.main_id', '=', 'm.id')
  2624. ->where('m.top_depart_id', $topDepartId)
  2625. ->whereIn('m.order_time', $allDates)
  2626. ->whereIn('m.item_id', array_values($dbItems))
  2627. ->whereIn('d.device_id', array_values($dbDevices)) // 改为 device_id
  2628. ->where('m.del_time', 0)
  2629. ->where('d.del_time', 0)
  2630. ->whereNotIn('m.code', $allCodes)
  2631. ->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')
  2632. ->get()
  2633. ->groupBy(function($item) {
  2634. return $item->order_time . '_' . $item->item_id . '_' . $item->device_id;
  2635. });
  2636. $errors = [];
  2637. $update_map = [];
  2638. $timeOverlapMap = [];
  2639. // 4. 全量循环检查
  2640. foreach ($array as $rowIndex => $row) {
  2641. $displayLine = $rowIndex + 1;
  2642. $ts = $row[$timeIdx];
  2643. $valCode = trim($row[$codeIdx] ?? '');
  2644. $valItemCode = trim($row[$itemIdx] ?? '');
  2645. $itemId = $dbItems[$valItemCode] ?? 0;
  2646. $valDevCode = trim($row[$devIdx] ?? '');
  2647. $devId = $dbDevices[$valDevCode] ?? 0;
  2648. $devName = $devDisplayMap[$devId] ?? "设备编号:{$valDevCode}";
  2649. if (!$itemId) $errors[] = "第{$displayLine}行:项目编号[{$valItemCode}]不存在";
  2650. if (!$devId) $errors[] = "第{$displayLine}行:设备编码[{$valDevCode}]不存在";
  2651. if (!$itemId || !$devId) continue;
  2652. if ($valCode !== '') {
  2653. if (isset($dbOrders[$valCode])) {
  2654. $dbOrder = $dbOrders[$valCode];
  2655. if ($dbOrder->order_time != $ts) {
  2656. $errors[] = "第{$displayLine}行:单据[{$valCode}]原日期不符,编辑模式不允许修改日期";
  2657. }
  2658. $update_map[$rowIndex] = $dbOrder->id;
  2659. } else {
  2660. $errors[] = "第{$displayLine}行:单据编号[{$valCode}]不存在";
  2661. }
  2662. }
  2663. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  2664. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  2665. if ($sH === null || $sM === null || $eH === null || $eM === null) {
  2666. $errors[] = "第{$displayLine}行:时间段格式非法";
  2667. continue;
  2668. }
  2669. $currentStart = $sH * 60 + $sM;
  2670. $currentEnd = $eH * 60 + $eM;
  2671. if ($currentStart >= $currentEnd) {
  2672. $errors[] = "第{$displayLine}行:设备{$devName}开始时间需早于结束时间";
  2673. continue;
  2674. }
  2675. $checkKey = $ts . "_" . $itemId . "_" . $devId;
  2676. // 跨单据检查
  2677. if (isset($dbExistingWork[$checkKey])) {
  2678. foreach ($dbExistingWork[$checkKey] as $p) {
  2679. $exStart = $p->start_time_hour * 60 + $p->start_time_min;
  2680. $exEnd = $p->end_time_hour * 60 + $p->end_time_min;
  2681. if ($currentStart < $exEnd && $exStart < $currentEnd) {
  2682. $errors[] = "第{$displayLine}行:设备{$devName}在该项目当日已有记录重叠";
  2683. break;
  2684. }
  2685. }
  2686. }
  2687. // Excel内部检查
  2688. if (isset($timeOverlapMap[$checkKey])) {
  2689. foreach ($timeOverlapMap[$checkKey] as $period) {
  2690. if ($currentStart < $period['e'] && $period['s'] < $currentEnd) {
  2691. $errors[] = "第{$displayLine}行:设备{$devName}与表格内其他行重叠";
  2692. break;
  2693. }
  2694. }
  2695. }
  2696. $timeOverlapMap[$checkKey][] = ['s' => $currentStart, 'e' => $currentEnd];
  2697. }
  2698. $error_string = !empty($errors) ? implode('|', $errors) : "";
  2699. return [$error_string, $update_map, $dbDevices, $dbItems];
  2700. }
  2701. // 人员请假单 --------------------------------
  2702. public function leaveOrderImport($array, $user, $other_param)
  2703. {
  2704. $upload = $array[0];
  2705. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2706. if (!$status) return [false, $msg];
  2707. $table_config = $msg;
  2708. unset($array[0]);
  2709. if (empty($array)) return [false, '导入数据不能为空'];
  2710. // 1. 基础格式检查
  2711. list($array, $error) = $this->checkCommon($array, $table_config);
  2712. if (!empty($error)) return [0, $error];
  2713. // 2. 详细业务校验 (固定为请假单校验)
  2714. list($error, $update_map, $dbEmps) = $this->leaveOrderCheck($array, $user, $table_config);
  2715. if (!empty($error)) return [0, $error];
  2716. $keys = array_column($table_config, 'key');
  2717. $codeIdx = array_search('code', $keys);
  2718. $timeIdx = array_search('order_time', $keys);
  2719. $empIdx = array_search('employee_id', $keys);
  2720. $startIdx = array_search('start_time', $keys);
  2721. $endIdx = array_search('end_time', $keys);
  2722. // 3. 数据聚合分组 (按日期聚合)
  2723. $groups = [];
  2724. foreach ($array as $rowIndex => $row) {
  2725. $cTimeTs = $row[$timeIdx];
  2726. $mainId = $update_map[$rowIndex] ?? 0;
  2727. // 聚合Key:如果是更新则按主表ID;如果是新增则按日期
  2728. $aggKey = $mainId > 0 ? "ID_" . $mainId : "DATE_" . $cTimeTs;
  2729. if (!isset($groups[$aggKey])) {
  2730. $groups[$aggKey] = [
  2731. 'main_id' => $mainId,
  2732. 'order_time' => $cTimeTs,
  2733. 'details' => []
  2734. ];
  2735. }
  2736. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2737. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2738. $groups[$aggKey]['details'][] = [
  2739. 'employee_id' => $dbEmps[trim($row[$empIdx])] ?? 0,
  2740. 'start_time_hour' => $sH,
  2741. 'start_time_min' => $sM,
  2742. 'end_time_hour' => $eH,
  2743. 'end_time_min' => $eM,
  2744. 'total_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM),
  2745. 'type' => PLeaveOverOrder::TYPE_ONE, // 固定请假类型
  2746. ];
  2747. }
  2748. // 4. 执行写入
  2749. DB::beginTransaction();
  2750. try {
  2751. $time = time();
  2752. foreach ($groups as $group) {
  2753. if ($group['main_id'] > 0) {
  2754. $mainId = $group['main_id'];
  2755. // 删除旧明细准备覆盖
  2756. DB::table('p_leave_over_order_details')->where('main_id', $mainId)->update(['del_time' => $time]);
  2757. } else {
  2758. // 生成请假单号
  2759. $newCode = $this->generateBillNo([
  2760. 'top_depart_id' => $user['top_depart_id'],
  2761. 'type' => PLeaveOverOrder::Order_type,
  2762. 'period' => date("Ym", $group['order_time'])
  2763. ]);
  2764. $mainId = DB::table('p_leave_over_order')->insertGetId([
  2765. 'code' => $newCode,
  2766. 'order_time' => $group['order_time'],
  2767. 'type' => PLeaveOverOrder::TYPE_ONE,
  2768. 'top_depart_id' => $user['top_depart_id'],
  2769. 'crt_id' => $user['id'],
  2770. 'crt_time' => $time,
  2771. ]);
  2772. }
  2773. foreach ($group['details'] as &$d) {
  2774. $d['main_id'] = $mainId;
  2775. $d['top_depart_id'] = $user['top_depart_id'];
  2776. $d['crt_time'] = $time;
  2777. }
  2778. DB::table('p_leave_over_order_details')->insert($group['details']);
  2779. }
  2780. DB::commit();
  2781. } catch (\Exception $e) {
  2782. DB::rollBack();
  2783. return [false, "失败:" . $e->getMessage()];
  2784. }
  2785. return [true, ''];
  2786. }
  2787. private function leaveOrderCheck(&$array, $user, $table_config)
  2788. {
  2789. $keys = array_column($table_config, 'key');
  2790. $codeIdx = array_search('code', $keys);
  2791. $timeIdx = array_search('order_time', $keys);
  2792. $empIdx = array_search('employee_id', $keys);
  2793. $startIdx = array_search('start_time', $keys);
  2794. $endIdx = array_search('end_time', $keys);
  2795. $topDepartId = $user['top_depart_id'];
  2796. $errors = [];
  2797. $update_map = [];
  2798. // --- 1. 基础档案预加载 (代码省略,保持原样) ---
  2799. $empCodes = array_filter(array_unique(array_column($array, $empIdx)));
  2800. $empModels = Employee::where('del_time', 0)->where('top_depart_id', $topDepartId)
  2801. ->whereIn('number', $empCodes)->get(['id', 'number', 'title']);
  2802. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  2803. $empDisplayMap = $empModels->mapWithKeys(fn($item) => [$item->id => "[{$item->number}]{$item->title}"])->toArray();
  2804. // --- 2. 日历 & 主表预查 (代码省略,保持原样) ---
  2805. $allDateTs = [];
  2806. foreach ($array as $rowIndex => $row) {
  2807. $valMonthRaw = $row[$timeIdx] ?? '';
  2808. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  2809. if(! $status) {
  2810. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  2811. continue;
  2812. }
  2813. $d = strtotime(date('Y-m-d', $ts));
  2814. $array[$rowIndex][$timeIdx] = $d;
  2815. $allDateTs[] = $d;
  2816. }
  2817. if (!empty($errors)) return [implode('|', $errors), [], []];
  2818. $allDateTs = array_unique($allDateTs);
  2819. //归档
  2820. list($status, $msg) = ArchiveService::isArchive($allDateTs, $user);
  2821. if(! $status) return [$msg, [], []];
  2822. $calendarMap = DB::table('calendar_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  2823. ->whereIn('time', $allDateTs)->pluck('is_work', 'time')->toArray();
  2824. $existMainOrders = DB::table('p_leave_over_order')
  2825. ->where('top_depart_id', $topDepartId)
  2826. ->whereIn('order_time', $allDateTs)
  2827. ->where('type', PLeaveOverOrder::TYPE_ONE)
  2828. ->where('del_time', 0)->get()->keyBy('order_time');
  2829. // --- 3. 工时设置 (代码省略,保持原样) ---
  2830. $specialWorkMap = DB::table('employee_work_range')->whereIn('employee_id', array_values($dbEmps))
  2831. ->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  2832. $commonWorkRanges = DB::table('work_range_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)->get();
  2833. $commonPeriods = [];
  2834. foreach ($commonWorkRanges as $wr) {
  2835. $commonPeriods[] = ['s' => $wr->start_time_hour * 60 + $wr->start_time_min, 'e' => $wr->end_time_hour * 60 + $wr->end_time_min];
  2836. }
  2837. // --- 4. 库内明细校验数据 (代码省略,保持原样) ---
  2838. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  2839. $dbExistingWork = DB::table('p_leave_over_order_details as d')
  2840. ->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  2841. ->where('m.top_depart_id', $topDepartId)
  2842. ->whereIn('m.order_time', $allDateTs)
  2843. ->where('m.type', PLeaveOverOrder::TYPE_ONE)
  2844. ->where('m.del_time', 0)->where('d.del_time', 0)
  2845. ->whereNotIn('m.code', $allCodes)
  2846. ->select('m.order_time', 'd.employee_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')
  2847. ->get()->groupBy(fn($item) => $item->order_time . '_' . $item->employee_id);
  2848. $dbOrders = DB::table('p_leave_over_order')->where('top_depart_id', $topDepartId)
  2849. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  2850. $internalOverlapMap = [];
  2851. // --- 5. 循环校验 (全量提示版) ---
  2852. foreach ($array as $rowIndex => $row) {
  2853. $line = $rowIndex + 1;
  2854. $rowErrors = []; // 临时收集本行的所有错误
  2855. $ts = $row[$timeIdx];
  2856. // 1. 单据与编辑逻辑检查
  2857. $valCode = trim($row[$codeIdx] ?? '');
  2858. if ($valCode === '') {
  2859. if (isset($existMainOrders[$ts])) {
  2860. $rowErrors[] = date('Y-m-d', $ts) . "已存在请假单[{$existMainOrders[$ts]->code}],请填写单号进行编辑";
  2861. }
  2862. } else {
  2863. if (isset($dbOrders[$valCode])) {
  2864. if ($dbOrders[$valCode]->order_time != $ts) {
  2865. $rowErrors[] = "单据[{$valCode}]原日期不符,不允许跨日期编辑";
  2866. }
  2867. $update_map[$rowIndex] = $dbOrders[$valCode]->id;
  2868. } else {
  2869. $rowErrors[] = "单据号[{$valCode}]不存在";
  2870. }
  2871. }
  2872. // 2. 日历检查
  2873. if (!isset($calendarMap[$ts]) || (int)$calendarMap[$ts] !== 1) {
  2874. $rowErrors[] = "该日期非工作日,无需请假";
  2875. }
  2876. // 3. 人员检查
  2877. $empId = $dbEmps[trim($row[$empIdx])] ?? 0;
  2878. $empName = $empDisplayMap[$empId] ?? "工号:".$row[$empIdx];
  2879. if (!$empId) {
  2880. $rowErrors[] = "人员不存在";
  2881. // 如果人都不存在,后面的时间校验没意义,报错合并
  2882. $errors[] = "第{$line}行:" . implode(';', $rowErrors);
  2883. continue;
  2884. }
  2885. // 4. 时间段合法性检查
  2886. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  2887. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  2888. $curS = $sH * 60 + $sM; $curE = $eH * 60 + $eM;
  2889. if ($curS >= $curE) {
  2890. $rowErrors[] = "结束时间需晚于开始时间";
  2891. } else {
  2892. // 只有在时间段本身合法的情况下,才检查范围和重叠
  2893. // A. 工作范围检查
  2894. $empPeriods = isset($specialWorkMap[$empId]) ? [] : $commonPeriods;
  2895. if (isset($specialWorkMap[$empId])) {
  2896. foreach ($specialWorkMap[$empId] as $sw) {
  2897. $empPeriods[] = ['s' => $sw->start_time_hour * 60 + $sw->start_time_min, 'e' => $sw->end_time_hour * 60 + $sw->end_time_min];
  2898. }
  2899. }
  2900. $inRange = false;
  2901. foreach ($empPeriods as $p) { if ($curS >= $p['s'] && $curE <= $p['e']) { $inRange = true; break; } }
  2902. if (!$inRange) {
  2903. $rowErrors[] = "请假需在规定的工作时间内";
  2904. }
  2905. // B. 重叠检查 (不再 continue,两个都查)
  2906. $checkKey = $ts . "_" . $empId;
  2907. // 表内
  2908. if (isset($internalOverlapMap[$checkKey])) {
  2909. foreach ($internalOverlapMap[$checkKey] as $p) {
  2910. if ($curS < $p['e'] && $p['s'] < $curE) {
  2911. $rowErrors[] = "在表内存在时间重叠";
  2912. break; // 同一行的“表内重叠”只提示一次
  2913. }
  2914. }
  2915. }
  2916. // 库内
  2917. if (isset($dbExistingWork[$checkKey])) {
  2918. foreach ($dbExistingWork[$checkKey] as $p) {
  2919. $exS = $p->start_time_hour * 60 + $p->start_time_min;
  2920. $exE = $p->end_time_hour * 60 + $p->end_time_min;
  2921. if ($curS < $exE && $exS < $curE) {
  2922. $rowErrors[] = "与已有的请假单时间重叠";
  2923. break; // 同一行的“库内重叠”只提示一次
  2924. }
  2925. }
  2926. }
  2927. }
  2928. // 收集汇总错误
  2929. if (!empty($rowErrors)) {
  2930. $errors[] = "第{$line}行:{$empName}" . implode(',', $rowErrors);
  2931. } else {
  2932. // 只有完全没错误的数据,才放入 internalOverlapMap 供后续行比对
  2933. // 这样可以防止第2行报错了,第3行又提示跟第2行重叠,造成提示混乱
  2934. $checkKey = $ts . "_" . $empId;
  2935. $internalOverlapMap[$checkKey][] = ['s' => $curS, 'e' => $curE];
  2936. }
  2937. }
  2938. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $dbEmps];
  2939. }
  2940. // 人员加班单
  2941. public function overtimeOrderImport($array, $user, $other_param)
  2942. {
  2943. $upload = $array[0];
  2944. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  2945. if (!$status) return [false, $msg];
  2946. $table_config = $msg;
  2947. unset($array[0]);
  2948. if (empty($array)) return [false, '导入数据不能为空'];
  2949. // 1. 基础格式检查
  2950. list($array, $error) = $this->checkCommon($array, $table_config);
  2951. if (!empty($error)) return [0, $error];
  2952. // 2. 业务逻辑校验 (专用于加班)
  2953. list($error, $update_map, $dbEmps) = $this->overtimeOrderCheck($array, $user, $table_config);
  2954. if (!empty($error)) return [0, $error];
  2955. $keys = array_column($table_config, 'key');
  2956. $codeIdx = array_search('code', $keys);
  2957. $timeIdx = array_search('order_time', $keys);
  2958. $empIdx = array_search('employee_id', $keys);
  2959. $startIdx = array_search('start_time', $keys);
  2960. $endIdx = array_search('end_time', $keys);
  2961. // 3. 数据聚合分组 (按日期聚合)
  2962. $groups = [];
  2963. foreach ($array as $rowIndex => $row) {
  2964. $cTimeTs = $row[$timeIdx];
  2965. $mainId = $update_map[$rowIndex] ?? 0;
  2966. $aggKey = $mainId > 0 ? "ID_" . $mainId : "DATE_" . $cTimeTs;
  2967. if (!isset($groups[$aggKey])) {
  2968. $groups[$aggKey] = [
  2969. 'main_id' => $mainId,
  2970. 'order_time' => $cTimeTs,
  2971. 'details' => []
  2972. ];
  2973. }
  2974. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx]);
  2975. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx]);
  2976. $groups[$aggKey]['details'][] = [
  2977. 'employee_id' => $dbEmps[trim($row[$empIdx])] ?? 0,
  2978. 'start_time_hour' => $sH,
  2979. 'start_time_min' => $sM,
  2980. 'end_time_hour' => $eH,
  2981. 'end_time_min' => $eM,
  2982. 'total_min' => ($eH * 60 + $eM) - ($sH * 60 + $sM),
  2983. 'type' => PLeaveOverOrder::TYPE_TWO, // 加班类型
  2984. ];
  2985. }
  2986. // 4. 执行写入
  2987. DB::beginTransaction();
  2988. try {
  2989. $time = time();
  2990. foreach ($groups as $group) {
  2991. if ($group['main_id'] > 0) {
  2992. $mainId = $group['main_id'];
  2993. DB::table('p_leave_over_order_details')->where('main_id', $mainId)->update(['del_time' => $time]);
  2994. } else {
  2995. $newCode = $this->generateBillNo([
  2996. 'top_depart_id' => $user['top_depart_id'],
  2997. 'type' => PLeaveOverOrder::Order_type,
  2998. 'period' => date("Ym", $group['order_time'])
  2999. ]);
  3000. $mainId = DB::table('p_leave_over_order')->insertGetId([
  3001. 'code' => $newCode,
  3002. 'order_time' => $group['order_time'],
  3003. 'type' => PLeaveOverOrder::TYPE_TWO,
  3004. 'top_depart_id' => $user['top_depart_id'],
  3005. 'crt_id' => $user['id'],
  3006. 'crt_time' => $time,
  3007. ]);
  3008. }
  3009. foreach ($group['details'] as &$d) {
  3010. $d['main_id'] = $mainId;
  3011. $d['top_depart_id'] = $user['top_depart_id'];
  3012. $d['crt_time'] = $time;
  3013. }
  3014. DB::table('p_leave_over_order_details')->insert($group['details']);
  3015. }
  3016. DB::commit();
  3017. } catch (\Exception $e) {
  3018. DB::rollBack();
  3019. return [false, "失败:" . $e->getMessage()];
  3020. }
  3021. return [true, ''];
  3022. }
  3023. private function overtimeOrderCheck(&$array, $user, $table_config)
  3024. {
  3025. $keys = array_column($table_config, 'key');
  3026. $codeIdx = array_search('code', $keys);
  3027. $timeIdx = array_search('order_time', $keys);
  3028. $empIdx = array_search('employee_id', $keys);
  3029. $startIdx = array_search('start_time', $keys);
  3030. $endIdx = array_search('end_time', $keys);
  3031. $topDepartId = $user['top_depart_id'];
  3032. $errors = [];
  3033. $update_map = [];
  3034. // 1. 档案预加载
  3035. $empCodes = array_filter(array_unique(array_column($array, $empIdx)));
  3036. $empModels = Employee::where('del_time', 0)->where('top_depart_id', $topDepartId)
  3037. ->whereIn('number', $empCodes)->get(['id', 'number', 'title']);
  3038. $dbEmps = $empModels->pluck('id', 'number')->toArray();
  3039. $empDisplayMap = $empModels->mapWithKeys(fn($item) => [$item->id => "[{$item->number}]{$item->title}"])->toArray();
  3040. // 2. 日期、日历、主表预查
  3041. $allDateTs = [];
  3042. foreach ($array as $rowIndex => $row) {
  3043. $valMonthRaw = $row[$timeIdx] ?? '';
  3044. list($status, $ts) = $this->convertExcelCellToDate($valMonthRaw);
  3045. if(! $status) {
  3046. $errors[] = "第" . ($rowIndex + 1) . "行:单据日期格式错误({$valMonthRaw})";
  3047. continue;
  3048. }
  3049. $d = strtotime(date('Y-m-d', $ts));
  3050. $array[$rowIndex][$timeIdx] = $d;
  3051. $allDateTs[] = $d;
  3052. }
  3053. if (!empty($errors)) return [implode('|', $errors), [], []];
  3054. $allDateTs = array_unique($allDateTs);
  3055. //归档
  3056. list($status, $msg) = ArchiveService::isArchive($allDateTs, $user);
  3057. if(! $status) return [$msg, [], []];
  3058. $calendarMap = DB::table('calendar_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3059. ->whereIn('time', $allDateTs)->pluck('is_work', 'time')->toArray();
  3060. $existMainOrders = DB::table('p_leave_over_order')
  3061. ->where('top_depart_id', $topDepartId)
  3062. ->whereIn('order_time', $allDateTs)
  3063. ->where('type', PLeaveOverOrder::TYPE_TWO)
  3064. ->where('del_time', 0)->get()->keyBy('order_time');
  3065. // 3. 工时设置预加载
  3066. $specialWorkMap = DB::table('employee_work_range')->whereIn('employee_id', array_values($dbEmps))
  3067. ->where('top_depart_id', $topDepartId)->get()->groupBy('employee_id');
  3068. $commonWorkRanges = DB::table('work_range_details')->where('del_time', 0)->where('top_depart_id', $topDepartId)->get();
  3069. $commonPeriods = [];
  3070. foreach ($commonWorkRanges as $wr) {
  3071. $commonPeriods[] = ['s' => $wr->start_time_hour * 60 + $wr->start_time_min, 'e' => $wr->end_time_hour * 60 + $wr->end_time_min];
  3072. }
  3073. // 4. 库内明细预查 (跨单重叠校验)
  3074. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  3075. $dbExistingWork = DB::table('p_leave_over_order_details as d')
  3076. ->join('p_leave_over_order as m', 'd.main_id', '=', 'm.id')
  3077. ->where('m.top_depart_id', $topDepartId)
  3078. ->whereIn('m.order_time', $allDateTs)
  3079. ->where('m.type', PLeaveOverOrder::TYPE_TWO)
  3080. ->where('m.del_time', 0)->where('d.del_time', 0)
  3081. ->whereNotIn('m.code', $allCodes)
  3082. ->select('m.order_time', 'd.employee_id', 'd.start_time_hour', 'd.start_time_min', 'd.end_time_hour', 'd.end_time_min')
  3083. ->get()->groupBy(fn($item) => $item->order_time . '_' . $item->employee_id);
  3084. $dbOrders = DB::table('p_leave_over_order')->where('top_depart_id', $topDepartId)
  3085. ->whereIn('code', $allCodes)->where('del_time', 0)->get()->keyBy('code');
  3086. $internalOverlapMap = [];
  3087. // 5. 全量循环检查
  3088. foreach ($array as $rowIndex => $row) {
  3089. $line = $rowIndex + 1;
  3090. $rowErrors = [];
  3091. $ts = $row[$timeIdx];
  3092. // A. 单据存在性逻辑
  3093. $valCode = trim($row[$codeIdx] ?? '');
  3094. if ($valCode === '') {
  3095. if (isset($existMainOrders[$ts])) {
  3096. $rowErrors[] = date('Y-m-d', $ts) . "已存在加班单[{$existMainOrders[$ts]->code}],请填写单号进行编辑";
  3097. }
  3098. } else {
  3099. if (isset($dbOrders[$valCode])) {
  3100. if ($dbOrders[$valCode]->order_time != $ts) $rowErrors[] = "单据[{$valCode}]原日期不符";
  3101. $update_map[$rowIndex] = $dbOrders[$valCode]->id;
  3102. } else { $rowErrors[] = "单据号[{$valCode}]不存在"; }
  3103. }
  3104. // B. 人员校验
  3105. $empId = $dbEmps[trim($row[$empIdx])] ?? 0;
  3106. $empName = $empDisplayMap[$empId] ?? "工号:".$row[$empIdx];
  3107. if (!$empId) {
  3108. $errors[] = "第{$line}行:人员不存在"; continue;
  3109. }
  3110. // C. 时间格式校验
  3111. list($sH, $sM) = $this->parseTimeHourMin($row[$startIdx] ?? '');
  3112. list($eH, $eM) = $this->parseTimeHourMin($row[$endIdx] ?? '');
  3113. $curS = $sH * 60 + $sM; $curE = $eH * 60 + $eM;
  3114. if ($curS >= $curE) {
  3115. $rowErrors[] = "结束时间需晚于开始时间";
  3116. } else {
  3117. // D. 加班规则校验 (核心逻辑)
  3118. $isWorkDay = (int)($calendarMap[$ts] ?? 0) === 1;
  3119. if ($isWorkDay) {
  3120. // 如果是工作日,加班不能在工作时间内
  3121. $empPeriods = isset($specialWorkMap[$empId]) ? [] : $commonPeriods;
  3122. if (isset($specialWorkMap[$empId])) {
  3123. foreach ($specialWorkMap[$empId] as $sw) {
  3124. $empPeriods[] = ['s' => $sw->start_time_hour * 60 + $sw->start_time_min, 'e' => $sw->end_time_hour * 60 + $sw->end_time_min];
  3125. }
  3126. }
  3127. foreach ($empPeriods as $p) {
  3128. if ($curS < $p['e'] && $p['s'] < $curE) {
  3129. $rowErrors[] = "加班时间不能与正常工作时间重叠";
  3130. break;
  3131. }
  3132. }
  3133. }
  3134. // E. 重叠校验
  3135. $checkKey = $ts . "_" . $empId;
  3136. // 表内重叠
  3137. if (isset($internalOverlapMap[$checkKey])) {
  3138. foreach ($internalOverlapMap[$checkKey] as $p) {
  3139. if ($curS < $p['e'] && $p['s'] < $curE) { $rowErrors[] = "在表内存在时间重叠"; break; }
  3140. }
  3141. }
  3142. // 库内重叠
  3143. if (isset($dbExistingWork[$checkKey])) {
  3144. foreach ($dbExistingWork[$checkKey] as $p) {
  3145. $exS = $p->start_time_hour * 60 + $p->start_time_min; $exE = $p->end_time_hour * 60 + $p->end_time_min;
  3146. if ($curS < $exE && $exS < $curE) { $rowErrors[] = "与已有的加班单时间重叠"; break; }
  3147. }
  3148. }
  3149. }
  3150. if (!empty($rowErrors)) {
  3151. $errors[] = "第{$line}行:{$empName} " . implode(',', $rowErrors);
  3152. } else {
  3153. $internalOverlapMap[$ts . "_" . $empId][] = ['s' => $curS, 'e' => $curE];
  3154. }
  3155. }
  3156. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $dbEmps];
  3157. }
  3158. // 费用项目单月度导入 ------------------------------
  3159. public function feeOrderImport($array, $user, $other_param)
  3160. {
  3161. $upload = $array[0];
  3162. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  3163. if (!$status) return [false, $msg];
  3164. $table_config = $msg;
  3165. unset($array[0]);
  3166. if (empty($array)) return [false, '导入数据不能为空'];
  3167. // 1. 基础校验(格式、必填项等)
  3168. list($array, $error) = $this->checkCommon($array, $table_config);
  3169. if (!empty($error)) return [0, $error];
  3170. // 2. 业务详细校验 (获取 update_map 和 基础档案映射)
  3171. // 此时 claim_date 会在 check 方法内部被转换为时间戳并校验月份归属
  3172. list($error, $update_map, $maps) = $this->feeOrderCheck($array, $user, $table_config);
  3173. if (!empty($error)) return [0, $error];
  3174. $keys = array_column($table_config, 'key');
  3175. $codeIdx = array_search('code', $keys);
  3176. $monthIdx = array_search('month', $keys);
  3177. // --- 步骤 1: 数据聚合分组 ---
  3178. $groups = [];
  3179. foreach ($array as $rowIndex => $row) {
  3180. $cCode = trim($row[$codeIdx] ?? '');
  3181. $cMonthTs = $row[$monthIdx];
  3182. // 聚合 Key:有编码用编码,没编码用月份
  3183. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  3184. if (!isset($groups[$aggKey])) {
  3185. $groups[$aggKey] = [
  3186. 'main_id' => $update_map[$rowIndex] ?? 0,
  3187. 'code' => $cCode,
  3188. 'month' => $cMonthTs,
  3189. 'details' => []
  3190. ];
  3191. }
  3192. // 准备详情行数据
  3193. $detailTmp = [];
  3194. foreach ($table_config as $k => $conf) {
  3195. if (!$conf['is_main']) {
  3196. $fieldKey = $conf['key'];
  3197. // 跳过仅用于展示的名称字段
  3198. if (in_array($fieldKey, ['employee_title', 'item_title', 'fee_title'])) continue;
  3199. $fieldVal = $row[$k];
  3200. // 转换编号为 ID
  3201. if ($fieldKey == 'employee_id') $fieldVal = $maps['emps'][$fieldVal] ?? 0;
  3202. if ($fieldKey == 'item_id') $fieldVal = $maps['items'][$fieldVal] ?? 0;
  3203. if ($fieldKey == 'fee_id') $fieldVal = $maps['fees'][$fieldVal] ?? 0;
  3204. // 转换枚举值(委托方式、是否定位到人)
  3205. // if ($fieldKey == 'entrust_type') {
  3206. // $fieldVal = array_search($fieldVal, \App\Model\ExpenseClaimsDetails::State_Type) ?: 0;
  3207. // }
  3208. // if ($fieldKey == 'expense_type') {
  3209. // $fieldVal = array_search($fieldVal, \App\Model\ExpenseClaimsDetails::State_Type_2) ?: 0;
  3210. // }
  3211. // 注意:claim_date 已经在 check 方法里转成了时间戳,这里直接赋值即可
  3212. $detailTmp[$fieldKey] = $fieldVal;
  3213. }
  3214. }
  3215. $groups[$aggKey]['details'][] = $detailTmp;
  3216. }
  3217. // --- 步骤 2: 事务写入 ---
  3218. DB::beginTransaction();
  3219. try {
  3220. $time = time();
  3221. foreach ($groups as $group) {
  3222. $mainId = $group['main_id'];
  3223. if ($mainId > 0) {
  3224. // 编辑:逻辑删除旧明细
  3225. DB::table('expense_claims_details')->where('del_time', 0)
  3226. ->where('expense_claims_id', $mainId)
  3227. ->update(['del_time' => $time]);
  3228. // 更新主表更新时间
  3229. DB::table('expense_claims')->where('id', $mainId)->update(['upd_time' => $time]);
  3230. } else {
  3231. // 新增:生成单号
  3232. $newCode = $this->generateBillNo([
  3233. 'top_depart_id' => $user['top_depart_id'],
  3234. 'type' => \App\Model\ExpenseClaims::Order_type,
  3235. 'period' => date("Ym", $group['month'])
  3236. ]);
  3237. $mainId = DB::table('expense_claims')->insertGetId([
  3238. 'code' => $newCode,
  3239. 'month' => $group['month'],
  3240. 'top_depart_id' => $user['top_depart_id'],
  3241. 'crt_id' => $user['id'],
  3242. 'crt_time' => $time,
  3243. 'upd_time' => $time,
  3244. 'del_time' => 0
  3245. ]);
  3246. }
  3247. // 批量插入详情
  3248. $insertDetails = [];
  3249. foreach ($group['details'] as $detail) {
  3250. $detail['expense_claims_id'] = $mainId;
  3251. $detail['top_depart_id'] = $user['top_depart_id'];
  3252. $detail['crt_id'] = $user['id'];
  3253. $detail['crt_time'] = $time;
  3254. $detail['upd_time'] = $time;
  3255. $detail['del_time'] = 0;
  3256. $insertDetails[] = $detail;
  3257. }
  3258. if (!empty($insertDetails)) {
  3259. DB::table('expense_claims_details')->insert($insertDetails);
  3260. }
  3261. }
  3262. DB::commit();
  3263. } catch (\Exception $e) {
  3264. DB::rollBack();
  3265. return [false, "写入失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  3266. }
  3267. return [true, ''];
  3268. }
  3269. private function feeOrderCheck(&$array, $user, $table_config)
  3270. {
  3271. $keys = array_column($table_config, 'key');
  3272. $codeIdx = array_search('code', $keys);
  3273. $monthIdx = array_search('month', $keys);
  3274. $empIdx = array_search('employee_id', $keys);
  3275. $itemIdx = array_search('item_id', $keys);
  3276. $feeIdx = array_search('fee_id', $keys);
  3277. $claimDateIdx = array_search('claim_date', $keys);
  3278. $amountIdx = array_search('amount', $keys);
  3279. $eAmountIdx = array_search('entrust1_amount', $keys);
  3280. $e2AmountIdx = array_search('entrust2_amount', $keys);
  3281. $eTypeIdx = array_search('entrust_type', $keys);
  3282. $exTypeIdx = array_search('expense_type', $keys);
  3283. $state_map = array_flip(ExpenseClaimsDetails::State_Type);
  3284. $ex_map = array_flip(ExpenseClaimsDetails::State_Type_2);
  3285. $topDepartId = $user['top_depart_id'];
  3286. $errors = [];
  3287. $allEmpNos = []; $allItemCodes = []; $allFeeCodes = []; $allMonthsTs = []; $allCodes = [];
  3288. // --- 1. 预处理:日期转换与基础编号提取 ---
  3289. foreach ($array as $rowIndex => $row) {
  3290. $line = $rowIndex + 1;
  3291. // A. 报销主月份处理
  3292. $valMonthRaw = trim($row[$monthIdx] ?? '');
  3293. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  3294. if (!$mStatus) {
  3295. $errors[] = "第{$line}行:月份格式错误";
  3296. continue;
  3297. }
  3298. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  3299. $array[$rowIndex][$monthIdx] = $valMonthTs; // 回写转换后的时间戳
  3300. $allMonthsTs[] = $valMonthTs;
  3301. // B. 费用产生日期校验 (claim_date)
  3302. $valClaimDateRaw = trim($row[$claimDateIdx] ?? '');
  3303. if (empty($valClaimDateRaw)) {
  3304. $errors[] = "第{$line}行:费用产生日期不能为空";
  3305. } else {
  3306. list($dStatus, $dTs) = $this->convertExcelCellToDate($valClaimDateRaw);
  3307. if (!$dStatus) {
  3308. $errors[] = "第{$line}行:费用产生日期格式错误";
  3309. } else {
  3310. // 核心逻辑:判断产生日期是否在主月份内
  3311. $monthStr = date('Y-m', $valMonthTs);
  3312. $claimMonthStr = date('Y-m', $dTs);
  3313. if ($monthStr !== $claimMonthStr) {
  3314. $errors[] = "第{$line}行:产生日期[{$claimMonthStr}]与报销月份[{$monthStr}]不符";
  3315. }
  3316. $array[$rowIndex][$claimDateIdx] = $dTs; // 回写转换后的时间戳
  3317. }
  3318. }
  3319. // C. 提取其他编号
  3320. if (!empty($row[$empIdx])) $allEmpNos[] = trim($row[$empIdx]);
  3321. if (!empty($row[$itemIdx])) $allItemCodes[] = trim($row[$itemIdx]);
  3322. if (!empty($row[$feeIdx])) $allFeeCodes[] = trim($row[$feeIdx]);
  3323. if (!empty($row[$codeIdx])) $allCodes[] = trim($row[$codeIdx]);
  3324. }
  3325. if (!empty($errors)) return [implode('|', $errors), [], []];
  3326. $allMonthsTs = array_unique($allMonthsTs);
  3327. //归档
  3328. list($status, $msg) = ArchiveService::isArchive($allMonthsTs, $user);
  3329. if(! $status) return [$msg, [], []];
  3330. // --- 2. 批量预加载档案映射 ---
  3331. $dbEmps = DB::table('employee')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3332. ->whereIn('number', array_unique($allEmpNos))->pluck('id', 'number')->toArray();
  3333. $dbItems = DB::table('item')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3334. ->whereIn('code', array_unique($allItemCodes))->pluck('id', 'code')->toArray();
  3335. $dbFees = DB::table('fee')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3336. ->whereIn('code', array_unique($allFeeCodes))->pluck('id', 'code')->toArray();
  3337. $existingMonthsMap = DB::table('expense_claims')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3338. ->whereIn('month', $allMonthsTs)->pluck('code', 'month')->toArray();
  3339. $dbOrdersByCode = DB::table('expense_claims')->where('del_time', 0)->where('top_depart_id', $topDepartId)
  3340. ->whereIn('code', array_unique($allCodes))->get()->keyBy('code');
  3341. // --- 3. 逐行校验档案存在性与单据逻辑 ---
  3342. $update_map = [];
  3343. foreach ($array as $rowIndex => $row) {
  3344. $line = $rowIndex + 1;
  3345. $valCode = trim($row[$codeIdx] ?? '');
  3346. $valMonthTs = $row[$monthIdx];
  3347. if (!empty($row[$empIdx]) && !isset($dbEmps[trim($row[$empIdx])])) {
  3348. $errors[] = "第{$line}行:工号[{$row[$empIdx]}]不存在";
  3349. }
  3350. if (!isset($dbItems[trim($row[$itemIdx])])) {
  3351. $errors[] = "第{$line}行:项目编号[{$row[$itemIdx]}]不存在";
  3352. }
  3353. if (!isset($dbFees[trim($row[$feeIdx])])) {
  3354. $errors[] = "第{$line}行:费用类型编号[{$row[$feeIdx]}]不存在";
  3355. }
  3356. if ($valCode !== '') {
  3357. if (isset($dbOrdersByCode[$valCode])) {
  3358. if ($dbOrdersByCode[$valCode]->month != $valMonthTs) {
  3359. $errors[] = "第{$line}行:单据[{$valCode}]对应月份为" . date('Y-m', $dbOrdersByCode[$valCode]->month) . ",Excel中月份不符";
  3360. }
  3361. $update_map[$rowIndex] = $dbOrdersByCode[$valCode]->id;
  3362. } else {
  3363. $errors[] = "第{$line}行:填写的单据编码[{$valCode}]系统中不存在";
  3364. }
  3365. } else {
  3366. if (isset($existingMonthsMap[$valMonthTs])) {
  3367. $errors[] = "第{$line}行:月份[" . date('Y-m', $valMonthTs) . "]已存在单据[{$existingMonthsMap[$valMonthTs]}],请填写该单号进行编辑";
  3368. }
  3369. }
  3370. // 数字格式校验
  3371. $amount = $row[$amountIdx];
  3372. $res = $this->checkNumber($amount, 2, 'non-negative');
  3373. if (!$res['valid']) $errors[] = "第{$line}行费用金额:" . $res['error'];
  3374. // 委托方式
  3375. $e_text = $row[$eTypeIdx] ?? '';
  3376. if (!isset($state_map[$e_text])) {
  3377. $errors[] = "第{$line}行:委托方式[{$e_text}]无效";
  3378. } else {
  3379. $v_tmp = $state_map[$e_text];
  3380. $array[$rowIndex][$eTypeIdx] = $v_tmp;
  3381. }
  3382. $e1_text = $row[$eAmountIdx];
  3383. $res = $this->checkNumber($e1_text, 2, 'non-negative');
  3384. if (!$res['valid']) {
  3385. $errors[] = "第{$line}行:境内委托金额" . $res['error'];
  3386. }
  3387. $e2_text = $row[$e2AmountIdx];
  3388. $res = $this->checkNumber($e2_text, 2, 'non-negative');
  3389. if (!$res['valid']) {
  3390. $errors[] = "第{$line}行:境外委托金额" . $res['error'];
  3391. }
  3392. $tmp = bcadd($e1_text, $e2_text,2);
  3393. if(floatval($tmp) > $amount) return [false, "第{$line}行委托金额总和不能超过费用金额"];
  3394. //是否定位到人
  3395. $ex_text = $row[$exTypeIdx] ?? '';
  3396. if (!isset($ex_map[$ex_text])) {
  3397. $errors[] = "第{$line}行:是否定位到人[{$ex_text}]无效";
  3398. } else {
  3399. $v_tmp = $ex_map[$ex_text];
  3400. $array[$rowIndex][$exTypeIdx] = $v_tmp;
  3401. }
  3402. }
  3403. $maps = ['emps' => $dbEmps, 'items' => $dbItems, 'fees' => $dbFees];
  3404. return [!empty($errors) ? implode('|', $errors) : "", $update_map, $maps];
  3405. }
  3406. // 标签管理
  3407. public function tagImport($array, $user, $other_param)
  3408. {
  3409. $upload = $array[0];
  3410. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  3411. if (!$status) return [false, $msg];
  3412. $table_config = $msg;
  3413. unset($array[0]);
  3414. if (empty($array)) return [false, '导入数据不能为空'];
  3415. // 基础格式校验
  3416. list($array, $error) = $this->checkCommon($array, $table_config);
  3417. if (!empty($error)) return [0, $error];
  3418. // 2. 业务逻辑校验
  3419. list($error, $update_map) = $this->tagCheck($array, $user, $table_config);
  3420. if (!empty($error)) return [0, $error];
  3421. $time = time();
  3422. $insert = [];
  3423. $update = [];
  3424. foreach ($array as $key => $value) {
  3425. $main_tmp = [];
  3426. foreach ($value as $k => $val){
  3427. if(!empty($table_config[$k]['is_main'])){
  3428. $main_tmp[$table_config[$k]['key']] = $val;
  3429. }
  3430. }
  3431. if (isset($update_map[$key])) {
  3432. // 更新逻辑
  3433. $update[] = array_merge($main_tmp, [
  3434. 'id' => $update_map[$key],
  3435. ]);
  3436. } else {
  3437. // 新增逻辑
  3438. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  3439. $main_tmp['crt_time'] = $time;
  3440. $insert[] = $main_tmp;
  3441. }
  3442. }
  3443. DB::beginTransaction();
  3444. try {
  3445. if (!empty($insert)) {
  3446. foreach (array_chunk($insert, 500) as $chunk) {
  3447. Tag::insert($chunk);
  3448. }
  3449. }
  3450. if (!empty($update)) {
  3451. foreach ($update as $item) {
  3452. $uId = $item['id'];
  3453. unset($item['id']);
  3454. Tag::where('id', $uId)->update($item);
  3455. }
  3456. }
  3457. DB::commit();
  3458. } catch (\Exception $e) {
  3459. DB::rollBack();
  3460. return [false, "导入失败:" . $e->getMessage()];
  3461. }
  3462. return [true, ''];
  3463. }
  3464. private function tagCheck(&$array, $user, $table_config)
  3465. {
  3466. $keys = array_column($table_config, 'key');
  3467. $codeIdx = array_search('code', $keys);
  3468. $sortIdx = array_search('sort', $keys);
  3469. $typeIdx = array_search('type', $keys);
  3470. $isUseIdx = array_search('is_use', $keys);
  3471. $type_map = array_flip(Tag::TYPE_TITLE);
  3472. $isUse_map = array_flip(Tag::IS_USE);
  3473. // 获取当前企业下已存在的标签,用于判断是新增还是更新
  3474. $dbMap = Tag::where('del_time', 0)
  3475. ->where('top_depart_id', $user['top_depart_id'])
  3476. ->get()
  3477. ->keyBy('code')
  3478. ->toArray();
  3479. $errors = [];
  3480. $update = [];
  3481. $excelCodes = [];
  3482. foreach ($array as $rowIndex => $value) {
  3483. $displayLine = $rowIndex + 1;
  3484. $valCode = trim($value[$codeIdx] ?? '');
  3485. if ($valCode === '') {
  3486. $errors[] = "第{$displayLine}行:编码不能为空";
  3487. continue;
  3488. }
  3489. // 校验 Excel 内部是否重复
  3490. if (isset($excelCodes[$valCode])) {
  3491. $errors[] = "第{$displayLine}行:编码[{$valCode}]在文件中重复出现";
  3492. continue;
  3493. }
  3494. $excelCodes[$valCode] = true;
  3495. // 类型
  3496. $e_text = $value[$typeIdx] ?? '';
  3497. if (!isset($type_map[$e_text])) {
  3498. $errors[] = "第{$displayLine}行:类型[{$e_text}]无效";
  3499. } else {
  3500. $array[$rowIndex][$typeIdx] = $type_map[$e_text];
  3501. }
  3502. // 是否启用
  3503. $e_text = $value[$isUseIdx] ?? '';
  3504. if (!isset($isUse_map[$e_text])) {
  3505. $errors[] = "第{$displayLine}行:是否启用[{$e_text}]无效";
  3506. } else {
  3507. $array[$rowIndex][$isUseIdx] = $isUse_map[$e_text];
  3508. }
  3509. // 数字格式校验
  3510. $sort = $value[$sortIdx];
  3511. if (filter_var($sort, FILTER_VALIDATE_INT) === false) return [false, "第{$displayLine}行排序字段排序字段必须是整数且不能含有小数点"];
  3512. // 如果数据库已存在,记录为更新操作
  3513. if (isset($dbMap[$valCode])) {
  3514. $update[$rowIndex] = $dbMap[$valCode]['id'];
  3515. }
  3516. }
  3517. $error_string = !empty($errors) ? implode('|', $errors) : "";
  3518. return [$error_string, $update];
  3519. }
  3520. // 团队 -----------------------------------
  3521. private function getTeamList($array, $user, $index){
  3522. $codes = array_unique(array_filter(array_column($array,$index)));
  3523. return Team::where('del_time', 0)
  3524. ->where('top_depart_id', $user['top_depart_id'])
  3525. ->whereIn('code', $codes)
  3526. ->pluck('id','code')
  3527. ->toArray();
  3528. }
  3529. public function teamImport($array, $user, $other_param)
  3530. {
  3531. $upload = $array[0];
  3532. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  3533. if (!$status) return [false, $msg];
  3534. $table_config = $msg;
  3535. unset($array[0]);
  3536. if (empty($array)) return [false, '导入数据不能为空'];
  3537. // 1. 公共校验 (必填、唯一性等)
  3538. list($array, $error) = $this->checkCommon($array, $table_config);
  3539. if (!empty($error)) return [0, $error];
  3540. // 2. 业务详细校验 (包含一致性校验、明细解析)
  3541. list($error, $update_map, $detail_data_map) = $this->teamCheck($array, $user, $table_config);
  3542. if (!empty($error)) return [0, $error];
  3543. $time = time();
  3544. $insert_data = [];
  3545. $update_data = [];
  3546. $all_detail_insert = [];
  3547. $update_main_ids = [];
  3548. $keys = array_column($table_config, 'key');
  3549. $codeIdx = array_search('code', $keys);
  3550. // 3. 数据分拣(聚合平铺数据)
  3551. foreach ($array as $key => $value) {
  3552. $itemCode = trim($value[$codeIdx]);
  3553. $main_tmp = [];
  3554. foreach ($value as $k => $val) {
  3555. if (!empty($table_config[$k]['is_main'])) {
  3556. if ($table_config[$k]['key'] == 'employee_title') continue;
  3557. $main_tmp[$table_config[$k]['key']] = $val;
  3558. }
  3559. }
  3560. if (isset($update_map[$key])) {
  3561. // 更新逻辑:以 ID 为键去重
  3562. $itemId = $update_map[$key];
  3563. $update_main_ids[$itemId] = $itemId;
  3564. $update_data[$itemId] = array_merge($main_tmp, ['id' => $itemId]);
  3565. if (isset($detail_data_map[$key])) {
  3566. foreach ($detail_data_map[$key] as $d) {
  3567. $all_detail_insert[] = array_merge($d, [
  3568. 'team_id' => $itemId,
  3569. 'crt_time' => $time,
  3570. 'top_depart_id' => $user['top_depart_id']
  3571. ]);
  3572. }
  3573. }
  3574. } else {
  3575. // 新增逻辑:以项目编码为键去重
  3576. if (!isset($insert_data[$itemCode])) {
  3577. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  3578. $main_tmp['crt_id'] = $user['id'];
  3579. $main_tmp['crt_time'] = $time;
  3580. $insert_data[$itemCode] = $main_tmp;
  3581. }
  3582. if (isset($detail_data_map[$key])) {
  3583. foreach ($detail_data_map[$key] as $d) {
  3584. $all_detail_insert[] = array_merge($d, [
  3585. '_code' => $itemCode,
  3586. 'crt_time' => $time,
  3587. 'top_depart_id' => $user['top_depart_id']
  3588. ]);
  3589. }
  3590. }
  3591. }
  3592. }
  3593. DB::beginTransaction();
  3594. try {
  3595. // 4. 执行新增主表
  3596. $new_item_maps = [];
  3597. if (!empty($insert_data)) {
  3598. foreach (array_chunk(array_values($insert_data), 500) as $chunk) {
  3599. Team::insert($chunk);
  3600. }
  3601. $new_item_maps = Team::whereIn('code', array_keys($insert_data))
  3602. ->where('del_time', 0)
  3603. ->where('top_depart_id', $user['top_depart_id'])
  3604. ->pluck('id', 'code')->toArray();
  3605. }
  3606. // 5. 执行更新主表
  3607. if (!empty($update_data)) {
  3608. foreach ($update_data as $id => $uItem) {
  3609. unset($uItem['id']);
  3610. Team::where('id', $id)->update($uItem);
  3611. }
  3612. }
  3613. // 6. 处理明细表 (先全删后插)
  3614. if (!empty($update_main_ids)) {
  3615. TeamDetails::whereIn('team_id', array_values($update_main_ids))
  3616. ->where('del_time', 0)
  3617. ->update(['del_time' => $time]);
  3618. }
  3619. foreach ($all_detail_insert as &$di) {
  3620. if (isset($di['_code'])) {
  3621. $di['item_id'] = $new_item_maps[$di['_code']] ?? 0;
  3622. unset($di['_code']);
  3623. }
  3624. }
  3625. unset($di);
  3626. if (!empty($all_detail_insert)) {
  3627. foreach (array_chunk($all_detail_insert, 500) as $chunk) {
  3628. TeamDetails::insert($chunk);
  3629. }
  3630. }
  3631. DB::commit();
  3632. } catch (\Exception $e) {
  3633. DB::rollBack();
  3634. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  3635. }
  3636. return [true, ''];
  3637. }
  3638. private function teamCheck(&$array, $user, $table_config)
  3639. {
  3640. $keys = array_column($table_config, 'key');
  3641. $codeIdx = array_search('code', $keys);
  3642. $stateIdx = array_search('state', $keys);
  3643. $code2Idx = array_search('code_2', $keys); // 工号列
  3644. $empIdx = array_search('charge_id', $keys);
  3645. // 假设 $array 是你的数据集
  3646. $allEmpNumbers = array_values(array_filter(array_unique([
  3647. array_column($array, $empIdx),
  3648. array_column($array, $code2Idx)
  3649. ])));
  3650. $dbEmps = Employee::where('del_time', 0)
  3651. ->whereIn('number', $allEmpNumbers)
  3652. ->where('top_depart_id', $user['top_depart_id'])
  3653. ->pluck('id', 'number')->toArray();
  3654. $code_map = $this->getTeamList($array, $user, $codeIdx);
  3655. $man_map = $this->getFlatDataList2($array, $user, $code2Idx);
  3656. $errors = [];
  3657. $update_mapping = [];
  3658. $detail_storage = [];
  3659. $mainDataConsistency = []; // 一致性校验
  3660. $state_type_map = array_flip(Team::State_Type);
  3661. // 识别主表字段列索引
  3662. $mainColIndices = [];
  3663. foreach ($table_config as $index => $conf) {
  3664. if (!empty($conf['is_main'])) $mainColIndices[$index] = $conf['value'];
  3665. }
  3666. foreach ($array as $rowIndex => $rowValue) {
  3667. $displayLine = $rowIndex + 1;
  3668. $valCode = trim($rowValue[$codeIdx] ?? '');
  3669. $valEmp = trim($rowValue[$empIdx] ?? '');
  3670. if ($valCode === '') continue;
  3671. // --- A. 主表一致性校验 ---
  3672. if (!isset($mainDataConsistency[$valCode])) {
  3673. $mainDataConsistency[$valCode] = array_intersect_key($rowValue, $mainColIndices);
  3674. } else {
  3675. foreach ($mainColIndices as $idx => $label) {
  3676. if (trim($rowValue[$idx] ?? '') != trim($mainDataConsistency[$valCode][$idx] ?? '')) {
  3677. $errors[] = "第{$displayLine}行:团队[{$valCode}]的主表信息[{$label}]与前文不一致";
  3678. }
  3679. }
  3680. }
  3681. // --- B. 基础校验 ---
  3682. if (isset($code_map[$valCode])) {
  3683. $update_mapping[$rowIndex] = $code_map[$valCode];
  3684. }
  3685. // 状态
  3686. $state_text = $rowValue[$stateIdx] ?? '';
  3687. if (!isset($state_type_map[$state_text])) {
  3688. $errors[] = "第{$displayLine}行:状态[{$state_text}]无效";
  3689. } else {
  3690. $array[$rowIndex][$stateIdx] = $state_type_map[$state_text];
  3691. }
  3692. // D. 人员校验
  3693. if(! empty($valEmp)){
  3694. if (!isset($dbEmps[$valEmp])) {
  3695. $errors[] = "第{$displayLine}行:负责人工号[{$valEmp}]不存在";
  3696. } else {
  3697. $array[$rowIndex][$empIdx] = $dbEmps[$valEmp];
  3698. }
  3699. }
  3700. $subCode = trim($rowValue[$code2Idx] ?? '');
  3701. if ($subCode !== '') {
  3702. if (!isset($man_map[$subCode])) {
  3703. $errors[] = "第{$displayLine}行:人员工号[{$subCode}]不存在";
  3704. } else {
  3705. $detail_storage[$rowIndex][] = ['data_id' => $man_map[$subCode]];
  3706. }
  3707. }
  3708. }
  3709. $error_str = !empty($errors) ? implode('|', $errors) : "";
  3710. return [$error_str, $update_mapping, $detail_storage];
  3711. }
  3712. private function getFlatDataList2($array, $user, $code2Idx)
  3713. {
  3714. $codes = array_unique(array_filter(array_column($array, $code2Idx)));
  3715. return Employee::where('del_time', 0)
  3716. ->where('top_depart_id', $user['top_depart_id'])
  3717. ->whereIn('number', $codes)
  3718. ->pluck('id', 'number')
  3719. ->toArray();
  3720. }
  3721. /**
  3722. * 解析并校验时间
  3723. */
  3724. private function parseTimeHourMin($val)
  3725. {
  3726. $h = -1; $m = -1;
  3727. if (strpos($val, ':') !== false) {
  3728. $parts = explode(':', $val);
  3729. $h = isset($parts[0]) ? (int)$parts[0] : -1;
  3730. $m = isset($parts[1]) ? (int)$parts[1] : -1;
  3731. } elseif (is_numeric($val)) {
  3732. $totalMinutes = (int)round($val * 1440);
  3733. $h = (int)floor($totalMinutes / 60);
  3734. $m = (int)($totalMinutes % 60);
  3735. }
  3736. if ($h < 0 || $h > 23 || $m < 0 || $m > 59) {
  3737. return [null, null];
  3738. }
  3739. return [$h, $m];
  3740. }
  3741. //公共校验 -----------------------------------------
  3742. private function checkCommon($array, $table_config) {
  3743. $error = [];
  3744. $uniqueCheck = [];
  3745. foreach ($array as $line => $row) {
  3746. // 如果整行都是空的(包括 null),直接剔除
  3747. if (empty(array_filter($row))) {
  3748. unset($array[$line]);
  3749. continue;
  3750. }
  3751. // --- 核心修正点:遍历配置,而不是遍历原始行数据 ---
  3752. // 这样即便 Excel 有 100 列,我们也只校验配置里的那 4 列
  3753. $newRow = [];
  3754. foreach ($table_config as $colIndex => $config) {
  3755. $value = isset($row[$colIndex]) ? trim($row[$colIndex]) : '';
  3756. $fieldName = $config['value'];
  3757. // 1. 必填校验
  3758. if (!empty($config['required']) && $value === '') {
  3759. $error[] = "第{$line}行:[{$fieldName}] 必填";
  3760. }
  3761. // 2. 默认值填充
  3762. if ($value === '' && isset($config['default'])) {
  3763. $value = $config['default'];
  3764. }
  3765. // 3. 唯一性校验
  3766. if (!empty($config['unique']) && $value !== '') {
  3767. if (isset($uniqueCheck[$colIndex][$value])) {
  3768. $prevLine = $uniqueCheck[$colIndex][$value];
  3769. $error[] = "第{$line}行:[{$fieldName}] 与第{$prevLine}行重复,重复值:{$value}";
  3770. } else {
  3771. $uniqueCheck[$colIndex][$value] = $line;
  3772. }
  3773. }
  3774. $newRow[$colIndex] = $value;
  3775. }
  3776. // 只保留校验过的数据列,多余的列(第4列之后)被自动丢弃
  3777. $array[$line] = $newRow;
  3778. }
  3779. $error_string = !empty($error) ? implode('|', $error) : "";
  3780. return [$array, $error_string];
  3781. }
  3782. //模板校验 -----------------------------------------
  3783. private function compareTableAndReturn($upload, $param){
  3784. if(empty($upload)) return [false, '表头不能为空'];
  3785. $config = $this->getTableConfig($param['type']);
  3786. $config_array = $config['array'];
  3787. if(empty($config_array)) return [false, '导入配置表头文件不存在'];
  3788. foreach ($config_array as $key => $value){
  3789. $key_position = $key + 1;
  3790. if(! isset($upload[$key])) return [false, "第" . $key_position . "列表头缺失"];
  3791. $tmp_v = trim($upload[$key]);
  3792. if($tmp_v != $value['value']) return [false, "第" . $key_position . "列表头与模板不符合,请重新下载模板"];
  3793. }
  3794. return [true, $config_array];
  3795. }
  3796. //转换日期 ------------------------------------------
  3797. function convertExcelCellToDate($cellValue) {
  3798. // 尝试将单元格值转换为浮点数(Excel 日期序列号)
  3799. $excelTimestamp = filter_var($cellValue, FILTER_VALIDATE_FLOAT);
  3800. if ($excelTimestamp !== false && $excelTimestamp > 0) {
  3801. // 如果成功转换并且值大于0,则认为是Excel日期序列号
  3802. try {
  3803. $dateTimeObject = Date::excelToDateTimeObject($cellValue);
  3804. // if ($dateTimeObject->format('H:i:s') === '00:00:00') {
  3805. // // 如果是,则将时间设置为 '23:59:00'
  3806. // $dateTimeObject->setTime(23, 59);
  3807. // }
  3808. // 现在你可以格式化这个日期了
  3809. $formattedDate = $dateTimeObject->format('Y-m-d');
  3810. if(! strtotime($formattedDate)) return [false, ''];
  3811. return [true, strtotime($formattedDate)];
  3812. } catch (\Exception $e) {
  3813. // 处理转换失败的情况
  3814. return [false, '单元格日期格式转换时间戳失败'];
  3815. }
  3816. }
  3817. // 如果不是有效的浮点数,则尝试按照多种日期格式解析
  3818. if(! strtotime($cellValue)) return [false, '单元格文本格式转换时间戳失败'];
  3819. return [true, strtotime($cellValue)];
  3820. }
  3821. }