Order.php 20 KB

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