Order.php 16 KB

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