ImportService.php 160 KB

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