ImportService.php 163 KB

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