Order.php 21 KB

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