Order.php 21 KB

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