ImportService.php 172 KB

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