Purchase.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. namespace app\api\controller\product;
  3. use app\common\controller\Frontend;
  4. use app\common\service\CompanyPackageService;
  5. use think\facade\Db;
  6. class Purchase extends Frontend
  7. {
  8. protected array $noNeedPermission = ['createOrder', 'orderDetail'];
  9. /**
  10. * 创建购买订单
  11. */
  12. public function createOrder(): void
  13. {
  14. if (!$this->request->isPost()) {
  15. $this->error('非法请求');
  16. }
  17. $userId = $this->auth->id;
  18. if (!$userId) {
  19. $this->error('请先登录');
  20. }
  21. // 获取参数
  22. $packageId = $this->request->post('package_id', 0);
  23. $quantity = $this->request->post('quantity', 1);
  24. // $distributorId = $this->request->post('distributor_id', 0); // 分销人ID
  25. if ($packageId <= 0) {
  26. $this->error('请选择套餐');
  27. }
  28. if ($quantity < 1) {
  29. $this->error('购买数量错误');
  30. }
  31. // 检查是否存在分销人ID
  32. $distributorId=Db::table('ba_user_invitation')
  33. ->where('invitee_id',$userId)
  34. ->value('inviter_id');
  35. if (!$distributorId){
  36. $distributorId=0;
  37. }
  38. // 查询套餐详情
  39. $package = Db::table('ba_package_price')
  40. ->alias('pp')
  41. ->leftJoin('ba_package p', 'p.id = pp.package_id')
  42. ->where('pp.id', $packageId)
  43. ->field('
  44. pp.*,
  45. p.name as package_name
  46. ')
  47. ->find();
  48. if (!$package) {
  49. $this->error('套餐不存在');
  50. }
  51. // 检查库存
  52. if ($package['stock'] < $quantity) {
  53. $this->error('库存不足');
  54. }
  55. // 在原有验证后,添加企业套餐验证
  56. if ($package['type'] == 2) { // 企业套餐
  57. $companyService = new CompanyPackageService();
  58. $validationResult = $companyService->validateCompanyPurchase($userId, $packageId, $quantity);
  59. if (!$validationResult['valid']) {
  60. $this->error('企业套餐购买验证失败');
  61. }
  62. $companyId = $validationResult['company_id'];
  63. }else{
  64. $companyId =0;
  65. }
  66. // 查找关联的产品
  67. $product = Db::table('ba_product')
  68. ->where('package_id', $package['package_id'])
  69. ->field('id, name')
  70. ->find();
  71. if (!$product) {
  72. $this->error('关联产品不存在');
  73. }
  74. // 计算金额
  75. $totalAmount = $package['price'] * $quantity;
  76. // 计算分销佣金
  77. $commissionService = new \app\common\service\CommissionService();
  78. $commissionResult = $commissionService->calculateCommission($totalAmount, $distributorId);
  79. $commissionAmount = $commissionResult['commission_amount'];
  80. $commissionRate = $commissionResult['commission_rate'];
  81. $hasCommission = $commissionResult['has_commission'];
  82. // 生成订单号
  83. $orderNo = 'BUY' . date('YmdHis') . mt_rand(1000, 9999);
  84. Db::startTrans();
  85. try {
  86. // 1. 创建订单
  87. $orderData = [
  88. 'order_no' => $orderNo,
  89. 'user_id' => $userId,
  90. 'company_id' => $companyId,
  91. 'total_amount' => $totalAmount,
  92. 'discount_amount' => 0.00,
  93. 'pay_amount' => $totalAmount,
  94. 'pay_method' => null, // 支付方式待选择
  95. 'pay_status' => 0, // 0=待支付
  96. 'order_status' => 0, // 0=待处理
  97. 'is_commission' => $hasCommission ? 1 : 0, // 0=未处理佣金,1=已处理
  98. 'distributor_id' => $hasCommission ? $distributorId : null,
  99. 'commission_amount' => $commissionAmount,
  100. 'order_time' => date('Y-m-d H:i:s'),
  101. 'create_time' => date('Y-m-d H:i:s'),
  102. 'update_time' => date('Y-m-d H:i:s')
  103. ];
  104. $orderId = Db::table('ba_order')->insertGetId($orderData);
  105. // 2. 创建订单商品
  106. $itemData = [
  107. 'order_id' => $orderId,
  108. 'product_id' => $product['id'],
  109. 'package_id' => $package['package_id'],
  110. 'package_price_id' => $packageId,
  111. 'company_id' => $companyId,
  112. 'item_type' => 2, // 套餐
  113. 'item_name' => $product['name'] . ' - ' . $package['spec_name'],
  114. 'spec_name' => $package['spec_name'],
  115. 'quantity' => $quantity,
  116. 'unit_price' => $package['price'],
  117. 'total_price' => $totalAmount,
  118. 'create_time' => date('Y-m-d H:i:s')
  119. ];
  120. Db::table('ba_order_item')->insert($itemData);
  121. // 3. 如果存在分销,创建分销记录
  122. if ($hasCommission && $distributorId > 0) {
  123. $commissionService->createDistributionRecord([
  124. 'order_id' => $orderId,
  125. 'product_id' => $product['id'],
  126. 'buyer_id' => $userId,
  127. 'distributor_id' => $distributorId,
  128. 'commission_rate' => $commissionRate,
  129. 'commission_amount' => $commissionAmount
  130. ]);
  131. }
  132. // 如果是企业套餐,处理企业套餐相关逻辑
  133. // if ($package['type'] == 2) {
  134. // // 在企业购买配额表中记录
  135. // $companyService->processCompanyPackagePurchase(
  136. // $orderId,
  137. // $companyId,
  138. // $packageId,
  139. // $quantity,
  140. // $package['card_type'],
  141. // $package['unit_value'],
  142. // $package['points_value']
  143. // );
  144. //
  145. // $orderData['company_id'] = $companyId;
  146. // }
  147. Db::commit();
  148. } catch (\Throwable $e) {
  149. Db::rollback();
  150. throw $e;
  151. }
  152. $this->success('订单创建成功', [
  153. 'order_id' => $orderId,
  154. 'order_no' => $orderNo,
  155. 'product_name' => $product['name'],
  156. 'package_name' => $package['spec_name'],
  157. 'total_amount' => $totalAmount,
  158. 'quantity' => $quantity,
  159. 'has_commission' => $hasCommission,
  160. 'commission_amount' => $commissionAmount
  161. ]);
  162. }
  163. /**
  164. * 获取订单详情
  165. */
  166. public function orderDetail(): void
  167. {
  168. try {
  169. $userId = $this->auth->id;
  170. $orderId = $this->request->get('order_id', 0);
  171. $orderNo = $this->request->get('order_no', '');
  172. if (empty($orderId) && empty($orderNo)) {
  173. $this->error('参数错误');
  174. }
  175. // 查询订单
  176. if ($orderId) {
  177. $order = Db::table('ba_order')
  178. ->where('id', $orderId)
  179. ->where('user_id', $userId)
  180. ->find();
  181. } else {
  182. $order = Db::table('ba_order')
  183. ->where('order_no', $orderNo)
  184. ->where('user_id', $userId)
  185. ->find();
  186. }
  187. if (!$order) {
  188. $this->error('订单不存在');
  189. }
  190. // 查询订单商品
  191. $orderItem = Db::table('ba_order_item')
  192. ->where('order_id', $order['id'])
  193. ->find();
  194. if ($orderItem) {
  195. // 查询套餐详情
  196. $package = Db::table('ba_package_price')
  197. ->where('id', $orderItem['package_price_id'])
  198. ->find();
  199. if ($package) {
  200. $orderItem['package_info'] = [
  201. 'name' => $package['spec_name'],
  202. 'price' => $package['price'],
  203. 'type' => $package['type'],
  204. 'type_text' => $package['type'] == 1 ? '个人' : '企业'
  205. ];
  206. }
  207. // 查询产品信息
  208. $product = Db::table('ba_product')
  209. ->where('id', $orderItem['product_id'])
  210. ->field('id, name')
  211. ->find();
  212. if ($product) {
  213. $orderItem['product_info'] = $product;
  214. }
  215. $order['item'] = $orderItem;
  216. }
  217. // 格式化状态
  218. $order['pay_status_text'] = $this->getPayStatusText($order['pay_status']);
  219. $order['order_status_text'] = $this->getOrderStatusText($order['order_status']);
  220. // 格式化时间
  221. $order['order_time_formatted'] = $order['order_time']
  222. ? date('m-d H:i', strtotime($order['order_time']))
  223. : '';
  224. $order['pay_time_formatted'] = $order['pay_time']
  225. ? date('m-d H:i', strtotime($order['pay_time']))
  226. : '';
  227. $this->success('', $order);
  228. } catch (\Throwable $e) {
  229. \think\facade\Log::error('获取订单详情失败: ' . $e->getMessage());
  230. $this->error('获取订单详情失败');
  231. }
  232. }
  233. /**
  234. * 获取支付状态文本
  235. */
  236. private function getPayStatusText($status): string
  237. {
  238. $texts = [
  239. 0 => '待支付',
  240. 1 => '已支付',
  241. 2 => '支付失败'
  242. ];
  243. return $texts[$status] ?? '未知';
  244. }
  245. /**
  246. * 获取订单状态文本
  247. */
  248. private function getOrderStatusText($status): string
  249. {
  250. $texts = [
  251. 0 => '待处理',
  252. 1 => '已确认',
  253. 2 => '已发货',
  254. 3 => '已完成',
  255. 4 => '已取消'
  256. ];
  257. return $texts[$status] ?? '未知';
  258. }
  259. }