123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516 |
- <?php
- namespace app\api\controller;
- use app\common\model\UserCoupon;
- use app\common\model\Carts;
- use app\common\model\Order as OrderModel;
- use app\common\model\Address;
- use app\common\model\Third;
- use app\common\model\OrderAction;
- use app\common\model\OrderGoods;
- use app\common\library\KdApiExpOrder;
- use think\Db;
- use app\common\Service\OrderService;
- use app\common\Service\ParentOrderService;
- use app\common\Enum\OrderEnum;
- use app\common\Service\CartService;
- use app\common\Service\Pay\PayOperService;
- use app\common\library\easywechatPlus\WechatMiniProgramShop;
- use app\common\facade\Wechat;
- /**
- * 订单接口
- */
- class Order extends Base
- {
- protected $noNeedLogin = [];
- public function __construct()
- {
- parent::__construct();
- }
- //计算邮费,判断商品 - 支持购物车和商品规格两种模式
- public function calculate()
- {
- // 验证请求参数
- $validate = new \app\api\validate\Order();
- $postData = $this->request->post();
- $postData['calculate_data'] = '1'; // 添加触发自定义验证的字段
- if (!$validate->scene('calculate')->check($postData)) {
- $this->error($validate->getError());
- }
- $userId = $this->auth->id;
- $config = get_addon_config('shop');
- $address_id = $postData['address_id'] ?? 0; // 地址id
- $user_coupon_id = $postData['user_coupon_id'] ?? 0; // 优惠券
- $profile_id = $postData['profile_id'] ?? 0; // 档案ID
- $cart_ids = $postData['cart_ids'] ?? []; // 购物车ID数组
- $goods_list = $postData['goods_list'] ?? []; // 商品列表
-
- $address = Address::get($address_id);
- $area_id = !empty($address) ? $address->area_id : 0;
-
- try {
- // 自动判断数据源类型并获取标准化的商品列表
- if (!empty($cart_ids) && !empty($goods_list)) {
- // 结算页有加减数量,需同步更新购物车
- CartService::updateCartByGoodsList($cart_ids, $goods_list, $userId);
- // goods_list 直接参与后续计算
- } elseif (!empty($cart_ids)) {
- $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
- } elseif (empty($goods_list)) {
- throw new \Exception("请提供购物车ID或商品列表");
- }
-
- // 统一调用计算方法
- $result = OrderService::calculateOrder($goods_list, $userId, $area_id, $user_coupon_id);
- $orderItem = $result['orderItem'];
- $goodsList = $result['goodsList'];
- $orderInfo = $result['orderInfo'];
- $userCoupon = $result['userCoupon'];
-
- if (empty($goodsList)) {
- throw new \Exception("未找到商品");
- }
- } catch (\Exception $e) {
- $this->error($e->getMessage());
- }
-
- // 处理商品数据
- foreach ($goodsList as $item) {
- //$item->category_id = $item->goods->category_id;
- $item->brand_id = $item->goods->brand_id;
- $item->goods->visible(explode(',', 'id,title,image,price,marketprice'));
- }
-
- // 获取我的可以使用的优惠券
- $goods_ids = array_column($goodsList, 'goods_id');
- $category_ids = array_column($goodsList, 'category_id');
- $brand_ids = array_column($goodsList, 'brand_id');
- // 检查是否有活动折扣
- $hasActivity = $orderInfo['activity_discount_amount'] > 0;
- $activityInfo = null;
-
- if ($hasActivity) {
- // 获取当前活动信息
- $activityInfo = \app\common\Service\DiscountService::getCurrentActivity();
- }
-
- $this->success('获取成功', [
- 'coupons' => UserCoupon::myGoodsCoupon($userId, $goods_ids, $category_ids, $brand_ids),
- 'goods_list' => $goodsList,
- 'order_info' => $orderInfo,
- 'activity_info' => $activityInfo, // 活动信息
- 'has_activity' => $hasActivity, // 是否有活动折扣
- ]);
- }
- /**
- * 提交订单 - 统一接口
- */
- public function create()
- {
- // 验证请求参数
- $validate = new \app\api\validate\Order();
- if (!$validate->scene('create')->check($this->request->post())) {
- $this->error($validate->getError());
- }
-
- $address_id = $this->request->post('address_id/d'); // 地址id
- $user_coupon_id = $this->request->post('user_coupon_id/d'); // 优惠券id
- $remark = $this->request->post('remark','','trim'); // 备注
- $profile_id = $this->request->post('profile_id/d'); // 档案ID
- $cart_ids = $this->request->post('cart_ids/a'); // 购物车ID数组
- $goods_list = $this->request->post('goods_list/a'); // 商品列表
- $userId = $this->auth->id;
- $order = null;
- try {
- if (!empty($cart_ids)) {
- // 购物车模式 - 校验购物车id合法性
- $row = (new Carts)->where('id', 'IN', $cart_ids)->where('user_id', '<>', $this->auth->id)->find();
- if ($row) {
- $this->error('存在不合法购物车数据');
- }
-
- // 先转换购物车为商品列表
- $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
- // 创建订单
- $order = OrderService::createOrder($address_id, $userId, $goods_list, $user_coupon_id, $remark, 0, $profile_id);
-
- // 购物车订单创建成功后清理购物车
- CartService::clear($cart_ids,$userId);
- } elseif (!empty($goods_list)) {
- // 商品列表模式 - 直接创建订单
- $order = OrderService::createOrder($address_id, $userId, $goods_list, $user_coupon_id, $remark, 0, $profile_id);
- } else {
- $this->error('请提供购物车ID或商品列表');
- }
- } catch (\Exception $e) {
- $this->error($e->getMessage());
- }
-
- $this->success('下单成功!', array_intersect_key($order->toArray(), array_flip(['order_sn', 'id', 'order_status'])));
- }
- /**
- * 创建单商品订单 - 一个商品一个订单
- */
- public function createSingleGoods()
- {
- // 验证请求参数
- $validate = new \app\api\validate\Order();
- if (!$validate->scene('create')->check($this->request->post())) {
- $this->error($validate->getError());
- }
-
- $address_id = $this->request->post('address_id/d'); // 地址id
- $user_coupon_id = $this->request->post('user_coupon_id/d'); // 优惠券id(仅用于第一个订单)
- $remark = $this->request->post('remark','','trim'); // 备注
- $profile_id = $this->request->post('profile_id/d'); // 档案ID
- $cart_ids = $this->request->post('cart_ids/a'); // 购物车ID数组
- $goods_list = $this->request->post('goods_list/a'); // 商品列表
- $userId = $this->auth->id;
- $orders = [];
-
- try {
- if (!empty($cart_ids)) {
- // 购物车模式 - 校验购物车id合法性
- $row = (new Carts)->where('id', 'IN', $cart_ids)->where('user_id', '<>', $this->auth->id)->find();
- if ($row) {
- $this->error('存在不合法购物车数据');
- }
-
- // 先转换购物车为商品列表
- $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
- // 创建单商品订单
- $orders = OrderService::createSingleGoodsOrders($address_id, $userId, $goods_list, $user_coupon_id, $remark, 0, $profile_id);
-
- // 购物车订单创建成功后清理购物车
- CartService::clear($cart_ids, $userId);
- } elseif (!empty($goods_list)) {
- // 商品列表模式 - 直接创建单商品订单
- $orders = OrderService::createSingleGoodsOrders($address_id, $userId, $goods_list, $user_coupon_id, $remark, 0, $profile_id);
- } else {
- $this->error('请提供购物车ID或商品列表');
- }
- } catch (\Exception $e) {
- $this->error($e->getMessage());
- }
-
- // 格式化返回数据
- $orderResults = [];
- foreach ($orders as $order) {
- $orderResults[] = array_intersect_key($order->toArray(), array_flip(['order_sn', 'id', 'order_status']));
- }
-
- $this->success('下单成功!共创建 ' . count($orders) . ' 个订单', [
- 'order_count' => count($orders),
- 'orders' => $orderResults
- ]);
- }
- /**
- * 创建父子订单 - 每个商品一个子订单,统一支付父订单
- */
- public function createParentChild()
- {
- // 验证请求参数
- $validate = new \app\api\validate\Order();
- if (!$validate->scene('create')->check($this->request->post())) {
- $this->error($validate->getError());
- }
-
- $address_id = $this->request->post('address_id/d'); // 地址id
- $user_coupon_id = $this->request->post('user_coupon_id/d'); // 优惠券id
- $remark = $this->request->post('remark','','trim'); // 备注
- $profile_id = $this->request->post('profile_id/d'); // 档案ID
- $cart_ids = $this->request->post('cart_ids/a'); // 购物车ID数组
- $goods_list = $this->request->post('goods_list/a'); // 商品列表
- $userId = $this->auth->id;
- $parentOrder = null;
-
- try {
- if (!empty($cart_ids)) {
- // 购物车模式 - 校验购物车id合法性
- $row = (new Carts)->where('id', 'IN', $cart_ids)->where('user_id', '<>', $this->auth->id)->find();
- if ($row) {
- $this->error('存在不合法购物车数据');
- }
-
- // 先转换购物车为商品列表
- $goods_list = CartService::convertCartToGoodsList($cart_ids, $userId);
- // 创建父子订单
- $parentOrder = ParentOrderService::createParentChildOrders($address_id, $userId, $goods_list, $user_coupon_id, $remark, $profile_id);
-
- // 购物车订单创建成功后清理购物车
- CartService::clear($cart_ids, $userId);
- } elseif (!empty($goods_list)) {
- // 商品列表模式 - 直接创建父子订单
- $parentOrder = ParentOrderService::createParentChildOrders($address_id, $userId, $goods_list, $user_coupon_id, $remark, $profile_id);
- } else {
- $this->error('请提供购物车ID或商品列表');
- }
- } catch (\Exception $e) {
- $this->error($e->getMessage());
- }
-
- // 获取子订单信息
- $childOrders = [];
- foreach ($parentOrder->childOrders as $childOrder) {
- $childOrders[] = [
- 'order_sn' => $childOrder->order_sn,
- 'id' => $childOrder->id,
- 'order_status' => $childOrder->order_status,
- 'amount' => $childOrder->amount,
- 'goods_price' => $childOrder->goods_price,
- 'express_fee' => $childOrder->express_fee
- ];
- }
-
- $this->success('父子订单创建成功!', [
- 'parent_order' => [
- 'parent_order_sn' => $parentOrder->parent_order_sn,
- 'id' => $parentOrder->id,
- 'order_status' => $parentOrder->order_status,
- 'pay_status' => $parentOrder->pay_status,
- 'total_amount' => $parentOrder->total_amount,
- 'pay_amount' => $parentOrder->pay_amount,
- 'child_order_count' => count($childOrders)
- ],
- 'child_orders' => $childOrders
- ]);
- }
- //订单详情
- public function detail()
- {
- // 验证请求参数
- $validate = new \app\api\validate\Order();
- $orderId = $this->request->get('orderId');
- $params = ['orderId' => $orderId];
- if (!$validate->scene('detail')->check($params)) {
- $this->error($validate->getError());
- }
- $order = OrderService::getDetail($orderId, $this->auth->id);
- if (empty($order)) {
- $this->error('未找到订单');
- }
- //$order->append(['order_status_text']);
- $address = OrderService::getAddressInfo($orderId);
- $order->address = $address;
- // $order->append(['status_text']);
- // $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
- // $order->expiretime = $order->expiretime - time();
- $order->order_status_text = OrderEnum::STATUS_TEXT_MAP[$order->order_status];
- // 处理商品的 发货信息
- foreach ($order->order_goods as $item) {
- $item->express_image = json_decode($item->express_image, true);
- }
- // 查询支付信息
- $payInfo = PayOperService::getPayInfoByOrderId($orderId, 1);
- $order->pay_info = $payInfo;
- $this->success('', $order);
- }
- //订单列表
- public function index()
- {
- // 验证请求参数
- $validate = new \app\api\validate\Order();
- $param = $this->request->param();
- $param['time_range'] = '1'; // 添加触发时间范围验证的字段
-
- if (!$validate->scene('lists')->check($param)) {
- $this->error($validate->getError());
- }
- // 设置默认值
- $userId = $this->auth->id;
- $param['page'] = $this->request->param('page', 1, 'intval');
- $param['pageSize'] = $this->request->param('pageSize', 10, 'intval');
- $status = $this->request->param('status', 0, 'intval'); // 默认为0(全部订单)
- $param['keywords'] = $this->request->param('keywords', '', 'trim');
- $status = OrderEnum::SHOW_TYPE_STATUS_MAP[$status];
- $list = OrderService::getOrderList($userId ,$param, $status);
- // 查询支付信息
- $orderIds = $list->column('id');
- $payInfo = PayOperService::getPayInfoByOrderIds($orderIds, 1);
- // 形成kv
- $payInfoKV = [];
- foreach ($payInfo as $item) {
- $payInfoKV[$item->order_id] = $item;
- }
- $list->each(function($row) use ($payInfoKV) {
- $row->pay_info = $payInfoKV[$row->id] ?? [];
- });
- foreach ($list as $item) {
- // $item->append(['order_status_text']);
- $field = 'id,order_sn,amount,goods_price,order_amount,express_name,express_no,order_goods,order_status_text,order_status,pay_info';
- $item->visible(explode(',', $field));
- $item->order_status_text = OrderEnum::STATUS_TEXT_MAP[$item->order_status];
- }
-
- $this->success('获取成功', $list);
- }
- //取消订单
- public function cancel()
- {
- // 验证请求参数
- $validate = new \app\api\validate\Order();
- $orderId = $this->request->post('orderId');
- $params = ['orderId' => $orderId];
- if (!$validate->scene('cancel')->check($params)) {
- $this->error($validate->getError());
- }
-
- $order = OrderService::getByOrderId($orderId);
- if (empty($order)) {
- $this->error('订单不存在');
- }
- if ($order->user_id != $this->auth->id) {
- $this->error('不能越权操作');
- }
- if ($order->status == 'hidden') {
- $this->error('订单已失效!');
- }
- //可以取消
- if ($order->canCancelHandle()) {
- // 启动事务
- Db::startTrans();
- try {
- $order->order_status = OrderEnum::STATUS_CANCEL;
- $order->cancel_time = time();
- $order->save();
- foreach ($order->order_goods as $item) {
- $sku = $item->sku;
- $goods = $item->goods;
- //商品库存恢复
- if ($sku) {
- $sku->setInc('stocks', $item->nums);
- }
- if ($goods) {
- $goods->setInc('stocks', $item->nums);
- }
- }
- //恢复优惠券
- UserCoupon::resetUserCoupon($order->user_coupon_id, $order->order_sn);
- // 提交事务
- Db::commit();
- } catch (\Exception $e) {
- // 回滚事务
- Db::rollback();
- $this->error('订单取消失败');
- }
- //记录操作
- OrderAction::push($order->order_sn, '系统', '订单取消成功');
- $this->success('订单取消成功!', $order['status']);
- } else {
- $this->error('订单不允许取消');
- }
- }
- //确认收货
- public function receipt()
- {
- // 验证请求参数
- $validate = new \app\api\validate\Order();
- $orderId = $this->request->post('orderId');
- $params = ['orderId' => $orderId];
- if (!$validate->scene('detail')->check($params)) {
- $this->error($validate->getError());
- }
- $order = OrderService::getByOrderId($orderId);
- if (empty($order)) {
- $this->error('订单不存在');
- }
- if ($order->user_id != $this->auth->id) {
- $this->error('该订单不属于当前用户');
- }
- if ($order->canConfirmHandle()) {
- $order->order_status = OrderEnum::STATUS_CONFIRM;
- $order->receive_time = time();
- $order->save();
- //记录操作
- OrderAction::push($order->order_sn, '系统', '订单确认收货成功');
- $this->success('确认收货成功');
- }
- $this->error('订单不允许确认收货');
- }
- //查询物流
- public function logistics()
- {
- // 验证请求参数
- $validate = new \app\api\validate\Order();
- $params = ['order_sn' => $this->request->param('order_sn')];
- if (!$validate->scene('detail')->check($params)) {
- $this->error($validate->getError());
- }
-
- $order_sn = $this->request->param('order_sn');
- $order = OrderModel::getDetail($order_sn, $this->auth->id);
- if (empty($order)) {
- $this->error('未找到订单');
- }
- if (!$order->shippingstate) {
- $this->error('订单未发货');
- }
- $electronics = Db::name('shop_order_electronics')->where('order_sn', $order_sn)->where('status', 0)->find();
- if (!$electronics) {
- $this->error('订单未发货');
- }
- $result = KdApiExpOrder::getLogisticsQuery([
- 'order_sn' => $order_sn,
- 'logistic_code' => $electronics['logistic_code'],
- 'shipper_code' => $electronics['shipper_code']
- ]);
- if ($result['Success']) {
- $this->success('查询成功', $result['Traces']);
- }
- $this->error('查询失败');
- }
- // 获取状态订单统计
- public function getOrderStatusCount(){
- $userId = $this->auth->id;
- $info = OrderService::getOrderStatusCount($userId);
- $this->success('获取成功', $info);
- }
- /**
- *
- * @return void
- */
- public function getWechatMiniProgramOrderDelivery(){
- $orderId = $this->request->post('order_id');
- if(empty($orderId )){
- $this->error('请上传正确的参数');
- }
- //查询 订单信息
- $order = OrderService::getByOrderId($orderId);
- if (empty($order)) {
- $this->error('订单不存在');
- }
- // 查询支付信息
- $payInfo = PayOperService::getPayInfoByOrderId($orderId, 1);
- if (empty($payInfo)) {
- $this->error('支付信息不存在或未找到微信支付订单号');
- }
- $wechatService = new WechatMiniProgramShop(Wechat::miniProgram());
- $result = $wechatService->getOrderShippingStatus($payInfo->transaction_id);
-
- // 根据微信接口返回数据重新组织
- $response = [
- 'errcode' => $result['errcode'] ?? 0,
- 'errmsg' => $result['errmsg'] ?? 'ok',
- 'order_state' => $result['order']['order_state'] ?? 0
- ];
-
- $this->success('获取成功', $response);
- }
- }
|