| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295 |
- <?php
- namespace app\api\controller\product;
- use app\common\controller\Frontend;
- use app\common\service\CompanyPackageService;
- use think\facade\Db;
- class Purchase extends Frontend
- {
- protected array $noNeedPermission = ['createOrder', 'orderDetail'];
- /**
- * 创建购买订单
- */
- public function createOrder(): void
- {
- if (!$this->request->isPost()) {
- $this->error('非法请求');
- }
- $userId = $this->auth->id;
- if (!$userId) {
- $this->error('请先登录');
- }
- // 获取参数
- $packageId = $this->request->post('package_id', 0);
- $quantity = $this->request->post('quantity', 1);
- // $distributorId = $this->request->post('distributor_id', 0); // 分销人ID
- if ($packageId <= 0) {
- $this->error('请选择套餐');
- }
- if ($quantity < 1) {
- $this->error('购买数量错误');
- }
- // 检查是否存在分销人ID
- $distributorId=Db::table('ba_user_invitation')
- ->where('invitee_id',$userId)
- ->value('inviter_id');
- if (!$distributorId){
- $distributorId=0;
- }
- // 查询套餐详情
- $package = Db::table('ba_package_price')
- ->alias('pp')
- ->leftJoin('ba_package p', 'p.id = pp.package_id')
- ->where('pp.id', $packageId)
- ->field('
- pp.*,
- p.name as package_name
- ')
- ->find();
- if (!$package) {
- $this->error('套餐不存在');
- }
- // 检查库存
- if ($package['stock'] < $quantity) {
- $this->error('库存不足');
- }
- // 在原有验证后,添加企业套餐验证
- if ($package['type'] == 2) { // 企业套餐
- $companyService = new CompanyPackageService();
- $validationResult = $companyService->validateCompanyPurchase($userId, $packageId, $quantity);
- if (!$validationResult['valid']) {
- $this->error('企业套餐购买验证失败');
- }
- $companyId = $validationResult['company_id'];
- }else{
- $companyId =0;
- }
- // 查找关联的产品
- $product = Db::table('ba_product')
- ->where('package_id', $package['package_id'])
- ->field('id, name')
- ->find();
- if (!$product) {
- $this->error('关联产品不存在');
- }
- // 计算金额
- $totalAmount = $package['price'] * $quantity;
- // 计算分销佣金
- $commissionService = new \app\common\service\CommissionService();
- $commissionResult = $commissionService->calculateCommission($totalAmount, $distributorId);
- $commissionAmount = $commissionResult['commission_amount'];
- $commissionRate = $commissionResult['commission_rate'];
- $hasCommission = $commissionResult['has_commission'];
- // 生成订单号
- $orderNo = 'BUY' . date('YmdHis') . mt_rand(1000, 9999);
- Db::startTrans();
- try {
- // 1. 创建订单
- $orderData = [
- 'order_no' => $orderNo,
- 'user_id' => $userId,
- 'company_id' => $companyId,
- 'total_amount' => $totalAmount,
- 'discount_amount' => 0.00,
- 'pay_amount' => $totalAmount,
- 'pay_method' => null, // 支付方式待选择
- 'pay_status' => 0, // 0=待支付
- 'order_status' => 0, // 0=待处理
- 'is_commission' => $hasCommission ? 1 : 0, // 0=未处理佣金,1=已处理
- 'distributor_id' => $hasCommission ? $distributorId : null,
- 'commission_amount' => $commissionAmount,
- 'order_time' => date('Y-m-d H:i:s'),
- 'create_time' => date('Y-m-d H:i:s'),
- 'update_time' => date('Y-m-d H:i:s')
- ];
- $orderId = Db::table('ba_order')->insertGetId($orderData);
- // 2. 创建订单商品
- $itemData = [
- 'order_id' => $orderId,
- 'product_id' => $product['id'],
- 'package_id' => $package['package_id'],
- 'package_price_id' => $packageId,
- 'company_id' => $companyId,
- 'item_type' => 2, // 套餐
- 'item_name' => $product['name'] . ' - ' . $package['spec_name'],
- 'spec_name' => $package['spec_name'],
- 'quantity' => $quantity,
- 'unit_price' => $package['price'],
- 'total_price' => $totalAmount,
- 'create_time' => date('Y-m-d H:i:s')
- ];
- Db::table('ba_order_item')->insert($itemData);
- // 3. 如果存在分销,创建分销记录
- if ($hasCommission && $distributorId > 0) {
- $commissionService->createDistributionRecord([
- 'order_id' => $orderId,
- 'product_id' => $product['id'],
- 'buyer_id' => $userId,
- 'distributor_id' => $distributorId,
- 'commission_rate' => $commissionRate,
- 'commission_amount' => $commissionAmount
- ]);
- }
- // 如果是企业套餐,处理企业套餐相关逻辑
- // if ($package['type'] == 2) {
- // // 在企业购买配额表中记录
- // $companyService->processCompanyPackagePurchase(
- // $orderId,
- // $companyId,
- // $packageId,
- // $quantity,
- // $package['card_type'],
- // $package['unit_value'],
- // $package['points_value']
- // );
- //
- // $orderData['company_id'] = $companyId;
- // }
- Db::commit();
- } catch (\Throwable $e) {
- Db::rollback();
- throw $e;
- }
- $this->success('订单创建成功', [
- 'order_id' => $orderId,
- 'order_no' => $orderNo,
- 'product_name' => $product['name'],
- 'package_name' => $package['spec_name'],
- 'total_amount' => $totalAmount,
- 'quantity' => $quantity,
- 'has_commission' => $hasCommission,
- 'commission_amount' => $commissionAmount
- ]);
- }
- /**
- * 获取订单详情
- */
- public function orderDetail(): void
- {
- try {
- $userId = $this->auth->id;
- $orderId = $this->request->get('order_id', 0);
- $orderNo = $this->request->get('order_no', '');
- if (empty($orderId) && empty($orderNo)) {
- $this->error('参数错误');
- }
- // 查询订单
- if ($orderId) {
- $order = Db::table('ba_order')
- ->where('id', $orderId)
- ->where('user_id', $userId)
- ->find();
- } else {
- $order = Db::table('ba_order')
- ->where('order_no', $orderNo)
- ->where('user_id', $userId)
- ->find();
- }
- if (!$order) {
- $this->error('订单不存在');
- }
- // 查询订单商品
- $orderItem = Db::table('ba_order_item')
- ->where('order_id', $order['id'])
- ->find();
- if ($orderItem) {
- // 查询套餐详情
- $package = Db::table('ba_package_price')
- ->where('id', $orderItem['package_price_id'])
- ->find();
- if ($package) {
- $orderItem['package_info'] = [
- 'name' => $package['spec_name'],
- 'price' => $package['price'],
- 'type' => $package['type'],
- 'type_text' => $package['type'] == 1 ? '个人' : '企业'
- ];
- }
- // 查询产品信息
- $product = Db::table('ba_product')
- ->where('id', $orderItem['product_id'])
- ->field('id, name')
- ->find();
- if ($product) {
- $orderItem['product_info'] = $product;
- }
- $order['item'] = $orderItem;
- }
- // 格式化状态
- $order['pay_status_text'] = $this->getPayStatusText($order['pay_status']);
- $order['order_status_text'] = $this->getOrderStatusText($order['order_status']);
- // 格式化时间
- $order['order_time_formatted'] = $order['order_time']
- ? date('m-d H:i', strtotime($order['order_time']))
- : '';
- $order['pay_time_formatted'] = $order['pay_time']
- ? date('m-d H:i', strtotime($order['pay_time']))
- : '';
- $this->success('', $order);
- } catch (\Throwable $e) {
- \think\facade\Log::error('获取订单详情失败: ' . $e->getMessage());
- $this->error('获取订单详情失败');
- }
- }
- /**
- * 获取支付状态文本
- */
- private function getPayStatusText($status): string
- {
- $texts = [
- 0 => '待支付',
- 1 => '已支付',
- 2 => '支付失败'
- ];
- return $texts[$status] ?? '未知';
- }
- /**
- * 获取订单状态文本
- */
- private function getOrderStatusText($status): string
- {
- $texts = [
- 0 => '待处理',
- 1 => '已确认',
- 2 => '已发货',
- 3 => '已完成',
- 4 => '已取消'
- ];
- return $texts[$status] ?? '未知';
- }
- }
|