ImportService.php 167 KB

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