Order.php 21 KB

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