| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229 |
- <?php
- namespace app\admin\controller;
- use app\common\controller\Backend;
- use think\Session;
- use think\Db;
- use Exception;
- use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
- use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
- use PhpOffice\PhpSpreadsheet\Reader\Xls;
- use PhpOffice\PhpSpreadsheet\Reader\Csv;
- /**
- * 库存管理
- *
- * @icon fa fa-circle-o
- */
- class Stock extends Backend
- {
- /**
- * Stock模型对象
- * @var \app\admin\model\Stock
- */
- protected $model = null;
- protected $importHeadType = 'name';//以字段名为EXCEL表格首行
- public function _initialize()
- {
- parent::_initialize();
- $this->model = new \app\admin\model\Stock;
- }
- /**
- * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
- * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
- * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
- */
- /**
- * 查看
- *
- * @return string|Json
- * @throws \think\Exception
- * @throws DbException
- */
- public function index()
- {
- //设置过滤方法
- $this->request->filter(['strip_tags', 'trim']);
- if (false === $this->request->isAjax()) {
- return $this->view->fetch();
- }
- //如果发送的来源是 Selectpage,则转发到 Selectpage
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- [$where, $sort, $order, $offset, $limit] = $this->buildparams();
- $user_info = Session::get('admin');
- $map = [];
- if ($user_info['id'] !== 1){
- $map['company_id'] = $user_info['company_id'];
- }
- $list = $this->model
- ->where($where)
- ->where($map)
- ->order($sort, $order)
- ->paginate($limit);
- $result = ['total' => $list->total(), 'rows' => $list->items()];
- return json($result);
- }
- /**
- * 添加
- *
- * @return string
- * @throws \think\Exception
- */
- public function add()
- {
- if (false === $this->request->isPost()) {
- return $this->view->fetch();
- }
- $params = $this->request->post('row/a');
- if (empty($params)) {
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $params = $this->preExcludeFields($params);
- $user_info = Session::get('admin');
- $params['company_id'] = $user_info['company_id'];
- if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
- $params[$this->dataLimitField] = $this->auth->id;
- }
- $result = false;
- Db::startTrans();
- try {
- //是否采用模型验证
- if ($this->modelValidate) {
- $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
- $this->model->validateFailException()->validate($validate);
- }
- $result = $this->model->allowField(true)->save($params);
- Db::commit();
- } catch (ValidateException|PDOException|Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result === false) {
- $this->error(__('No rows were inserted'));
- }
- $this->success();
- }
- /**
- * 导入
- */
- public function import()
- {
- $file = $this->request->request('file');
- if (!$file) {
- $this->error(__('Parameter %s can not be empty', 'file'));
- }
- $filePath = ROOT_PATH . DS . 'public' . DS . $file;
- if (!is_file($filePath)) {
- $this->error(__('No results were found'));
- }
- //实例化reader
- $ext = pathinfo($filePath, PATHINFO_EXTENSION);
- if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
- $this->error(__('Unknown data format'));
- }
- if ($ext === 'csv') {
- $file = fopen($filePath, 'r');
- $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
- $fp = fopen($filePath, 'w');
- $n = 0;
- while ($line = fgets($file)) {
- $line = rtrim($line, "\n\r\0");
- $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
- if ($encoding !== 'utf-8') {
- $line = mb_convert_encoding($line, 'utf-8', $encoding);
- }
- if ($n == 0 || preg_match('/^".*"$/', $line)) {
- fwrite($fp, $line . "\n");
- } else {
- fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
- }
- $n++;
- }
- fclose($file) || fclose($fp);
- $reader = new Csv();
- } elseif ($ext === 'xls') {
- $reader = new Xls();
- } else {
- $reader = new Xlsx();
- }
- //加载文件
- $insert = [];
- try {
- if (!$PHPExcel = $reader->load($filePath)) {
- $this->error(__('Unknown data format'));
- }
- $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
- $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
- $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
- $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
- $fields = [];
- for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $fields[] = $val;
- }
- }
- $i = 0;
- $row = [];
- for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
- $values = [];
- for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $values[] = is_null($val) ? '' : $val;
- }
- $row[$i]['name'] = $values[0];
- $row[$i]['unit'] = $values[1];
- $row[$i]['l_number'] = $values[2];
- $row[$i]['number'] = $values[3];
- $user_info = Session::get('admin');
- $row[$i]['company_id'] = $user_info['company_id'];
- $row[$i]['create'] = date('Y-m-d H:i:s');
- $row[$i]['update'] = date('Y-m-d H:i:s');
- $i++;
- }
- } catch (Exception $exception) {
- $this->error($exception->getMessage());
- }
- if (!$row) {
- $this->error(__('No rows were updated'));
- }
- try {
- $insert = [];
- foreach ($row as $key => $vol){
- $where = [];
- $where['name'] = $vol['name'];
- $where['company_id'] = $vol['company_id'];
- $is_exit = Db::name('stock')->where($where)->find();
- if ($is_exit){
- Db::name('stock')->where($where)->setField('l_number',$vol['l_number']);
- Db::name('stock')->where($where)->setField('number',$vol['number']);
- }else{
- $insert[] = $vol;
- }
- }
- $this->model->saveAll($insert);
- } catch (PDOException $exception) {
- $msg = $exception->getMessage();
- if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
- $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
- };
- $this->error($msg);
- } catch (Exception $e) {
- $this->error($e->getMessage());
- }
- $this->success();
- }
- }
|