Order.php 21 KB

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