ImportService.php 41 KB

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