Import.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace app\api\controller\ps;
  3. use app\common\controller\Api;
  4. use app\common\library\ps\BizExtractor;
  5. use app\common\library\ps\BizIngest;
  6. use app\common\library\ps\FactoryContext;
  7. /**
  8. * 文件导入产品 / 工单(登录工厂账号)
  9. */
  10. class Import extends Api
  11. {
  12. protected $noNeedRight = '*';
  13. public function _initialize()
  14. {
  15. parent::_initialize();
  16. if (!FactoryContext::id()) {
  17. $this->error('账号未绑定工厂');
  18. }
  19. }
  20. /**
  21. * 上传文件,AI/规则提取后返回预览,不入库
  22. */
  23. public function preview()
  24. {
  25. @set_time_limit(180);
  26. $type = $this->request->post('type', 'workorder');
  27. $type = $type === 'product' ? 'product' : 'workorder';
  28. $file = $this->request->file('file');
  29. if (!$file) {
  30. $this->error('请选择文件');
  31. }
  32. $dir = RUNTIME_PATH . 'import' . DS;
  33. if (!is_dir($dir)) {
  34. @mkdir($dir, 0755, true);
  35. }
  36. $info = $file->validate([
  37. 'size' => 12 * 1024 * 1024,
  38. 'ext' => 'csv,txt,xlsx,xls,pdf,png,jpg,jpeg,webp,bmp',
  39. ])->move($dir);
  40. if (!$info) {
  41. $this->error($file->getError() ?: '上传失败');
  42. }
  43. $path = $info->getPathname();
  44. try {
  45. $data = BizExtractor::extract($path, $type);
  46. } catch (\Exception $e) {
  47. @unlink($path);
  48. $this->error($e->getMessage());
  49. }
  50. @unlink($path);
  51. $this->success('已识别,请核对后确认导入', $data);
  52. }
  53. /**
  54. * 确认写入数据库
  55. */
  56. public function confirm()
  57. {
  58. $type = $this->request->post('type', 'workorder');
  59. $type = $type === 'product' ? 'product' : 'workorder';
  60. $items = $this->request->post('items/a');
  61. if (!$items) {
  62. $raw = $this->request->post('items_json', '', null);
  63. $items = json_decode((string)$raw, true);
  64. }
  65. if (!is_array($items) || !$items) {
  66. $this->error('没有可导入的数据');
  67. }
  68. $items = BizExtractor::normalizeItems($items, $type);
  69. $saved = [];
  70. $errors = [];
  71. foreach ($items as $i => $item) {
  72. try {
  73. if ($type === 'product') {
  74. $row = BizIngest::saveProduct($item, $this->auth->id);
  75. $saved[] = ['id' => (int)$row->id, 'code' => $row->code, 'name' => $row->name];
  76. } else {
  77. $row = BizIngest::saveWorkorder($item, $this->auth->id);
  78. $saved[] = ['id' => (int)$row->id, 'no' => $row->no];
  79. }
  80. } catch (\Exception $e) {
  81. $errors[] = '第' . ($i + 1) . '条:' . $e->getMessage();
  82. }
  83. }
  84. if (!$saved) {
  85. $this->error($errors ? implode(';', $errors) : '导入失败');
  86. }
  87. $this->success('已导入 ' . count($saved) . ' 条', [
  88. 'saved' => $saved,
  89. 'errors' => $errors,
  90. ]);
  91. }
  92. }