ImportService.php 125 KB

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