作者 开飞机的舒克

接口优化

@@ -11,6 +11,10 @@ use think\db\exception\DataNotFoundException; @@ -11,6 +11,10 @@ use think\db\exception\DataNotFoundException;
11 use think\db\exception\ModelNotFoundException; 11 use think\db\exception\ModelNotFoundException;
12 use think\exception\DbException; 12 use think\exception\DbException;
13 use think\exception\PDOException; 13 use think\exception\PDOException;
  14 +use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  15 +use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  16 +use PhpOffice\PhpSpreadsheet\Reader\Xls;
  17 +use PhpOffice\PhpSpreadsheet\Reader\Csv;
14 use think\exception\ValidateException; 18 use think\exception\ValidateException;
15 19
16 /** 20 /**
@@ -38,10 +42,144 @@ class Study extends Backend @@ -38,10 +42,144 @@ class Study extends Backend
38 42
39 43
40 /* 44 /*
41 - * 45 + * 导入
42 */ 46 */
43 public function import(){ 47 public function import(){
44 - return parent::import(); 48 + $file = $this->request->request('file');
  49 + if (!$file) {
  50 + $this->error(__('Parameter %s can not be empty', 'file'));
  51 + }
  52 + $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  53 + if (!is_file($filePath)) {
  54 + $this->error(__('No results were found'));
  55 + }
  56 + //实例化reader
  57 + $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  58 + if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  59 + $this->error(__('Unknown data format'));
  60 + }
  61 + if ($ext === 'csv') {
  62 + $file = fopen($filePath, 'r');
  63 + $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  64 + $fp = fopen($filePath, 'w');
  65 + $n = 0;
  66 + while ($line = fgets($file)) {
  67 + $line = rtrim($line, "\n\r\0");
  68 + $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  69 + if ($encoding !== 'utf-8') {
  70 + $line = mb_convert_encoding($line, 'utf-8', $encoding);
  71 + }
  72 + if ($n == 0 || preg_match('/^".*"$/', $line)) {
  73 + fwrite($fp, $line . "\n");
  74 + } else {
  75 + fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  76 + }
  77 + $n++;
  78 + }
  79 + fclose($file) || fclose($fp);
  80 +
  81 + $reader = new Csv();
  82 + } elseif ($ext === 'xls') {
  83 + $reader = new Xls();
  84 + } else {
  85 + $reader = new Xlsx();
  86 + }
  87 +
  88 + //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  89 + $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  90 +
  91 + $table = $this->model->getQuery()->getTable();
  92 + $database = \think\Config::get('database.database');
  93 + $fieldArr = [];
  94 + $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
  95 + foreach ($list as $k => $v) {
  96 + if ($importHeadType == 'comment') {
  97 + $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
  98 + $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
  99 + } else {
  100 + $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
  101 + }
  102 + }
  103 +
  104 + //加载文件
  105 + $insert = [];
  106 + try {
  107 + if (!$PHPExcel = $reader->load($filePath)) {
  108 + $this->error(__('Unknown data format'));
  109 + }
  110 + $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  111 + $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  112 + $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  113 + $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  114 + $fields = [];
  115 + for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  116 + for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  117 + $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  118 + $fields[] = $val;
  119 + }
  120 + }
  121 +
  122 + for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  123 + $values = [];
  124 + for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  125 + $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  126 + $values[] = is_null($val) ? '' : $val;
  127 + }
  128 + $row = [];
  129 + $temp = array_combine($fields, $values);
  130 + foreach ($temp as $k => $v) {
  131 + if (isset($fieldArr[$k]) && $k !== '') {
  132 + $row[$fieldArr[$k]] = $v;
  133 + }
  134 + }
  135 + //自动生成条形码
  136 + if ($row) {
  137 + $insert[] = $row;
  138 + }
  139 + $id = \db('study')->order('id','desc')->value('id');
  140 + $ids = $allRow+$id+1;
  141 + dump($ids);
  142 + $res = str_pad($ids,8,"0",STR_PAD_LEFT);
  143 + $barpath = Resource::StudyBar($res);
  144 + $insert['barcode'] = $barpath;
  145 + $insert['unique'] = $res;
  146 + }
  147 + } catch (Exception $exception) {
  148 + $this->error($exception->getMessage());
  149 + }
  150 + if (!$insert) {
  151 + $this->error(__('No rows were updated'));
  152 + }
  153 +
  154 + try {
  155 + //是否包含admin_id字段
  156 + $has_admin_id = false;
  157 + foreach ($fieldArr as $name => $key) {
  158 + if ($key == 'admin_id') {
  159 + $has_admin_id = true;
  160 + break;
  161 + }
  162 + }
  163 + if ($has_admin_id) {
  164 + $auth = Auth::instance();
  165 + foreach ($insert as &$val) {
  166 + if (!isset($val['admin_id']) || empty($val['admin_id'])) {
  167 + $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
  168 + }
  169 + }
  170 + }
  171 + $this->model->saveAll($insert);
  172 + } catch (PDOException $exception) {
  173 + $msg = $exception->getMessage();
  174 + if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  175 + $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  176 + };
  177 + $this->error($msg);
  178 + } catch (Exception $e) {
  179 + $this->error($e->getMessage());
  180 + }
  181 +
  182 + $this->success();
45 } 183 }
46 184
47 /** 185 /**
@@ -8,7 +8,7 @@ @@ -8,7 +8,7 @@
8 <div id="toolbar" class="toolbar"> 8 <div id="toolbar" class="toolbar">
9 <a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> </a> 9 <a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> </a>
10 <a href="javascript:;" class="btn btn-success btn-add {:$auth->check('study/add')?'':'hide'}" title="{:__('Add')}" ><i class="fa fa-plus"></i> {:__('Add')}</a> 10 <a href="javascript:;" class="btn btn-success btn-add {:$auth->check('study/add')?'':'hide'}" title="{:__('Add')}" ><i class="fa fa-plus"></i> {:__('Add')}</a>
11 - <a href="javascript:;" class="btn btn-success btn-import {:$auth->check('你的权限规则')?'':'hide'}" title="导入" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="fa fa-upload"></i> 导入</a> 11 + <a href="javascript:;" class="btn btn-success btn-import {:$auth->check('study/import')?'':'hide'}" title="导入" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="fa fa-upload"></i> 导入</a>
12 <a href="javascript:;" class="btn btn-danger btn-export {:$auth->check('study/export')?'':'hide'}" title="{:__('Export')}" id="btn-export-file"><i class="fa fa-download"></i> {:__('Export')}</a> 12 <a href="javascript:;" class="btn btn-danger btn-export {:$auth->check('study/export')?'':'hide'}" title="{:__('Export')}" id="btn-export-file"><i class="fa fa-download"></i> {:__('Export')}</a>
13 <a href="#" title="下载分享码" class="btn btn-success btn-disabled download {:$auth->check('study/multi')?'':'hide'} ">下载条形码</a> 13 <a href="#" title="下载分享码" class="btn btn-success btn-disabled download {:$auth->check('study/multi')?'':'hide'} ">下载条形码</a>
14 14
@@ -202,7 +202,7 @@ class Activity extends Api @@ -202,7 +202,7 @@ class Activity extends Api
202 ]) 202 ])
203 ->find(); 203 ->find();
204 $data['images'] = cdnurl($data['images'], true); 204 $data['images'] = cdnurl($data['images'], true);
205 - $data['holdtime'] = date('Ymd',$data['holdtime']); 205 + $data['holdtime'] = date('Y-m-d',$data['holdtime']);
206 $this->success('获取项目详情成功', $data); 206 $this->success('获取项目详情成功', $data);
207 } 207 }
208 } 208 }
@@ -5200,7 +5200,7 @@ @@ -5200,7 +5200,7 @@
5200 5200
5201 </div> 5201 </div>
5202 <div class="col-md-6" align="right"> 5202 <div class="col-md-6" align="right">
5203 - Generated on 2023-03-17 14:45:40 <a href="./" target="_blank">校园活动</a> 5203 + Generated on 2023-03-17 15:48:06 <a href="./" target="_blank">校园活动</a>
5204 </div> 5204 </div>
5205 </div> 5205 </div>
5206 5206