ImportService.php 192 KB

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