ImportService.php 181 KB

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