ImportService.php 191 KB

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