Order.php 22 KB

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