Order.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. <?php
  2. namespace app\data\controller\api\auth;
  3. use app\data\controller\api\Auth;
  4. use app\data\model\BaseUserPayment;
  5. use app\data\model\DataUser;
  6. use app\data\model\DataUserAddress;
  7. use app\data\model\ShopGoods;
  8. use app\data\model\ShopGoodsItem;
  9. use app\data\model\ShopOrder;
  10. use app\data\model\ShopOrderItem;
  11. use app\data\service\ExpressService;
  12. use app\data\service\GoodsService;
  13. use app\data\service\OrderService;
  14. use app\data\service\PaymentService;
  15. use app\data\service\UserAdminService;
  16. use think\admin\extend\CodeExtend;
  17. use think\exception\HttpResponseException;
  18. /**
  19. * 用户订单数据接口
  20. * Class Order
  21. * @package app\data\controller\api\auth
  22. */
  23. class Order extends Auth
  24. {
  25. /**
  26. * 控制器初始化
  27. */
  28. protected function initialize()
  29. {
  30. parent::initialize();
  31. if (empty($this->user['status'])) {
  32. $this->error('账户已被冻结,不能操作订单数据哦!');
  33. }
  34. }
  35. /**
  36. * 获取订单列表
  37. * @throws \think\db\exception\DataNotFoundException
  38. * @throws \think\db\exception\DbException
  39. * @throws \think\db\exception\ModelNotFoundException
  40. */
  41. public function get()
  42. {
  43. $map = ['uuid' => $this->uuid, 'deleted_status' => 0];
  44. $query = $this->_query(ShopOrder::class)->in('status')->equal('order_no');
  45. $result = $query->where($map)->order('id desc')->page(true, false, false, 20);
  46. if (count($result['list']) > 0) OrderService::instance()->buildData($result['list']);
  47. $this->success('获取订单数据成功!', $result);
  48. }
  49. /**
  50. * 用户创建订单
  51. * @throws \think\db\exception\DataNotFoundException
  52. * @throws \think\db\exception\DbException
  53. * @throws \think\db\exception\ModelNotFoundException
  54. */
  55. public function add()
  56. {
  57. // 检查用户状态
  58. $this->checkUserStatus();
  59. // 商品规则
  60. $rules = $this->request->post('items', '');
  61. if (empty($rules)) $this->error('商品不能为空');
  62. // 订单数据
  63. [$items, $order, $truckType, $allowPayments] = [[], [], -1, null];
  64. $order['uuid'] = $this->uuid;
  65. $order['order_no'] = CodeExtend::uniqidDate(18, 'N');
  66. // 代理处理
  67. $order['puid1'] = input('from', $this->user['pid1']);
  68. if ($order['puid1'] == $this->uuid) $order['puid1'] = 0;
  69. if ($order['puid1'] > 0) {
  70. $map = ['id' => $order['puid1'], 'status' => 1];
  71. $order['puid2'] = DataUser::mk()->where($map)->value('pid2');
  72. if (is_null($order['puid2'])) $this->error('代理异常');
  73. }
  74. // 订单商品处理
  75. foreach (explode('||', $rules) as $rule) {
  76. [$code, $spec, $count] = explode('@', $rule);
  77. // 商品信息检查
  78. $goodsInfo = ShopGoods::mk()->where(['code' => $code, 'status' => 1, 'deleted' => 0])->find();
  79. $goodsItem = ShopGoodsItem::mk()->where(['status' => 1, 'goods_code' => $code, 'goods_spec' => $spec])->find();
  80. if (empty($goodsInfo) || empty($goodsItem)) $this->error('商品查询异常');
  81. // 商品类型检查
  82. if ($truckType < 0) $truckType = $goodsInfo['truck_type'];
  83. if ($truckType !== $goodsInfo['truck_type']) $this->error('不能混合下单');
  84. // 限制购买数量
  85. if (isset($goods['limit_max_num']) && $goods['limit_max_num'] > 0) {
  86. $map = [['a.uuid', '=', $this->uuid], ['a.status', 'in', [2, 3, 4, 5]], ['b.goods_code', '=', $goods['code']]];
  87. $buys = ShopOrder::mk()->alias('a')->join('store_order_item b', 'a.order_no=b.order_no')->where($map)->sum('b.stock_sales');
  88. if ($buys + $count > $goods['limit_max_num']) $this->error('超过限购数量');
  89. }
  90. // 限制购买身份
  91. if ($goodsInfo['limit_low_vip'] > $this->user['vip_code']) $this->error('用户等级不够');
  92. // 商品库存检查
  93. if ($goodsItem['stock_sales'] + $count > $goodsItem['stock_total']) $this->error('商品库存不足');
  94. // 支付支付处理
  95. $_allowPayments = [];
  96. foreach (str2arr($goodsInfo['payment']) as $code) {
  97. if (is_null($allowPayments) || in_array($code, $allowPayments)) $_allowPayments[] = $code;
  98. }
  99. if (empty($_allowPayments)) {
  100. $this->error('订单无法统一支付');
  101. } else {
  102. $allowPayments = $_allowPayments;
  103. }
  104. // 商品折扣处理
  105. [$discountId, $discountRate] = OrderService::instance()->discount($goodsInfo['discount_id'], $this->user['vip_code']);
  106. // 订单详情处理
  107. $items[] = [
  108. 'uuid' => $order['uuid'],
  109. 'order_no' => $order['order_no'],
  110. // 商品信息字段
  111. 'goods_name' => $goodsInfo['name'],
  112. 'goods_cover' => $goodsInfo['cover'],
  113. 'goods_payment' => $goodsInfo['payment'],
  114. 'goods_sku' => $goodsItem['goods_sku'],
  115. 'goods_code' => $goodsItem['goods_code'],
  116. 'goods_spec' => $goodsItem['goods_spec'],
  117. // 库存数量处理
  118. 'stock_sales' => $count,
  119. // 快递发货数据
  120. 'truck_type' => $goodsInfo['truck_type'],
  121. 'truck_code' => $goodsInfo['truck_code'],
  122. 'truck_number' => $goodsInfo['rebate_type'] > 0 ? $goodsItem['number_express'] * $count : 0,
  123. // 商品费用字段
  124. 'price_market' => $goodsItem['price_market'],
  125. 'price_selling' => $goodsItem['price_selling'],
  126. 'total_market' => $goodsItem['price_market'] * $count,
  127. 'total_selling' => $goodsItem['price_selling'] * $count,
  128. // 奖励金额积分
  129. 'reward_balance' => $goodsItem['reward_balance'] * $count,
  130. 'reward_integral' => $goodsItem['reward_integral'] * $count,
  131. // 绑定用户等级
  132. 'vip_name' => $this->user['vip_name'],
  133. 'vip_code' => $this->user['vip_code'],
  134. // 是否入会礼包
  135. 'vip_entry' => $goodsInfo['vip_entry'],
  136. 'vip_upgrade' => $goodsInfo['vip_upgrade'],
  137. // 是否参与返利
  138. 'rebate_type' => $goodsInfo['rebate_type'],
  139. 'rebate_amount' => $goodsInfo['rebate_type'] > 0 ? $goodsItem['price_selling'] * $count : 0,
  140. // 等级优惠方案
  141. 'discount_id' => $discountId,
  142. 'discount_rate' => $discountRate,
  143. 'discount_amount' => $discountRate * $goodsItem['price_selling'] * $count / 100,
  144. ];
  145. }
  146. try {
  147. $order['payment_allow'] = arr2str($allowPayments);
  148. $order['rebate_amount'] = array_sum(array_column($items, 'rebate_amount'));
  149. $order['reward_balance'] = array_sum(array_column($items, 'reward_balance'));
  150. // 订单发货类型
  151. $order['status'] = $truckType ? 1 : 2;
  152. $order['truck_type'] = $truckType;
  153. // 统计商品数量
  154. $order['number_goods'] = array_sum(array_column($items, 'stock_sales'));
  155. $order['number_express'] = array_sum(array_column($items, 'truck_number'));
  156. // 统计商品金额
  157. $order['amount_goods'] = array_sum(array_column($items, 'total_selling'));
  158. // 优惠后的金额
  159. $order['amount_discount'] = array_sum(array_column($items, 'discount_amount'));
  160. // 订单随机免减
  161. $order['amount_reduct'] = OrderService::instance()->getReduct();
  162. if ($order['amount_reduct'] > $order['amount_goods']) {
  163. $order['amount_reduct'] = $order['amount_goods'];
  164. }
  165. // 统计订单金额
  166. $order['amount_real'] = $order['amount_discount'] - $order['amount_reduct'];
  167. $order['amount_total'] = $order['amount_goods'];
  168. // 写入商品数据
  169. $this->app->db->transaction(function () use ($order, $items) {
  170. ShopOrder::mk()->insert($order);
  171. ShopOrderItem::mk()->insertAll($items);
  172. });
  173. // 同步商品库存销量
  174. foreach (array_unique(array_column($items, 'goods_code')) as $code) {
  175. GoodsService::instance()->stock($code);
  176. }
  177. // 触发订单创建事件
  178. $this->app->event->trigger('ShopOrderCreate', $order['order_no']);
  179. // 组装订单商品数据
  180. $order['items'] = $items;
  181. // 返回处理成功数据
  182. $this->success('商品下单成功', $order);
  183. } catch (HttpResponseException $exception) {
  184. throw $exception;
  185. } catch (\Exception $exception) {
  186. $this->error("商品下单失败,{$exception->getMessage()}");
  187. }
  188. }
  189. /**
  190. * 获取用户折扣
  191. */
  192. public function discount()
  193. {
  194. $data = $this->_vali(['discount.require' => '折扣编号不能为空!']);
  195. [, $rate] = OrderService::instance()->discount(intval($data['discount']), $this->user['vip_code']);
  196. $this->success('获取用户折扣', ['rate' => $rate]);
  197. }
  198. /**
  199. * 模拟计算订单运费
  200. * @throws \think\db\exception\DataNotFoundException
  201. * @throws \think\db\exception\DbException
  202. * @throws \think\db\exception\ModelNotFoundException
  203. */
  204. public function express()
  205. {
  206. $data = $this->_vali([
  207. 'uuid.value' => $this->uuid,
  208. 'code.require' => '地址不能为空',
  209. 'order_no.require' => '单号不能为空',
  210. ]);
  211. // 用户收货地址
  212. $map = ['uuid' => $this->uuid, 'code' => $data['code']];
  213. $addr = DataUserAddress::mk()->where($map)->find();
  214. if (empty($addr)) $this->error('收货地址异常');
  215. // 订单状态检查
  216. $map = ['uuid' => $this->uuid, 'order_no' => $data['order_no']];
  217. $tCount = ShopOrderItem::mk()->where($map)->sum('truck_number');
  218. // 根据地址计算运费
  219. $map = ['status' => 1, 'deleted' => 0, 'order_no' => $data['order_no']];
  220. $tCode = ShopOrderItem::mk()->where($map)->column('truck_code');
  221. [$amount, , , $remark] = ExpressService::instance()->amount($tCode, $addr['province'], $addr['city'], $tCount);
  222. $this->success('计算运费成功', ['amount' => $amount, 'remark' => $remark]);
  223. }
  224. /**
  225. * 订单信息完成
  226. * @throws \think\db\exception\DataNotFoundException
  227. * @throws \think\db\exception\DbException
  228. * @throws \think\db\exception\ModelNotFoundException
  229. */
  230. public function perfect()
  231. {
  232. $data = $this->_vali([
  233. 'uuid.value' => $this->uuid,
  234. 'code.require' => '地址不能为空',
  235. 'order_no.require' => '单号不能为空',
  236. ]);
  237. // 用户收货地址
  238. $map = ['uuid' => $this->uuid, 'code' => $data['code'], 'deleted' => 0];
  239. $addr = DataUserAddress::mk()->where($map)->find();
  240. if (empty($addr)) $this->error('收货地址异常');
  241. // 订单状态检查
  242. $map1 = ['uuid' => $this->uuid, 'order_no' => $data['order_no']];
  243. $order = ShopOrder::mk()->where($map1)->whereIn('status', [1, 2])->find();
  244. if (empty($order)) $this->error('不能修改地址');
  245. if (empty($order['truck_type'])) $this->success('无需快递配送', ['order_no' => $order['order_no']]);
  246. // 根据地址计算运费
  247. $map2 = ['status' => 1, 'deleted' => 0, 'order_no' => $data['order_no']];
  248. $tCount = ShopOrderItem::mk()->where($map1)->sum('truck_number');
  249. $tCodes = ShopOrderItem::mk()->where($map2)->column('truck_code');
  250. [$amount, $tCount, $tCode, $remark] = ExpressService::instance()->amount($tCodes, $addr['province'], $addr['city'], $tCount);
  251. // 创建订单发货信息
  252. $express = [
  253. 'template_code' => $tCode, 'template_count' => $tCount, 'uuid' => $this->uuid,
  254. 'template_remark' => $remark, 'template_amount' => $amount, 'status' => 1,
  255. ];
  256. $express['order_no'] = $data['order_no'];
  257. $express['address_code'] = $data['code'];
  258. $express['address_datetime'] = date('Y-m-d H:i:s');
  259. // 收货人信息
  260. $express['address_name'] = $addr['name'];
  261. $express['address_phone'] = $addr['phone'];
  262. $express['address_idcode'] = $addr['idcode'];
  263. $express['address_idimg1'] = $addr['idimg1'];
  264. $express['address_idimg2'] = $addr['idimg2'];
  265. // 收货地址信息
  266. $express['address_province'] = $addr['province'];
  267. $express['address_city'] = $addr['city'];
  268. $express['address_area'] = $addr['area'];
  269. $express['address_content'] = $addr['address'];
  270. data_save('ShopOrderSend', $express, 'order_no');
  271. // 组装更新订单数据
  272. $update = ['status' => 2, 'amount_express' => $express['template_amount']];
  273. // 重新计算订单金额
  274. $update['amount_real'] = $order['amount_discount'] + $amount - $order['amount_reduct'];
  275. $update['amount_total'] = $order['amount_goods'] + $amount;
  276. // 支付金额不能为零
  277. if ($update['amount_real'] <= 0) $update['amount_real'] = 0.00;
  278. if ($update['amount_total'] <= 0) $update['amount_total'] = 0.00;
  279. // 更新用户订单数据
  280. $map = ['uuid' => $this->uuid, 'order_no' => $data['order_no']];
  281. if (ShopOrder::mk()->where($map)->update($update) !== false) {
  282. // 触发订单确认事件
  283. $this->app->event->trigger('ShopOrderPerfect', $order['order_no']);
  284. // 返回处理成功数据
  285. $this->success('订单确认成功', ['order_no' => $order['order_no']]);
  286. } else {
  287. $this->error('订单确认失败');
  288. }
  289. }
  290. /**
  291. * 获取支付支付数据
  292. */
  293. public function channel()
  294. {
  295. $data = $this->_vali(['uuid.value' => $this->uuid, 'order_no.require' => '单号不能为空']);
  296. $payments = ShopOrder::mk()->where($data)->value('payment_allow');
  297. if (empty($payments)) $this->error('获取订单支付参数失败');
  298. // 读取支付通道配置
  299. $query = BaseUserPayment::mk()->where(['status' => 1, 'deleted' => 0]);
  300. $query->whereIn('code', str2arr($payments))->whereIn('type', PaymentService::getTypeApi($this->type));
  301. $result = $query->order('sort desc,id desc')->column('type,code,name,cover,content,remark', 'code');
  302. foreach ($result as &$vo) $vo['content'] = ['voucher_qrcode' => json_decode($vo['content'])->voucher_qrcode ?? ''];
  303. $this->success('获取支付参数数据', array_values($result));
  304. }
  305. /**
  306. * 获取订单支付状态
  307. * @throws \think\db\exception\DbException
  308. */
  309. public function payment()
  310. {
  311. $data = $this->_vali([
  312. 'uuid.value' => $this->uuid,
  313. 'order_no.require' => '单号不能为空',
  314. 'order_remark.default' => '',
  315. 'payment_code.require' => '支付不能为空',
  316. 'payment_back.default' => '', # 支付回跳地址
  317. 'payment_image.default' => '', # 支付凭证图片
  318. ]);
  319. [$map, $order] = $this->getOrderData();
  320. if ($order['status'] !== 2) $this->error('不能发起支付');
  321. if ($order['payment_status'] > 0) $this->error('已经完成支付');
  322. // 更新订单备注
  323. if (!empty($data['order_remark'])) {
  324. ShopOrder::mk()->where($map)->update([
  325. 'order_remark' => $data['order_remark'],
  326. ]);
  327. }
  328. // 自动处理用户字段
  329. $openid = '';
  330. if (in_array($this->type, [UserAdminService::API_TYPE_WXAPP, UserAdminService::API_TYPE_WECHAT])) {
  331. $openid = $this->user[UserAdminService::TYPES[$this->type]['auth']] ?? '';
  332. if (empty($openid)) $this->error("发起支付失败");
  333. }
  334. try {
  335. // 返回订单数据及支付发起参数
  336. $type = $order['amount_real'] <= 0 ? 'empty' : $data['payment_code'];
  337. $param = PaymentService::instance($type)->create($openid, $order['order_no'], $order['amount_real'], '商城订单支付', '', $data['payment_back'], $data['payment_image']);
  338. $this->success('获取支付参数', ['order' => ShopOrder::mk()->where($map)->find() ?: new \stdClass(), 'param' => $param]);
  339. } catch (HttpResponseException $exception) {
  340. throw $exception;
  341. } catch (\Exception $exception) {
  342. $this->error($exception->getMessage());
  343. }
  344. }
  345. /**
  346. * 主动取消未支付的订单
  347. * @throws \think\db\exception\DataNotFoundException
  348. * @throws \think\db\exception\DbException
  349. * @throws \think\db\exception\ModelNotFoundException
  350. */
  351. public function cancel()
  352. {
  353. [$map, $order] = $this->getOrderData();
  354. if (in_array($order['status'], [1, 2, 3])) {
  355. $result = ShopOrder::mk()->where($map)->update([
  356. 'status' => 0,
  357. 'cancel_status' => 1,
  358. 'cancel_remark' => '用户主动取消订单',
  359. 'cancel_datetime' => date('Y-m-d H:i:s'),
  360. ]);
  361. if ($result !== false && OrderService::instance()->stock($order['order_no'])) {
  362. // 触发订单取消事件
  363. $this->app->event->trigger('ShopOrderCancel', $order['order_no']);
  364. // 返回处理成功数据
  365. $this->success('订单取消成功');
  366. } else {
  367. $this->error('订单取消失败');
  368. }
  369. } else {
  370. $this->error('订单不可取消');
  371. }
  372. }
  373. /**
  374. * 用户主动删除已取消的订单
  375. * @throws \think\db\exception\DbException
  376. */
  377. public function remove()
  378. {
  379. [$map, $order] = $this->getOrderData();
  380. if (empty($order)) $this->error('读取订单失败');
  381. if (in_array($order['status'], [0])) {
  382. $result = ShopOrder::mk()->where($map)->update([
  383. 'status' => 0,
  384. 'deleted_status' => 1,
  385. 'deleted_remark' => '用户主动删除订单',
  386. 'deleted_datetime' => date('Y-m-d H:i:s'),
  387. ]);
  388. if ($result !== false) {
  389. // 触发订单删除事件
  390. $this->app->event->trigger('ShopOrderRemove', $order['order_no']);
  391. // 返回处理成功数据
  392. $this->success('订单删除成功');
  393. } else {
  394. $this->error('订单删除失败');
  395. }
  396. } else {
  397. $this->error('订单不可删除');
  398. }
  399. }
  400. /**
  401. * 订单确认收货
  402. * @throws \think\db\exception\DbException
  403. */
  404. public function confirm()
  405. {
  406. [$map, $order] = $this->getOrderData();
  407. if (in_array($order['status'], [5])) {
  408. if (ShopOrder::mk()->where($map)->update(['status' => 6]) !== false) {
  409. // 触发订单确认事件
  410. $this->app->event->trigger('ShopOrderConfirm', $order['order_no']);
  411. // 返回处理成功数据
  412. $this->success('订单确认成功');
  413. } else {
  414. $this->error('订单确认失败');
  415. }
  416. } else {
  417. $this->error('订单确认失败');
  418. }
  419. }
  420. /**
  421. * 获取输入订单
  422. * @return array [map, order]
  423. * @throws \think\db\exception\DataNotFoundException
  424. * @throws \think\db\exception\DbException
  425. * @throws \think\db\exception\ModelNotFoundException
  426. */
  427. private function getOrderData(): array
  428. {
  429. $map = $this->_vali([
  430. 'uuid.value' => $this->uuid,
  431. 'order_no.require' => '单号不能为空',
  432. ]);
  433. $order = ShopOrder::mk()->where($map)->find();
  434. if (empty($order)) $this->error('读取订单失败');
  435. return [$map, $order];
  436. }
  437. /**
  438. * 订单状态统计
  439. */
  440. public function total()
  441. {
  442. $data = ['t0' => 0, 't1' => 0, 't2' => 0, 't3' => 0, 't4' => 0, 't5' => 0, 't6' => 0];
  443. $query = ShopOrder::mk()->where(['uuid' => $this->uuid, 'deleted_status' => 0]);
  444. foreach ($query->field('status,count(1) count')->group('status')->cursor() as $item) {
  445. $data["t{$item['status']}"] = $item['count'];
  446. }
  447. $this->success('获取订单统计', $data);
  448. }
  449. /**
  450. * 物流追踪查询
  451. */
  452. public function track()
  453. {
  454. try {
  455. $data = $this->_vali(['code.require' => '快递不能为空', 'number.require' => '单号不能为空']);
  456. $result = ExpressService::instance()->query($data['code'], $data['number']);
  457. empty($result['code']) ? $this->error($result['info']) : $this->success('快递追踪信息', $result);
  458. } catch (HttpResponseException $exception) {
  459. throw $exception;
  460. } catch (\Exception $exception) {
  461. $this->error($exception->getMessage());
  462. }
  463. }
  464. }