ImportService.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. <?php
  2. namespace App\Service;
  3. use App\Exports\TableHeadExport;
  4. use App\Import\ImportAll;
  5. use App\Model\Device;
  6. use App\Model\Employee;
  7. use App\Model\Fee;
  8. use App\Model\Item;
  9. use App\Model\ItemDetails;
  10. use App\Model\MonthlyPwOrder;
  11. use Illuminate\Support\Facades\DB;
  12. use Maatwebsite\Excel\Facades\Excel;
  13. use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F;
  14. use PhpOffice\PhpSpreadsheet\IOFactory;
  15. use PhpOffice\PhpSpreadsheet\Shared\Date;
  16. class ImportService extends Service
  17. {
  18. public static $type = [
  19. 'device', // 设备
  20. 'item', // 项目
  21. 'fee', // 费用
  22. 'monthPwOrder', // 人员月度研发工时单
  23. 'monthDwOrder', // 设备月度研发工时单
  24. ];
  25. public function getTableTitleXls($data,$user){
  26. if(empty($data['type'])) return [false,'缺少类型'];
  27. if(! in_array($data['type'],self::$type)) return [false,'类型不存在'];
  28. //获取配置文件
  29. $fuc = $data['type'];
  30. if (! method_exists(self::class, $fuc)) return [false, "导入文件获取不存在,请联系开发"];
  31. list($status,$return) = $this->$fuc($data,$user);
  32. list($msg,$filename) = $return;
  33. if(! $status) return [false, $msg];
  34. $headers = array_column($msg,'value');
  35. $comments = $enums = [];
  36. foreach ($msg as $value){
  37. if(! empty($value['comments'])) $comments[$value['value']] = $value['comments'];
  38. if(! empty($value['enums'])) $enums[$value['value']] = $value['enums'];
  39. }
  40. Excel::store(new TableHeadExport([], $headers, $comments, $enums),"/public/export/{$filename}", null, 'Xlsx', []);
  41. return [true, ['file' => $filename]];
  42. }
  43. private function getTableConfig($type = ""){
  44. if(empty($type)) return [];
  45. //获取配置文件
  46. $config = "excel." . $type;
  47. return config($config) ?? [];
  48. }
  49. private function device($data,$user){
  50. $config = $this->getTableConfig($data['type']);
  51. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  52. $config_array = $config['array'] ?? [];
  53. //生成下载文件
  54. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  55. return [true, [$config_array, $filename]];
  56. }
  57. private function item($data,$user){
  58. $config = $this->getTableConfig($data['type']);
  59. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  60. $config_array = $config['array'] ?? [];
  61. //生成下载文件
  62. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  63. return [true, [$config_array, $filename]];
  64. }
  65. private function fee($data,$user){
  66. $config = $this->getTableConfig($data['type']);
  67. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  68. $config_array = $config['array'] ?? [];
  69. //生成下载文件
  70. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  71. return [true, [$config_array, $filename]];
  72. }
  73. private function monthPwOrder($data,$user){
  74. $config = $this->getTableConfig($data['type']);
  75. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  76. $config_array = $config['array'] ?? [];
  77. //生成下载文件
  78. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  79. return [true, [$config_array, $filename]];
  80. }
  81. private function monthDwOrder($data,$user){
  82. $config = $this->getTableConfig($data['type']);
  83. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  84. $config_array = $config['array'] ?? [];
  85. //生成下载文件
  86. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  87. return [true, [$config_array, $filename]];
  88. }
  89. //导入入口
  90. public function importAll($data,$user){
  91. // //不超时
  92. // ini_set('max_execution_time', 0);
  93. // //内存设置
  94. // ini_set('memory_limit', -1);
  95. // $reader = IOFactory::createReader('Xlsx');
  96. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  97. // $spreadsheet = $reader->load($data['file']);
  98. // dd($spreadsheet);
  99. // // 创建一个Reader对象
  100. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  101. //
  102. //// 加载Excel文件
  103. // $spreadsheet = $reader->load($data['file']);
  104. //
  105. //// 获取第一个工作表
  106. // $worksheet = $spreadsheet->getActiveSheet();
  107. //
  108. //// 获取总行数
  109. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  110. if(empty($data['type'])) return [false,'缺少导入类型,导入失败'];
  111. if(! in_array($data['type'],self::$type)) return [false,'导入类型不存在,导入失败'];
  112. if(empty($data['file'])) return [false,'导入文件不能为空'];
  113. try {
  114. $import = new ImportAll();
  115. //设置导入人id
  116. $import->setCrt($user['id']);
  117. $import->setUser($user);
  118. $import->setType($data['type']);
  119. $other = $data;
  120. unset($other['file']);
  121. $import->setOtherParam($other);
  122. //导入
  123. \Maatwebsite\Excel\Facades\Excel::import($import,$data['file']);
  124. if($import->getMsg()) {
  125. $bool = $import->getIsLongText();
  126. if($bool) {
  127. return [0, $import->getMsg()];
  128. }else{
  129. return [false, $import->getMsg()];
  130. }
  131. }
  132. }catch (\Throwable $exception) {
  133. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  134. }
  135. return [true, ''];
  136. }
  137. // 设备 ------------------------------------
  138. public function deviceImport($array, $user, $other_param){
  139. $upload = $array[0];
  140. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  141. if(!$status) return [false, $msg];
  142. $table_config = $msg;
  143. unset($array[0]);
  144. if(empty($array)) return [false, '导入数据不能为空'];
  145. // 公共校验
  146. list($array, $error) = $this->checkCommon($array, $table_config);
  147. if(!empty($error)) return [0, $error];
  148. // 详细校验 (这里 $array 传引用,内部会转换日期)
  149. list($error, $update_map) = $this->deviceCheck($array, $user, $table_config);
  150. if(!empty($error)) return [0, $error];
  151. $time = time();
  152. $insert = [];
  153. $update = [];
  154. foreach ($array as $key => $value){
  155. $main_tmp = [];
  156. foreach ($value as $k => $val){
  157. if(!empty($table_config[$k]['is_main'])){
  158. $main_tmp[$table_config[$k]['key']] = $val;
  159. }
  160. }
  161. if(isset($update_map[$key])){
  162. // 存入待更新数组
  163. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  164. } else {
  165. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  166. $main_tmp['crt_id'] = $user['id'];
  167. $main_tmp['crt_time'] = $time;
  168. $insert[] = $main_tmp;
  169. }
  170. }
  171. DB::beginTransaction();
  172. try {
  173. // 1. 批量新增
  174. if(!empty($insert)){
  175. foreach(array_chunk($insert, 500) as $chunkInsert){
  176. Device::insert($chunkInsert);
  177. }
  178. }
  179. // 批量更新
  180. foreach (array_chunk($update, 100) as $chunk) {
  181. foreach ($chunk as $item) {
  182. $id = $item['id'];
  183. unset($item['id']);
  184. Device::where('id', $id)->update($item);
  185. }
  186. }
  187. DB::commit();
  188. } catch (\Exception $e) {
  189. DB::rollBack();
  190. return [false, "错误:" . $e->getMessage() . " 行:" . $e->getLine()];
  191. }
  192. return [true, ''];
  193. }
  194. private function deviceCheck(&$array, $user, $table_config)
  195. {
  196. // 动态获取关键列的索引
  197. $codeIdx = array_search('code', array_column($table_config, 'key'));
  198. $dateIdx = array_search('in_time', array_column($table_config, 'key'));
  199. $typeIdx = array_search('type', array_column($table_config, 'key'));
  200. $type2Idx = array_search('is_use', array_column($table_config, 'key'));
  201. $code_map = $this->getDeviceList($array, $user, $codeIdx);
  202. $errors = [];
  203. $update = [];
  204. $map_type = array_flip(Device::$type);
  205. $map_type_2 = array_flip(Device::Use);
  206. foreach ($array as $rowIndex => $value) {
  207. $valCode = $value[$codeIdx] ?? '';
  208. // 记录更新 ID
  209. if(isset($code_map[$valCode])){
  210. $update[$rowIndex] = $code_map[$valCode];
  211. }
  212. if(empty($map_type[$value[$typeIdx]])){
  213. $errors[] = "第{$rowIndex}行固定资产类型错误";
  214. }else{
  215. $array[$rowIndex][$typeIdx] = $map_type[$value[$typeIdx]];
  216. }
  217. if(empty($map_type_2[$value[$type2Idx]])){
  218. $errors[] = "第{$rowIndex}行是否启用错误";
  219. }else{
  220. $array[$rowIndex][$type2Idx] = $map_type_2[$value[$type2Idx]];
  221. }
  222. // 日期处理
  223. if($dateIdx !== false && !empty($value[$dateIdx])){
  224. list($status, $msg) = $this->convertExcelCellToDate($value[$dateIdx]);
  225. if(!$status) {
  226. $errors[] = "第{$rowIndex}行日期格式错误";
  227. } else {
  228. $array[$rowIndex][$dateIdx] = $msg;
  229. }
  230. }
  231. }
  232. $error_string = "";
  233. if(! empty($errors)) $error_string = implode('|', $errors);
  234. return [$error_string, $update];
  235. }
  236. private function getDeviceList($array, $user, $index){
  237. //查找设备
  238. $codes = array_unique(array_filter(array_column($array,$index)));
  239. return Device::where('del_time', 0)
  240. ->where('top_depart_id', $user['top_depart_id'])
  241. ->whereIn('code', $codes)
  242. ->pluck('id','code')
  243. ->toArray();
  244. }
  245. // 项目 -----------------------------------
  246. public function itemImport($array, $user, $other_param)
  247. {
  248. $upload = $array[0];
  249. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  250. if (!$status) return [false, $msg];
  251. $table_config = $msg;
  252. unset($array[0]);
  253. if (empty($array)) return [false, '导入数据不能为空'];
  254. // 1. 公共校验 (必填、唯一性等)
  255. list($array, $error) = $this->checkCommon($array, $table_config);
  256. if (!empty($error)) return [0, $error];
  257. // 2. 业务详细校验 (获取更新映射及明细数据)
  258. list($error, $update_map, $detail_data_map) = $this->itemCheck($array, $user, $table_config);
  259. if (!empty($error)) return [0, $error];
  260. $time = time();
  261. $insert_data = [];
  262. $update_data = [];
  263. $all_detail_insert = [];
  264. $update_main_ids = [];
  265. // 3. 数据分拣
  266. foreach ($array as $key => $value) {
  267. $main_tmp = [];
  268. foreach ($value as $k => $val) {
  269. if (!empty($table_config[$k]['is_main'])) {
  270. $main_tmp[$table_config[$k]['key']] = $val;
  271. }
  272. }
  273. if (isset($update_map[$key])) {
  274. // 更新逻辑
  275. $itemId = $update_map[$key];
  276. $update_data[] = array_merge($main_tmp, ['id' => $itemId]);
  277. $update_main_ids[] = $itemId;
  278. // 收集明细 (后续统一插入)
  279. if (isset($detail_data_map[$key])) {
  280. foreach ($detail_data_map[$key] as $d) {
  281. $all_detail_insert[] = array_merge($d, ['item_id' => $itemId, 'crt_time' => $time, 'top_depart_id' => $user['top_depart_id']]);
  282. }
  283. }
  284. } else {
  285. // 新增逻辑
  286. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  287. $main_tmp['crt_id'] = $user['id'];
  288. $main_tmp['crt_time'] = $time;
  289. // 以 code 为键,方便后续回填 ID
  290. $insert_data[$main_tmp['code']] = $main_tmp;
  291. if (isset($detail_data_map[$key])) {
  292. foreach ($detail_data_map[$key] as $d) {
  293. $all_detail_insert[] = array_merge($d, ['_code' => $main_tmp['code'], 'crt_time' => $time, 'top_depart_id' => $main_tmp['top_depart_id']]);
  294. }
  295. }
  296. }
  297. }
  298. DB::beginTransaction();
  299. try {
  300. // 4. 执行新增主表
  301. if (!empty($insert_data)) {
  302. foreach (array_chunk($insert_data, 500) as $chunk) {
  303. Item::insert($chunk);
  304. }
  305. // 获取新插入数据的 ID 映射
  306. $new_item_maps = Item::whereIn('code', array_keys($insert_data))
  307. ->where('del_time', 0)
  308. ->where('top_depart_id', $user['top_depart_id'])
  309. ->pluck('id', 'code')->toArray();
  310. }
  311. // 5. 执行更新主表 (分批更新)
  312. if (!empty($update_data)) {
  313. foreach (array_chunk($update_data, 100) as $chunk) {
  314. foreach ($chunk as $uItem) {
  315. $id = $uItem['id'];
  316. unset($uItem['id']);
  317. Item::where('id', $id)->update($uItem);
  318. }
  319. }
  320. }
  321. // 6. 处理明细表 (先删后插策略)
  322. // 删除旧明细 (逻辑删除)
  323. if (!empty($update_main_ids)) {
  324. ItemDetails::whereIn('item_id', $update_main_ids)
  325. ->where('del_time', 0)
  326. ->update(['del_time' => $time]);
  327. }
  328. // 回填新增主表的 ID 到明细数组
  329. foreach ($all_detail_insert as &$di) {
  330. if (isset($di['_code'])) {
  331. $di['item_id'] = $new_item_maps[$di['_code']] ?? 0;
  332. unset($di['_code']);
  333. }
  334. }
  335. unset($di);
  336. // 批量插入所有明细
  337. if (!empty($all_detail_insert)) {
  338. foreach (array_chunk($all_detail_insert, 500) as $chunk) {
  339. ItemDetails::insert($chunk);
  340. }
  341. }
  342. DB::commit();
  343. } catch (\Exception $e) {
  344. DB::rollBack();
  345. return [false, "入库失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  346. }
  347. return [true, '导入成功'];
  348. }
  349. private function getItemList($array, $user, $index){
  350. //查找设备
  351. $codes = array_unique(array_filter(array_column($array,$index)));
  352. return Item::where('del_time', 0)
  353. ->where('top_depart_id', $user['top_depart_id'])
  354. ->whereIn('code', $codes)
  355. ->pluck('id','code')
  356. ->toArray();
  357. }
  358. private function itemCheck(&$array, $user, $table_config)
  359. {
  360. $keys = array_column($table_config, 'key');
  361. $codeIdx = array_search('code', $keys);
  362. $stateIdx = array_search('state', $keys);
  363. $manIdx = array_search('man_list', $keys);
  364. $deviceIdx = array_search('device_list', $keys);
  365. // 日期索引
  366. $dateIdx = array_search('start_time', $keys);
  367. $date2Idx = array_search('end_time', $keys);
  368. $code_map = $this->getItemList($array, $user, $codeIdx);
  369. list($man_map, $device_map) = $this->getDataList($array, $user, $manIdx, $deviceIdx);
  370. $errors = [];
  371. $update_mapping = [];
  372. $detail_storage = [];
  373. $state_type_map = array_flip(Item::State_Type);
  374. foreach ($array as $rowIndex => $rowValue) {
  375. $valCode = $rowValue[$codeIdx] ?? '';
  376. // 1. 判定更新还是新增
  377. if (isset($code_map[$valCode])) {
  378. $update_mapping[$rowIndex] = $code_map[$valCode];
  379. }
  380. // 2. 状态校验
  381. $state_text = $rowValue[$stateIdx] ?? '';
  382. if (!isset($state_type_map[$state_text])) {
  383. $errors[] = "第{$rowIndex}行:状态[{$state_text}]无效";
  384. } else {
  385. $array[$rowIndex][$stateIdx] = $state_type_map[$state_text];
  386. }
  387. // 3. 日期转换
  388. foreach ([$dateIdx, $date2Idx] as $dIdx) {
  389. if ($dIdx !== false && !empty($rowValue[$dIdx])) {
  390. list($s, $m) = $this->convertExcelCellToDate($rowValue[$dIdx]);
  391. if (!$s) $errors[] = "第{$rowIndex}行:日期格式非法";
  392. else $array[$rowIndex][$dIdx] = $m;
  393. }
  394. }
  395. // 4. 解析人员 (明细类型1)
  396. if ($manIdx !== false && !empty($rowValue[$manIdx])) {
  397. foreach (explode(',', $rowValue[$manIdx]) as $mNum) {
  398. $mNum = trim($mNum);
  399. if (!isset($man_map[$mNum])) {
  400. $errors[] = "第{$rowIndex}行:人员编码[{$mNum}]不存在";
  401. } else {
  402. $detail_storage[$rowIndex][] = [
  403. 'type' => ItemDetails::type_one,
  404. 'data_id' => $man_map[$mNum],
  405. ];
  406. }
  407. }
  408. }
  409. // 5. 解析设备 (明细类型2)
  410. if ($deviceIdx !== false && !empty($rowValue[$deviceIdx])) {
  411. foreach (explode(',', $rowValue[$deviceIdx]) as $dCode) {
  412. $dCode = trim($dCode);
  413. if (!isset($device_map[$dCode])) {
  414. $errors[] = "第{$rowIndex}行:资产编码[{$dCode}]不存在";
  415. } else {
  416. $detail_storage[$rowIndex][] = [
  417. 'type' => ItemDetails::type_two,
  418. 'data_id' => $device_map[$dCode],
  419. ];
  420. }
  421. }
  422. }
  423. }
  424. $error_str = !empty($errors) ? implode('|', $errors) : "";
  425. return [$error_str, $update_mapping, $detail_storage];
  426. }
  427. private function getDataList($array, $user, $index1, $index2)
  428. {
  429. $manNums = [];
  430. $devCodes = [];
  431. // 去重收集
  432. foreach ($array as $row) {
  433. if (!empty($row[$index1])) {
  434. foreach (explode(',', $row[$index1]) as $v) $manNums[trim($v)] = true;
  435. }
  436. if (!empty($row[$index2])) {
  437. foreach (explode(',', $row[$index2]) as $v) $devCodes[trim($v)] = true;
  438. }
  439. }
  440. $manMap = Employee::where('del_time', 0)
  441. ->where('top_depart_id', $user['top_depart_id'])
  442. ->whereIn('number', array_keys($manNums))
  443. ->pluck('id', 'number')->toArray();
  444. $devMap = Device::where('del_time', 0)
  445. ->where('top_depart_id', $user['top_depart_id'])
  446. ->whereIn('code', array_keys($devCodes))
  447. ->pluck('id', 'code')->toArray();
  448. return [$manMap, $devMap];
  449. }
  450. // 费用 ----------------------------------
  451. public function feeImport($array, $user, $other_param)
  452. {
  453. $upload = $array[0];
  454. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  455. if (!$status) return [false, $msg];
  456. $table_config = $msg;
  457. unset($array[0]);
  458. if (empty($array)) return [false, '导入数据不能为空'];
  459. list($array, $error) = $this->checkCommon($array, $table_config);
  460. if (!empty($error)) return [0, $error];
  461. // 2. 详细校验
  462. list($error, $update_map, $parent_code_map) = $this->feeCheck($array, $user, $table_config);
  463. if (!empty($error)) return [0, $error];
  464. $time = time();
  465. $insert = [];
  466. $update = [];
  467. $all_codes = [];
  468. // --- 修正点 1: 必须确保索引提取准确 ---
  469. $keys = array_column($table_config, 'key');
  470. $codeIdx = array_search('code', $keys);
  471. // ------------------------------------
  472. foreach ($array as $key => $value) {
  473. $cCode = trim($value[$codeIdx] ?? '');
  474. if($cCode === '') continue;
  475. $all_codes[] = $cCode;
  476. $main_tmp = [];
  477. foreach ($value as $k => $val){
  478. if(!empty($table_config[$k]['is_main'])){
  479. if ($table_config[$k]['key'] !== 'parent_id') {
  480. $main_tmp[$table_config[$k]['key']] = $val;
  481. }
  482. }
  483. }
  484. if (isset($update_map[$key])) {
  485. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  486. } else {
  487. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  488. $main_tmp['crt_time'] = $time;
  489. $main_tmp['parent_id'] = 0;
  490. $insert[] = $main_tmp;
  491. }
  492. }
  493. DB::beginTransaction();
  494. try {
  495. if (!empty($insert)) {
  496. foreach (array_chunk($insert, 500) as $chunk) {
  497. Fee::insert($chunk);
  498. }
  499. }
  500. if (!empty($update)) {
  501. foreach ($update as $item) {
  502. $uId = $item['id']; unset($item['id']);
  503. Fee::where('id', $uId)->update($item);
  504. }
  505. }
  506. // --- 修正点 2: 核心回填逻辑 ---
  507. $newCodeToIdMap = Fee::where('del_time', 0)
  508. ->where('top_depart_id', $user['top_depart_id'])
  509. ->whereIn('code', array_unique($all_codes))
  510. ->pluck('id', 'code')
  511. ->toArray();
  512. foreach ($parent_code_map as $rowIndex => $pCode) {
  513. // 这里必须通过 $rowIndex 从原始 $array 中精准获取当前行的编码
  514. $currentCode = isset($array[$rowIndex][$codeIdx]) ? trim($array[$rowIndex][$codeIdx]) : '';
  515. $pCode = trim($pCode);
  516. if ($currentCode === '' || $pCode === '') continue;
  517. $currentId = $newCodeToIdMap[$currentCode] ?? null;
  518. $parentId = $newCodeToIdMap[$pCode] ?? null;
  519. // 严谨判断:只有当前记录存在,且上级记录也存在,且两者不是同一个 ID 时才更新
  520. if ($currentId && $parentId && $currentId != $parentId) {
  521. Fee::where('id', $currentId)->update(['parent_id' => $parentId]);
  522. }
  523. }
  524. DB::commit();
  525. } catch (\Exception $e) {
  526. DB::rollBack();
  527. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  528. }
  529. return [true, ''];
  530. }
  531. private function feeCheck(&$array, $user, $table_config)
  532. {
  533. $keys = array_column($table_config, 'key');
  534. $codeIdx = array_search('code', $keys);
  535. $parentIdx = array_search('parent_id', $keys);
  536. // 1. 获取基础数据
  537. list($dbFeeMap, $excelCodesMap) = $this->getFeeList($array, $user, $codeIdx);
  538. $errors = [];
  539. $update = [];
  540. $parent_code_map = [];
  541. // 2. 建立 Excel 内部父子关系映射(用于环路追溯)
  542. $currentExcelMap = [];
  543. foreach ($array as $row) {
  544. $c = trim($row[$codeIdx] ?? '');
  545. $p = trim($row[$parentIdx] ?? '');
  546. if ($c !== '') $currentExcelMap[$c] = $p;
  547. }
  548. // 3. 逐行校验
  549. foreach ($array as $rowIndex => $value) {
  550. $valCode = trim($value[$codeIdx] ?? '');
  551. $valParentCode = trim($value[$parentIdx] ?? '');
  552. if ($valCode === '') continue;
  553. // 更新状态记录
  554. if (isset($dbFeeMap[$valCode])) {
  555. $update[$rowIndex] = $dbFeeMap[$valCode]['id'];
  556. }
  557. if ($valParentCode !== '') {
  558. // --- A. 存在性校验 ---
  559. // 这里会检查 006 是否在数据库,或者是否在本次 Excel 的其他行中
  560. if (!isset($dbFeeMap[$valParentCode]) && !isset($excelCodesMap[$valParentCode])) {
  561. $errors[] = "第{$rowIndex}行:上级编码[{$valParentCode}]在系统和文件中均不存在";
  562. continue;
  563. }
  564. // --- B. 自引用校验 ---
  565. if ($valCode === $valParentCode) {
  566. $errors[] = "第{$rowIndex}行:上级编码不能是自身";
  567. continue;
  568. }
  569. // --- C. 环路追溯 ---
  570. $visited = [];
  571. $res = $this->findLoopInAncestors($valParentCode, $valCode, $currentExcelMap, $dbFeeMap, $visited);
  572. if ($res !== false) {
  573. if ($res['type'] === 'LOOP_SELF') {
  574. $errors[] = "第{$rowIndex}行:编码[{$valCode}]与上级[{$valParentCode}]存在循环引用";
  575. } else {
  576. $errors[] = "第{$rowIndex}行:上级[{$valParentCode}]的溯源链条已成环";
  577. }
  578. continue;
  579. }
  580. // 记录有效的父级关系
  581. $parent_code_map[$rowIndex] = $valParentCode;
  582. }
  583. }
  584. $error_string = !empty($errors) ? implode('|', $errors) : "";
  585. return [$error_string, $update, $parent_code_map];
  586. }
  587. private function getFeeList($array, $user, $index)
  588. {
  589. // 关键:一定要把 Excel 里所有的 code 这一列全部拿出来,并去除空值
  590. $codesInExcel = [];
  591. foreach ($array as $row) {
  592. $c = trim($row[$index] ?? '');
  593. if ($c !== '') {
  594. $codesInExcel[$c] = true;
  595. }
  596. }
  597. $allFees = Fee::where('del_time', 0)
  598. ->where('top_depart_id', $user['top_depart_id'])
  599. ->select('id', 'code', 'parent_id')
  600. ->get();
  601. $dbFeeMap = [];
  602. foreach ($allFees as $fee) {
  603. $dbFeeMap[$fee->code] = [
  604. 'id' => $fee->id,
  605. 'code' => $fee->code,
  606. 'parent_id' => $fee->parent_id
  607. ];
  608. }
  609. // 返回数据库映射和 Excel 编码映射
  610. return [$dbFeeMap, $codesInExcel];
  611. }
  612. private function findLoopInAncestors($startParentCode, $targetCode, $excelMap, $dbFeeMap, &$visited)
  613. {
  614. $current = $startParentCode;
  615. while ($current !== '' && $current !== 0) {
  616. if ($current === $targetCode) {
  617. return ['type' => 'LOOP_SELF', 'code' => $current];
  618. }
  619. if (isset($visited[$current])) {
  620. return ['type' => 'EXISTING_LOOP', 'code' => $current];
  621. }
  622. $visited[$current] = true;
  623. if (isset($excelMap[$current]) && $excelMap[$current] !== '') {
  624. $current = $excelMap[$current];
  625. } elseif (isset($dbFeeMap[$current])) {
  626. $parentId = $dbFeeMap[$current]['parent_id'];
  627. $parentCode = '';
  628. foreach ($dbFeeMap as $item) {
  629. if ($item['id'] == $parentId) {
  630. $parentCode = $item['code'];
  631. break;
  632. }
  633. }
  634. $current = $parentCode;
  635. } else {
  636. break;
  637. }
  638. }
  639. return false;
  640. }
  641. // 人员月度工时单 ------------------------------
  642. public function monthPwOrderImport($array, $user, $other_param)
  643. {
  644. $upload = $array[0];
  645. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  646. if (!$status) return [false, $msg];
  647. $table_config = $msg;
  648. unset($array[0]);
  649. if (empty($array)) return [false, '导入数据不能为空'];
  650. list($array, $error) = $this->checkCommon($array, $table_config);
  651. if (!empty($error)) return [0, $error];
  652. // 2. 详细校验 (这里会返回 update_map 和 dbEmps 映射)
  653. list($error, $update_map, $dbEmps) = $this->monthPwOrderCheck($array, $user, $table_config);
  654. if (!empty($error)) return [0, $error];
  655. $keys = array_column($table_config, 'key');
  656. $codeIdx = array_search('code', $keys);
  657. $monthIdx = array_search('month', $keys);
  658. $empIdx = array_search('employee_id', $keys);
  659. // --- 步骤 1: 数据聚合分组 ---
  660. // 将 Excel 数据按“单据”维度归类
  661. $groups = [];
  662. foreach ($array as $rowIndex => $row) {
  663. $cCode = trim($row[$codeIdx] ?? '');
  664. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  665. // 聚合 Key:有编码用编码,没编码用月份标记
  666. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  667. if (!isset($groups[$aggKey])) {
  668. $groups[$aggKey] = [
  669. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  670. 'code' => $cCode,
  671. 'month' => $cMonthTs,
  672. 'details' => []
  673. ];
  674. }
  675. // 准备详情行数据
  676. $detailTmp = [];
  677. foreach ($table_config as $k => $conf) {
  678. if (!$conf['is_main']) {
  679. $fieldKey = $conf['key'];
  680. $fieldVal = $row[$k];
  681. // 如果是人员,转换为 ID
  682. if ($fieldKey == 'employee_id') {
  683. $fieldVal = $dbEmps[$fieldVal] ?? 0;
  684. }
  685. $detailTmp[$fieldKey] = $fieldVal;
  686. }
  687. }
  688. $groups[$aggKey]['details'][] = $detailTmp;
  689. }
  690. // --- 步骤 2: 开启事务写入 ---
  691. DB::beginTransaction();
  692. try {
  693. $time = time();
  694. foreach ($groups as $aggKey => $group) {
  695. $mainId = $group['main_id'];
  696. if ($mainId > 0) {
  697. // 删除旧详情
  698. DB::table('monthly_pw_order_details')->where('del_time',0)
  699. ->where('main_id', $mainId)
  700. ->update(['del_time' => $time]);
  701. } else {
  702. // B. 新增逻辑
  703. $newCode = $this->generateBillNo([
  704. 'top_depart_id' => $user['top_depart_id'],
  705. 'type' => MonthlyPwOrder::Order_type,
  706. 'period' => date("Ym", $group['month'])
  707. ]);
  708. $mainId = DB::table('monthly_pw_order')->insertGetId([
  709. 'code' => $newCode,
  710. 'month' => $group['month'],
  711. 'top_depart_id' => $user['top_depart_id'],
  712. 'crt_id' => $user['id'],
  713. 'crt_time' => $time,
  714. 'upd_time' => $time,
  715. 'del_time' => 0
  716. ]);
  717. }
  718. // C. 批量插入详情
  719. $insertDetails = [];
  720. foreach ($group['details'] as $detail) {
  721. $detail['main_id'] = $mainId;
  722. $detail['top_depart_id']= $user['top_depart_id'];
  723. $detail['crt_time'] = $time;
  724. $detail['del_time'] = 0;
  725. $insertDetails[] = $detail;
  726. }
  727. if (!empty($insertDetails)) {
  728. DB::table('monthly_pw_order_details')->insert($insertDetails);
  729. }
  730. }
  731. DB::commit();
  732. } catch (\Exception $e) {
  733. DB::rollBack();
  734. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  735. }
  736. return [true, ''];
  737. }
  738. private function monthPwOrderCheck(&$array, $user, $table_config)
  739. {
  740. $keys = array_column($table_config, 'key');
  741. $codeIdx = array_search('code', $keys);
  742. $monthIdx = array_search('month', $keys);
  743. $empIdx = array_search('employee_id', $keys);
  744. $startIdx = array_search('start_time', $keys);
  745. $endIdx = array_search('end_time', $keys);
  746. // 1. 预加载基础数据
  747. $allEmpNumbers = array_filter(array_unique(array_column($array, $empIdx)));
  748. $dbEmps = Employee::where('del_time', 0)
  749. ->whereIn('number', $allEmpNumbers)
  750. ->where('top_depart_id', $user['top_depart_id'])
  751. ->pluck('id', 'number')->toArray();
  752. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  753. $dbOrders = DB::table('monthly_pw_order')
  754. ->whereIn('code', $allCodes)
  755. ->where('top_depart_id', $user['top_depart_id'])
  756. ->get()->keyBy('code');
  757. $existingMonths = DB::table('monthly_pw_order')
  758. ->where('top_depart_id', $user['top_depart_id'])
  759. ->pluck('month')
  760. ->toArray();
  761. $existingMonthsMap = array_fill_keys($existingMonths, true);
  762. $excelAggregator = [];
  763. $errors = [];
  764. $update_map = [];
  765. foreach ($array as $rowIndex => $row) {
  766. // 用户看到的行号(假设数据从第2行开始)
  767. $displayLine = $rowIndex + 1;
  768. $valCode = trim($row[$codeIdx] ?? '');
  769. $valMonthRaw = trim($row[$monthIdx] ?? '');
  770. $valEmp = trim($row[$empIdx] ?? '');
  771. $valStartRaw = $row[$startIdx] ?? '';
  772. $valEndRaw = $row[$endIdx] ?? '';
  773. // --- A. 日期转换校验 ---
  774. // 转换月份
  775. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  776. if (!$mStatus) {
  777. $errors[] = "第{$displayLine}行:月份格式错误({$valMonthRaw})";
  778. continue;
  779. }
  780. // 强制格式化为当月1号的时间戳,确保聚合逻辑一致
  781. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  782. // 转换开始日期
  783. list($sStatus, $startTime) = $this->convertExcelCellToDate($valStartRaw);
  784. if (!$sStatus) {
  785. $errors[] = "第{$displayLine}行:开始日期格式错误";
  786. continue;
  787. }
  788. // 转换结束日期
  789. list($eStatus, $endTime) = $this->convertExcelCellToDate($valEndRaw);
  790. if (!$eStatus) {
  791. $errors[] = "第{$displayLine}行:结束日期格式错误";
  792. continue;
  793. }
  794. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  795. // --- B. 校验单据与月份的一致性 ---
  796. if ($valCode && isset($dbOrders[$valCode])) {
  797. $dbOrder = $dbOrders[$valCode];
  798. if ($dbOrder->month != $valMonthTs) {
  799. $errors[] = "第{$displayLine}行:单据编码[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入月份不符";
  800. }
  801. $update_map[$rowIndex] = $dbOrder->id;
  802. }
  803. // --- C. 校验人员存在性与单据内唯一性 ---
  804. if (!isset($dbEmps[$valEmp])) {
  805. $errors[] = "第{$displayLine}行:人员工号[{$valEmp}]不存在";
  806. } else {
  807. if (isset($excelAggregator[$aggKey]['emps'][$valEmp])) {
  808. $errors[] = "第{$displayLine}行:人员[{$valEmp}]在同一单据中重复";
  809. }
  810. $excelAggregator[$aggKey]['emps'][$valEmp] = true;
  811. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  812. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  813. }
  814. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  815. }
  816. // --- D. 逻辑校验:日期范围 ---
  817. if ($startTime > $endTime) {
  818. $errors[] = "第{$displayLine}行:开始日期大于结束日期";
  819. } else {
  820. $monthEndTs = strtotime("+1 month", $valMonthTs) - 1;
  821. if ($startTime < $valMonthTs || $endTime > $monthEndTs) {
  822. $errors[] = "第{$displayLine}行:日期超出[ " . date('Y-m', $valMonthTs) . " ]范围";
  823. }
  824. }
  825. // --- E. 月份唯一单据校验 (新增) ---
  826. if (!$valCode) {
  827. if (isset($existingMonthsMap[$valMonthTs])) {
  828. $errors[] = "第{$displayLine}行:月份[ " . date('Y-m', $valMonthTs) . " ]已存在单据,请填编码编辑";
  829. }
  830. }
  831. // 将转换后的时间戳写回原数组,方便后续写入数据库时直接使用
  832. $array[$rowIndex][$monthIdx] = $valMonthTs;
  833. $array[$rowIndex][$startIdx] = $startTime;
  834. $array[$rowIndex][$endIdx] = $endTime;
  835. }
  836. $error_string = !empty($errors) ? implode('|', $errors) : "";
  837. return [$error_string, $update_map, $dbEmps];
  838. }
  839. // 设备月度工时单
  840. public function monthDwOrderImport($array, $user, $other_param)
  841. {
  842. $upload = $array[0];
  843. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  844. if (!$status) return [false, $msg];
  845. $table_config = $msg;
  846. unset($array[0]);
  847. if (empty($array)) return [false, '导入数据不能为空'];
  848. list($array, $error) = $this->checkCommon($array, $table_config);
  849. if (!empty($error)) return [0, $error];
  850. // 2. 详细校验 (这里会返回 update_map 和 dbDevs 映射)
  851. list($error, $update_map, $dbDevs) = $this->monthDwOrderCheck($array, $user, $table_config);
  852. if (!empty($error)) return [0, $error];
  853. $keys = array_column($table_config, 'key');
  854. $codeIdx = array_search('code', $keys);
  855. $monthIdx = array_search('month', $keys);
  856. $empIdx = array_search('device_id', $keys);
  857. // --- 步骤 1: 数据聚合分组 ---
  858. // 将 Excel 数据按“单据”维度归类
  859. $groups = [];
  860. foreach ($array as $rowIndex => $row) {
  861. $cCode = trim($row[$codeIdx] ?? '');
  862. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  863. // 聚合 Key:有编码用编码,没编码用月份标记
  864. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  865. if (!isset($groups[$aggKey])) {
  866. $groups[$aggKey] = [
  867. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  868. 'code' => $cCode,
  869. 'month' => $cMonthTs,
  870. 'details' => []
  871. ];
  872. }
  873. // 准备详情行数据
  874. $detailTmp = [];
  875. foreach ($table_config as $k => $conf) {
  876. if (!$conf['is_main']) {
  877. $fieldKey = $conf['key'];
  878. $fieldVal = $row[$k];
  879. // 如果是人员,转换为 ID
  880. if ($fieldKey == 'device_id') {
  881. $fieldVal = $dbDevs[$fieldVal] ?? 0;
  882. }
  883. $detailTmp[$fieldKey] = $fieldVal;
  884. }
  885. }
  886. $groups[$aggKey]['details'][] = $detailTmp;
  887. }
  888. // --- 步骤 2: 开启事务写入 ---
  889. DB::beginTransaction();
  890. try {
  891. $time = time();
  892. foreach ($groups as $aggKey => $group) {
  893. $mainId = $group['main_id'];
  894. if ($mainId > 0) {
  895. // 删除旧详情
  896. DB::table('monthly_dw_order_details')->where('del_time',0)
  897. ->where('main_id', $mainId)
  898. ->update(['del_time' => $time]);
  899. } else {
  900. // B. 新增逻辑
  901. $newCode = $this->generateBillNo([
  902. 'top_depart_id' => $user['top_depart_id'],
  903. 'type' => MonthlyPwOrder::Order_type,
  904. 'period' => date("Ym", $group['month'])
  905. ]);
  906. $mainId = DB::table('monthly_dw_order')->insertGetId([
  907. 'code' => $newCode,
  908. 'month' => $group['month'],
  909. 'top_depart_id' => $user['top_depart_id'],
  910. 'crt_id' => $user['id'],
  911. 'crt_time' => $time,
  912. 'upd_time' => $time,
  913. 'del_time' => 0
  914. ]);
  915. }
  916. // C. 批量插入详情
  917. $insertDetails = [];
  918. foreach ($group['details'] as $detail) {
  919. $detail['main_id'] = $mainId;
  920. $detail['top_depart_id']= $user['top_depart_id'];
  921. $detail['crt_time'] = $time;
  922. $detail['del_time'] = 0;
  923. $insertDetails[] = $detail;
  924. }
  925. if (!empty($insertDetails)) {
  926. DB::table('monthly_dw_order_details')->insert($insertDetails);
  927. }
  928. }
  929. DB::commit();
  930. } catch (\Exception $e) {
  931. DB::rollBack();
  932. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  933. }
  934. return [true, ''];
  935. }
  936. private function monthDwOrderCheck(&$array, $user, $table_config)
  937. {
  938. $keys = array_column($table_config, 'key');
  939. $codeIdx = array_search('code', $keys);
  940. $monthIdx = array_search('month', $keys);
  941. $devIdx = array_search('device_id', $keys);
  942. $startIdx = array_search('start_time', $keys);
  943. $endIdx = array_search('end_time', $keys);
  944. // 1. 预加载基础数据
  945. $allEmpNumbers = array_filter(array_unique(array_column($array, $devIdx)));
  946. $dbDevs = Device::where('del_time', 0)
  947. ->whereIn('code', $allEmpNumbers)
  948. ->where('top_depart_id', $user['top_depart_id'])
  949. ->pluck('id', 'code')->toArray();
  950. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  951. $dbOrders = DB::table('monthly_dw_order')
  952. ->whereIn('code', $allCodes)
  953. ->where('top_depart_id', $user['top_depart_id'])
  954. ->get()->keyBy('code');
  955. $existingMonths = DB::table('monthly_dw_order')
  956. ->where('top_depart_id', $user['top_depart_id'])
  957. ->pluck('month')
  958. ->toArray();
  959. $existingMonthsMap = array_fill_keys($existingMonths, true);
  960. $excelAggregator = [];
  961. $errors = [];
  962. $update_map = [];
  963. foreach ($array as $rowIndex => $row) {
  964. // 用户看到的行号(假设数据从第2行开始)
  965. $displayLine = $rowIndex + 1;
  966. $valCode = trim($row[$codeIdx] ?? '');
  967. $valMonthRaw = trim($row[$monthIdx] ?? '');
  968. $valDev = trim($row[$devIdx] ?? '');
  969. $valStartRaw = $row[$startIdx] ?? '';
  970. $valEndRaw = $row[$endIdx] ?? '';
  971. // --- A. 日期转换校验 ---
  972. // 转换月份
  973. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  974. if (!$mStatus) {
  975. $errors[] = "第{$displayLine}行:月份格式错误({$valMonthRaw})";
  976. continue;
  977. }
  978. // 强制格式化为当月1号的时间戳,确保聚合逻辑一致
  979. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  980. // 转换开始日期
  981. list($sStatus, $startTime) = $this->convertExcelCellToDate($valStartRaw);
  982. if (!$sStatus) {
  983. $errors[] = "第{$displayLine}行:开始日期格式错误";
  984. continue;
  985. }
  986. // 转换结束日期
  987. list($eStatus, $endTime) = $this->convertExcelCellToDate($valEndRaw);
  988. if (!$eStatus) {
  989. $errors[] = "第{$displayLine}行:结束日期格式错误";
  990. continue;
  991. }
  992. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  993. // --- B. 校验单据与月份的一致性 ---
  994. if ($valCode && isset($dbOrders[$valCode])) {
  995. $dbOrder = $dbOrders[$valCode];
  996. if ($dbOrder->month != $valMonthTs) {
  997. $errors[] = "第{$displayLine}行:单据编码[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入月份不符";
  998. }
  999. $update_map[$rowIndex] = $dbOrder->id;
  1000. }
  1001. // --- C. 校验设备存在性与单据内唯一性 ---
  1002. if (!isset($dbDevs[$valDev])) {
  1003. $errors[] = "第{$displayLine}行:设备的资产编码[{$valDev}]不存在";
  1004. } else {
  1005. if (isset($excelAggregator[$aggKey]['devs'][$valDev])) {
  1006. $errors[] = "第{$displayLine}行:设备的资产编码[{$valDev}]在同一单据中重复";
  1007. }
  1008. $excelAggregator[$aggKey]['devs'][$valDev] = true;
  1009. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  1010. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  1011. }
  1012. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  1013. }
  1014. // --- D. 逻辑校验:日期范围 ---
  1015. if ($startTime > $endTime) {
  1016. $errors[] = "第{$displayLine}行:开始日期大于结束日期";
  1017. } else {
  1018. $monthEndTs = strtotime("+1 month", $valMonthTs) - 1;
  1019. if ($startTime < $valMonthTs || $endTime > $monthEndTs) {
  1020. $errors[] = "第{$displayLine}行:日期超出[ " . date('Y-m', $valMonthTs) . " ]范围";
  1021. }
  1022. }
  1023. // --- E. 月份唯一单据校验 (新增) ---
  1024. if (!$valCode) {
  1025. if (isset($existingMonthsMap[$valMonthTs])) {
  1026. $errors[] = "第{$displayLine}行:月份[ " . date('Y-m', $valMonthTs) . " ]已存在单据,请填编码编辑";
  1027. }
  1028. }
  1029. // 将转换后的时间戳写回原数组,方便后续写入数据库时直接使用
  1030. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1031. $array[$rowIndex][$startIdx] = $startTime;
  1032. $array[$rowIndex][$endIdx] = $endTime;
  1033. }
  1034. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1035. return [$error_string, $update_map, $dbDevs];
  1036. }
  1037. //公共校验 -----------------------------------------
  1038. private function checkCommon($array, $table_config) {
  1039. $error = [];
  1040. $uniqueCheck = []; // 格式:[$column_index => [$value => $first_line]]
  1041. foreach ($array as $line => $row) {
  1042. $rowData = array_filter($row);
  1043. if (empty($rowData)) {
  1044. unset($array[$line]);
  1045. continue;
  1046. }
  1047. foreach ($row as $colIndex => $value) {
  1048. $value = trim($value);
  1049. $config = $table_config[$colIndex] ?? null;
  1050. // 1. 基础存在性检查
  1051. if (!$config) {
  1052. $error[] = "第{$line}行第{$colIndex}列配置不存在";
  1053. continue;
  1054. }
  1055. $fieldName = $config['value'];
  1056. // 2. 必填校验
  1057. if (!empty($config['required']) && ($value === '' || !isset($value))) {
  1058. $error[] = "第{$line}行:[{$fieldName}] 必填";
  1059. }
  1060. // 3. 默认值填充
  1061. if ($value === '' && isset($config['default'])) {
  1062. $value = $config['default'];
  1063. }
  1064. // 4. 唯一性校验(重点:一次遍历解决)
  1065. if (!empty($config['unique']) && $value !== '') {
  1066. if (isset($uniqueCheck[$colIndex][$value])) {
  1067. $prevLine = $uniqueCheck[$colIndex][$value];
  1068. $error[] = "第{$line}行:[{$fieldName}] 与第{$prevLine}行重复,重复值:{$value}";
  1069. } else {
  1070. // 记录该值第一次出现的位置
  1071. $uniqueCheck[$colIndex][$value] = $line;
  1072. }
  1073. }
  1074. $row[$colIndex] = $value;
  1075. }
  1076. $array[$line] = $row;
  1077. }
  1078. $error_string = !empty($error) ? implode('|', $error) : "";
  1079. return [$array, $error_string];
  1080. }
  1081. //模板校验 -----------------------------------------
  1082. private function compareTableAndReturn($upload, $param){
  1083. if(empty($upload)) return [false, '表头不能为空'];
  1084. $config = $this->getTableConfig($param['type']);
  1085. $config_array = $config['array'];
  1086. if(empty($config_array)) return [false, '导入配置表头文件不存在'];
  1087. foreach ($config_array as $key => $value){
  1088. $key_position = $key + 1;
  1089. if(! isset($upload[$key])) return [false, "第" . $key_position . "列表头缺失"];
  1090. $tmp_v = trim($upload[$key]);
  1091. if($tmp_v != $value['value']) return [false, "第" . $key_position . "列表头与模板不符合,请重新下载模板"];
  1092. }
  1093. return [true, $config_array];
  1094. }
  1095. //转换日期 ------------------------------------------
  1096. function convertExcelCellToDate($cellValue) {
  1097. // 尝试将单元格值转换为浮点数(Excel 日期序列号)
  1098. $excelTimestamp = filter_var($cellValue, FILTER_VALIDATE_FLOAT);
  1099. if ($excelTimestamp !== false && $excelTimestamp > 0) {
  1100. // 如果成功转换并且值大于0,则认为是Excel日期序列号
  1101. try {
  1102. $dateTimeObject = Date::excelToDateTimeObject($cellValue);
  1103. // if ($dateTimeObject->format('H:i:s') === '00:00:00') {
  1104. // // 如果是,则将时间设置为 '23:59:00'
  1105. // $dateTimeObject->setTime(23, 59);
  1106. // }
  1107. // 现在你可以格式化这个日期了
  1108. $formattedDate = $dateTimeObject->format('Y-m-d');
  1109. if(! strtotime($formattedDate)) return [false, ''];
  1110. return [true, strtotime($formattedDate)];
  1111. } catch (\Exception $e) {
  1112. // 处理转换失败的情况
  1113. return [false, '单元格日期格式转换时间戳失败'];
  1114. }
  1115. }
  1116. // 如果不是有效的浮点数,则尝试按照多种日期格式解析
  1117. if(! strtotime($cellValue)) return [false, '单元格文本格式转换时间戳失败'];
  1118. return [true, strtotime($cellValue)];
  1119. }
  1120. }