ImportService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. <?php
  2. namespace App\Service;
  3. use App\Exports\TableHeadExport;
  4. use App\Import\ImportAll;
  5. use App\Model\CustomerSupply;
  6. use App\Model\Employee;
  7. use App\Model\RD;
  8. use App\Model\RdDetails;
  9. use App\Model\Item;
  10. use App\Model\GiveOut;
  11. use App\Model\Product;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Log;
  14. use Maatwebsite\Excel\Facades\Excel;
  15. use PhpOffice\PhpSpreadsheet\IOFactory;
  16. use PhpOffice\PhpSpreadsheet\Shared\Date;
  17. class ImportService extends Service
  18. {
  19. public static $type = [
  20. 'order', //订单
  21. ];
  22. public function getTableTitleXls($data,$user){
  23. if(empty($data['type'])) return [false,'缺少类型'];
  24. if(! in_array($data['type'],self::$type)) return [false,'类型不存在'];
  25. //获取配置文件
  26. $fuc = $data['type'];
  27. list($status,$return) = $this->$fuc($data,$user);
  28. list($msg,$filename) = $return;
  29. if(! $status) return [false, $msg];
  30. $headers = array_column($msg,'value');
  31. $comments = [];
  32. foreach ($msg as $value){
  33. if(! empty($value['comments'])) $comments[$value['value']] = $value['comments'];
  34. }
  35. Excel::store(new TableHeadExport([], $headers, $comments),"/public/export/{$filename}", null, 'Xlsx', []);
  36. return [true, ['file' => $filename]];
  37. }
  38. private function getTableConfig($type = ""){
  39. if(empty($type)) return [];
  40. //获取配置文件
  41. $config = "excel." . $type;
  42. return config($config) ?? [];
  43. }
  44. private function order($data,$user){
  45. $config_array = $this->getTableConfig($data['type']);
  46. if(empty($config_array)) return [false, ['导入配置表头文件不存在','']];
  47. //生成下载文件
  48. $filename = "订单导入模板_" . time() . '.' . 'xlsx';
  49. return [true, [$config_array, $filename]];
  50. }
  51. //导入入口
  52. public function importAll($data,$user){
  53. // //不超时
  54. // ini_set('max_execution_time', 0);
  55. // //内存设置
  56. // ini_set('memory_limit', -1);
  57. // $reader = IOFactory::createReader('Xlsx');
  58. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  59. // $spreadsheet = $reader->load($data['file']);
  60. // dd($spreadsheet);
  61. // // 创建一个Reader对象
  62. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  63. //
  64. //// 加载Excel文件
  65. // $spreadsheet = $reader->load($data['file']);
  66. //
  67. //// 获取第一个工作表
  68. // $worksheet = $spreadsheet->getActiveSheet();
  69. //
  70. //// 获取总行数
  71. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  72. if(empty($data['type'])) return [false,'缺少导入类型,导入失败'];
  73. if(! in_array($data['type'],self::$type)) return [false,'导入类型不存在,导入失败'];
  74. if(empty($data['file'])) return [false,'导入文件不能为空'];
  75. try {
  76. $import = new ImportAll();
  77. //设置导入人id
  78. $import->setCrt($user['id']);
  79. $import->setUser($user);
  80. $import->setType($data['type']);
  81. $other = $data;
  82. unset($other['file']);
  83. $import->setOtherParam($other);
  84. //导入
  85. \Maatwebsite\Excel\Facades\Excel::import($import,$data['file']);
  86. if($import->getMsg()) {
  87. $bool = $import->getIsLongText();
  88. if($bool) {
  89. return [0, $import->getMsg()];
  90. }else{
  91. return [false, $import->getMsg()];
  92. }
  93. }
  94. }catch (\Throwable $exception) {
  95. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  96. }
  97. return [true, ''];
  98. }
  99. public function orderImport($array, $user, $other_param){
  100. $upload = $array[0];
  101. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  102. if(! $status) return [false, $msg];
  103. $table_config = $msg;
  104. // 去除表头
  105. unset($array[0]);
  106. if(empty($array)) return [false, '导入数据不能为空'];
  107. list($array, $error) = $this->checkCommon($array, $table_config);
  108. if(! empty($error)) return [0, $error];
  109. if(empty($array)) return [false, '导入数据不能为空'];
  110. list($error, $map, $total_map) = $this->orderCheck($array, $user);
  111. if(! empty($error)) return [0, $error];
  112. $order_map = $this->getOrder($array, $user);
  113. $time = time();
  114. $insert = $update = $detail = $order_number = [];
  115. foreach ($array as $key => $value){
  116. $main_tmp = $detail_tmp = [];
  117. foreach ($value as $k => $val){
  118. $t = $table_config[$k];
  119. $field = $t['key'];
  120. if(! empty($t['is_main'])){
  121. $main_tmp[$field] = $val;
  122. }
  123. if(! empty($t['is_detail'])){
  124. $detail_tmp[$field] = $val;
  125. }
  126. }
  127. $main_tmp['customer_id'] = $map[$key]['customer_id'] ?? 0;
  128. $main_tmp['supply_id'] = $map[$key]['supply_id'] ?? 0;
  129. $main_tmp['quantity'] = $total_map[$main_tmp['order_number']] ?? 0;
  130. if(isset($order_map[$main_tmp['order_number']])){
  131. $order_id = $order_map[$main_tmp['order_number']];
  132. //更新
  133. $update[$order_id] = $main_tmp;
  134. }else{
  135. $main_tmp['crt_id'] = $user['id'];
  136. $main_tmp['crt_time'] = $time;
  137. //新增
  138. $insert[$main_tmp['order_number']] = $main_tmp;
  139. }
  140. $detail_tmp['order_number'] = $main_tmp['order_number'];
  141. $detail_tmp['crt_time'] = $time;
  142. $detail[] = $detail_tmp;
  143. $order_number[] = $main_tmp['order_number'];
  144. }
  145. try{
  146. //新增
  147. if(! empty($insert)){
  148. RD::insert($insert);
  149. }
  150. //编辑
  151. if(! empty($update)){
  152. foreach ($update as $p_id => $value){
  153. RD::where('id',$p_id)
  154. ->update($value);
  155. }
  156. }
  157. if(! empty($detail)){
  158. $maps = RD::where('del_time',0)
  159. ->whereIn('order_number',$order_number)
  160. ->pluck('id','order_number')
  161. ->toArray();
  162. foreach ($detail as $key => $value){
  163. $detail[$key]['order_id'] = $maps[$value['order_number']] ?? 0;
  164. unset($detail[$key]['order_number']);
  165. }
  166. RdDetails::where('del_time',0)
  167. ->where('order_id',array_values($maps))
  168. ->update(['del_time' => $time]);
  169. RdDetails::insert($detail);
  170. }
  171. DB::commit();
  172. }catch (\Exception $e){
  173. DB::rollBack();
  174. return [false, $e->getMessage() . $e->getLine() . $e->getCode()];
  175. }
  176. return [true, ''];
  177. }
  178. private function getCustomerSupply($array, $user){
  179. //查找客户 供应商
  180. $customer_codes = array_unique(array_filter(array_column($array,1)));
  181. $customer_titles = array_unique(array_filter(array_column($array,2)));
  182. $supply_codes = array_unique(array_filter(array_column($array,3)));
  183. $supply_titles = array_unique(array_filter(array_column($array,4)));
  184. $records = CustomerSupply::where('del_time', 0)
  185. ->where('crt_id', $user['id'])
  186. ->where(function($query) use ($customer_codes, $customer_titles, $supply_codes, $supply_titles) {
  187. $query->where(function($q) use ($customer_codes, $customer_titles) {
  188. $q->where('type', CustomerSupply::type_one)
  189. ->where(function($sub) use ($customer_codes, $customer_titles) {
  190. $sub->whereIn('code', $customer_codes)
  191. ->orWhereIn('title', $customer_titles);
  192. });
  193. })->orWhere(function($q) use ($supply_codes, $supply_titles) {
  194. $q->where('type', CustomerSupply::type_two)
  195. ->where(function($sub) use ($supply_codes, $supply_titles) {
  196. $sub->whereIn('code', $supply_codes)
  197. ->orWhereIn('title', $supply_titles);
  198. });
  199. });
  200. })
  201. ->select('id','title','code','type')
  202. ->get()
  203. ->toArray();
  204. return $records;
  205. }
  206. private function getOrder($array, $user){
  207. $order = array_unique(array_filter(array_column($array,0)));
  208. $records = RD::where('del_time', 0)
  209. ->where('crt_id', $user['id'])
  210. ->whereIn('order_number', $order)
  211. ->pluck('id','order_number')
  212. ->toArray();
  213. return $records;
  214. }
  215. private function orderCheck(&$array, $user)
  216. {
  217. // 查询所有客户 / 供应商档案
  218. $customer_supply = $this->getCustomerSupply($array, $user);
  219. // 建立映射表(code、title 都可以匹配到记录)
  220. $map_by_code = array_column($customer_supply, null, 'code');
  221. $map_by_title = [];
  222. foreach ($customer_supply as $value){
  223. $map_by_title[$value['title']][] = $value;
  224. }
  225. $errors = []; // 存放错误信息
  226. $success = []; // 存放校验通过的行
  227. $order_material_map = [];
  228. $order_total_map = []; // 统计每个订单号的总数量
  229. foreach ($array as $rowIndex => $value) {
  230. $rowNum = $rowIndex; // 行号
  231. if(! empty($value[5])){
  232. list($status, $msg) = $this->convertExcelCellToDate($value[5]);
  233. if(! $status){
  234. $error_2[] = "第" . $rowNum ."行" . "的订单日期错误";
  235. }else{
  236. $array[$rowIndex][5] = $msg;
  237. }
  238. }
  239. // -------- 客户校验 --------
  240. $customer_id = 0;
  241. if (!empty($value[1]) || !empty($value[2])) {
  242. $customer_id = $this->checkData($value, $rowNum,'客户',CustomerSupply::type_one, $errors,$map_by_code,$map_by_title);
  243. }
  244. // -------- 供应商校验 --------
  245. $supply_id = 0;
  246. if (!empty($value[3]) || !empty($value[4])) {
  247. $supply_id = $this->checkData($value, $rowNum,'供应商',CustomerSupply::type_two, $errors,$map_by_code,$map_by_title);
  248. }
  249. $success[$rowNum] = [
  250. 'customer_id' => $customer_id,
  251. 'supply_id' => $supply_id,
  252. ];
  253. // -------- 新增:校验订单号 + 物料编码 不重复 --------
  254. $order_no = trim($value[0] ?? '');
  255. $material_code = trim($value[6] ?? '');
  256. if ($order_no !== '' && $material_code !== '') {
  257. // 组合唯一 key
  258. $unique_key = $order_no . '|' . $material_code;
  259. if (isset($order_material_map[$unique_key])) {
  260. // 已经存在重复
  261. $firstRow = $order_material_map[$unique_key];
  262. $errors[] = "第{$rowNum}行:订单号 {$order_no} 下的物料编码 {$material_code} 重复(首次出现在第 {$firstRow} 行)";
  263. } else {
  264. // 记录首次出现的行号
  265. $order_material_map[$unique_key] = $rowNum;
  266. }
  267. }
  268. $qty = $value[10];
  269. if ($order_no !== '') {
  270. if (isset($order_total_map[$order_no])) {
  271. $tmp_num = bcadd($qty, $order_total_map[$order_no],2);
  272. $order_total_map[$order_no] = $tmp_num;
  273. }else{
  274. $order_total_map[$order_no] = $qty;
  275. }
  276. }
  277. }
  278. $error_string = "";
  279. if(! empty($errors)) $error_string = implode('|', $errors);
  280. return [
  281. $error_string ,
  282. $success,
  283. $order_total_map
  284. ];
  285. }
  286. private function checkData($value, $rowNum, $main_title, $type,&$errors,$map_by_code,$map_by_title){
  287. $customer_id_1 = $customer_id_2 = 0;
  288. if($type == CustomerSupply::type_one){
  289. $code = $value[1] ?? '';
  290. $title = $value[2] ?? '';
  291. }else{
  292. $code = $value[3] ?? '';
  293. $title = $value[4] ?? '';
  294. }
  295. $match_code = $map_by_code[$code] ?? null;
  296. $match_title = $map_by_title[$title] ?? null;
  297. if($code){
  298. if(empty($match_code) || $match_code['type'] != $type){
  299. $errors[] = "第{$rowNum}行:{$main_title}编码({$code}) 未在档案中找到";
  300. }else {
  301. $customer_id_1 = $match_code['id'];
  302. }
  303. }
  304. if($title){
  305. if(empty($match_title)){
  306. $errors[] = "第{$rowNum}行:{$main_title}名称({$title}) 未在档案中找到";
  307. }elseif (count($match_title) > 1){
  308. if(empty($code)){
  309. $errors[] = "第{$rowNum}行:{$main_title}名称({$title}) 在档案中找到多条数据,请填写客户编码";
  310. }else{
  311. $tmp = array_column($match_title,null,'code');
  312. if(isset($tmp[$code])){
  313. $t = $tmp[$code];
  314. if($t['type'] != $type) {
  315. $errors[] = "第{$rowNum}行:{$main_title}名称({$title}) 未在档案中找到";
  316. }else{
  317. $customer_id_2 = $t['id'];
  318. }
  319. }else{
  320. $errors[] = "第{$rowNum}行:{$main_title}编码和名称对应数据未在档案中找到";
  321. }
  322. }
  323. }else {
  324. $tt = $match_title[0] ?? [];
  325. $customer_id_2 = $tt['id'] ?? 0;
  326. }
  327. }
  328. if($customer_id_1 && $customer_id_2 && $customer_id_1 != $customer_id_2) $errors[] = "第{$rowNum}行:{$main_title}编码和名称对应数据未在档案中找到";
  329. $customer_id = $customer_id_1 ? $customer_id_1 : $customer_id_2;
  330. return $customer_id;
  331. }
  332. //公共校验
  333. private function checkCommon($array, $table_config){
  334. $error = [];
  335. $uniqueValues = []; // 用于存储需要唯一性检查的值
  336. // 第一次遍历:收集所有唯一字段的值
  337. foreach ($array as $key => $value) {
  338. foreach ($value as $k => $v) {
  339. if (isset($table_config[$k]) && ! empty($table_config[$k]['unique'])) {
  340. $uniqueValues[$k][] = [
  341. 'value' => trim($v),
  342. 'line' => $key
  343. ];
  344. }
  345. }
  346. }
  347. // 检查唯一性
  348. foreach ($uniqueValues as $column => $values) {
  349. $valueCount = [];
  350. foreach ($values as $item) {
  351. $valueCount[$item['value']][] = $item['line'];
  352. }
  353. foreach ($valueCount as $value => $lines) {
  354. if (count($lines) > 1) {
  355. $lineNumbers = implode(',', $lines);
  356. $error[] = $table_config[$column]['value'] . "重复,在第{$lineNumbers}行出现重复值:{$value}";
  357. }
  358. }
  359. }
  360. // 第二次遍历:进行其他验证
  361. foreach ($array as $key => $value){
  362. $line = '第' . $key . '行';
  363. $rowData = array_filter($value);
  364. if (empty($rowData)) {
  365. unset($array[$key]);
  366. } else{
  367. foreach ($value as $k => $v){
  368. $row = '第' . $k . '列';
  369. $tmp_v = trim($v);
  370. if(! isset($table_config[$k])){
  371. $error[] = $line . $row . "数据不存在";
  372. }else{
  373. $table_tmp = $table_config[$k] ?? [];
  374. if(! empty($table_tmp['required'])){
  375. if ($tmp_v === '' || ! isset($tmp_v)) {
  376. $error[] = $line . $table_tmp['value'] . "必填";
  377. }
  378. }
  379. }
  380. if(empty($tmp_v) && isset($table_tmp['default'])) $tmp_v = $table_tmp['default'];
  381. $value[$k] = $tmp_v;
  382. }
  383. $array[$key] = $value;
  384. }
  385. }
  386. $error_string = "";
  387. if(! empty($error)) $error_string = implode('|', $error);
  388. return [$array, $error_string];
  389. }
  390. //模板校验
  391. private function compareTableAndReturn($upload, $param){
  392. if(empty($upload)) return [false, '表头不能为空'];
  393. $config_array = $this->getTableConfig($param['type']);
  394. if(empty($config_array)) return [false, '导入配置表头文件不存在'];
  395. foreach ($config_array as $key => $value){
  396. $key_position = $key + 1;
  397. if(! isset($upload[$key])) return [false, "第" . $key_position . "列表头缺失"];
  398. $tmp_v = trim($upload[$key]);
  399. if($tmp_v != $value['value']) return [false, "第" . $key_position . "列表头与模板不符合,请重新下载模板"];
  400. }
  401. return [true, $config_array];
  402. }
  403. //转换日期
  404. function convertExcelCellToDate($cellValue) {
  405. // 尝试将单元格值转换为浮点数(Excel 日期序列号)
  406. $excelTimestamp = filter_var($cellValue, FILTER_VALIDATE_FLOAT);
  407. if ($excelTimestamp !== false && $excelTimestamp > 0) {
  408. // 如果成功转换并且值大于0,则认为是Excel日期序列号
  409. try {
  410. $dateTimeObject = Date::excelToDateTimeObject($cellValue);
  411. // if ($dateTimeObject->format('H:i:s') === '00:00:00') {
  412. // // 如果是,则将时间设置为 '23:59:00'
  413. // $dateTimeObject->setTime(23, 59);
  414. // }
  415. // 现在你可以格式化这个日期了
  416. $formattedDate = $dateTimeObject->format('Y-m-d');
  417. if(! strtotime($formattedDate)) return [false, ''];
  418. return [true, strtotime($formattedDate)];
  419. } catch (\Exception $e) {
  420. // 处理转换失败的情况
  421. return [false, '单元格日期格式转换时间戳失败'];
  422. }
  423. }
  424. // 如果不是有效的浮点数,则尝试按照多种日期格式解析
  425. if(! strtotime($cellValue)) return [false, '单元格文本格式转换时间戳失败'];
  426. return [true, strtotime($cellValue)];
  427. }
  428. }