Certificate.php 16 KB

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