Order.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 $orderList
  242. * @return bool
  243. */
  244. private function sendDeliveryMessage($orderList)
  245. {
  246. // 发送消息通知
  247. foreach ($orderList as $item) {
  248. MessageService::send('order.delivery', [
  249. 'order' => $item,
  250. 'order_type' => OrderTypeEnum::MASTER,
  251. ]);
  252. }
  253. return true;
  254. }
  255. /**
  256. * 更新订单发货状态(批量)
  257. * @param $orderList
  258. * @return array|false
  259. * @throws \Exception
  260. */
  261. private function updateToDelivery($orderList)
  262. {
  263. $data = [];
  264. foreach ($orderList as $item) {
  265. $data[] = [
  266. 'order_id' => $item['order_id'],
  267. 'express_no' => $item['express_no'],
  268. 'express_id' => $item['express_id'],
  269. 'delivery_status' => 20,
  270. 'delivery_time' => time(),
  271. ];
  272. }
  273. return $this->isUpdate()->saveAll($data);
  274. }
  275. /**
  276. * 验证订单是否满足发货条件
  277. * @param $orderList
  278. * @return bool
  279. */
  280. private function verifyDelivery($orderList)
  281. {
  282. foreach ($orderList as $order) {
  283. if (
  284. $order['pay_status']['value'] != 20
  285. || $order['delivery_type']['value'] != DeliveryTypeEnum::EXPRESS
  286. || $order['delivery_status']['value'] != 10
  287. ) {
  288. $this->error = "订单号[{$order['order_no']}] 不满足发货条件!";
  289. return false;
  290. }
  291. }
  292. return true;
  293. }
  294. /**
  295. * 获取csv文件中的数据
  296. * @return array|bool
  297. */
  298. private function getCsvData()
  299. {
  300. // 获取表单上传文件 例如上传了001.jpg
  301. $file = \request()->file('iFile');
  302. if (empty($file)) {
  303. $this->error = '请上传发货模板';
  304. return false;
  305. }
  306. // 设置区域信息
  307. setlocale(LC_ALL, 'zh_CN');
  308. // 打开上传的文件
  309. $csvFile = fopen($file->getInfo()['tmp_name'], 'r');
  310. // 忽略第一行(csv标题)
  311. fgetcsv($csvFile);
  312. // 遍历并记录订单信息
  313. $orderList = [];
  314. while ($item = fgetcsv($csvFile)) {
  315. if (!isset($item[0]) || empty($item[0]) || !isset($item[1]) || empty($item[1])) {
  316. $this->error = '模板文件数据不合法';
  317. return false;
  318. }
  319. $orderList[] = $item;
  320. }
  321. if (empty($orderList)) {
  322. $this->error = '模板文件中没有订单数据';
  323. return false;
  324. }
  325. return $orderList;
  326. }
  327. /**
  328. * 修改订单价格
  329. * @param $data
  330. * @return bool
  331. */
  332. public function updatePrice($data)
  333. {
  334. if ($this['pay_status']['value'] != 10) {
  335. $this->error = '该订单不合法';
  336. return false;
  337. }
  338. // 实际付款金额
  339. $payPrice = bcadd($data['update_price'], $data['update_express_price'], 2);
  340. if ($payPrice <= 0) {
  341. $this->error = '订单实付款价格不能为0.00元';
  342. return false;
  343. }
  344. return $this->save([
  345. 'order_no' => $this->orderNo(), // 修改订单号, 否则微信支付提示重复
  346. 'order_price' => $data['update_price'],
  347. 'pay_price' => $payPrice,
  348. 'update_price' => helper::bcsub($data['update_price'], helper::bcsub($this['total_price'], $this['coupon_money'])),
  349. 'express_price' => $data['update_express_price']
  350. ]) !== false;
  351. }
  352. /**
  353. * 审核:用户取消订单
  354. * @param $data
  355. * @return bool|mixed
  356. * @throws \app\common\exception\BaseException
  357. * @throws \think\exception\DbException
  358. */
  359. public function confirmCancel($data)
  360. {
  361. // 判断订单是否有效
  362. if ($this['pay_status']['value'] != 20) {
  363. $this->error = '该订单不合法';
  364. return false;
  365. }
  366. // 订单取消事件
  367. $status = $this->transaction(function () use ($data) {
  368. if ($data['is_cancel'] == true) {
  369. // 执行退款操作
  370. (new RefundService)->execute($this);
  371. // 回退商品库存
  372. FactoryStock::getFactory($this['order_source'])->backGoodsStock($this['goods'], true);
  373. // 回退用户优惠券
  374. $this['coupon_id'] > 0 && UserCouponModel::setIsUse($this['coupon_id'], false);
  375. // 回退用户积分
  376. $User = UserModel::detail($this['user_id']);
  377. $describe = "订单取消:{$this['order_no']}";
  378. $this['points_num'] > 0 && $User->setIncPoints($this['points_num'], $describe);
  379. }
  380. // 更新订单状态
  381. return $this->save(['order_status' => $data['is_cancel'] ? 20 : 10]);
  382. });
  383. if ($status == true) {
  384. // 同步好物圈订单
  385. (new WowService(self::$wxapp_id))->update([$this]);
  386. }
  387. return $status;
  388. }
  389. /**
  390. * 获取已付款订单总数 (可指定某天)
  391. * @param null $startDate
  392. * @param null $endDate
  393. * @return int|string
  394. * @throws \think\Exception
  395. */
  396. public function getPayOrderTotal($startDate = null, $endDate = null)
  397. {
  398. $filter = [
  399. 'pay_status' => PayStatusEnum::SUCCESS,
  400. 'order_status' => ['<>', OrderStatusEnum::CANCELLED],
  401. ];
  402. if (!is_null($startDate) && !is_null($endDate)) {
  403. $filter['pay_time'] = [
  404. ['>=', strtotime($startDate)],
  405. ['<', strtotime($endDate) + 86400],
  406. ];
  407. }
  408. return $this->getOrderTotal($filter);
  409. }
  410. /**
  411. * 获取订单总数量
  412. * @param array $filter
  413. * @return int|string
  414. * @throws \think\Exception
  415. */
  416. private function getOrderTotal($filter = [])
  417. {
  418. return $this->where($filter)
  419. ->where('is_delete', '=', 0)
  420. ->count();
  421. }
  422. /**
  423. * 获取某天的总销售额
  424. * @param null $startDate
  425. * @param null $endDate
  426. * @return float|int
  427. */
  428. public function getOrderTotalPrice($startDate = null, $endDate = null)
  429. {
  430. if (!is_null($startDate) && !is_null($endDate)) {
  431. $this->where('pay_time', '>=', strtotime($startDate))
  432. ->where('pay_time', '<', strtotime($endDate) + 86400);
  433. }
  434. return $this->where('pay_status', '=', 20)
  435. ->where('order_status', '<>', 20)
  436. ->where('is_delete', '=', 0)
  437. ->sum('pay_price');
  438. }
  439. /**
  440. * 获取某天的下单用户数
  441. * @param $day
  442. * @return float|int
  443. */
  444. public function getPayOrderUserTotal($day)
  445. {
  446. $startTime = strtotime($day);
  447. $userIds = $this->distinct(true)
  448. ->where('pay_time', '>=', $startTime)
  449. ->where('pay_time', '<', $startTime + 86400)
  450. ->where('pay_status', '=', 20)
  451. ->where('is_delete', '=', 0)
  452. ->column('user_id');
  453. return count($userIds);
  454. }
  455. }