ImportService.php 164 KB

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