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.
 
 
 
 
 
 

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