Certificate.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. <?php
  2. namespace app\admin\controller\books;
  3. use app\admin\library\Auth;
  4. use app\common\controller\Backend;
  5. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  6. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  7. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  8. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  9. use think\Db;
  10. use think\db\exception\BindParamException;
  11. use think\db\exception\DataNotFoundException;
  12. use think\db\exception\ModelNotFoundException;
  13. use think\exception\DbException;
  14. use think\exception\PDOException;
  15. use think\exception\ValidateException;
  16. use think\response\Json;
  17. /**
  18. * 体验卡管理
  19. *
  20. * @icon fa fa-certificate
  21. */
  22. class Certificate extends Backend
  23. {
  24. /**
  25. * Certificate模型对象
  26. * @var \app\admin\model\books\Certificate
  27. */
  28. protected $model = null;
  29. public function _initialize()
  30. {
  31. parent::_initialize();
  32. $this->model = new \app\admin\model\books\Certificate;
  33. $this->view->assign("statusList", $this->model->getStatusList());
  34. $this->view->assign("isExpireList", $this->model->getIsExpireList());
  35. }
  36. /**
  37. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
  38. * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
  39. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  40. */
  41. /**
  42. * 查看
  43. *
  44. * @return string|Json
  45. * @throws \think\Exception
  46. * @throws DbException
  47. */
  48. public function index()
  49. {
  50. //设置过滤方法
  51. $this->request->filter(['strip_tags', 'trim']);
  52. if (false === $this->request->isAjax()) {
  53. return $this->view->fetch();
  54. }
  55. //如果发送的来源是 Selectpage,则转发到 Selectpage
  56. if ($this->request->request('keyField')) {
  57. return $this->selectpage();
  58. }
  59. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  60. $list = $this->model
  61. ->where($where)
  62. ->with(['user','goods'])
  63. ->order($sort, $order)
  64. ->paginate($limit);
  65. $result = ['total' => $list->total(), 'rows' => $list->items()];
  66. return json($result);
  67. }
  68. /**
  69. * 回收站
  70. *
  71. * @return string|Json
  72. * @throws \think\Exception
  73. */
  74. public function recyclebin()
  75. {
  76. //设置过滤方法
  77. $this->request->filter(['strip_tags', 'trim']);
  78. if (false === $this->request->isAjax()) {
  79. return $this->view->fetch();
  80. }
  81. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  82. $list = $this->model
  83. ->onlyTrashed()
  84. ->where($where)
  85. ->order($sort, $order)
  86. ->paginate($limit);
  87. $result = ['total' => $list->total(), 'rows' => $list->items()];
  88. return json($result);
  89. }
  90. /**
  91. * 添加
  92. *
  93. * @return string
  94. * @throws \think\Exception
  95. */
  96. public function add()
  97. {
  98. if (false === $this->request->isPost()) {
  99. return $this->view->fetch();
  100. }
  101. $params = $this->request->post('row/a');
  102. if (empty($params)) {
  103. $this->error(__('Parameter %s can not be empty', ''));
  104. }
  105. $params = $this->preExcludeFields($params);
  106. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  107. $params[$this->dataLimitField] = $this->auth->id;
  108. }
  109. $result = false;
  110. Db::startTrans();
  111. try {
  112. //是否采用模型验证
  113. if ($this->modelValidate) {
  114. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  115. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  116. $this->model->validateFailException()->validate($validate);
  117. }
  118. $result = $this->model->allowField(true)->save($params);
  119. Db::commit();
  120. } catch (ValidateException|PDOException|Exception $e) {
  121. Db::rollback();
  122. $this->error($e->getMessage());
  123. }
  124. if ($result === false) {
  125. $this->error(__('No rows were inserted'));
  126. }
  127. $this->success();
  128. }
  129. /**
  130. * 编辑
  131. *
  132. * @param $ids
  133. * @return string
  134. * @throws DbException
  135. * @throws \think\Exception
  136. */
  137. public function edit($ids = null)
  138. {
  139. $row = $this->model->get($ids);
  140. if (!$row) {
  141. $this->error(__('No Results were found'));
  142. }
  143. $adminIds = $this->getDataLimitAdminIds();
  144. if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
  145. $this->error(__('You have no permission'));
  146. }
  147. if (false === $this->request->isPost()) {
  148. $this->view->assign('row', $row);
  149. return $this->view->fetch();
  150. }
  151. $params = $this->request->post('row/a');
  152. if (empty($params)) {
  153. $this->error(__('Parameter %s can not be empty', ''));
  154. }
  155. $params = $this->preExcludeFields($params);
  156. $result = false;
  157. Db::startTrans();
  158. try {
  159. //是否采用模型验证
  160. if ($this->modelValidate) {
  161. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  162. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  163. $row->validateFailException()->validate($validate);
  164. }
  165. $result = $row->allowField(true)->save($params);
  166. Db::commit();
  167. } catch (ValidateException|PDOException|Exception $e) {
  168. Db::rollback();
  169. $this->error($e->getMessage());
  170. }
  171. if (false === $result) {
  172. $this->error(__('No rows were updated'));
  173. }
  174. $this->success();
  175. }
  176. /**
  177. * 删除
  178. *
  179. * @param $ids
  180. * @return void
  181. * @throws DbException
  182. * @throws DataNotFoundException
  183. * @throws ModelNotFoundException
  184. */
  185. public function del($ids = null)
  186. {
  187. if (false === $this->request->isPost()) {
  188. $this->error(__("Invalid parameters"));
  189. }
  190. $ids = $ids ?: $this->request->post("ids");
  191. if (empty($ids)) {
  192. $this->error(__('Parameter %s can not be empty', 'ids'));
  193. }
  194. $pk = $this->model->getPk();
  195. $adminIds = $this->getDataLimitAdminIds();
  196. if (is_array($adminIds)) {
  197. $this->model->where($this->dataLimitField, 'in', $adminIds);
  198. }
  199. $list = $this->model->where($pk, 'in', $ids)->select();
  200. $count = 0;
  201. Db::startTrans();
  202. try {
  203. $arr = ['is_deleted' => 0];
  204. foreach ($list as $item) {
  205. $count += $item->where('id',$item['id'])->update($arr);
  206. }
  207. Db::commit();
  208. } catch (PDOException|Exception $e) {
  209. Db::rollback();
  210. $this->error($e->getMessage());
  211. }
  212. if ($count) {
  213. $this->success();
  214. }
  215. $this->error(__('No rows were deleted'));
  216. }
  217. /**
  218. * 真实删除
  219. *
  220. * @param $ids
  221. * @return void
  222. */
  223. public function destroy($ids = null)
  224. {
  225. if (false === $this->request->isPost()) {
  226. $this->error(__("Invalid parameters"));
  227. }
  228. $ids = $ids ?: $this->request->post('ids');
  229. $pk = $this->model->getPk();
  230. $adminIds = $this->getDataLimitAdminIds();
  231. if (is_array($adminIds)) {
  232. $this->model->where($this->dataLimitField, 'in', $adminIds);
  233. }
  234. if ($ids) {
  235. $this->model->where($pk, 'in', $ids);
  236. }
  237. $count = 0;
  238. Db::startTrans();
  239. try {
  240. $list = $this->model->onlyTrashed()->select();
  241. foreach ($list as $item) {
  242. $count += $item->delete(true);
  243. }
  244. Db::commit();
  245. } catch (PDOException|Exception $e) {
  246. Db::rollback();
  247. $this->error($e->getMessage());
  248. }
  249. if ($count) {
  250. $this->success();
  251. }
  252. $this->error(__('No rows were deleted'));
  253. }
  254. /**
  255. * 还原
  256. *
  257. * @param $ids
  258. * @return void
  259. */
  260. public function restore($ids = null)
  261. {
  262. if (false === $this->request->isPost()) {
  263. $this->error(__('Invalid parameters'));
  264. }
  265. $ids = $ids ?: $this->request->post('ids');
  266. $pk = $this->model->getPk();
  267. $adminIds = $this->getDataLimitAdminIds();
  268. if (is_array($adminIds)) {
  269. $this->model->where($this->dataLimitField, 'in', $adminIds);
  270. }
  271. if ($ids) {
  272. $this->model->where($pk, 'in', $ids);
  273. }
  274. $count = 0;
  275. Db::startTrans();
  276. try {
  277. $list = $this->model->onlyTrashed()->select();
  278. foreach ($list as $item) {
  279. $count += $item->restore();
  280. }
  281. Db::commit();
  282. } catch (PDOException|Exception $e) {
  283. Db::rollback();
  284. $this->error($e->getMessage());
  285. }
  286. if ($count) {
  287. $this->success();
  288. }
  289. $this->error(__('No rows were updated'));
  290. }
  291. /**
  292. * 批量更新
  293. *
  294. * @param $ids
  295. * @return void
  296. */
  297. public function multi($ids = null)
  298. {
  299. if (false === $this->request->isPost()) {
  300. $this->error(__('Invalid parameters'));
  301. }
  302. $ids = $ids ?: $this->request->post('ids');
  303. if (empty($ids)) {
  304. $this->error(__('Parameter %s can not be empty', 'ids'));
  305. }
  306. if (false === $this->request->has('params')) {
  307. $this->error(__('No rows were updated'));
  308. }
  309. parse_str($this->request->post('params'), $values);
  310. $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
  311. if (empty($values)) {
  312. $this->error(__('You have no permission'));
  313. }
  314. $adminIds = $this->getDataLimitAdminIds();
  315. if (is_array($adminIds)) {
  316. $this->model->where($this->dataLimitField, 'in', $adminIds);
  317. }
  318. $count = 0;
  319. Db::startTrans();
  320. try {
  321. $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
  322. foreach ($list as $item) {
  323. $count += $item->allowField(true)->isUpdate(true)->save($values);
  324. }
  325. Db::commit();
  326. } catch (PDOException|Exception $e) {
  327. Db::rollback();
  328. $this->error($e->getMessage());
  329. }
  330. if ($count) {
  331. $this->success();
  332. }
  333. $this->error(__('No rows were updated'));
  334. }
  335. /**
  336. * 导入
  337. *
  338. * @return void
  339. * @throws PDOException
  340. * @throws BindParamException
  341. */
  342. protected function import()
  343. {
  344. $file = $this->request->request('file');
  345. if (!$file) {
  346. $this->error(__('Parameter %s can not be empty', 'file'));
  347. }
  348. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  349. if (!is_file($filePath)) {
  350. $this->error(__('No results were found'));
  351. }
  352. //实例化reader
  353. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  354. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  355. $this->error(__('Unknown data format'));
  356. }
  357. if ($ext === 'csv') {
  358. $file = fopen($filePath, 'r');
  359. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  360. $fp = fopen($filePath, 'w');
  361. $n = 0;
  362. while ($line = fgets($file)) {
  363. $line = rtrim($line, "\n\r\0");
  364. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  365. if ($encoding !== 'utf-8') {
  366. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  367. }
  368. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  369. fwrite($fp, $line . "\n");
  370. } else {
  371. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  372. }
  373. $n++;
  374. }
  375. fclose($file) || fclose($fp);
  376. $reader = new Csv();
  377. } elseif ($ext === 'xls') {
  378. $reader = new Xls();
  379. } else {
  380. $reader = new Xlsx();
  381. }
  382. //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  383. $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  384. $table = $this->model->getQuery()->getTable();
  385. $database = \think\Config::get('database.database');
  386. $fieldArr = [];
  387. $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
  388. foreach ($list as $k => $v) {
  389. if ($importHeadType == 'comment') {
  390. $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
  391. $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
  392. } else {
  393. $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
  394. }
  395. }
  396. //加载文件
  397. $insert = [];
  398. try {
  399. if (!$PHPExcel = $reader->load($filePath)) {
  400. $this->error(__('Unknown data format'));
  401. }
  402. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  403. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  404. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  405. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  406. $fields = [];
  407. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  408. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  409. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  410. $fields[] = $val;
  411. }
  412. }
  413. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  414. $values = [];
  415. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  416. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  417. $values[] = is_null($val) ? '' : $val;
  418. }
  419. $row = [];
  420. $temp = array_combine($fields, $values);
  421. foreach ($temp as $k => $v) {
  422. if (isset($fieldArr[$k]) && $k !== '') {
  423. $row[$fieldArr[$k]] = $v;
  424. }
  425. }
  426. if ($row) {
  427. $insert[] = $row;
  428. }
  429. }
  430. } catch (Exception $exception) {
  431. $this->error($exception->getMessage());
  432. }
  433. if (!$insert) {
  434. $this->error(__('No rows were updated'));
  435. }
  436. try {
  437. //是否包含admin_id字段
  438. $has_admin_id = false;
  439. foreach ($fieldArr as $name => $key) {
  440. if ($key == 'admin_id') {
  441. $has_admin_id = true;
  442. break;
  443. }
  444. }
  445. if ($has_admin_id) {
  446. $auth = Auth::instance();
  447. foreach ($insert as &$val) {
  448. if (!isset($val['admin_id']) || empty($val['admin_id'])) {
  449. $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
  450. }
  451. }
  452. }
  453. $this->model->saveAll($insert);
  454. } catch (PDOException $exception) {
  455. $msg = $exception->getMessage();
  456. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  457. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  458. };
  459. $this->error($msg);
  460. } catch (Exception $e) {
  461. $this->error($e->getMessage());
  462. }
  463. $this->success();
  464. }
  465. }