Books.php 17 KB

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