作者 开飞机的舒克

后台学生管理新增导入功能

@@ -2,9 +2,19 @@ @@ -2,9 +2,19 @@
2 2
3 namespace app\admin\controller; 3 namespace app\admin\controller;
4 4
  5 +use app\admin\library\Auth;
5 use app\common\controller\Backend; 6 use app\common\controller\Backend;
6 use app\common\controller\Resource; 7 use app\common\controller\Resource;
  8 +use Exception;
  9 +use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  10 +use PhpOffice\PhpSpreadsheet\Reader\Csv;
  11 +use PhpOffice\PhpSpreadsheet\Reader\Xls;
  12 +use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
7 use think\Db; 13 use think\Db;
  14 +use think\db\exception\BindParamException;
  15 +use think\exception\DbException;
  16 +use think\exception\PDOException;
  17 +use think\exception\ValidateException;
8 18
9 /** 19 /**
10 * 学生管理 20 * 学生管理
@@ -199,4 +209,189 @@ class Study extends Backend @@ -199,4 +209,189 @@ class Study extends Backend
199 $this->success(); 209 $this->success();
200 } 210 }
201 211
  212 + /**
  213 + * 编辑
  214 + *
  215 + * @param $ids
  216 + * @return string
  217 + * @throws DbException
  218 + * @throws \think\Exception
  219 + */
  220 + public function edit($ids = null)
  221 + {
  222 + $row = $this->model->get($ids);
  223 + if (!$row) {
  224 + $this->error(__('No Results were found'));
  225 + }
  226 + $adminIds = $this->getDataLimitAdminIds();
  227 + if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
  228 + $this->error(__('You have no permission'));
  229 + }
  230 + if (false === $this->request->isPost()) {
  231 + $this->view->assign('row', $row);
  232 + return $this->view->fetch();
  233 + }
  234 + $params = $this->request->post('row/a');
  235 + if (empty($params)) {
  236 + $this->error(__('Parameter %s can not be empty', ''));
  237 + }
  238 + $params = $this->preExcludeFields($params);
  239 + $result = false;
  240 + Db::startTrans();
  241 + try {
  242 + //是否采用模型验证
  243 + if ($this->modelValidate) {
  244 + $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  245 + $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  246 + $row->validateFailException()->validate($validate);
  247 + }
  248 + $result = $row->allowField(true)->save($params);
  249 + Db::commit();
  250 + } catch (ValidateException|PDOException|Exception $e) {
  251 + Db::rollback();
  252 + $this->error($e->getMessage());
  253 + }
  254 + if (false === $result) {
  255 + $this->error(__('No rows were updated'));
  256 + }
  257 + $this->success();
  258 + }
  259 +
  260 + /**
  261 + * 导入
  262 + *
  263 + * @return void
  264 + * @throws PDOException
  265 + * @throws BindParamException
  266 + */
  267 + protected function import()
  268 + {
  269 + $file = $this->request->request('file');
  270 + if (!$file) {
  271 + $this->error(__('Parameter %s can not be empty', 'file'));
  272 + }
  273 + $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  274 + if (!is_file($filePath)) {
  275 + $this->error(__('No results were found'));
  276 + }
  277 + //实例化reader
  278 + $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  279 + if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  280 + $this->error(__('Unknown data format'));
  281 + }
  282 + if ($ext === 'csv') {
  283 + $file = fopen($filePath, 'r');
  284 + $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  285 + $fp = fopen($filePath, 'w');
  286 + $n = 0;
  287 + while ($line = fgets($file)) {
  288 + $line = rtrim($line, "\n\r\0");
  289 + $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  290 + if ($encoding !== 'utf-8') {
  291 + $line = mb_convert_encoding($line, 'utf-8', $encoding);
  292 + }
  293 + if ($n == 0 || preg_match('/^".*"$/', $line)) {
  294 + fwrite($fp, $line . "\n");
  295 + } else {
  296 + fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  297 + }
  298 + $n++;
  299 + }
  300 + fclose($file) || fclose($fp);
  301 +
  302 + $reader = new Csv();
  303 + } elseif ($ext === 'xls') {
  304 + $reader = new Xls();
  305 + } else {
  306 + $reader = new Xlsx();
  307 + }
  308 +
  309 + //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  310 + $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  311 +
  312 + $table = $this->model->getQuery()->getTable();
  313 + $database = \think\Config::get('database.database');
  314 + $fieldArr = [];
  315 + $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
  316 + foreach ($list as $k => $v) {
  317 + if ($importHeadType == 'comment') {
  318 + $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
  319 + $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
  320 + } else {
  321 + $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
  322 + }
  323 + }
  324 +
  325 + //加载文件
  326 + $insert = [];
  327 + try {
  328 + if (!$PHPExcel = $reader->load($filePath)) {
  329 + $this->error(__('Unknown data format'));
  330 + }
  331 + $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  332 + $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  333 + $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  334 + $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  335 + $fields = [];
  336 + for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  337 + for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  338 + $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  339 + $fields[] = $val;
  340 + }
  341 + }
  342 +
  343 + for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  344 + $values = [];
  345 + for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  346 + $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  347 + $values[] = is_null($val) ? '' : $val;
  348 + }
  349 + $row = [];
  350 + $temp = array_combine($fields, $values);
  351 + foreach ($temp as $k => $v) {
  352 + if (isset($fieldArr[$k]) && $k !== '') {
  353 + $row[$fieldArr[$k]] = $v;
  354 + }
  355 + }
  356 + if ($row) {
  357 + $insert[] = $row;
  358 + }
  359 + }
  360 + } catch (Exception $exception) {
  361 + $this->error($exception->getMessage());
  362 + }
  363 + if (!$insert) {
  364 + $this->error(__('No rows were updated'));
  365 + }
  366 +
  367 + try {
  368 + //是否包含admin_id字段
  369 + $has_admin_id = false;
  370 + foreach ($fieldArr as $name => $key) {
  371 + if ($key == 'admin_id') {
  372 + $has_admin_id = true;
  373 + break;
  374 + }
  375 + }
  376 + if ($has_admin_id) {
  377 + $auth = Auth::instance();
  378 + foreach ($insert as &$val) {
  379 + if (!isset($val['admin_id']) || empty($val['admin_id'])) {
  380 + $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
  381 + }
  382 + }
  383 + }
  384 + $this->model->saveAll($insert);
  385 + } catch (PDOException $exception) {
  386 + $msg = $exception->getMessage();
  387 + if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  388 + $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  389 + };
  390 + $this->error($msg);
  391 + } catch (Exception $e) {
  392 + $this->error($e->getMessage());
  393 + }
  394 +
  395 + $this->success();
  396 + }
202 } 397 }
@@ -10,18 +10,21 @@ class Study extends Validate @@ -10,18 +10,21 @@ class Study extends Validate
10 * 验证规则 10 * 验证规则
11 */ 11 */
12 protected $rule = [ 12 protected $rule = [
  13 + 'name'=>'require|/^[\u4e00-\u9fa5]{2,4}$/'
13 ]; 14 ];
14 /** 15 /**
15 * 提示消息 16 * 提示消息
16 */ 17 */
17 protected $message = [ 18 protected $message = [
  19 + 'name.require'=>'必填',
  20 + 'name./^[\u4e00-\u9fa5]{2,4}$/'=>'只能是2-4个字符',
18 ]; 21 ];
19 /** 22 /**
20 * 验证场景 23 * 验证场景
21 */ 24 */
22 protected $scene = [ 25 protected $scene = [
23 'add' => [], 26 'add' => [],
24 - 'edit' => [], 27 + 'edit' => ['name'],
25 ]; 28 ];
26 29
27 } 30 }
@@ -228,20 +228,28 @@ class Bind extends Api @@ -228,20 +228,28 @@ class Bind extends Api
228 $sid = \db('study')->where('user_id', $user['id'])->value('id'); 228 $sid = \db('study')->where('user_id', $user['id'])->value('id');
229 //获取学生的信息 229 //获取学生的信息
230 $data = \db('study')->where('id', $sid)->field('avatar,name,earn_score')->find(); 230 $data = \db('study')->where('id', $sid)->field('avatar,name,earn_score')->find();
231 - $data['avatar'] = cdnurl( $data['avatar'], true); 231 + //$data['avatar'] = cdnurl( $data['avatar'], true);
232 //获取雷达维度 232 //获取雷达维度
233 - $data['study_score'] = \db('study_score_log') 233 + $data['item'] = \db('study_score_log')
234 ->distinct('item_id') 234 ->distinct('item_id')
235 ->field('item_id,SUM(score) as sum_score') 235 ->field('item_id,SUM(score) as sum_score')
236 ->group('item_id') 236 ->group('item_id')
237 ->where(['campus_id' => $campus_id, 'study_id' => $sid]) 237 ->where(['campus_id' => $campus_id, 'study_id' => $sid])
238 - ->paginate(3, false) 238 +// ->limit(3)
  239 +// ->select();
  240 +// foreach ($res as $k) {
  241 +// $list = $k['sum_score'];
  242 +// $list['radar'] = \db('item i')
  243 +// ->join('radar r', 'i.radar_id = r.id')
  244 +// ->where('i.id', $k['item_id'])
  245 +// ->value('r.title');
  246 +// }
  247 + ->paginate(3)
239 ->each(function ($item, $key) { 248 ->each(function ($item, $key) {
240 - $item['item_radar'] = \db('item i') 249 + $item['title'] = \db('item i')
241 ->join('radar r', 'i.radar_id = r.id') 250 ->join('radar r', 'i.radar_id = r.id')
242 ->where('i.id', $item['item_id']) 251 ->where('i.id', $item['item_id'])
243 - ->field('i.radar_id,r.title')  
244 - ->select(); 252 + ->value('r.title');
245 return $item; 253 return $item;
246 }); 254 });
247 $this->success('获取学生信息成功', $data); 255 $this->success('获取学生信息成功', $data);
@@ -4973,7 +4973,7 @@ @@ -4973,7 +4973,7 @@
4973 4973
4974 </div> 4974 </div>
4975 <div class="col-md-6" align="right"> 4975 <div class="col-md-6" align="right">
4976 - Generated on 2023-03-14 11:57:04 <a href="./" target="_blank">校园活动</a> 4976 + Generated on 2023-03-14 13:41:04 <a href="./" target="_blank">校园活动</a>
4977 </div> 4977 </div>
4978 </div> 4978 </div>
4979 4979