You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

576 lines
22 KiB

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