Order.php 15 KB

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