Order.php 20 KB

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