Order.php 22 KB

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