Stock.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use think\Session;
  5. use think\Db;
  6. use Exception;
  7. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  8. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  9. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  10. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  11. /**
  12. * 库存管理
  13. *
  14. * @icon fa fa-circle-o
  15. */
  16. class Stock extends Backend
  17. {
  18. /**
  19. * Stock模型对象
  20. * @var \app\admin\model\Stock
  21. */
  22. protected $model = null;
  23. protected $importHeadType = 'name';//以字段名为EXCEL表格首行
  24. public function _initialize()
  25. {
  26. parent::_initialize();
  27. $this->model = new \app\admin\model\Stock;
  28. }
  29. /**
  30. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
  31. * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
  32. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  33. */
  34. /**
  35. * 查看
  36. *
  37. * @return string|Json
  38. * @throws \think\Exception
  39. * @throws DbException
  40. */
  41. public function index()
  42. {
  43. //设置过滤方法
  44. $this->request->filter(['strip_tags', 'trim']);
  45. if (false === $this->request->isAjax()) {
  46. return $this->view->fetch();
  47. }
  48. //如果发送的来源是 Selectpage,则转发到 Selectpage
  49. if ($this->request->request('keyField')) {
  50. return $this->selectpage();
  51. }
  52. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  53. $user_info = Session::get('admin');
  54. $map = [];
  55. if ($user_info['id'] !== 1){
  56. $map['company_id'] = $user_info['company_id'];
  57. }
  58. $list = $this->model
  59. ->where($where)
  60. ->where($map)
  61. ->order($sort, $order)
  62. ->paginate($limit);
  63. $result = ['total' => $list->total(), 'rows' => $list->items()];
  64. return json($result);
  65. }
  66. /**
  67. * 添加
  68. *
  69. * @return string
  70. * @throws \think\Exception
  71. */
  72. public function add()
  73. {
  74. if (false === $this->request->isPost()) {
  75. return $this->view->fetch();
  76. }
  77. $params = $this->request->post('row/a');
  78. if (empty($params)) {
  79. $this->error(__('Parameter %s can not be empty', ''));
  80. }
  81. $params = $this->preExcludeFields($params);
  82. $user_info = Session::get('admin');
  83. $params['company_id'] = $user_info['company_id'];
  84. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  85. $params[$this->dataLimitField] = $this->auth->id;
  86. }
  87. $result = false;
  88. Db::startTrans();
  89. try {
  90. //是否采用模型验证
  91. if ($this->modelValidate) {
  92. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  93. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  94. $this->model->validateFailException()->validate($validate);
  95. }
  96. $result = $this->model->allowField(true)->save($params);
  97. Db::commit();
  98. } catch (ValidateException|PDOException|Exception $e) {
  99. Db::rollback();
  100. $this->error($e->getMessage());
  101. }
  102. if ($result === false) {
  103. $this->error(__('No rows were inserted'));
  104. }
  105. $this->success();
  106. }
  107. /**
  108. * 导入
  109. */
  110. public function import()
  111. {
  112. $file = $this->request->request('file');
  113. if (!$file) {
  114. $this->error(__('Parameter %s can not be empty', 'file'));
  115. }
  116. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  117. if (!is_file($filePath)) {
  118. $this->error(__('No results were found'));
  119. }
  120. //实例化reader
  121. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  122. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  123. $this->error(__('Unknown data format'));
  124. }
  125. if ($ext === 'csv') {
  126. $file = fopen($filePath, 'r');
  127. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  128. $fp = fopen($filePath, 'w');
  129. $n = 0;
  130. while ($line = fgets($file)) {
  131. $line = rtrim($line, "\n\r\0");
  132. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  133. if ($encoding !== 'utf-8') {
  134. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  135. }
  136. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  137. fwrite($fp, $line . "\n");
  138. } else {
  139. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  140. }
  141. $n++;
  142. }
  143. fclose($file) || fclose($fp);
  144. $reader = new Csv();
  145. } elseif ($ext === 'xls') {
  146. $reader = new Xls();
  147. } else {
  148. $reader = new Xlsx();
  149. }
  150. //加载文件
  151. $insert = [];
  152. try {
  153. if (!$PHPExcel = $reader->load($filePath)) {
  154. $this->error(__('Unknown data format'));
  155. }
  156. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  157. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  158. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  159. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  160. $fields = [];
  161. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  162. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  163. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  164. $fields[] = $val;
  165. }
  166. }
  167. $i = 0;
  168. $row = [];
  169. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  170. $values = [];
  171. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  172. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  173. $values[] = is_null($val) ? '' : $val;
  174. }
  175. $row[$i]['name'] = $values[0];
  176. $row[$i]['unit'] = $values[1];
  177. $row[$i]['l_number'] = $values[2];
  178. $row[$i]['number'] = $values[3];
  179. $user_info = Session::get('admin');
  180. $row[$i]['company_id'] = $user_info['company_id'];
  181. $row[$i]['create'] = date('Y-m-d H:i:s');
  182. $row[$i]['update'] = date('Y-m-d H:i:s');
  183. $i++;
  184. }
  185. } catch (Exception $exception) {
  186. $this->error($exception->getMessage());
  187. }
  188. if (!$row) {
  189. $this->error(__('No rows were updated'));
  190. }
  191. try {
  192. $insert = [];
  193. foreach ($row as $key => $vol){
  194. $where = [];
  195. $where['name'] = $vol['name'];
  196. $where['company_id'] = $vol['company_id'];
  197. $is_exit = Db::name('stock')->where($where)->find();
  198. if ($is_exit){
  199. Db::name('stock')->where($where)->setField('l_number',$vol['l_number']);
  200. Db::name('stock')->where($where)->setField('number',$vol['number']);
  201. }else{
  202. $insert[] = $vol;
  203. }
  204. }
  205. $this->model->saveAll($insert);
  206. } catch (PDOException $exception) {
  207. $msg = $exception->getMessage();
  208. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  209. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  210. };
  211. $this->error($msg);
  212. } catch (Exception $e) {
  213. $this->error($e->getMessage());
  214. }
  215. $this->success();
  216. }
  217. }