You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

480 lines
16 KiB

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