ImportService.php 167 KB

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