ImportService.php 137 KB

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