ImportService.php 160 KB

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