Order.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. <?php
  2. namespace app\admin\controller\unishop;
  3. use app\admin\model\unishop\Area;
  4. use app\admin\model\unishop\OrderRefund;
  5. use app\common\controller\Backend;
  6. use think\Db;
  7. use think\Exception;
  8. use think\exception\PDOException;
  9. use think\exception\ValidateException;
  10. use think\Hook;
  11. /**
  12. * 订单管理
  13. *
  14. * @icon fa fa-circle-o
  15. */
  16. class Order extends Backend
  17. {
  18. /**
  19. * 是否是关联查询
  20. */
  21. protected $relationSearch = true;
  22. /**
  23. * Order模型对象
  24. * @var \app\admin\model\unishop\Order
  25. */
  26. protected $model = null;
  27. public function _initialize()
  28. {
  29. parent::_initialize();
  30. $this->model = new \app\admin\model\unishop\Order;
  31. $this->view->assign("payTypeList", $this->model->getPayTypeList());
  32. $this->view->assign("statusList", $this->model->getStatusList());
  33. $this->view->assign("refundStatusList", $this->model->getRefundStatusList());
  34. }
  35. /**
  36. * 查看
  37. */
  38. public function index()
  39. {
  40. //设置过滤方法
  41. $this->request->filter(['strip_tags']);
  42. if ($this->request->isAjax()) {
  43. //如果发送的来源是Selectpage,则转发到Selectpage
  44. if ($this->request->request('keyField')) {
  45. return $this->selectpage();
  46. }
  47. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  48. $total = $this->model
  49. ->alias('order')
  50. ->join('user', 'user.id = order.user_id','LEFT')
  51. ->join('user intro', 'intro.id = order.intro_uid','LEFT')
  52. ->join('user hexiao', 'hexiao.id = order.hexiao_uid','LEFT')
  53. ->where($where)
  54. ->count();
  55. $list = $this->model
  56. ->alias('order')
  57. ->join('user', 'user.id = order.user_id','LEFT')
  58. ->join('user intro', 'intro.id = order.intro_uid','LEFT')
  59. ->join('user hexiao', 'hexiao.id = order.hexiao_uid','LEFT')
  60. ->where($where)
  61. ->order($sort, $order)
  62. ->limit($offset, $limit)
  63. ->field('order.*,user.username,intro.username as intro_username,hexiao.username as hexiao_username')
  64. ->select();
  65. $list = collection($list)->toArray();
  66. foreach ($list as &$item) {
  67. $item['id'] = (string)$item['id']; // 整形数字太大js会失准
  68. $item['user'] = [];
  69. $item['user']['username'] = $item['username'] ? $item['username'] : '';
  70. $item['intro'] = [];
  71. $item['intro']['username'] = $item['intro_username'] ? $item['intro_username'] : '';
  72. $item['hexiao'] = [];
  73. $item['hexiao']['username'] = $item['hexiao_username'] ? $item['hexiao_username'] : '';
  74. $item['have_paid_status'] = $item['have_paid'];
  75. $item['have_delivered_status'] = $item['have_delivered'];
  76. $item['have_received_status'] = $item['have_received'];
  77. $item['have_commented_status'] = $item['have_commented'];
  78. }
  79. $result = array("total" => $total, "rows" => $list);
  80. return json($result);
  81. }
  82. return $this->view->fetch();
  83. }
  84. /**
  85. * 生成查询所需要的条件,排序方式
  86. * @param mixed $searchfields 快速查询的字段
  87. * @param boolean $relationSearch 是否关联查询
  88. * @return array
  89. */
  90. protected function buildparams($searchfields = null, $relationSearch = null)
  91. {
  92. $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
  93. $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
  94. $search = $this->request->get("search", '');
  95. $filter = $this->request->get("filter", '');
  96. $op = $this->request->get("op", '', 'trim');
  97. $sort = $this->request->get("sort", "id");
  98. $order = $this->request->get("order", "DESC");
  99. $offset = $this->request->get("offset", 0);
  100. $limit = $this->request->get("limit", 0);
  101. $filter = (array)json_decode($filter, true);
  102. $op = (array)json_decode($op, true);
  103. $filter = $filter ? $filter : [];
  104. $where = [];
  105. $tableName = '';
  106. if ($relationSearch) {
  107. if (!empty($this->model)) {
  108. $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
  109. $tableName = '' . $name . '.';
  110. }
  111. $sortArr = explode(',', $sort);
  112. foreach ($sortArr as $index => & $item) {
  113. $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
  114. }
  115. unset($item);
  116. $sort = implode(',', $sortArr);
  117. }
  118. $adminIds = $this->getDataLimitAdminIds();
  119. if (is_array($adminIds)) {
  120. $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
  121. }
  122. if ($search) {
  123. $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
  124. foreach ($searcharr as $k => &$v) {
  125. $v = stripos($v, ".") === false ? $tableName . $v : $v;
  126. }
  127. unset($v);
  128. $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
  129. }
  130. foreach ($filter as $k => $v) {
  131. // 搜索订单状态
  132. if (in_array($k, ['have_paid_status', 'have_delivered_status', 'have_received_status', 'have_commented_status'])) {
  133. switch ($k) {
  134. case 'have_paid_status':
  135. $k = 'have_paid';
  136. break;
  137. case 'have_delivered_status':
  138. $k = 'have_delivered';
  139. break;
  140. case 'have_received_status':
  141. $k = 'have_received';
  142. break;
  143. case 'have_commented_status':
  144. $k = 'have_commented';
  145. break;
  146. }
  147. $v == 0 ? ($op[$k] = '=') : ($op[$k] = '>');
  148. $v = 0;
  149. }
  150. $sym = isset($op[$k]) ? $op[$k] : '=';
  151. if (stripos($k, ".") === false) {
  152. $k = $tableName . $k;
  153. }
  154. $v = !is_array($v) ? trim($v) : $v;
  155. $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
  156. switch ($sym) {
  157. case '=':
  158. case '<>':
  159. $where[] = [$k, $sym, (string)$v];
  160. break;
  161. case 'LIKE':
  162. case 'NOT LIKE':
  163. case 'LIKE %...%':
  164. case 'NOT LIKE %...%':
  165. $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
  166. break;
  167. case '>':
  168. case '>=':
  169. case '<':
  170. case '<=':
  171. $where[] = [$k, $sym, intval($v)];
  172. break;
  173. case 'FINDIN':
  174. case 'FINDINSET':
  175. case 'FIND_IN_SET':
  176. $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
  177. break;
  178. case 'IN':
  179. case 'IN(...)':
  180. case 'NOT IN':
  181. case 'NOT IN(...)':
  182. $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
  183. break;
  184. case 'BETWEEN':
  185. case 'NOT BETWEEN':
  186. $arr = array_slice(explode(',', $v), 0, 2);
  187. if (stripos($v, ',') === false || !array_filter($arr)) {
  188. continue 2;
  189. }
  190. //当出现一边为空时改变操作符
  191. if ($arr[0] === '') {
  192. $sym = $sym == 'BETWEEN' ? '<=' : '>';
  193. $arr = $arr[1];
  194. } elseif ($arr[1] === '') {
  195. $sym = $sym == 'BETWEEN' ? '>=' : '<';
  196. $arr = $arr[0];
  197. }
  198. $where[] = [$k, $sym, $arr];
  199. break;
  200. case 'RANGE':
  201. case 'NOT RANGE':
  202. $v = str_replace(' - ', ',', $v);
  203. $arr = array_slice(explode(',', $v), 0, 2);
  204. if (stripos($v, ',') === false || !array_filter($arr)) {
  205. continue 2;
  206. }
  207. //当出现一边为空时改变操作符
  208. if ($arr[0] === '') {
  209. $sym = $sym == 'RANGE' ? '<=' : '>';
  210. $arr = $arr[1];
  211. } elseif ($arr[1] === '') {
  212. $sym = $sym == 'RANGE' ? '>=' : '<';
  213. $arr = $arr[0];
  214. }
  215. $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
  216. break;
  217. case 'LIKE':
  218. case 'LIKE %...%':
  219. $where[] = [$k, 'LIKE', "%{$v}%"];
  220. break;
  221. case 'NULL':
  222. case 'IS NULL':
  223. case 'NOT NULL':
  224. case 'IS NOT NULL':
  225. $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
  226. break;
  227. default:
  228. break;
  229. }
  230. }
  231. $where = function ($query) use ($where) {
  232. foreach ($where as $k => $v) {
  233. if (is_array($v)) {
  234. call_user_func_array([$query, 'where'], $v);
  235. } else {
  236. $query->where($v);
  237. }
  238. }
  239. };
  240. return [$where, $sort, $order, $offset, $limit];
  241. }
  242. /**
  243. * 编辑
  244. */
  245. public function edit($ids = null)
  246. {
  247. $row = $this->model->get($ids);
  248. if (!$row) {
  249. $this->error(__('No Results were found'));
  250. }
  251. $adminIds = $this->getDataLimitAdminIds();
  252. if (is_array($adminIds)) {
  253. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  254. $this->error(__('You have no permission'));
  255. }
  256. }
  257. if ($this->request->isPost()) {
  258. $params = $this->request->post("row/a");
  259. if ($params) {
  260. $params = $this->preExcludeFields($params);
  261. $result = false;
  262. Db::startTrans();
  263. try {
  264. //是否采用模型验证
  265. if ($this->modelValidate) {
  266. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  267. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  268. $row->validateFailException(true)->validate($validate);
  269. }
  270. $updatetime = $this->request->post('updatetime');
  271. // 乐观锁
  272. $result = $this->model->allowField(true)->save($params, ['id' => $ids, 'updatetime' => $updatetime]);
  273. if (!$result) {
  274. throw new Exception(__('Data had been update before saved, close windows and do it again'));
  275. }
  276. Db::commit();
  277. } catch (ValidateException $e) {
  278. Db::rollback();
  279. $this->error($e->getMessage());
  280. } catch (PDOException $e) {
  281. Db::rollback();
  282. $this->error($e->getMessage());
  283. } catch (Exception $e) {
  284. Db::rollback();
  285. $this->error($e->getMessage());
  286. }
  287. if ($result !== false) {
  288. $this->success();
  289. } else {
  290. $this->error(__('No rows were updated'));
  291. }
  292. }
  293. $this->error(__('Parameter %s can not be empty', ''));
  294. }
  295. $this->view->assign("row", $row);
  296. return $this->view->fetch();
  297. }
  298. /**
  299. * 物流管理
  300. */
  301. public function delivery($ids = null)
  302. {
  303. $row = $this->model->get($ids, ['extend']);
  304. if (!$row) {
  305. $this->error(__('No Results were found'));
  306. }
  307. $adminIds = $this->getDataLimitAdminIds();
  308. if (is_array($adminIds)) {
  309. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  310. $this->error(__('You have no permission'));
  311. }
  312. }
  313. if ($this->request->isPost()) {
  314. $result = false;
  315. Db::startTrans();
  316. try {
  317. $express_number = $this->request->post('express_number');
  318. $express_company = $this->request->post('express_company');
  319. $have_delivered = $express_number ? time() : 0;
  320. $res1 = $row->allowField(true)->save(['have_delivered' => $have_delivered]);
  321. $res2 = $row->extend->allowField(true)->save(['express_number' => $express_number, 'express_company' => $express_company]);
  322. if ($res1 && $res2) {
  323. $result = true;
  324. } else {
  325. throw new Exception(__('No rows were updated'));
  326. }
  327. Db::commit();
  328. } catch (ValidateException $e) {
  329. Db::rollback();
  330. $this->error($e->getMessage());
  331. } catch (PDOException $e) {
  332. Db::rollback();
  333. $this->error($e->getMessage());
  334. } catch (Exception $e) {
  335. Db::rollback();
  336. $this->error($e->getMessage());
  337. }
  338. if ($result !== false) {
  339. $this->success();
  340. } else {
  341. $this->error(__('No rows were updated'));
  342. }
  343. $this->error(__('Parameter %s can not be empty', ''));
  344. }
  345. $address = json_decode($row->extend->address_json,true);
  346. if ($address) {
  347. $area = (new Area)->whereIn('id',[$address['province_id'],$address['city_id'],$address['area_id']])->column('name', 'id');
  348. $row['addressText'] = $area[$address['province_id']].$area[$address['city_id']].$area[$address['area_id']].' '.$address['address'];
  349. $row['address'] = $address;
  350. }
  351. $this->view->assign("row", $row);
  352. // 快递公司
  353. if (!class_exists(\addons\expressquery\library\Expressquery::class)) {
  354. $expressInfo = array_merge(['' => '请先安装插件《物流信息接口》']);
  355. } else {
  356. $expressInfo = Db::name('expressquery')->column('name', 'express');
  357. $expressInfo = $expressInfo ?? [];
  358. $expressInfo = array_merge(['' => '请选择快递公司'], $expressInfo);
  359. }
  360. $this->view->assign('expressCompany', $expressInfo);
  361. return $this->view->fetch();
  362. }
  363. /**
  364. * 商品管理
  365. */
  366. public function product($ids = null)
  367. {
  368. if ($this->request->isPost()) {
  369. $this->success();
  370. }
  371. $row = $this->model->get($ids, ['product','evaluate']);
  372. $this->view->assign('product', $row->product);
  373. $evaluate = [];
  374. foreach ($row->evaluate as $key => $item) {
  375. $evaluate[$item['product_id']] = $item;
  376. }
  377. $this->view->assign('order', $row);
  378. $this->view->assign('evaluate', $evaluate);
  379. return $this->view->fetch();
  380. }
  381. /**
  382. * 退货管理
  383. */
  384. public function refund($ids = null)
  385. {
  386. $row = $this->model->get($ids, ['refund']);
  387. if ($row['status'] != \app\admin\model\unishop\Order::STATUS_REFUND) {
  388. $this->error(__('This order is not returned'));
  389. }
  390. if ($this->request->isPost()) {
  391. $params = $this->request->post("row/a");
  392. if ($params) {
  393. $params = $this->preExcludeFields($params);
  394. $result = false;
  395. Db::startTrans();
  396. try {
  397. // 退款
  398. if($params['refund_action'] == 1) {
  399. $params['had_refund'] = time();
  400. Hook::add('order_refund', 'addons\\unishop\\behavior\\Order');
  401. }
  402. $updatetime = $this->request->post('updatetime');
  403. // 乐观锁
  404. $result = $this->model->allowField(true)->save($params, ['id' => $ids, 'updatetime' => $updatetime]);
  405. if (!$result) {
  406. throw new Exception(__('Data had been update before saved, close windows and do it again'));
  407. }
  408. Db::commit();
  409. } catch (ValidateException $e) {
  410. Db::rollback();
  411. $this->error($e->getMessage());
  412. } catch (PDOException $e) {
  413. Db::rollback();
  414. $this->error($e->getMessage());
  415. } catch (Exception $e) {
  416. Db::rollback();
  417. $this->error($e->getMessage());
  418. }
  419. if ($result !== false) {
  420. Hook::listen('order_refund', $row);
  421. $this->success();
  422. } else {
  423. $this->error(__('No rows were updated'));
  424. }
  425. }
  426. $this->error(__('Parameter %s can not be empty', ''));
  427. }
  428. $products = $row->product;
  429. $refundProducts = $row->refundProduct;
  430. foreach ($products as &$product) {
  431. $product['choose'] = 0;
  432. foreach ($refundProducts as $refundProduct) {
  433. if ($product['id'] == $refundProduct['order_product_id']) {
  434. $product['choose'] = 1;
  435. }
  436. }
  437. }
  438. if ($row->refund) {
  439. $refund = $row->refund->append(['receiving_status_text', 'service_type_text'])->toArray();
  440. } else {
  441. $refund = [
  442. 'service_type' => 0,
  443. 'express_number' => -1,
  444. 'receiving_status_text' => -1,
  445. 'receiving_status' => -1,
  446. 'service_type_text' => -1,
  447. 'amount' => -1,
  448. 'reason_type' => -1,
  449. 'refund_explain' => -1,
  450. ];
  451. }
  452. $this->view->assign('row', $row);
  453. $this->view->assign('product', $products);
  454. $this->view->assign('refund', $refund);
  455. return $this->view->fetch();
  456. }
  457. /**
  458. * 回收站
  459. */
  460. public function recyclebin()
  461. {
  462. //设置过滤方法
  463. $this->request->filter(['strip_tags']);
  464. if ($this->request->isAjax()) {
  465. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  466. $total = $this->model
  467. ->onlyTrashed()
  468. ->alias('order')
  469. ->join('user', 'user.id = order.user_id')
  470. ->where($where)
  471. ->count();
  472. $list = $this->model
  473. ->onlyTrashed()
  474. ->alias('order')
  475. ->join('user', 'user.id = order.user_id')
  476. ->where($where)
  477. ->field('order.*,user.username')
  478. ->order($sort, $order)
  479. ->limit($offset, $limit)
  480. ->select();
  481. $list = collection($list)->toArray();
  482. foreach ($list as &$item) {
  483. $item['id'] = (string)$item['id'];
  484. $item['user'] = [];
  485. $item['user']['username'] = $item['username'] ? $item['username'] : __('Tourist');
  486. $item['have_paid_status'] = $item['have_paid'];
  487. $item['have_delivered_status'] = $item['have_delivered'];
  488. $item['have_received_status'] = $item['have_received'];
  489. $item['have_commented_status'] = $item['have_commented'];
  490. }
  491. $result = array("total" => $total, "rows" => $list);
  492. return json($result);
  493. }
  494. return $this->view->fetch();
  495. }
  496. }