ImportService.php 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  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\MonthlyDdOrder;
  11. use App\Model\MonthlyPsOrder;
  12. use App\Model\MonthlyPwOrder;
  13. use Illuminate\Support\Facades\DB;
  14. use Maatwebsite\Excel\Facades\Excel;
  15. use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F;
  16. use PhpOffice\PhpSpreadsheet\IOFactory;
  17. use PhpOffice\PhpSpreadsheet\Shared\Date;
  18. class ImportService extends Service
  19. {
  20. public static $type = [
  21. 'device', // 设备
  22. 'item', // 项目
  23. 'fee', // 费用
  24. 'monthPwOrder', // 人员月度研发工时单
  25. 'monthDwOrder', // 设备月度研发工时单
  26. 'monthPsOrder', // 人员月度工资单
  27. 'monthDdOrder', // 设备月度折旧单
  28. ];
  29. public function getTableTitleXls($data,$user){
  30. if(empty($data['type'])) return [false,'缺少类型'];
  31. if(! in_array($data['type'],self::$type)) return [false,'类型不存在'];
  32. //获取配置文件
  33. $fuc = $data['type'];
  34. if (! method_exists(self::class, $fuc)) return [false, "导入文件获取不存在,请联系开发"];
  35. list($status,$return) = $this->$fuc($data,$user);
  36. list($msg,$filename) = $return;
  37. if(! $status) return [false, $msg];
  38. $headers = array_column($msg,'value');
  39. $comments = $enums = [];
  40. foreach ($msg as $value){
  41. if(! empty($value['comments'])) $comments[$value['value']] = $value['comments'];
  42. if(! empty($value['enums'])) $enums[$value['value']] = $value['enums'];
  43. }
  44. Excel::store(new TableHeadExport([], $headers, $comments, $enums),"/public/export/{$filename}", null, 'Xlsx', []);
  45. return [true, ['file' => $filename]];
  46. }
  47. private function getTableConfig($type = ""){
  48. if(empty($type)) return [];
  49. //获取配置文件
  50. $config = "excel." . $type;
  51. return config($config) ?? [];
  52. }
  53. private function device($data,$user){
  54. $config = $this->getTableConfig($data['type']);
  55. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  56. $config_array = $config['array'] ?? [];
  57. //生成下载文件
  58. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  59. return [true, [$config_array, $filename]];
  60. }
  61. private function item($data,$user){
  62. $config = $this->getTableConfig($data['type']);
  63. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  64. $config_array = $config['array'] ?? [];
  65. //生成下载文件
  66. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  67. return [true, [$config_array, $filename]];
  68. }
  69. private function fee($data,$user){
  70. $config = $this->getTableConfig($data['type']);
  71. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  72. $config_array = $config['array'] ?? [];
  73. //生成下载文件
  74. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  75. return [true, [$config_array, $filename]];
  76. }
  77. private function monthPwOrder($data,$user){
  78. $config = $this->getTableConfig($data['type']);
  79. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  80. $config_array = $config['array'] ?? [];
  81. //生成下载文件
  82. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  83. return [true, [$config_array, $filename]];
  84. }
  85. private function monthDwOrder($data,$user){
  86. $config = $this->getTableConfig($data['type']);
  87. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  88. $config_array = $config['array'] ?? [];
  89. //生成下载文件
  90. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  91. return [true, [$config_array, $filename]];
  92. }
  93. private function monthPsOrder($data,$user){
  94. $config = $this->getTableConfig($data['type']);
  95. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  96. $config_array = $config['array'] ?? [];
  97. //生成下载文件
  98. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  99. return [true, [$config_array, $filename]];
  100. }
  101. private function monthDdOrder($data,$user){
  102. $config = $this->getTableConfig($data['type']);
  103. if(empty($config)) return [false, ['导入配置表头文件不存在','']];
  104. $config_array = $config['array'] ?? [];
  105. //生成下载文件
  106. $filename = $config['name'] . "导入模板_" . time() . '.' . 'xlsx';
  107. return [true, [$config_array, $filename]];
  108. }
  109. //导入入口
  110. public function importAll($data,$user){
  111. // //不超时
  112. // ini_set('max_execution_time', 0);
  113. // //内存设置
  114. // ini_set('memory_limit', -1);
  115. // $reader = IOFactory::createReader('Xlsx');
  116. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  117. // $spreadsheet = $reader->load($data['file']);
  118. // dd($spreadsheet);
  119. // // 创建一个Reader对象
  120. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  121. //
  122. //// 加载Excel文件
  123. // $spreadsheet = $reader->load($data['file']);
  124. //
  125. //// 获取第一个工作表
  126. // $worksheet = $spreadsheet->getActiveSheet();
  127. //
  128. //// 获取总行数
  129. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  130. if(empty($data['type'])) return [false,'缺少导入类型,导入失败'];
  131. if(! in_array($data['type'],self::$type)) return [false,'导入类型不存在,导入失败'];
  132. if(empty($data['file'])) return [false,'导入文件不能为空'];
  133. try {
  134. $import = new ImportAll();
  135. //设置导入人id
  136. $import->setCrt($user['id']);
  137. $import->setUser($user);
  138. $import->setType($data['type']);
  139. $other = $data;
  140. unset($other['file']);
  141. $import->setOtherParam($other);
  142. //导入
  143. \Maatwebsite\Excel\Facades\Excel::import($import,$data['file']);
  144. if($import->getMsg()) {
  145. $bool = $import->getIsLongText();
  146. if($bool) {
  147. return [0, $import->getMsg()];
  148. }else{
  149. return [false, $import->getMsg()];
  150. }
  151. }
  152. }catch (\Throwable $exception) {
  153. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  154. }
  155. return [true, ''];
  156. }
  157. // 设备 ------------------------------------
  158. public function deviceImport($array, $user, $other_param){
  159. $upload = $array[0];
  160. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  161. if(!$status) return [false, $msg];
  162. $table_config = $msg;
  163. unset($array[0]);
  164. if(empty($array)) return [false, '导入数据不能为空'];
  165. // 公共校验
  166. list($array, $error) = $this->checkCommon($array, $table_config);
  167. if(!empty($error)) return [0, $error];
  168. // 详细校验 (这里 $array 传引用,内部会转换日期)
  169. list($error, $update_map) = $this->deviceCheck($array, $user, $table_config);
  170. if(!empty($error)) return [0, $error];
  171. $time = time();
  172. $insert = [];
  173. $update = [];
  174. foreach ($array as $key => $value){
  175. $main_tmp = [];
  176. foreach ($value as $k => $val){
  177. if(!empty($table_config[$k]['is_main'])){
  178. $main_tmp[$table_config[$k]['key']] = $val;
  179. }
  180. }
  181. if(isset($update_map[$key])){
  182. // 存入待更新数组
  183. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  184. } else {
  185. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  186. $main_tmp['crt_id'] = $user['id'];
  187. $main_tmp['crt_time'] = $time;
  188. $insert[] = $main_tmp;
  189. }
  190. }
  191. DB::beginTransaction();
  192. try {
  193. // 1. 批量新增
  194. if(!empty($insert)){
  195. foreach(array_chunk($insert, 500) as $chunkInsert){
  196. Device::insert($chunkInsert);
  197. }
  198. }
  199. // 批量更新
  200. foreach (array_chunk($update, 100) as $chunk) {
  201. foreach ($chunk as $item) {
  202. $id = $item['id'];
  203. unset($item['id']);
  204. Device::where('id', $id)->update($item);
  205. }
  206. }
  207. DB::commit();
  208. } catch (\Exception $e) {
  209. DB::rollBack();
  210. return [false, "错误:" . $e->getMessage() . " 行:" . $e->getLine()];
  211. }
  212. return [true, ''];
  213. }
  214. private function deviceCheck(&$array, $user, $table_config)
  215. {
  216. // 动态获取关键列的索引
  217. $codeIdx = array_search('code', array_column($table_config, 'key'));
  218. $dateIdx = array_search('in_time', array_column($table_config, 'key'));
  219. $typeIdx = array_search('type', array_column($table_config, 'key'));
  220. $type2Idx = array_search('is_use', array_column($table_config, 'key'));
  221. $code_map = $this->getDeviceList($array, $user, $codeIdx);
  222. $errors = [];
  223. $update = [];
  224. $map_type = array_flip(Device::$type);
  225. $map_type_2 = array_flip(Device::Use);
  226. foreach ($array as $rowIndex => $value) {
  227. $displayLine = $rowIndex + 1;
  228. $valCode = $value[$codeIdx] ?? '';
  229. // 记录更新 ID
  230. if(isset($code_map[$valCode])){
  231. $update[$rowIndex] = $code_map[$valCode];
  232. }
  233. if(empty($map_type[$value[$typeIdx]])){
  234. $errors[] = "第{$displayLine}行固定资产类型错误";
  235. }else{
  236. $array[$rowIndex][$typeIdx] = $map_type[$value[$typeIdx]];
  237. }
  238. if(empty($map_type_2[$value[$type2Idx]])){
  239. $errors[] = "第{$displayLine}行是否启用错误";
  240. }else{
  241. $array[$rowIndex][$type2Idx] = $map_type_2[$value[$type2Idx]];
  242. }
  243. // 日期处理
  244. if($dateIdx !== false && !empty($value[$dateIdx])){
  245. list($status, $msg) = $this->convertExcelCellToDate($value[$dateIdx]);
  246. if(!$status) {
  247. $errors[] = "第{$displayLine}行日期格式错误";
  248. } else {
  249. $array[$rowIndex][$dateIdx] = $msg;
  250. }
  251. }
  252. }
  253. $error_string = "";
  254. if(! empty($errors)) $error_string = implode('|', $errors);
  255. return [$error_string, $update];
  256. }
  257. private function getDeviceList($array, $user, $index){
  258. //查找设备
  259. $codes = array_unique(array_filter(array_column($array,$index)));
  260. return Device::where('del_time', 0)
  261. ->where('top_depart_id', $user['top_depart_id'])
  262. ->whereIn('code', $codes)
  263. ->pluck('id','code')
  264. ->toArray();
  265. }
  266. // 项目 -----------------------------------
  267. public function itemImport($array, $user, $other_param)
  268. {
  269. $upload = $array[0];
  270. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  271. if (!$status) return [false, $msg];
  272. $table_config = $msg;
  273. unset($array[0]);
  274. if (empty($array)) return [false, '导入数据不能为空'];
  275. // 1. 公共校验 (必填、唯一性等)
  276. list($array, $error) = $this->checkCommon($array, $table_config);
  277. if (!empty($error)) return [0, $error];
  278. // 2. 业务详细校验 (获取更新映射及明细数据)
  279. list($error, $update_map, $detail_data_map) = $this->itemCheck($array, $user, $table_config);
  280. if (!empty($error)) return [0, $error];
  281. $time = time();
  282. $insert_data = [];
  283. $update_data = [];
  284. $all_detail_insert = [];
  285. $update_main_ids = [];
  286. // 3. 数据分拣
  287. foreach ($array as $key => $value) {
  288. $main_tmp = [];
  289. foreach ($value as $k => $val) {
  290. if (!empty($table_config[$k]['is_main'])) {
  291. $main_tmp[$table_config[$k]['key']] = $val;
  292. }
  293. }
  294. if (isset($update_map[$key])) {
  295. // 更新逻辑
  296. $itemId = $update_map[$key];
  297. $update_data[] = array_merge($main_tmp, ['id' => $itemId]);
  298. $update_main_ids[] = $itemId;
  299. // 收集明细 (后续统一插入)
  300. if (isset($detail_data_map[$key])) {
  301. foreach ($detail_data_map[$key] as $d) {
  302. $all_detail_insert[] = array_merge($d, ['item_id' => $itemId, 'crt_time' => $time, 'top_depart_id' => $user['top_depart_id']]);
  303. }
  304. }
  305. } else {
  306. // 新增逻辑
  307. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  308. $main_tmp['crt_id'] = $user['id'];
  309. $main_tmp['crt_time'] = $time;
  310. // 以 code 为键,方便后续回填 ID
  311. $insert_data[$main_tmp['code']] = $main_tmp;
  312. if (isset($detail_data_map[$key])) {
  313. foreach ($detail_data_map[$key] as $d) {
  314. $all_detail_insert[] = array_merge($d, ['_code' => $main_tmp['code'], 'crt_time' => $time, 'top_depart_id' => $main_tmp['top_depart_id']]);
  315. }
  316. }
  317. }
  318. }
  319. DB::beginTransaction();
  320. try {
  321. // 4. 执行新增主表
  322. if (!empty($insert_data)) {
  323. foreach (array_chunk($insert_data, 500) as $chunk) {
  324. Item::insert($chunk);
  325. }
  326. // 获取新插入数据的 ID 映射
  327. $new_item_maps = Item::whereIn('code', array_keys($insert_data))
  328. ->where('del_time', 0)
  329. ->where('top_depart_id', $user['top_depart_id'])
  330. ->pluck('id', 'code')->toArray();
  331. }
  332. // 5. 执行更新主表 (分批更新)
  333. if (!empty($update_data)) {
  334. foreach (array_chunk($update_data, 100) as $chunk) {
  335. foreach ($chunk as $uItem) {
  336. $id = $uItem['id'];
  337. unset($uItem['id']);
  338. Item::where('id', $id)->update($uItem);
  339. }
  340. }
  341. }
  342. // 6. 处理明细表 (先删后插策略)
  343. // 删除旧明细 (逻辑删除)
  344. if (!empty($update_main_ids)) {
  345. ItemDetails::whereIn('item_id', $update_main_ids)
  346. ->where('del_time', 0)
  347. ->update(['del_time' => $time]);
  348. }
  349. // 回填新增主表的 ID 到明细数组
  350. foreach ($all_detail_insert as &$di) {
  351. if (isset($di['_code'])) {
  352. $di['item_id'] = $new_item_maps[$di['_code']] ?? 0;
  353. unset($di['_code']);
  354. }
  355. }
  356. unset($di);
  357. // 批量插入所有明细
  358. if (!empty($all_detail_insert)) {
  359. foreach (array_chunk($all_detail_insert, 500) as $chunk) {
  360. ItemDetails::insert($chunk);
  361. }
  362. }
  363. DB::commit();
  364. } catch (\Exception $e) {
  365. DB::rollBack();
  366. return [false, "入库失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  367. }
  368. return [true, '导入成功'];
  369. }
  370. private function getItemList($array, $user, $index){
  371. //查找设备
  372. $codes = array_unique(array_filter(array_column($array,$index)));
  373. return Item::where('del_time', 0)
  374. ->where('top_depart_id', $user['top_depart_id'])
  375. ->whereIn('code', $codes)
  376. ->pluck('id','code')
  377. ->toArray();
  378. }
  379. private function itemCheck(&$array, $user, $table_config)
  380. {
  381. $keys = array_column($table_config, 'key');
  382. $codeIdx = array_search('code', $keys);
  383. $stateIdx = array_search('state', $keys);
  384. $manIdx = array_search('man_list', $keys);
  385. $deviceIdx = array_search('device_list', $keys);
  386. // 日期索引
  387. $dateIdx = array_search('start_time', $keys);
  388. $date2Idx = array_search('end_time', $keys);
  389. $code_map = $this->getItemList($array, $user, $codeIdx);
  390. list($man_map, $device_map) = $this->getDataList($array, $user, $manIdx, $deviceIdx);
  391. $errors = [];
  392. $update_mapping = [];
  393. $detail_storage = [];
  394. $state_type_map = array_flip(Item::State_Type);
  395. foreach ($array as $rowIndex => $rowValue) {
  396. $displayLine = $rowIndex + 1;
  397. $valCode = $rowValue[$codeIdx] ?? '';
  398. // 1. 判定更新还是新增
  399. if (isset($code_map[$valCode])) {
  400. $update_mapping[$rowIndex] = $code_map[$valCode];
  401. }
  402. // 2. 状态校验
  403. $state_text = $rowValue[$stateIdx] ?? '';
  404. if (!isset($state_type_map[$state_text])) {
  405. $errors[] = "第{$displayLine}行:状态[{$state_text}]无效";
  406. } else {
  407. $array[$rowIndex][$stateIdx] = $state_type_map[$state_text];
  408. }
  409. // 3. 日期转换
  410. foreach ([$dateIdx, $date2Idx] as $dIdx) {
  411. if ($dIdx !== false && !empty($rowValue[$dIdx])) {
  412. list($s, $m) = $this->convertExcelCellToDate($rowValue[$dIdx]);
  413. if (!$s) $errors[] = "第{$displayLine}行:日期格式非法";
  414. else $array[$rowIndex][$dIdx] = $m;
  415. }
  416. }
  417. // 4. 解析人员 (明细类型1)
  418. if ($manIdx !== false && !empty($rowValue[$manIdx])) {
  419. foreach (explode(',', $rowValue[$manIdx]) as $mNum) {
  420. $mNum = trim($mNum);
  421. if (!isset($man_map[$mNum])) {
  422. $errors[] = "第{$displayLine}行:人员工号[{$mNum}]不存在";
  423. } else {
  424. $detail_storage[$rowIndex][] = [
  425. 'type' => ItemDetails::type_one,
  426. 'data_id' => $man_map[$mNum],
  427. ];
  428. }
  429. }
  430. }
  431. // 5. 解析设备 (明细类型2)
  432. if ($deviceIdx !== false && !empty($rowValue[$deviceIdx])) {
  433. foreach (explode(',', $rowValue[$deviceIdx]) as $dCode) {
  434. $dCode = trim($dCode);
  435. if (!isset($device_map[$dCode])) {
  436. $errors[] = "第{$displayLine}行:设备的资产编码[{$dCode}]不存在";
  437. } else {
  438. $detail_storage[$rowIndex][] = [
  439. 'type' => ItemDetails::type_two,
  440. 'data_id' => $device_map[$dCode],
  441. ];
  442. }
  443. }
  444. }
  445. }
  446. $error_str = !empty($errors) ? implode('|', $errors) : "";
  447. return [$error_str, $update_mapping, $detail_storage];
  448. }
  449. private function getDataList($array, $user, $index1, $index2)
  450. {
  451. $manNums = [];
  452. $devCodes = [];
  453. // 去重收集
  454. foreach ($array as $row) {
  455. if (!empty($row[$index1])) {
  456. foreach (explode(',', $row[$index1]) as $v) $manNums[trim($v)] = true;
  457. }
  458. if (!empty($row[$index2])) {
  459. foreach (explode(',', $row[$index2]) as $v) $devCodes[trim($v)] = true;
  460. }
  461. }
  462. $manMap = Employee::where('del_time', 0)
  463. ->where('top_depart_id', $user['top_depart_id'])
  464. ->whereIn('number', array_keys($manNums))
  465. ->pluck('id', 'number')->toArray();
  466. $devMap = Device::where('del_time', 0)
  467. ->where('top_depart_id', $user['top_depart_id'])
  468. ->whereIn('code', array_keys($devCodes))
  469. ->pluck('id', 'code')->toArray();
  470. return [$manMap, $devMap];
  471. }
  472. // 费用 ----------------------------------
  473. public function feeImport($array, $user, $other_param)
  474. {
  475. $upload = $array[0];
  476. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  477. if (!$status) return [false, $msg];
  478. $table_config = $msg;
  479. unset($array[0]);
  480. if (empty($array)) return [false, '导入数据不能为空'];
  481. list($array, $error) = $this->checkCommon($array, $table_config);
  482. if (!empty($error)) return [0, $error];
  483. // 2. 详细校验
  484. list($error, $update_map, $parent_code_map) = $this->feeCheck($array, $user, $table_config);
  485. if (!empty($error)) return [0, $error];
  486. $time = time();
  487. $insert = [];
  488. $update = [];
  489. $all_codes = [];
  490. // --- 修正点 1: 必须确保索引提取准确 ---
  491. $keys = array_column($table_config, 'key');
  492. $codeIdx = array_search('code', $keys);
  493. // ------------------------------------
  494. foreach ($array as $key => $value) {
  495. $cCode = trim($value[$codeIdx] ?? '');
  496. if($cCode === '') continue;
  497. $all_codes[] = $cCode;
  498. $main_tmp = [];
  499. foreach ($value as $k => $val){
  500. if(!empty($table_config[$k]['is_main'])){
  501. if ($table_config[$k]['key'] !== 'parent_id') {
  502. $main_tmp[$table_config[$k]['key']] = $val;
  503. }
  504. }
  505. }
  506. if (isset($update_map[$key])) {
  507. $update[] = array_merge($main_tmp, ['id' => $update_map[$key]]);
  508. } else {
  509. $main_tmp['top_depart_id'] = $user['top_depart_id'];
  510. $main_tmp['crt_time'] = $time;
  511. $main_tmp['parent_id'] = 0;
  512. $insert[] = $main_tmp;
  513. }
  514. }
  515. DB::beginTransaction();
  516. try {
  517. if (!empty($insert)) {
  518. foreach (array_chunk($insert, 500) as $chunk) {
  519. Fee::insert($chunk);
  520. }
  521. }
  522. if (!empty($update)) {
  523. foreach ($update as $item) {
  524. $uId = $item['id']; unset($item['id']);
  525. Fee::where('id', $uId)->update($item);
  526. }
  527. }
  528. // --- 修正点 2: 核心回填逻辑 ---
  529. $newCodeToIdMap = Fee::where('del_time', 0)
  530. ->where('top_depart_id', $user['top_depart_id'])
  531. ->whereIn('code', array_unique($all_codes))
  532. ->pluck('id', 'code')
  533. ->toArray();
  534. foreach ($parent_code_map as $rowIndex => $pCode) {
  535. // 这里必须通过 $rowIndex 从原始 $array 中精准获取当前行的编码
  536. $currentCode = isset($array[$rowIndex][$codeIdx]) ? trim($array[$rowIndex][$codeIdx]) : '';
  537. $pCode = trim($pCode);
  538. if ($currentCode === '' || $pCode === '') continue;
  539. $currentId = $newCodeToIdMap[$currentCode] ?? null;
  540. $parentId = $newCodeToIdMap[$pCode] ?? null;
  541. // 严谨判断:只有当前记录存在,且上级记录也存在,且两者不是同一个 ID 时才更新
  542. if ($currentId && $parentId && $currentId != $parentId) {
  543. Fee::where('id', $currentId)->update(['parent_id' => $parentId]);
  544. }
  545. }
  546. DB::commit();
  547. } catch (\Exception $e) {
  548. DB::rollBack();
  549. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  550. }
  551. return [true, ''];
  552. }
  553. private function feeCheck(&$array, $user, $table_config)
  554. {
  555. $keys = array_column($table_config, 'key');
  556. $codeIdx = array_search('code', $keys);
  557. $parentIdx = array_search('parent_id', $keys);
  558. // 1. 获取基础数据
  559. list($dbFeeMap, $excelCodesMap) = $this->getFeeList($array, $user, $codeIdx);
  560. $errors = [];
  561. $update = [];
  562. $parent_code_map = [];
  563. // 2. 建立 Excel 内部父子关系映射(用于环路追溯)
  564. $currentExcelMap = [];
  565. foreach ($array as $row) {
  566. $c = trim($row[$codeIdx] ?? '');
  567. $p = trim($row[$parentIdx] ?? '');
  568. if ($c !== '') $currentExcelMap[$c] = $p;
  569. }
  570. // 3. 逐行校验
  571. foreach ($array as $rowIndex => $value) {
  572. $displayLine = $rowIndex + 1;
  573. $valCode = trim($value[$codeIdx] ?? '');
  574. $valParentCode = trim($value[$parentIdx] ?? '');
  575. if ($valCode === '') continue;
  576. // 更新状态记录
  577. if (isset($dbFeeMap[$valCode])) {
  578. $update[$rowIndex] = $dbFeeMap[$valCode]['id'];
  579. }
  580. if ($valParentCode !== '') {
  581. // --- A. 存在性校验 ---
  582. // 这里会检查 006 是否在数据库,或者是否在本次 Excel 的其他行中
  583. if (!isset($dbFeeMap[$valParentCode]) && !isset($excelCodesMap[$valParentCode])) {
  584. $errors[] = "第{$displayLine}行:上级编码[{$valParentCode}]在系统和文件中均不存在";
  585. continue;
  586. }
  587. // --- B. 自引用校验 ---
  588. if ($valCode === $valParentCode) {
  589. $errors[] = "第{$displayLine}行:上级编码不能是自身";
  590. continue;
  591. }
  592. // --- C. 环路追溯 ---
  593. $visited = [];
  594. $res = $this->findLoopInAncestors($valParentCode, $valCode, $currentExcelMap, $dbFeeMap, $visited);
  595. if ($res !== false) {
  596. if ($res['type'] === 'LOOP_SELF') {
  597. $errors[] = "第{$displayLine}行:编码[{$valCode}]与上级[{$valParentCode}]存在循环引用";
  598. } else {
  599. $errors[] = "第{$displayLine}行:上级[{$valParentCode}]的溯源链条已成环";
  600. }
  601. continue;
  602. }
  603. // 记录有效的父级关系
  604. $parent_code_map[$rowIndex] = $valParentCode;
  605. }
  606. }
  607. $error_string = !empty($errors) ? implode('|', $errors) : "";
  608. return [$error_string, $update, $parent_code_map];
  609. }
  610. private function getFeeList($array, $user, $index)
  611. {
  612. // 关键:一定要把 Excel 里所有的 code 这一列全部拿出来,并去除空值
  613. $codesInExcel = [];
  614. foreach ($array as $row) {
  615. $c = trim($row[$index] ?? '');
  616. if ($c !== '') {
  617. $codesInExcel[$c] = true;
  618. }
  619. }
  620. $allFees = Fee::where('del_time', 0)
  621. ->where('top_depart_id', $user['top_depart_id'])
  622. ->select('id', 'code', 'parent_id')
  623. ->get();
  624. $dbFeeMap = [];
  625. foreach ($allFees as $fee) {
  626. $dbFeeMap[$fee->code] = [
  627. 'id' => $fee->id,
  628. 'code' => $fee->code,
  629. 'parent_id' => $fee->parent_id
  630. ];
  631. }
  632. // 返回数据库映射和 Excel 编码映射
  633. return [$dbFeeMap, $codesInExcel];
  634. }
  635. private function findLoopInAncestors($startParentCode, $targetCode, $excelMap, $dbFeeMap, &$visited)
  636. {
  637. $current = $startParentCode;
  638. while ($current !== '' && $current !== 0) {
  639. if ($current === $targetCode) {
  640. return ['type' => 'LOOP_SELF', 'code' => $current];
  641. }
  642. if (isset($visited[$current])) {
  643. return ['type' => 'EXISTING_LOOP', 'code' => $current];
  644. }
  645. $visited[$current] = true;
  646. if (isset($excelMap[$current]) && $excelMap[$current] !== '') {
  647. $current = $excelMap[$current];
  648. } elseif (isset($dbFeeMap[$current])) {
  649. $parentId = $dbFeeMap[$current]['parent_id'];
  650. $parentCode = '';
  651. foreach ($dbFeeMap as $item) {
  652. if ($item['id'] == $parentId) {
  653. $parentCode = $item['code'];
  654. break;
  655. }
  656. }
  657. $current = $parentCode;
  658. } else {
  659. break;
  660. }
  661. }
  662. return false;
  663. }
  664. // 人员月度工时单 ------------------------------
  665. public function monthPwOrderImport($array, $user, $other_param)
  666. {
  667. $upload = $array[0];
  668. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  669. if (!$status) return [false, $msg];
  670. $table_config = $msg;
  671. unset($array[0]);
  672. if (empty($array)) return [false, '导入数据不能为空'];
  673. list($array, $error) = $this->checkCommon($array, $table_config);
  674. if (!empty($error)) return [0, $error];
  675. // 2. 详细校验 (这里会返回 update_map 和 dbEmps 映射)
  676. list($error, $update_map, $dbEmps) = $this->monthPwOrderCheck($array, $user, $table_config);
  677. if (!empty($error)) return [0, $error];
  678. $keys = array_column($table_config, 'key');
  679. $codeIdx = array_search('code', $keys);
  680. $monthIdx = array_search('month', $keys);
  681. $empIdx = array_search('employee_id', $keys);
  682. // --- 步骤 1: 数据聚合分组 ---
  683. // 将 Excel 数据按“单据”维度归类
  684. $groups = [];
  685. foreach ($array as $rowIndex => $row) {
  686. $cCode = trim($row[$codeIdx] ?? '');
  687. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  688. // 聚合 Key:有编码用编码,没编码用月份标记
  689. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  690. if (!isset($groups[$aggKey])) {
  691. $groups[$aggKey] = [
  692. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  693. 'code' => $cCode,
  694. 'month' => $cMonthTs,
  695. 'details' => []
  696. ];
  697. }
  698. // 准备详情行数据
  699. $detailTmp = [];
  700. foreach ($table_config as $k => $conf) {
  701. if (!$conf['is_main']) {
  702. $fieldKey = $conf['key'];
  703. $fieldVal = $row[$k];
  704. // 如果是人员,转换为 ID
  705. if ($fieldKey == 'employee_id') {
  706. $fieldVal = $dbEmps[$fieldVal] ?? 0;
  707. }
  708. $detailTmp[$fieldKey] = $fieldVal;
  709. }
  710. }
  711. $groups[$aggKey]['details'][] = $detailTmp;
  712. }
  713. // --- 步骤 2: 开启事务写入 ---
  714. DB::beginTransaction();
  715. try {
  716. $time = time();
  717. foreach ($groups as $aggKey => $group) {
  718. $mainId = $group['main_id'];
  719. if ($mainId > 0) {
  720. // 删除旧详情
  721. DB::table('monthly_pw_order_details')->where('del_time',0)
  722. ->where('main_id', $mainId)
  723. ->update(['del_time' => $time]);
  724. } else {
  725. // B. 新增逻辑
  726. $newCode = $this->generateBillNo([
  727. 'top_depart_id' => $user['top_depart_id'],
  728. 'type' => MonthlyPwOrder::Order_type,
  729. 'period' => date("Ym", $group['month'])
  730. ]);
  731. $mainId = DB::table('monthly_pw_order')->insertGetId([
  732. 'code' => $newCode,
  733. 'month' => $group['month'],
  734. 'top_depart_id' => $user['top_depart_id'],
  735. 'crt_id' => $user['id'],
  736. 'crt_time' => $time,
  737. 'upd_time' => $time,
  738. 'del_time' => 0
  739. ]);
  740. }
  741. // C. 批量插入详情
  742. $insertDetails = [];
  743. foreach ($group['details'] as $detail) {
  744. $detail['main_id'] = $mainId;
  745. $detail['top_depart_id']= $user['top_depart_id'];
  746. $detail['crt_time'] = $time;
  747. $detail['del_time'] = 0;
  748. $insertDetails[] = $detail;
  749. }
  750. if (!empty($insertDetails)) {
  751. DB::table('monthly_pw_order_details')->insert($insertDetails);
  752. }
  753. }
  754. DB::commit();
  755. } catch (\Exception $e) {
  756. DB::rollBack();
  757. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  758. }
  759. return [true, ''];
  760. }
  761. private function monthPwOrderCheck(&$array, $user, $table_config)
  762. {
  763. $keys = array_column($table_config, 'key');
  764. $codeIdx = array_search('code', $keys);
  765. $monthIdx = array_search('month', $keys);
  766. $empIdx = array_search('employee_id', $keys);
  767. $startIdx = array_search('start_time', $keys);
  768. $endIdx = array_search('end_time', $keys);
  769. $numIdx = array_search('total_days', $keys);
  770. $num2Idx = array_search('rd_total_days', $keys);
  771. $num3Idx = array_search('total_hours', $keys);
  772. $num4Idx = array_search('rd_total_hours', $keys);
  773. // 1. 预加载基础数据
  774. $allEmpNumbers = array_filter(array_unique(array_column($array, $empIdx)));
  775. $dbEmps = Employee::where('del_time', 0)
  776. ->whereIn('number', $allEmpNumbers)
  777. ->where('top_depart_id', $user['top_depart_id'])
  778. ->pluck('id', 'number')->toArray();
  779. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  780. $dbOrders = DB::table('monthly_pw_order')
  781. ->whereIn('code', $allCodes)
  782. ->where('top_depart_id', $user['top_depart_id'])
  783. ->get()->keyBy('code');
  784. $errors = [];
  785. //时间转换
  786. foreach ($array as $rowIndex => $row) {
  787. $valMonthRaw = trim($row[$monthIdx] ?? '');
  788. if ($valMonthRaw === '') continue;
  789. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  790. if (!$mStatus) {
  791. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  792. continue;
  793. }
  794. // 标准化并存回数组,这样后面的循环直接拿到的就是时间戳
  795. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  796. $array[$rowIndex][$monthIdx] = $valMonthTs;
  797. $uniqueMonths[] = $valMonthTs;
  798. }
  799. $existingMonthsMap = [];
  800. if (!empty($uniqueMonths)) {
  801. $existingMonths = DB::table('monthly_pw_order')
  802. ->where('top_depart_id', $user['top_depart_id'])
  803. ->where('del_time', 0)
  804. ->whereIn('month', array_unique($uniqueMonths))
  805. ->pluck('month')
  806. ->toArray();
  807. $existingMonthsMap = array_fill_keys($existingMonths, true);
  808. }
  809. $excelAggregator = [];
  810. $update_map = [];
  811. foreach ($array as $rowIndex => $row) {
  812. // 用户看到的行号(假设数据从第2行开始)
  813. $displayLine = $rowIndex + 1;
  814. $valCode = trim($row[$codeIdx] ?? '');
  815. $valMonthTs = trim($row[$monthIdx] ?? '');
  816. $valEmp = trim($row[$empIdx] ?? '');
  817. $valStartRaw = $row[$startIdx] ?? '';
  818. $valEndRaw = $row[$endIdx] ?? '';
  819. $valNumRaw = $row[$numIdx] ?? 0;
  820. $valNum2Raw = $row[$num2Idx] ?? 0;
  821. $valNum3Raw = $row[$num3Idx] ?? 0;
  822. $valNum4Raw = $row[$num4Idx] ?? 0;
  823. if (!is_numeric($valMonthTs)) continue;
  824. // 转换开始日期
  825. list($sStatus, $startTime) = $this->convertExcelCellToDate($valStartRaw);
  826. if (!$sStatus) {
  827. $errors[] = "第{$displayLine}行:开始日期格式错误";
  828. continue;
  829. }
  830. // 转换结束日期
  831. list($eStatus, $endTime) = $this->convertExcelCellToDate($valEndRaw);
  832. if (!$eStatus) {
  833. $errors[] = "第{$displayLine}行:结束日期格式错误";
  834. continue;
  835. }
  836. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  837. // --- B. 校验单据与月份的一致性 ---
  838. if ($valCode && isset($dbOrders[$valCode])) {
  839. $dbOrder = $dbOrders[$valCode];
  840. if ($dbOrder->month != $valMonthTs) {
  841. $errors[] = "第{$displayLine}行:单据编码[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入月份不符";
  842. }
  843. $update_map[$rowIndex] = $dbOrder->id;
  844. }
  845. // --- C. 校验人员存在性与单据内唯一性 ---
  846. if (!isset($dbEmps[$valEmp])) {
  847. $errors[] = "第{$displayLine}行:人员工号[{$valEmp}]不存在";
  848. } else {
  849. if (isset($excelAggregator[$aggKey]['emps'][$valEmp])) {
  850. $errors[] = "第{$displayLine}行:人员[{$valEmp}]在同一单据中重复";
  851. }
  852. $excelAggregator[$aggKey]['emps'][$valEmp] = true;
  853. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  854. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  855. }
  856. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  857. }
  858. // --- D. 逻辑校验:日期范围 ---
  859. if ($startTime > $endTime) {
  860. $errors[] = "第{$displayLine}行:开始日期大于结束日期";
  861. } else {
  862. $monthEndTs = strtotime("+1 month", $valMonthTs) - 1;
  863. if ($startTime < $valMonthTs || $endTime > $monthEndTs) {
  864. $errors[] = "第{$displayLine}行:日期超出[ " . date('Y-m', $valMonthTs) . " ]范围";
  865. }
  866. }
  867. // --- E. 月份唯一单据校验 (新增) ---
  868. if (!$valCode) {
  869. if (isset($existingMonthsMap[$valMonthTs])) {
  870. $errors[] = "第{$displayLine}行:月份[ " . date('Y-m', $valMonthTs) . " ]已存在单据,请填编码编辑";
  871. }
  872. }
  873. // --- F. 数字校验
  874. $res = $this->checkNumber($valNumRaw,0,'non-negative');
  875. if(! $res['valid']) $errors[] = "第{$displayLine}行出勤总天数:" . $res['error'];
  876. $res = $this->checkNumber($valNum2Raw,0,'non-negative');
  877. if(! $res['valid']) $errors[] = "第{$displayLine}行研发出勤总天数:" . $res['error'];
  878. $res = $this->checkNumber($valNum3Raw,2,'non-negative');
  879. if(! $res['valid']) $errors[] = "第{$displayLine}行出勤总工时:" . $res['error'];
  880. $res = $this->checkNumber($valNum4Raw,2,'non-negative');
  881. if(! $res['valid']) $errors[] = "第{$displayLine}行研发总工时:" . $res['error'];
  882. // 将转换后的时间戳写回原数组,方便后续写入数据库时直接使用
  883. $array[$rowIndex][$startIdx] = $startTime;
  884. $array[$rowIndex][$endIdx] = $endTime;
  885. }
  886. $error_string = !empty($errors) ? implode('|', $errors) : "";
  887. return [$error_string, $update_map, $dbEmps];
  888. }
  889. // 设备月度工时单
  890. public function monthDwOrderImport($array, $user, $other_param)
  891. {
  892. $upload = $array[0];
  893. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  894. if (!$status) return [false, $msg];
  895. $table_config = $msg;
  896. unset($array[0]);
  897. if (empty($array)) return [false, '导入数据不能为空'];
  898. list($array, $error) = $this->checkCommon($array, $table_config);
  899. if (!empty($error)) return [0, $error];
  900. // 2. 详细校验 (这里会返回 update_map 和 dbDevs 映射)
  901. list($error, $update_map, $dbDevs) = $this->monthDwOrderCheck($array, $user, $table_config);
  902. if (!empty($error)) return [0, $error];
  903. $keys = array_column($table_config, 'key');
  904. $codeIdx = array_search('code', $keys);
  905. $monthIdx = array_search('month', $keys);
  906. $empIdx = array_search('device_id', $keys);
  907. // --- 步骤 1: 数据聚合分组 ---
  908. // 将 Excel 数据按“单据”维度归类
  909. $groups = [];
  910. foreach ($array as $rowIndex => $row) {
  911. $cCode = trim($row[$codeIdx] ?? '');
  912. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  913. // 聚合 Key:有编码用编码,没编码用月份标记
  914. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  915. if (!isset($groups[$aggKey])) {
  916. $groups[$aggKey] = [
  917. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  918. 'code' => $cCode,
  919. 'month' => $cMonthTs,
  920. 'details' => []
  921. ];
  922. }
  923. // 准备详情行数据
  924. $detailTmp = [];
  925. foreach ($table_config as $k => $conf) {
  926. if (!$conf['is_main']) {
  927. $fieldKey = $conf['key'];
  928. $fieldVal = $row[$k];
  929. // 如果是人员,转换为 ID
  930. if ($fieldKey == 'device_id') {
  931. $fieldVal = $dbDevs[$fieldVal] ?? 0;
  932. }
  933. $detailTmp[$fieldKey] = $fieldVal;
  934. }
  935. }
  936. $groups[$aggKey]['details'][] = $detailTmp;
  937. }
  938. // --- 步骤 2: 开启事务写入 ---
  939. DB::beginTransaction();
  940. try {
  941. $time = time();
  942. foreach ($groups as $aggKey => $group) {
  943. $mainId = $group['main_id'];
  944. if ($mainId > 0) {
  945. // 删除旧详情
  946. DB::table('monthly_dw_order_details')->where('del_time',0)
  947. ->where('main_id', $mainId)
  948. ->update(['del_time' => $time]);
  949. } else {
  950. // B. 新增逻辑
  951. $newCode = $this->generateBillNo([
  952. 'top_depart_id' => $user['top_depart_id'],
  953. 'type' => MonthlyPwOrder::Order_type,
  954. 'period' => date("Ym", $group['month'])
  955. ]);
  956. $mainId = DB::table('monthly_dw_order')->insertGetId([
  957. 'code' => $newCode,
  958. 'month' => $group['month'],
  959. 'top_depart_id' => $user['top_depart_id'],
  960. 'crt_id' => $user['id'],
  961. 'crt_time' => $time,
  962. 'upd_time' => $time,
  963. 'del_time' => 0
  964. ]);
  965. }
  966. // C. 批量插入详情
  967. $insertDetails = [];
  968. foreach ($group['details'] as $detail) {
  969. $detail['main_id'] = $mainId;
  970. $detail['top_depart_id']= $user['top_depart_id'];
  971. $detail['crt_time'] = $time;
  972. $detail['del_time'] = 0;
  973. $insertDetails[] = $detail;
  974. }
  975. if (!empty($insertDetails)) {
  976. DB::table('monthly_dw_order_details')->insert($insertDetails);
  977. }
  978. }
  979. DB::commit();
  980. } catch (\Exception $e) {
  981. DB::rollBack();
  982. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  983. }
  984. return [true, ''];
  985. }
  986. private function monthDwOrderCheck(&$array, $user, $table_config)
  987. {
  988. $keys = array_column($table_config, 'key');
  989. $codeIdx = array_search('code', $keys);
  990. $monthIdx = array_search('month', $keys);
  991. $devIdx = array_search('device_id', $keys);
  992. $startIdx = array_search('start_time', $keys);
  993. $endIdx = array_search('end_time', $keys);
  994. $numIdx = array_search('total_days', $keys);
  995. $num2Idx = array_search('rd_total_days', $keys);
  996. $num3Idx = array_search('total_hours', $keys);
  997. $num4Idx = array_search('rd_total_hours', $keys);
  998. // 1. 预加载基础数据
  999. $allEmpNumbers = array_filter(array_unique(array_column($array, $devIdx)));
  1000. $dbDevs = Device::where('del_time', 0)
  1001. ->whereIn('code', $allEmpNumbers)
  1002. ->where('top_depart_id', $user['top_depart_id'])
  1003. ->pluck('id', 'code')->toArray();
  1004. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1005. $dbOrders = DB::table('monthly_dw_order')
  1006. ->whereIn('code', $allCodes)
  1007. ->where('top_depart_id', $user['top_depart_id'])
  1008. ->get()->keyBy('code');
  1009. $errors = [];
  1010. //时间转换
  1011. foreach ($array as $rowIndex => $row) {
  1012. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1013. if ($valMonthRaw === '') continue;
  1014. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1015. if (!$mStatus) {
  1016. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  1017. continue;
  1018. }
  1019. // 标准化并存回数组,这样后面的循环直接拿到的就是时间戳
  1020. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1021. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1022. $uniqueMonths[] = $valMonthTs;
  1023. }
  1024. $existingMonthsMap = [];
  1025. if (!empty($uniqueMonths)) {
  1026. $existingMonths = DB::table('monthly_dw_order')
  1027. ->where('top_depart_id', $user['top_depart_id'])
  1028. ->where('del_time', 0)
  1029. ->whereIn('month', array_unique($uniqueMonths))
  1030. ->pluck('month')
  1031. ->toArray();
  1032. $existingMonthsMap = array_fill_keys($existingMonths, true);
  1033. }
  1034. $excelAggregator = [];
  1035. $update_map = [];
  1036. foreach ($array as $rowIndex => $row) {
  1037. // 用户看到的行号(假设数据从第2行开始)
  1038. $displayLine = $rowIndex + 1;
  1039. $valCode = trim($row[$codeIdx] ?? '');
  1040. $valMonthTs = trim($row[$monthIdx] ?? '');
  1041. $valDev = trim($row[$devIdx] ?? '');
  1042. $valStartRaw = $row[$startIdx] ?? '';
  1043. $valEndRaw = $row[$endIdx] ?? '';
  1044. $valNumRaw = $row[$numIdx] ?? 0;
  1045. $valNum2Raw = $row[$num2Idx] ?? 0;
  1046. $valNum3Raw = $row[$num3Idx] ?? 0;
  1047. $valNum4Raw = $row[$num4Idx] ?? 0;
  1048. if (!is_numeric($valMonthTs)) continue;
  1049. // 转换开始日期
  1050. list($sStatus, $startTime) = $this->convertExcelCellToDate($valStartRaw);
  1051. if (!$sStatus) {
  1052. $errors[] = "第{$displayLine}行:开始日期格式错误";
  1053. continue;
  1054. }
  1055. // 转换结束日期
  1056. list($eStatus, $endTime) = $this->convertExcelCellToDate($valEndRaw);
  1057. if (!$eStatus) {
  1058. $errors[] = "第{$displayLine}行:结束日期格式错误";
  1059. continue;
  1060. }
  1061. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  1062. // --- B. 校验单据与月份的一致性 ---
  1063. if ($valCode && isset($dbOrders[$valCode])) {
  1064. $dbOrder = $dbOrders[$valCode];
  1065. if ($dbOrder->month != $valMonthTs) {
  1066. $errors[] = "第{$displayLine}行:单据编码[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入月份不符";
  1067. }
  1068. $update_map[$rowIndex] = $dbOrder->id;
  1069. }
  1070. // --- C. 校验设备存在性与单据内唯一性 ---
  1071. if (!isset($dbDevs[$valDev])) {
  1072. $errors[] = "第{$displayLine}行:设备的资产编码[{$valDev}]不存在";
  1073. } else {
  1074. if (isset($excelAggregator[$aggKey]['devs'][$valDev])) {
  1075. $errors[] = "第{$displayLine}行:设备的资产编码[{$valDev}]在同一单据中重复";
  1076. }
  1077. $excelAggregator[$aggKey]['devs'][$valDev] = true;
  1078. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  1079. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  1080. }
  1081. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  1082. }
  1083. // --- D. 逻辑校验:日期范围 ---
  1084. if ($startTime > $endTime) {
  1085. $errors[] = "第{$displayLine}行:开始日期大于结束日期";
  1086. } else {
  1087. $monthEndTs = strtotime("+1 month", $valMonthTs) - 1;
  1088. if ($startTime < $valMonthTs || $endTime > $monthEndTs) {
  1089. $errors[] = "第{$displayLine}行:日期超出[ " . date('Y-m', $valMonthTs) . " ]范围";
  1090. }
  1091. }
  1092. // --- E. 月份唯一单据校验 (新增) ---
  1093. if (!$valCode) {
  1094. if (isset($existingMonthsMap[$valMonthTs])) {
  1095. $errors[] = "第{$displayLine}行:月份[ " . date('Y-m', $valMonthTs) . " ]已存在单据,请填编码编辑";
  1096. }
  1097. }
  1098. // --- F. 数字校验
  1099. $res = $this->checkNumber($valNumRaw,0,'non-negative');
  1100. if(! $res['valid']) $errors[] = "第{$displayLine}行出勤总天数:" . $res['error'];
  1101. $res = $this->checkNumber($valNum2Raw,0,'non-negative');
  1102. if(! $res['valid']) $errors[] = "第{$displayLine}行研发出勤总天数:" . $res['error'];
  1103. $res = $this->checkNumber($valNum3Raw,2,'non-negative');
  1104. if(! $res['valid']) $errors[] = "第{$displayLine}行出勤总工时:" . $res['error'];
  1105. $res = $this->checkNumber($valNum4Raw,2,'non-negative');
  1106. if(! $res['valid']) $errors[] = "第{$displayLine}行研发总工时:" . $res['error'];
  1107. // 将转换后的时间戳写回原数组,方便后续写入数据库时直接使用
  1108. $array[$rowIndex][$startIdx] = $startTime;
  1109. $array[$rowIndex][$endIdx] = $endTime;
  1110. }
  1111. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1112. return [$error_string, $update_map, $dbDevs];
  1113. }
  1114. // 人员月度工资单
  1115. public function monthPsOrderImport($array, $user, $other_param)
  1116. {
  1117. $upload = $array[0];
  1118. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1119. if (!$status) return [false, $msg];
  1120. $table_config = $msg;
  1121. unset($array[0]);
  1122. if (empty($array)) return [false, '导入数据不能为空'];
  1123. list($array, $error) = $this->checkCommon($array, $table_config);
  1124. if (!empty($error)) return [0, $error];
  1125. // 2. 详细校验 (这里会返回 update_map 和 dbEmps 映射)
  1126. list($error, $update_map, $dbEmps) = $this->monthPsOrderCheck($array, $user, $table_config);
  1127. if (!empty($error)) return [0, $error];
  1128. $keys = array_column($table_config, 'key');
  1129. $codeIdx = array_search('code', $keys);
  1130. $monthIdx = array_search('month', $keys);
  1131. $empIdx = array_search('employee_id', $keys);
  1132. // --- 步骤 1: 数据聚合分组 ---
  1133. // 将 Excel 数据按“单据”维度归类
  1134. $groups = [];
  1135. foreach ($array as $rowIndex => $row) {
  1136. $cCode = trim($row[$codeIdx] ?? '');
  1137. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1138. // 聚合 Key:有编码用编码,没编码用月份标记
  1139. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1140. if (!isset($groups[$aggKey])) {
  1141. $groups[$aggKey] = [
  1142. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1143. 'code' => $cCode,
  1144. 'month' => $cMonthTs,
  1145. 'details' => []
  1146. ];
  1147. }
  1148. // 准备详情行数据
  1149. $detailTmp = [];
  1150. foreach ($table_config as $k => $conf) {
  1151. if (!$conf['is_main']) {
  1152. $fieldKey = $conf['key'];
  1153. $fieldVal = $row[$k];
  1154. // 如果是人员,转换为 ID
  1155. if ($fieldKey == 'employee_id') {
  1156. $fieldVal = $dbEmps[$fieldVal] ?? 0;
  1157. }
  1158. $detailTmp[$fieldKey] = $fieldVal;
  1159. }
  1160. }
  1161. $groups[$aggKey]['details'][] = $detailTmp;
  1162. }
  1163. // --- 步骤 2: 开启事务写入 ---
  1164. DB::beginTransaction();
  1165. try {
  1166. $time = time();
  1167. foreach ($groups as $aggKey => $group) {
  1168. $mainId = $group['main_id'];
  1169. if ($mainId > 0) {
  1170. // 删除旧详情
  1171. DB::table('monthly_ps_order_details')->where('del_time',0)
  1172. ->where('main_id', $mainId)
  1173. ->update(['del_time' => $time]);
  1174. } else {
  1175. // B. 新增逻辑
  1176. $newCode = $this->generateBillNo([
  1177. 'top_depart_id' => $user['top_depart_id'],
  1178. 'type' => MonthlyPsOrder::Order_type,
  1179. 'period' => date("Ym", $group['month'])
  1180. ]);
  1181. $mainId = DB::table('monthly_ps_order')->insertGetId([
  1182. 'code' => $newCode,
  1183. 'month' => $group['month'],
  1184. 'top_depart_id' => $user['top_depart_id'],
  1185. 'crt_id' => $user['id'],
  1186. 'crt_time' => $time,
  1187. 'upd_time' => $time,
  1188. 'del_time' => 0
  1189. ]);
  1190. }
  1191. // C. 批量插入详情
  1192. $insertDetails = [];
  1193. foreach ($group['details'] as $detail) {
  1194. $detail['main_id'] = $mainId;
  1195. $detail['top_depart_id']= $user['top_depart_id'];
  1196. $detail['crt_time'] = $time;
  1197. $detail['del_time'] = 0;
  1198. $insertDetails[] = $detail;
  1199. }
  1200. if (!empty($insertDetails)) {
  1201. DB::table('monthly_ps_order_details')->insert($insertDetails);
  1202. }
  1203. }
  1204. DB::commit();
  1205. } catch (\Exception $e) {
  1206. DB::rollBack();
  1207. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1208. }
  1209. return [true, ''];
  1210. }
  1211. private function monthPsOrderCheck(&$array, $user, $table_config)
  1212. {
  1213. $keys = array_column($table_config, 'key');
  1214. $codeIdx = array_search('code', $keys);
  1215. $monthIdx = array_search('month', $keys);
  1216. $empIdx = array_search('employee_id', $keys);
  1217. $numIdx = array_search('salary', $keys);
  1218. $num2Idx = array_search('social_insurance', $keys);
  1219. $num3Idx = array_search('public_housing_fund', $keys);
  1220. // 1. 预加载基础数据
  1221. $allEmpNumbers = array_filter(array_unique(array_column($array, $empIdx)));
  1222. $dbEmps = Employee::where('del_time', 0)
  1223. ->whereIn('number', $allEmpNumbers)
  1224. ->where('top_depart_id', $user['top_depart_id'])
  1225. ->pluck('id', 'number')->toArray();
  1226. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1227. $dbOrders = DB::table('monthly_ps_order')
  1228. ->whereIn('code', $allCodes)
  1229. ->where('top_depart_id', $user['top_depart_id'])
  1230. ->get()->keyBy('code');
  1231. $errors = [];
  1232. //时间转换
  1233. foreach ($array as $rowIndex => $row) {
  1234. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1235. if ($valMonthRaw === '') continue;
  1236. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1237. if (!$mStatus) {
  1238. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  1239. continue;
  1240. }
  1241. // 标准化并存回数组,这样后面的循环直接拿到的就是时间戳
  1242. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1243. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1244. $uniqueMonths[] = $valMonthTs;
  1245. }
  1246. $existingMonthsMap = [];
  1247. if (!empty($uniqueMonths)) {
  1248. $existingMonths = DB::table('monthly_ps_order')
  1249. ->where('top_depart_id', $user['top_depart_id'])
  1250. ->where('del_time', 0)
  1251. ->whereIn('month', array_unique($uniqueMonths))
  1252. ->pluck('month')
  1253. ->toArray();
  1254. $existingMonthsMap = array_fill_keys($existingMonths, true);
  1255. }
  1256. $excelAggregator = [];
  1257. $update_map = [];
  1258. foreach ($array as $rowIndex => $row) {
  1259. // 用户看到的行号(假设数据从第2行开始)
  1260. $displayLine = $rowIndex + 1;
  1261. $valCode = trim($row[$codeIdx] ?? '');
  1262. $valMonthTs = trim($row[$monthIdx] ?? '');
  1263. $valEmp = trim($row[$empIdx] ?? '');
  1264. $valNumRaw = $row[$numIdx] ?? 0;
  1265. $valNum2Raw = $row[$num2Idx] ?? 0;
  1266. $valNum3Raw = $row[$num3Idx] ?? 0;
  1267. if (!is_numeric($valMonthTs)) continue;
  1268. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  1269. // --- B. 校验单据与月份的一致性 ---
  1270. if ($valCode && isset($dbOrders[$valCode])) {
  1271. $dbOrder = $dbOrders[$valCode];
  1272. if ($dbOrder->month != $valMonthTs) {
  1273. $errors[] = "第{$displayLine}行:单据编码[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入月份不符";
  1274. }
  1275. $update_map[$rowIndex] = $dbOrder->id;
  1276. }
  1277. // --- C. 校验人员存在性与单据内唯一性 ---
  1278. if (!isset($dbEmps[$valEmp])) {
  1279. $errors[] = "第{$displayLine}行:人员工号[{$valEmp}]不存在";
  1280. } else {
  1281. if (isset($excelAggregator[$aggKey]['emps'][$valEmp])) {
  1282. $errors[] = "第{$displayLine}行:人员[{$valEmp}]在同一单据中重复";
  1283. }
  1284. $excelAggregator[$aggKey]['emps'][$valEmp] = true;
  1285. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  1286. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  1287. }
  1288. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  1289. }
  1290. // --- E. 月份唯一单据校验 (新增) ---
  1291. if (!$valCode) {
  1292. if (isset($existingMonthsMap[$valMonthTs])) {
  1293. $errors[] = "第{$displayLine}行:月份[ " . date('Y-m', $valMonthTs) . " ]已存在单据,请填编码编辑";
  1294. }
  1295. }
  1296. // --- F. 数字校验
  1297. $res = $this->checkNumber($valNumRaw,0,'non-negative');
  1298. if(! $res['valid']) $errors[] = "第{$displayLine}行工资总额:" . $res['error'];
  1299. $res = $this->checkNumber($valNum2Raw,0,'non-negative');
  1300. if(! $res['valid']) $errors[] = "第{$displayLine}行社保:" . $res['error'];
  1301. $res = $this->checkNumber($valNum3Raw,2,'non-negative');
  1302. if(! $res['valid']) $errors[] = "第{$displayLine}行公积金:" . $res['error'];
  1303. }
  1304. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1305. return [$error_string, $update_map, $dbEmps];
  1306. }
  1307. // 设备月度折旧单
  1308. public function monthDdOrderImport($array, $user, $other_param)
  1309. {
  1310. $upload = $array[0];
  1311. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  1312. if (!$status) return [false, $msg];
  1313. $table_config = $msg;
  1314. unset($array[0]);
  1315. if (empty($array)) return [false, '导入数据不能为空'];
  1316. list($array, $error) = $this->checkCommon($array, $table_config);
  1317. if (!empty($error)) return [0, $error];
  1318. // 2. 详细校验 (这里会返回 update_map 和 dbDevs 映射)
  1319. list($error, $update_map, $dbDevs) = $this->monthDdOrderCheck($array, $user, $table_config);
  1320. if (!empty($error)) return [0, $error];
  1321. $keys = array_column($table_config, 'key');
  1322. $codeIdx = array_search('code', $keys);
  1323. $monthIdx = array_search('month', $keys);
  1324. $empIdx = array_search('device_id', $keys);
  1325. // --- 步骤 1: 数据聚合分组 ---
  1326. // 将 Excel 数据按“单据”维度归类
  1327. $groups = [];
  1328. foreach ($array as $rowIndex => $row) {
  1329. $cCode = trim($row[$codeIdx] ?? '');
  1330. $cMonthTs = $row[$monthIdx]; // 校验阶段已转为时间戳
  1331. // 聚合 Key:有编码用编码,没编码用月份标记
  1332. $aggKey = $cCode ?: "MONTH_" . $cMonthTs;
  1333. if (!isset($groups[$aggKey])) {
  1334. $groups[$aggKey] = [
  1335. 'main_id' => $update_map[$rowIndex] ?? 0, // 如果存在则是编辑
  1336. 'code' => $cCode,
  1337. 'month' => $cMonthTs,
  1338. 'details' => []
  1339. ];
  1340. }
  1341. // 准备详情行数据
  1342. $detailTmp = [];
  1343. foreach ($table_config as $k => $conf) {
  1344. if (!$conf['is_main']) {
  1345. $fieldKey = $conf['key'];
  1346. $fieldVal = $row[$k];
  1347. // 如果是人员,转换为 ID
  1348. if ($fieldKey == 'device_id') {
  1349. $fieldVal = $dbDevs[$fieldVal] ?? 0;
  1350. }
  1351. $detailTmp[$fieldKey] = $fieldVal;
  1352. }
  1353. }
  1354. $groups[$aggKey]['details'][] = $detailTmp;
  1355. }
  1356. // --- 步骤 2: 开启事务写入 ---
  1357. DB::beginTransaction();
  1358. try {
  1359. $time = time();
  1360. foreach ($groups as $aggKey => $group) {
  1361. $mainId = $group['main_id'];
  1362. if ($mainId > 0) {
  1363. // 删除旧详情
  1364. DB::table('monthly_dd_order_details')->where('del_time',0)
  1365. ->where('main_id', $mainId)
  1366. ->update(['del_time' => $time]);
  1367. } else {
  1368. // B. 新增逻辑
  1369. $newCode = $this->generateBillNo([
  1370. 'top_depart_id' => $user['top_depart_id'],
  1371. 'type' => MonthlyDdOrder::Order_type,
  1372. 'period' => date("Ym", $group['month'])
  1373. ]);
  1374. $mainId = DB::table('monthly_dd_order')->insertGetId([
  1375. 'code' => $newCode,
  1376. 'month' => $group['month'],
  1377. 'top_depart_id' => $user['top_depart_id'],
  1378. 'crt_id' => $user['id'],
  1379. 'crt_time' => $time,
  1380. 'upd_time' => $time,
  1381. 'del_time' => 0
  1382. ]);
  1383. }
  1384. // C. 批量插入详情
  1385. $insertDetails = [];
  1386. foreach ($group['details'] as $detail) {
  1387. $detail['main_id'] = $mainId;
  1388. $detail['top_depart_id']= $user['top_depart_id'];
  1389. $detail['crt_time'] = $time;
  1390. $detail['del_time'] = 0;
  1391. $insertDetails[] = $detail;
  1392. }
  1393. if (!empty($insertDetails)) {
  1394. DB::table('monthly_dd_order_details')->insert($insertDetails);
  1395. }
  1396. }
  1397. DB::commit();
  1398. } catch (\Exception $e) {
  1399. DB::rollBack();
  1400. return [false, "失败:" . $e->getMessage() . " (行号:" . $e->getLine() . ")"];
  1401. }
  1402. return [true, ''];
  1403. }
  1404. private function monthDdOrderCheck(&$array, $user, $table_config)
  1405. {
  1406. $keys = array_column($table_config, 'key');
  1407. $codeIdx = array_search('code', $keys);
  1408. $monthIdx = array_search('month', $keys);
  1409. $devIdx = array_search('device_id', $keys);
  1410. $numIdx = array_search('depreciation_amount', $keys);
  1411. // 1. 预加载基础数据
  1412. $allEmpNumbers = array_filter(array_unique(array_column($array, $devIdx)));
  1413. $dbDevs = Device::where('del_time', 0)
  1414. ->whereIn('code', $allEmpNumbers)
  1415. ->where('top_depart_id', $user['top_depart_id'])
  1416. ->pluck('id', 'code')->toArray();
  1417. $allCodes = array_filter(array_unique(array_column($array, $codeIdx)));
  1418. $dbOrders = DB::table('monthly_dd_order')
  1419. ->whereIn('code', $allCodes)
  1420. ->where('top_depart_id', $user['top_depart_id'])
  1421. ->get()->keyBy('code');
  1422. $errors = [];
  1423. //时间转换
  1424. foreach ($array as $rowIndex => $row) {
  1425. $valMonthRaw = trim($row[$monthIdx] ?? '');
  1426. if ($valMonthRaw === '') continue;
  1427. list($mStatus, $valMonthTs) = $this->convertExcelCellToDate($valMonthRaw);
  1428. if (!$mStatus) {
  1429. $errors[] = "第" . ($rowIndex + 1) . "行:月份格式错误({$valMonthRaw})";
  1430. continue;
  1431. }
  1432. // 标准化并存回数组,这样后面的循环直接拿到的就是时间戳
  1433. $valMonthTs = strtotime(date('Y-m-01', $valMonthTs));
  1434. $array[$rowIndex][$monthIdx] = $valMonthTs;
  1435. $uniqueMonths[] = $valMonthTs;
  1436. }
  1437. $existingMonthsMap = [];
  1438. if (!empty($uniqueMonths)) {
  1439. $existingMonths = DB::table('monthly_dd_order')
  1440. ->where('top_depart_id', $user['top_depart_id'])
  1441. ->where('del_time', 0)
  1442. ->whereIn('month', array_unique($uniqueMonths))
  1443. ->pluck('month')
  1444. ->toArray();
  1445. $existingMonthsMap = array_fill_keys($existingMonths, true);
  1446. }
  1447. $excelAggregator = [];
  1448. $update_map = [];
  1449. foreach ($array as $rowIndex => $row) {
  1450. // 用户看到的行号(假设数据从第2行开始)
  1451. $displayLine = $rowIndex + 1;
  1452. $valCode = trim($row[$codeIdx] ?? '');
  1453. $valMonthTs = trim($row[$monthIdx] ?? '');
  1454. $valDev = trim($row[$devIdx] ?? '');
  1455. $valNumRaw = $row[$numIdx] ?? 0;
  1456. if (!is_numeric($valMonthTs)) continue;
  1457. $aggKey = $valCode ?: "NEW_ORDER_" . $valMonthTs;
  1458. // --- B. 校验单据与月份的一致性 ---
  1459. if ($valCode && isset($dbOrders[$valCode])) {
  1460. $dbOrder = $dbOrders[$valCode];
  1461. if ($dbOrder->month != $valMonthTs) {
  1462. $errors[] = "第{$displayLine}行:单据编码[{$valCode}]对应月份为[" . date('Y-m', $dbOrder->month) . "],与导入月份不符";
  1463. }
  1464. $update_map[$rowIndex] = $dbOrder->id;
  1465. }
  1466. // --- C. 校验设备存在性与单据内唯一性 ---
  1467. if (!isset($dbDevs[$valDev])) {
  1468. $errors[] = "第{$displayLine}行:设备的资产编码[{$valDev}]不存在";
  1469. } else {
  1470. if (isset($excelAggregator[$aggKey]['devs'][$valDev])) {
  1471. $errors[] = "第{$displayLine}行:设备的资产编码[{$valDev}]在同一单据中重复";
  1472. }
  1473. $excelAggregator[$aggKey]['devs'][$valDev] = true;
  1474. if (isset($excelAggregator[$aggKey]['month_ts']) && $excelAggregator[$aggKey]['month_ts'] !== $valMonthTs) {
  1475. $errors[] = "第{$displayLine}行:同组数据的月份不统一";
  1476. }
  1477. $excelAggregator[$aggKey]['month_ts'] = $valMonthTs;
  1478. }
  1479. // --- E. 月份唯一单据校验 (新增) ---
  1480. if (!$valCode) {
  1481. if (isset($existingMonthsMap[$valMonthTs])) {
  1482. $errors[] = "第{$displayLine}行:月份[ " . date('Y-m', $valMonthTs) . " ]已存在单据,请填编码编辑";
  1483. }
  1484. }
  1485. // --- F. 数字校验
  1486. $res = $this->checkNumber($valNumRaw,2,'non-negative');
  1487. if(! $res['valid']) $errors[] = "第{$displayLine}行月折旧额:" . $res['error'];
  1488. }
  1489. $error_string = !empty($errors) ? implode('|', $errors) : "";
  1490. return [$error_string, $update_map, $dbDevs];
  1491. }
  1492. //公共校验 -----------------------------------------
  1493. private function checkCommon($array, $table_config) {
  1494. $error = [];
  1495. $uniqueCheck = []; // 格式:[$column_index => [$value => $first_line]]
  1496. foreach ($array as $line => $row) {
  1497. $rowData = array_filter($row);
  1498. if (empty($rowData)) {
  1499. unset($array[$line]);
  1500. continue;
  1501. }
  1502. foreach ($row as $colIndex => $value) {
  1503. $value = trim($value);
  1504. $config = $table_config[$colIndex] ?? null;
  1505. // 1. 基础存在性检查
  1506. if (!$config) {
  1507. $error[] = "第{$line}行第{$colIndex}列配置不存在";
  1508. continue;
  1509. }
  1510. $fieldName = $config['value'];
  1511. // 2. 必填校验
  1512. if (!empty($config['required']) && ($value === '' || !isset($value))) {
  1513. $error[] = "第{$line}行:[{$fieldName}] 必填";
  1514. }
  1515. // 3. 默认值填充
  1516. if ($value === '' && isset($config['default'])) {
  1517. $value = $config['default'];
  1518. }
  1519. // 4. 唯一性校验(重点:一次遍历解决)
  1520. if (!empty($config['unique']) && $value !== '') {
  1521. if (isset($uniqueCheck[$colIndex][$value])) {
  1522. $prevLine = $uniqueCheck[$colIndex][$value];
  1523. $error[] = "第{$line}行:[{$fieldName}] 与第{$prevLine}行重复,重复值:{$value}";
  1524. } else {
  1525. // 记录该值第一次出现的位置
  1526. $uniqueCheck[$colIndex][$value] = $line;
  1527. }
  1528. }
  1529. $row[$colIndex] = $value;
  1530. }
  1531. $array[$line] = $row;
  1532. }
  1533. $error_string = !empty($error) ? implode('|', $error) : "";
  1534. return [$array, $error_string];
  1535. }
  1536. //模板校验 -----------------------------------------
  1537. private function compareTableAndReturn($upload, $param){
  1538. if(empty($upload)) return [false, '表头不能为空'];
  1539. $config = $this->getTableConfig($param['type']);
  1540. $config_array = $config['array'];
  1541. if(empty($config_array)) return [false, '导入配置表头文件不存在'];
  1542. foreach ($config_array as $key => $value){
  1543. $key_position = $key + 1;
  1544. if(! isset($upload[$key])) return [false, "第" . $key_position . "列表头缺失"];
  1545. $tmp_v = trim($upload[$key]);
  1546. if($tmp_v != $value['value']) return [false, "第" . $key_position . "列表头与模板不符合,请重新下载模板"];
  1547. }
  1548. return [true, $config_array];
  1549. }
  1550. //转换日期 ------------------------------------------
  1551. function convertExcelCellToDate($cellValue) {
  1552. // 尝试将单元格值转换为浮点数(Excel 日期序列号)
  1553. $excelTimestamp = filter_var($cellValue, FILTER_VALIDATE_FLOAT);
  1554. if ($excelTimestamp !== false && $excelTimestamp > 0) {
  1555. // 如果成功转换并且值大于0,则认为是Excel日期序列号
  1556. try {
  1557. $dateTimeObject = Date::excelToDateTimeObject($cellValue);
  1558. // if ($dateTimeObject->format('H:i:s') === '00:00:00') {
  1559. // // 如果是,则将时间设置为 '23:59:00'
  1560. // $dateTimeObject->setTime(23, 59);
  1561. // }
  1562. // 现在你可以格式化这个日期了
  1563. $formattedDate = $dateTimeObject->format('Y-m-d');
  1564. if(! strtotime($formattedDate)) return [false, ''];
  1565. return [true, strtotime($formattedDate)];
  1566. } catch (\Exception $e) {
  1567. // 处理转换失败的情况
  1568. return [false, '单元格日期格式转换时间戳失败'];
  1569. }
  1570. }
  1571. // 如果不是有效的浮点数,则尝试按照多种日期格式解析
  1572. if(! strtotime($cellValue)) return [false, '单元格文本格式转换时间戳失败'];
  1573. return [true, strtotime($cellValue)];
  1574. }
  1575. }