ImportService.php 184 KB

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