ImportService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. namespace App\Service;
  3. use App\Exports\TableHeadExport;
  4. use App\Import\ImportAll;
  5. use App\Model\Employee;
  6. use App\Model\Freight;
  7. use App\Model\GiveOut;
  8. use App\Model\Product;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use Maatwebsite\Excel\Facades\Excel;
  12. use PhpOffice\PhpSpreadsheet\IOFactory;
  13. use PhpOffice\PhpSpreadsheet\Shared\Date;
  14. class ImportService extends Service
  15. {
  16. public static $type = [
  17. 'product', //存货
  18. 'freight', //运费设置
  19. 'giveOut', //发放统计
  20. ];
  21. public function getTableTitleXls($data,$user){
  22. if(empty($data['type'])) return [false,'缺少类型'];
  23. if(! in_array($data['type'],self::$type)) return [false,'类型不存在'];
  24. //获取配置文件
  25. $fuc = $data['type'];
  26. list($status,$return) = $this->$fuc($data,$user);
  27. list($msg,$filename) = $return;
  28. if(! $status) return [false, $msg];
  29. $headers = array_column($msg,'value');
  30. $comments = [];
  31. foreach ($msg as $value){
  32. if(! empty($value['comments'])) $comments[$value['value']] = $value['comments'];
  33. }
  34. Excel::store(new TableHeadExport([], $headers, $comments),"/public/export/{$filename}", null, 'Xlsx', []);
  35. return [true, ['file' => $filename]];
  36. }
  37. private function getTableConfig($type = ""){
  38. if(empty($type)) return [];
  39. //获取配置文件
  40. $config = "excel." . $type . "Table";
  41. return config($config) ?? [];
  42. }
  43. private function product($data,$user){
  44. $config_array = $this->getTableConfig($data['type']);
  45. if(empty($config_array)) return [false, ['导入配置表头文件不存在','']];
  46. //生成下载文件
  47. $filename = "存货导入模板_" . time() . '.' . 'xlsx';
  48. return [true, [$config_array, $filename]];
  49. }
  50. private function freight($data,$user){
  51. $config_array = $this->getTableConfig($data['type']);
  52. if(empty($config_array)) return [false, ['导入配置表头文件不存在','']];
  53. //生成下载文件
  54. $filename = "运费设置导入模板_" . time() . '.' . 'xlsx';
  55. return [true, [$config_array, $filename]];
  56. }
  57. private function giveOut($data,$user){
  58. $config_array = $this->getTableConfig($data['type']);
  59. if(empty($config_array)) return [false, ['导入配置表头文件不存在','']];
  60. //生成下载文件
  61. $filename = "发放统计导入模板_" . time() . '.' . 'xlsx';
  62. return [true, [$config_array, $filename]];
  63. }
  64. //导入入口
  65. public function importAll($data,$user){
  66. // //不超时
  67. // ini_set('max_execution_time', 0);
  68. // //内存设置
  69. // ini_set('memory_limit', -1);
  70. // $reader = IOFactory::createReader('Xlsx');
  71. // $reader->setReadDataOnly(true); // 只读取有数据的单元格
  72. // $spreadsheet = $reader->load($data['file']);
  73. // dd($spreadsheet);
  74. // // 创建一个Reader对象
  75. // $reader = IOFactory::createReader('Xlsx'); // 根据你的文件格式选择合适的reader
  76. //
  77. //// 加载Excel文件
  78. // $spreadsheet = $reader->load($data['file']);
  79. //
  80. //// 获取第一个工作表
  81. // $worksheet = $spreadsheet->getActiveSheet();
  82. //
  83. //// 获取总行数
  84. // $totalRows = $worksheet->getHighestRow();dd($totalRows);
  85. if(empty($data['type'])) return [false,'缺少导入类型,导入失败'];
  86. if(! in_array($data['type'],self::$type)) return [false,'导入类型不存在,导入失败'];
  87. if(empty($data['file'])) return [false,'导入文件不能为空'];
  88. try {
  89. $import = new ImportAll();
  90. //设置导入人id
  91. $import->setCrt($user['id']);
  92. $import->setUser($user);
  93. $import->setType($data['type']);
  94. $other = $data;
  95. unset($other['file']);
  96. $import->setOtherParam($other);
  97. //导入
  98. \Maatwebsite\Excel\Facades\Excel::import($import,$data['file']);
  99. if($import->getMsg()) {
  100. $bool = $import->getIsLongText();
  101. if($bool) {
  102. return [0, $import->getMsg()];
  103. }else{
  104. return [false, $import->getMsg()];
  105. }
  106. }
  107. }catch (\Throwable $exception) {
  108. return [false, $exception->getMessage() . ' (Code: ' . $exception->getCode() . ', Line: ' . $exception->getLine() . ')'];
  109. }
  110. return [true, ''];
  111. }
  112. public function productImport($array, $user, $other_param){
  113. $upload = $array[0];
  114. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  115. if(! $status) return [false, $msg];
  116. $table_config = $msg;
  117. // 去除表头
  118. unset($array[0]);
  119. if(empty($array)) return [false, '导入数据不能为空'];
  120. list($array, $error) = $this->checkCommon($array, $table_config);
  121. if(! empty($error)) return [0, $error];
  122. if(empty($array)) return [false, '导入数据不能为空'];
  123. //查找产品
  124. $product_map = Product::whereIn("code", array_column($array,0))
  125. ->where('del_time',0)
  126. ->pluck('id','code')
  127. ->toArray();
  128. $time = time();
  129. $insert = $update = [];
  130. foreach ($array as $value){
  131. $tmp = [];
  132. foreach ($value as $k => $val){
  133. $field = $table_config[$k]['key'];
  134. $tmp[$field] = $val;
  135. }
  136. if(isset($product_map[$tmp['code']])){
  137. $product_id = $product_map[$tmp['code']];
  138. //产品主表
  139. $update[$product_id] = $tmp;
  140. }else{
  141. $tmp['crt_id'] = $user['id'];
  142. $tmp['crt_time'] = $time;
  143. //产品主表
  144. $insert[$tmp['code']] = $tmp;
  145. }
  146. }
  147. try{
  148. //新增
  149. if(! empty($insert)){
  150. Product::insert($insert);
  151. }
  152. //编辑
  153. if(! empty($update)){
  154. foreach ($update as $p_id => $value){
  155. Product::where('id',$p_id)
  156. ->update($value);
  157. }
  158. }
  159. DB::commit();
  160. }catch (\Exception $e){
  161. DB::rollBack();
  162. return [false, $e->getMessage() . $e->getLine() . $e->getCode()];
  163. }
  164. return [true, ''];
  165. }
  166. public function freightImport($array, $user, $other_param){
  167. $upload = $array[0];
  168. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  169. if(! $status) return [false, $msg];
  170. $table_config = $msg;
  171. // 去除表头
  172. unset($array[0]);
  173. if(empty($array)) return [false, '导入数据不能为空'];
  174. list($array, $error) = $this->checkCommon($array, $table_config);
  175. if(! empty($error)) return [0, $error];
  176. if(empty($array)) return [false, '导入数据不能为空'];
  177. $time = time();
  178. $insert = [];
  179. foreach ($array as $value){
  180. $tmp = [];
  181. foreach ($value as $k => $val){
  182. $field = $table_config[$k]['key'];
  183. $tmp[$field] = $val;
  184. }
  185. $tmp['crt_id'] = $user['id'];
  186. $tmp['crt_time'] = $time;
  187. $insert[] = $tmp;
  188. }
  189. try{
  190. Freight::where('del_time',0)
  191. ->update(['del_time' => $time]);
  192. //新增
  193. if(! empty($insert)) Freight::insert($insert);
  194. DB::commit();
  195. }catch (\Exception $e){
  196. DB::rollBack();
  197. return [false, $e->getMessage() . $e->getLine() . $e->getCode()];
  198. }
  199. return [true, ''];
  200. }
  201. public function giveOutImport($array, $user, $other_param){
  202. $upload = $array[0];
  203. list($status, $msg) = $this->compareTableAndReturn($upload, $other_param);
  204. if(! $status) return [false, $msg];
  205. $table_config = $msg;
  206. // 去除表头
  207. unset($array[0]);
  208. if(empty($array)) return [false, '导入数据不能为空'];
  209. list($array, $error) = $this->checkCommon($array, $table_config);
  210. if(! empty($error)) return [0, $error];
  211. if(empty($array)) return [false, '导入数据不能为空'];
  212. $time = time();
  213. $new_array = [];
  214. foreach ($array as $value){
  215. $tmp = [];
  216. foreach ($value as $k => $val){
  217. $field = $table_config[$k]['key'];
  218. $tmp[$field] = $val;
  219. }
  220. $tmp['crt_id'] = $user['id'];
  221. $tmp['crt_time'] = $time;
  222. $new_array[] = $tmp;
  223. }
  224. $emp_map = Employee::where('del_time',0)
  225. ->whereIn('emp_name', array_column($new_array,'employee_id_1_title'))
  226. ->pluck('id','emp_name')
  227. ->toArray();
  228. $error_2 = [];
  229. foreach ($new_array as $key => $value){
  230. $line_number = $key + 2;
  231. $line = '第' . $line_number . '行';
  232. if(! isset($emp_map[$value['employee_id_1_title']])) {
  233. $error_2[] = $line . "业务员不存在或已被删除";
  234. }else{
  235. $new_array[$key]['employee_id_1'] = $emp_map[$value['employee_id_1_title']];
  236. }
  237. list($status, $msg) = $this->convertExcelCellToDate($value['send_time']);
  238. if(! $status){
  239. $error_2[] = $line . "发放日期错误";
  240. }else{
  241. $new_array[$key]['send_time'] = $msg;
  242. }
  243. if (strpos($value['belong_time'], '|') !== false) {
  244. list($start,$end) = explode('|', $value['belong_time']);
  245. $startStamp = strtotime($start);
  246. $endStamp = strtotime($end);
  247. if(! $startStamp || ! $endStamp || $startStamp > $endStamp) {
  248. $error_2[] = $line . "归属日期错误";
  249. }else{
  250. $new_array[$key]['start_time'] = $startStamp;
  251. $new_array[$key]['end_time'] = $endStamp;
  252. unset($new_array[$key]['belong_time']);
  253. }
  254. }else{
  255. list($status, $msg) = $this->convertExcelCellToDate($value['belong_time']);
  256. if(! $status){
  257. $error_2[] = $line . "归属日期错误";
  258. }else{
  259. $new_array[$key]['start_time'] = $msg;
  260. $new_array[$key]['end_time'] = $msg;
  261. unset($new_array[$key]['belong_time']);
  262. }
  263. }
  264. $res = $this->checkNumber($value['give_out_amount'],2,'positive');
  265. if(! $res['valid']) $error_2[] = $line . "分红已发放金额:" . $res['error'];
  266. }
  267. if(! empty($error_2)) {
  268. $error_string = implode('|', $error_2);
  269. return [0, $error_string];
  270. }
  271. try{
  272. //新增
  273. if(! empty($new_array)) GiveOut::insert($new_array);
  274. DB::commit();
  275. }catch (\Exception $e){
  276. DB::rollBack();
  277. return [false, $e->getMessage() . $e->getLine() . $e->getCode()];
  278. }
  279. return [true, ''];
  280. }
  281. //公共校验
  282. private function checkCommon($array, $table_config){
  283. $error = [];
  284. $uniqueValues = []; // 用于存储需要唯一性检查的值
  285. // 第一次遍历:收集所有唯一字段的值
  286. foreach ($array as $key => $value) {
  287. foreach ($value as $k => $v) {
  288. if (isset($table_config[$k]) && ! empty($table_config[$k]['unique'])) {
  289. $uniqueValues[$k][] = [
  290. 'value' => trim($v),
  291. 'line' => $key
  292. ];
  293. }
  294. }
  295. }
  296. // 检查唯一性
  297. foreach ($uniqueValues as $column => $values) {
  298. $valueCount = [];
  299. foreach ($values as $item) {
  300. $valueCount[$item['value']][] = $item['line'];
  301. }
  302. foreach ($valueCount as $value => $lines) {
  303. if (count($lines) > 1) {
  304. $lineNumbers = implode(',', $lines);
  305. $error[] = $table_config[$column]['value'] . "重复,在第{$lineNumbers}行出现重复值:{$value}";
  306. }
  307. }
  308. }
  309. // 第二次遍历:进行其他验证
  310. foreach ($array as $key => $value){
  311. $line = '第' . $key . '行';
  312. $rowData = array_filter($value);
  313. if (empty($rowData)) {
  314. unset($array[$key]);
  315. } else{
  316. foreach ($value as $k => $v){
  317. $row = '第' . $k . '列';
  318. $tmp_v = trim($v);
  319. if(! isset($table_config[$k])){
  320. $error[] = $line . $row . "数据不存在";
  321. }else{
  322. $table_tmp = $table_config[$k] ?? [];
  323. if(! empty($table_tmp['required'])){
  324. if ($tmp_v === '' || ! isset($tmp_v)) {
  325. $error[] = $line . $table_tmp['value'] . "必填";
  326. }
  327. }
  328. }
  329. if(empty($tmp_v) && isset($table_tmp['default'])) $tmp_v = $table_tmp['default'];
  330. $value[$k] = $tmp_v;
  331. }
  332. $array[$key] = $value;
  333. }
  334. }
  335. $error_string = "";
  336. if(! empty($error)) $error_string = implode('|', $error);
  337. return [$array, $error_string];
  338. }
  339. //模板校验
  340. private function compareTableAndReturn($upload, $param){
  341. if(empty($upload)) return [false, '表头不能为空'];
  342. $config_array = $this->getTableConfig($param['type']);
  343. if(empty($config_array)) return [false, '导入配置表头文件不存在'];
  344. foreach ($config_array as $key => $value){
  345. $key_position = $key + 1;
  346. if(! isset($upload[$key])) return [false, "第" . $key_position . "列表头缺失"];
  347. $tmp_v = trim($upload[$key]);
  348. if($tmp_v != $value['value']) return [false, "第" . $key_position . "列表头与模板不符合,请重新下载模板"];
  349. }
  350. return [true, $config_array];
  351. }
  352. //转换日期
  353. function convertExcelCellToDate($cellValue) {
  354. // 尝试将单元格值转换为浮点数(Excel 日期序列号)
  355. $excelTimestamp = filter_var($cellValue, FILTER_VALIDATE_FLOAT);
  356. if ($excelTimestamp !== false && $excelTimestamp > 0) {
  357. // 如果成功转换并且值大于0,则认为是Excel日期序列号
  358. try {
  359. $dateTimeObject = Date::excelToDateTimeObject($cellValue);
  360. // if ($dateTimeObject->format('H:i:s') === '00:00:00') {
  361. // // 如果是,则将时间设置为 '23:59:00'
  362. // $dateTimeObject->setTime(23, 59);
  363. // }
  364. // 现在你可以格式化这个日期了
  365. $formattedDate = $dateTimeObject->format('Y-m-d');
  366. if(! strtotime($formattedDate)) return [false, ''];
  367. return [true, strtotime($formattedDate)];
  368. } catch (\Exception $e) {
  369. // 处理转换失败的情况
  370. return [false, '单元格日期格式转换时间戳失败'];
  371. }
  372. }
  373. // 如果不是有效的浮点数,则尝试按照多种日期格式解析
  374. if(! strtotime($cellValue)) return [false, '单元格文本格式转换时间戳失败'];
  375. return [true, strtotime($cellValue)];
  376. }
  377. }