Order.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <?php
  2. /**
  3. *
  4. * @copyright ©2020 点小铺
  5. * @author hanj
  6. * @link: https://dyuit.com
  7. * Created by VSCode
  8. */
  9. namespace app\store\model;
  10. use app\common\model\Order as OrderModel;
  11. use app\store\model\User as UserModel;
  12. use app\store\model\UserCoupon as UserCouponModel;
  13. use app\store\service\order\Export as Exportservice;
  14. use app\common\library\helper;
  15. use app\common\enum\OrderType as OrderTypeEnum;
  16. use app\common\enum\DeliveryType as DeliveryTypeEnum;
  17. use app\common\service\Message as MessageService;
  18. use app\common\service\order\Refund as RefundService;
  19. use app\common\service\wechat\wow\Order as WowService;
  20. use app\common\service\goods\source\Factory as FactoryStock;
  21. use app\common\enum\order\PayStatus as PayStatusEnum;
  22. use app\common\enum\order\Status as OrderStatusEnum;
  23. /**
  24. * 订单管理
  25. * Class Order
  26. * @package app\store\model
  27. */
  28. class Order extends OrderModel
  29. {
  30. /**
  31. * 订单列表
  32. * @param string $dataType
  33. * @param array $query
  34. * @return \think\Paginator
  35. * @throws \think\exception\DbException
  36. */
  37. public function getList($dataType, $query = [])
  38. {
  39. // 检索查询条件
  40. !empty($query) && $this->setWhere($query);
  41. // 获取数据列表
  42. return $this->with(['goods.image', 'address', 'user'])
  43. ->alias('order')
  44. ->field('order.*')
  45. ->join('user', 'user.user_id = order.user_id')
  46. ->where($this->transferDataType($dataType))
  47. ->where('order.is_delete', '=', 0)
  48. ->order(['order.create_time' => 'desc'])
  49. ->paginate(10, false, [
  50. 'query' => \request()->request()
  51. ]);
  52. }
  53. /**
  54. * 订单列表(全部)
  55. * @param $dataType
  56. * @param array $query
  57. * @return false|\PDOStatement|string|\think\Collection
  58. * @throws \think\db\exception\DataNotFoundException
  59. * @throws \think\db\exception\ModelNotFoundException
  60. * @throws \think\exception\DbException
  61. */
  62. public function getListAll($dataType, $query = [])
  63. {
  64. // 检索查询条件
  65. !empty($query) && $this->setWhere($query);
  66. // 获取数据列表
  67. return $this->with(['goods.image', 'address', 'user', 'extract', 'extract_shop'])
  68. ->alias('order')
  69. ->field('order.*')
  70. ->join('user', 'user.user_id = order.user_id')
  71. ->where($this->transferDataType($dataType))
  72. ->where('order.is_delete', '=', 0)
  73. ->order(['order.create_time' => 'desc'])
  74. ->select();
  75. }
  76. /**
  77. * 订单导出
  78. * @param $dataType
  79. * @param $query
  80. * @throws \think\db\exception\DataNotFoundException
  81. * @throws \think\db\exception\ModelNotFoundException
  82. * @throws \think\exception\DbException
  83. */
  84. public function exportList($dataType, $query)
  85. {
  86. // 获取订单列表
  87. $list = $this->getListAll($dataType, $query);
  88. // 导出csv文件
  89. return (new Exportservice)->orderList($list);
  90. }
  91. /**
  92. * 批量发货模板
  93. */
  94. public function deliveryTpl()
  95. {
  96. return (new Exportservice)->deliveryTpl();
  97. }
  98. /**
  99. * 设置检索查询条件
  100. * @param $query
  101. */
  102. private function setWhere($query)
  103. {
  104. if (isset($query['search']) && !empty($query['search'])) {
  105. $this->where('order_no|user.nickName', 'like', '%' . trim($query['search']) . '%');
  106. }
  107. if (isset($query['start_time']) && !empty($query['start_time'])) {
  108. $this->where('order.create_time', '>=', strtotime($query['start_time']));
  109. }
  110. if (isset($query['end_time']) && !empty($query['end_time'])) {
  111. $this->where('order.create_time', '<', strtotime($query['end_time']) + 86400);
  112. }
  113. if (isset($query['delivery_type']) && !empty($query['delivery_type'])) {
  114. $query['delivery_type'] > -1 && $this->where('delivery_type', '=', $query['delivery_type']);
  115. }
  116. if (isset($query['extract_shop_id']) && !empty($query['extract_shop_id'])) {
  117. $query['extract_shop_id'] > -1 && $this->where('extract_shop_id', '=', $query['extract_shop_id']);
  118. }
  119. // 用户id
  120. if (isset($query['user_id']) && $query['user_id'] > 0) {
  121. $this->where('order.user_id', '=', (int)$query['user_id']);
  122. }
  123. }
  124. /**
  125. * 转义数据类型条件
  126. * @param $dataType
  127. * @return array
  128. */
  129. private function transferDataType($dataType)
  130. {
  131. // 数据类型
  132. $filter = [];
  133. switch ($dataType) {
  134. case 'delivery':
  135. $filter = [
  136. 'pay_status' => 20,
  137. 'delivery_status' => 10,
  138. 'order_status' => ['in', [10, 21]]
  139. ];
  140. break;
  141. case 'receipt':
  142. $filter = [
  143. 'pay_status' => 20,
  144. 'delivery_status' => 20,
  145. 'receipt_status' => 10
  146. ];
  147. break;
  148. case 'pay':
  149. $filter = ['pay_status' => 10, 'order_status' => 10];
  150. break;
  151. case 'complete':
  152. $filter = ['order_status' => 30];
  153. break;
  154. case 'cancel':
  155. $filter = ['order_status' => 20];
  156. break;
  157. case 'all':
  158. $filter = [];
  159. break;
  160. }
  161. return $filter;
  162. }
  163. /**
  164. * 确认发货(单独订单)
  165. * @param $data
  166. * @return array|bool|false
  167. * @throws \app\common\exception\BaseException
  168. * @throws \think\Exception
  169. * @throws \think\exception\DbException
  170. * @throws \Exception
  171. */
  172. public function delivery($data)
  173. {
  174. // 转义为订单列表
  175. $orderList = [$this];
  176. // 验证订单是否满足发货条件
  177. if (!$this->verifyDelivery($orderList)) {
  178. return false;
  179. }
  180. // 整理更新的数据
  181. $updateList = [[
  182. 'order_id' => $this['order_id'],
  183. 'express_id' => $data['express_id'],
  184. 'express_no' => $data['express_no']
  185. ]];
  186. // 更新订单发货状态
  187. if ($status = $this->updateToDelivery($updateList)) {
  188. // 获取已发货的订单
  189. $completed = self::detail($this['order_id'], ['user', 'address', 'goods', 'express']);
  190. // 发送消息通知
  191. $this->sendDeliveryMessage([$completed]);
  192. // 同步好物圈订单
  193. (new WowService($this['wxapp_id']))->update([$completed]);
  194. }
  195. return $status;
  196. }
  197. /**
  198. * 批量发货
  199. * @param $data
  200. * @return bool
  201. * @throws \think\db\exception\DataNotFoundException
  202. * @throws \think\db\exception\ModelNotFoundException
  203. * @throws \think\exception\DbException
  204. * @throws \Exception
  205. */
  206. public function batchDelivery($data)
  207. {
  208. // 获取csv文件中的数据
  209. if (!$csvData = $this->getCsvData()) {
  210. return false;
  211. }
  212. // 整理订单id集
  213. $orderNos = helper::getArrayColumn($csvData, 0);
  214. // 获取订单列表数据
  215. $orderList = helper::arrayColumn2Key($this->getListByOrderNos($orderNos), 'order_no');
  216. // 验证订单是否存在
  217. $tempArr = array_values(array_diff($orderNos, array_keys($orderList)));
  218. if (!empty($tempArr)) {
  219. $this->error = "订单号[{$tempArr[0]}] 不存在!";
  220. return false;
  221. }
  222. // 整理物流单号
  223. $updateList = [];
  224. foreach ($csvData as $item) {
  225. $updateList[] = [
  226. 'order_id' => $orderList[$item[0]]['order_id'],
  227. 'express_id' => $data['express_id'],
  228. 'express_no' => $item[1],
  229. ];
  230. }
  231. // 验证订单是否满足发货条件
  232. if (!$this->verifyDelivery($orderList)) {
  233. return false;
  234. }
  235. // 更新订单发货状态(批量)
  236. if ($status = $this->updateToDelivery($updateList)) {
  237. // 获取已发货的订单
  238. $completed = $this->getListByOrderNos($orderNos, ['user', 'address', 'goods', 'express']);
  239. // 发送消息通知
  240. $this->sendDeliveryMessage($completed);
  241. // 同步好物圈订单
  242. (new WowService(self::$wxapp_id))->update($completed);
  243. }
  244. return $status;
  245. }
  246. /**
  247. * 确认发货后发送消息通知
  248. * @param array|\think\Collection $orderList
  249. * @return bool
  250. * @throws \app\common\exception\BaseException
  251. * @throws \think\Exception
  252. * @throws \think\exception\DbException
  253. */
  254. private function sendDeliveryMessage($orderList)
  255. {
  256. // 实例化消息通知服务类
  257. $Service = new MessageService;
  258. foreach ($orderList as $item) {
  259. // 发送消息通知
  260. $Service->delivery($item, OrderTypeEnum::MASTER);
  261. }
  262. return true;
  263. }
  264. /**
  265. * 更新订单发货状态(批量)
  266. * @param $orderList
  267. * @return array|false
  268. * @throws \Exception
  269. */
  270. private function updateToDelivery($orderList)
  271. {
  272. $data = [];
  273. foreach ($orderList as $item) {
  274. $data[] = [
  275. 'order_id' => $item['order_id'],
  276. 'express_no' => $item['express_no'],
  277. 'express_id' => $item['express_id'],
  278. 'delivery_status' => 20,
  279. 'delivery_time' => time(),
  280. ];
  281. }
  282. return $this->isUpdate()->saveAll($data);
  283. }
  284. /**
  285. * 验证订单是否满足发货条件
  286. * @param $orderList
  287. * @return bool
  288. */
  289. private function verifyDelivery($orderList)
  290. {
  291. foreach ($orderList as $order) {
  292. if (
  293. $order['pay_status']['value'] != 20
  294. || $order['delivery_type']['value'] != DeliveryTypeEnum::EXPRESS
  295. || $order['delivery_status']['value'] != 10
  296. ) {
  297. $this->error = "订单号[{$order['order_no']}] 不满足发货条件!";
  298. return false;
  299. }
  300. }
  301. return true;
  302. }
  303. /**
  304. * 获取csv文件中的数据
  305. * @return array|bool
  306. */
  307. private function getCsvData()
  308. {
  309. // 获取表单上传文件 例如上传了001.jpg
  310. $file = \request()->file('iFile');
  311. if (empty($file)) {
  312. $this->error = '请上传发货模板';
  313. return false;
  314. }
  315. // 设置区域信息
  316. setlocale(LC_ALL, 'zh_CN');
  317. // 打开上传的文件
  318. $csvFile = fopen($file->getInfo()['tmp_name'], 'r');
  319. // 忽略第一行(csv标题)
  320. fgetcsv($csvFile);
  321. // 遍历并记录订单信息
  322. $orderList = [];
  323. while ($item = fgetcsv($csvFile)) {
  324. if (!isset($item[0]) || empty($item[0]) || !isset($item[1]) || empty($item[1])) {
  325. $this->error = '模板文件数据不合法';
  326. return false;
  327. }
  328. $orderList[] = $item;
  329. }
  330. if (empty($orderList)) {
  331. $this->error = '模板文件中没有订单数据';
  332. return false;
  333. }
  334. return $orderList;
  335. }
  336. /**
  337. * 修改订单价格
  338. * @param $data
  339. * @return bool
  340. */
  341. public function updatePrice($data)
  342. {
  343. if ($this['pay_status']['value'] != 10) {
  344. $this->error = '该订单不合法';
  345. return false;
  346. }
  347. // 实际付款金额
  348. $payPrice = bcadd($data['update_price'], $data['update_express_price'], 2);
  349. if ($payPrice <= 0) {
  350. $this->error = '订单实付款价格不能为0.00元';
  351. return false;
  352. }
  353. return $this->save([
  354. 'order_no' => $this->orderNo(), // 修改订单号, 否则微信支付提示重复
  355. 'order_price' => $data['update_price'],
  356. 'pay_price' => $payPrice,
  357. 'update_price' => helper::bcsub($data['update_price'], helper::bcsub($this['total_price'], $this['coupon_money'])),
  358. 'express_price' => $data['update_express_price']
  359. ]) !== false;
  360. }
  361. /**
  362. * 审核:用户取消订单
  363. * @param $data
  364. * @return bool|mixed
  365. * @throws \app\common\exception\BaseException
  366. * @throws \think\exception\DbException
  367. */
  368. public function confirmCancel($data)
  369. {
  370. // 判断订单是否有效
  371. if ($this['pay_status']['value'] != 20) {
  372. $this->error = '该订单不合法';
  373. return false;
  374. }
  375. // 订单取消事件
  376. $status = $this->transaction(function () use ($data) {
  377. if ($data['is_cancel'] == true) {
  378. // 执行退款操作
  379. (new RefundService)->execute($this);
  380. // 回退商品库存
  381. FactoryStock::getFactory($this['order_source'])->backGoodsStock($this['goods'], true);
  382. // 回退用户优惠券
  383. $this['coupon_id'] > 0 && UserCouponModel::setIsUse($this['coupon_id'], false);
  384. // 回退用户积分
  385. $User = UserModel::detail($this['user_id']);
  386. $describe = "订单取消:{$this['order_no']}";
  387. $this['points_num'] > 0 && $User->setIncPoints($this['points_num'], $describe);
  388. }
  389. // 更新订单状态
  390. return $this->save(['order_status' => $data['is_cancel'] ? 20 : 10]);
  391. });
  392. if ($status == true) {
  393. // 同步好物圈订单
  394. (new WowService(self::$wxapp_id))->update([$this]);
  395. }
  396. return $status;
  397. }
  398. /**
  399. * 获取已付款订单总数 (可指定某天)
  400. * @param null $startDate
  401. * @param null $endDate
  402. * @return int|string
  403. * @throws \think\Exception
  404. */
  405. public function getPayOrderTotal($startDate = null, $endDate = null)
  406. {
  407. $filter = [
  408. 'pay_status' => PayStatusEnum::SUCCESS,
  409. 'order_status' => ['<>', OrderStatusEnum::CANCELLED],
  410. ];
  411. if (!is_null($startDate) && !is_null($endDate)) {
  412. $filter['pay_time'] = [
  413. ['>=', strtotime($startDate)],
  414. ['<', strtotime($endDate) + 86400],
  415. ];
  416. }
  417. return $this->getOrderTotal($filter);
  418. }
  419. /**
  420. * 获取订单总数量
  421. * @param array $filter
  422. * @return int|string
  423. * @throws \think\Exception
  424. */
  425. private function getOrderTotal($filter = [])
  426. {
  427. return $this->where($filter)
  428. ->where('is_delete', '=', 0)
  429. ->count();
  430. }
  431. /**
  432. * 获取某天的总销售额
  433. * @param null $startDate
  434. * @param null $endDate
  435. * @return float|int
  436. */
  437. public function getOrderTotalPrice($startDate = null, $endDate = null)
  438. {
  439. if (!is_null($startDate) && !is_null($endDate)) {
  440. $this->where('pay_time', '>=', strtotime($startDate))
  441. ->where('pay_time', '<', strtotime($endDate) + 86400);
  442. }
  443. return $this->where('pay_status', '=', 20)
  444. ->where('order_status', '<>', 20)
  445. ->where('is_delete', '=', 0)
  446. ->sum('pay_price');
  447. }
  448. /**
  449. * 获取某天的下单用户数
  450. * @param $day
  451. * @return float|int
  452. */
  453. public function getPayOrderUserTotal($day)
  454. {
  455. $startTime = strtotime($day);
  456. $userIds = $this->distinct(true)
  457. ->where('pay_time', '>=', $startTime)
  458. ->where('pay_time', '<', $startTime + 86400)
  459. ->where('pay_status', '=', 20)
  460. ->where('is_delete', '=', 0)
  461. ->column('user_id');
  462. return count($userIds);
  463. }
  464. }