Order.php 22 KB

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