海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

235 lines
6.3 KiB

  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\AgentProduct;
  5. use App\Models\Coupon;
  6. use App\Models\UserMoneyLog;
  7. use App\Models\Order;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Support\Facades\DB;
  10. /**
  11. * 订单
  12. * Class OrderController
  13. * @package App\Http\Controllers\Api
  14. */
  15. class OrderController extends Controller
  16. {
  17. //订单列表
  18. public function index(Request $request)
  19. {
  20. $formData = $request->only(['page', 'status']);
  21. $request->validate([
  22. 'page' => 'regex:/^\d+$/',
  23. 'status' => 'nullable|integer'
  24. ], [
  25. 'page.regex' => '页码错误',
  26. 'status.integer' => '订单状态错误'
  27. ]);
  28. if (isset($formData['status'])) {
  29. $where['status'] = $formData['status'];
  30. }
  31. $where['user_id'] = $this->user_id;
  32. $order_list = Order::where($where)
  33. ->with('product:id,title,pictures')
  34. ->select('id', 'product_id', 'price', 'num', 'status', 'created_at')
  35. ->orderBy('id', 'DESC')
  36. ->simplePaginate(15)
  37. ->toArray();
  38. $time = time();
  39. $timeout_ids = [];
  40. //10分钟内未付款订单提示付款
  41. foreach ($order_list['data'] as &$v) {
  42. if ($v['status'] == 0) {
  43. $minute = $time - $v['created_at'];
  44. //订单创建后10分钟内未付款则提示,否则取消订单
  45. if ($minute < 600) {
  46. $v['status_text'] = '请在' . ceil($minute / 60) . '分钟内付款';
  47. } else {
  48. $timeout_ids[] = $v['id'];
  49. $v['status'] = -1;
  50. $v['status_text'] = '已取消';
  51. }
  52. }
  53. }
  54. //超时订单设置为已取消
  55. Order::query()->whereIn('id', $timeout_ids)->update(['status' => -1]);
  56. return $this->success($order_list);
  57. }
  58. //提交订单
  59. public function create(Request $request)
  60. {
  61. $formData = $request->only(['id', 'name', 'mobile', 'pay_type', 'num']);
  62. $formData = array_map(fn($v) => trim($v), $formData); //过滤,删除首尾空
  63. //表单验证
  64. $request->validate([
  65. 'id' => ['required', 'regex:/^\d+$/'],
  66. 'name' => ['required', 'between:2,20'],
  67. 'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/'],
  68. 'pay_type' => ['required', 'in:0,1,2'],
  69. 'num' => ['required', 'min:1'],
  70. ], [
  71. 'id.required' => '未指定产品ID',
  72. 'name.required' => '请输入联系人姓名',
  73. 'mobile.required' => '请输入联系手机号',
  74. 'id.regex' => '产品ID错误',
  75. 'name.between' => '联系人姓名在2~20字符之间',
  76. 'mobile.regex' => '请输入11位手机号',
  77. 'pay_type.required' => '请选择支付方式',
  78. 'pay_type.in' => '不存在此支付方式',
  79. 'num.required' => '请输入购买数量',
  80. 'num.min' => '购买数量输入错误',
  81. ]);
  82. $ap = AgentProduct::query()
  83. ->where('id', $formData['id'])
  84. ->with('coupon')
  85. ->with('product')
  86. ->first();
  87. if (!$ap || !$ap->product) {
  88. $this->error('产品不存在');
  89. }
  90. if ($ap->product->stock < $formData['num']) {
  91. $this->error('对不起,库存不足');
  92. }
  93. $coupon_ids = [];
  94. if ($ap->coupon) {
  95. foreach ($ap->coupon as $v) {
  96. $coupon_ids[] = $v['id'];
  97. }
  98. }
  99. DB::beginTransaction();
  100. try {
  101. $price = $this->calc($ap, $formData['num']);
  102. $title = $ap->product->title; //产品标题
  103. //代理商产品表增加销量
  104. $ap->increment('sale', $formData['num']);
  105. //供应商产品表加销量、减库存
  106. $ap->product->sale += $formData['num'];
  107. $ap->product->stock -= $formData['num'];
  108. $ap->product->save();
  109. // 存入订单表
  110. $order = Order::query()->create([
  111. 'user_id' => $this->user_id,
  112. 'order_no' => $this->getOrderNo(),
  113. 'num' => $formData['num'],
  114. 'price' => $price,
  115. 'name' => $formData['name'],
  116. 'mobile' => $formData['mobile'],
  117. 'title' => $title,
  118. 'picture' => $ap->product->picture,
  119. 'agent_product_id' => $ap->id,
  120. 'product_id' => $ap->product_id,
  121. 'status' => 0,
  122. 'pay_type' => $formData['pay_type'],
  123. 'coupon_id' => join(',', $coupon_ids),
  124. ]);
  125. //资金流水
  126. UserMoneyLog::query()->create([
  127. 'user_id' => $this->user_id,
  128. 'agent_id' => $this->agent_id,
  129. 'money' => -$price,
  130. 'order_id' => $order->id,
  131. 'type' => 1,
  132. 'desc' => '购买产品:' . $title,
  133. 'created_at' => time(), //已关闭模型自动写入时间
  134. ]);
  135. DB::commit();
  136. } catch (\Exception $e) {
  137. DB::rollBack();
  138. return $e->getMessage();
  139. }
  140. return $this->success();
  141. }
  142. //获取应付金额
  143. public function getPrice(Request $request)
  144. {
  145. $id = (int)$request->input('id');
  146. $num = (float)$request->input('num');
  147. if (!$num || $num < 1) {
  148. return $this->error('未指定产品数量');
  149. }
  150. $agent_product = AgentProduct::query()
  151. ->with('coupon:agent_product_id,type,detail,agent_id,start_at,end_at')
  152. ->find($id);
  153. $final_price = $this->calc($agent_product, $num);
  154. return $this->success(['price' => $final_price]);
  155. }
  156. //订单详情
  157. public function show()
  158. {
  159. $id = (int)request()->input('id');
  160. $fields = ['id', 'order_no', 'agent_product_id', 'num', 'price', 'title',
  161. 'picture', 'status', 'pay_type', 'coupon_id', 'paid_at', 'created_at'];
  162. $order = Order::query()
  163. ->where('user_id', $this->user_id)
  164. ->find($id, $fields);
  165. if (!$order) {
  166. return $this->error('订单不存在');
  167. }
  168. $order->coupon = Coupon::query()
  169. ->whereIn('id', $order->coupon_id)
  170. ->where(['agent_id' => $this->agent_id, 'agent_product_id' => $order->agent_product_id,])
  171. ->get(['tag']);
  172. return $this->success($order);
  173. }
  174. /**
  175. * 计算最终价格(扣除优惠券之后的价格)
  176. * @param $agent_product
  177. * @param $num
  178. * @return float
  179. */
  180. private function calc($agent_product, $num)
  181. {
  182. $total_price = $agent_product->price * $num;
  183. //没有任何优惠券时直接返回最终价
  184. if ($agent_product->coupon->isEmpty()) {
  185. return $total_price;
  186. }
  187. $coupon = $agent_product->coupon->toArray();
  188. foreach ($coupon as $v) {
  189. // TODO 未判断优惠券有效期
  190. if ($v['type'] == 1 && !empty($v['detail']['full']) && !empty($v['detail']['reduction'])) { //满减
  191. if ($total_price >= $v['detail']['full']) {
  192. $total_price -= $v['detail']['reduction'];
  193. }
  194. } else if ($v['type'] == 2 && !empty($v['detail']['discount'])) { //打折
  195. $total_price *= $v['detail']['discount'];
  196. }
  197. }
  198. return round($total_price, 2);
  199. }
  200. // 生成订单号
  201. private function getOrderNo(): string
  202. {
  203. list($micro, $sec) = explode(' ', microtime());
  204. $micro = str_pad(floor($micro * 1000000), 6, 0, STR_PAD_LEFT);
  205. return date('YmdHis', $sec) . $micro . mt_rand(1000, 9999);
  206. }
  207. }