ImportService.php 113 KB

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