Stock.php 9.0 KB

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