海南旅游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.

317 lines
8.7 KiB

  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Agent;
  5. use App\Models\AgentProduct;
  6. use App\Models\Coupon;
  7. use App\Models\Product;
  8. use App\Models\User;
  9. use App\Models\UserMoneyLog;
  10. use App\Models\Order;
  11. use EasyWeChat\Factory;
  12. use Illuminate\Http\Request;
  13. use Illuminate\Support\Facades\DB;
  14. use App\Service\OrderStatus as Status;
  15. /**
  16. * 订单
  17. * Class OrderController
  18. * @package App\Http\Controllers\Api
  19. */
  20. class OrderController extends Controller
  21. {
  22. //订单列表
  23. public function index(Request $request)
  24. {
  25. $formData = $request->only(['page', 'status']);
  26. $request->validate([
  27. 'page' => 'regex:/^\d+$/',
  28. 'status' => 'nullable|integer'
  29. ], [
  30. 'page.regex' => '页码错误',
  31. 'status.integer' => '订单状态错误'
  32. ]);
  33. if (isset($formData['status'])) {
  34. $where['status'] = $formData['status'];
  35. }
  36. $where['user_id'] = $this->user_id;
  37. $order_list = Order::where($where)
  38. ->with('product:id,title,pictures')
  39. ->select('id', 'product_id', 'price', 'num', 'status', 'created_at')
  40. ->orderBy('id', 'DESC')
  41. ->simplePaginate(15)
  42. ->toArray();
  43. $time = time();
  44. $timeout_ids = [];
  45. //10分钟内未付款订单提示付款
  46. foreach ($order_list['data'] as &$v) {
  47. if ($v['status'] == Status::UNPAID) {
  48. $minute = $time - $v['created_at'];
  49. //订单创建后10分钟内未付款则提示,否则取消订单
  50. if ($minute < 600) {
  51. $v['status_text'] = '请在' . ceil($minute / 60) . '分钟内付款';
  52. } else {
  53. $timeout_ids[] = $v['id'];
  54. $v['status'] = Status::CANCEL;
  55. $v['status_text'] = '已取消';
  56. //TODO 加回库存,未考虑到几天/几个月后再打开订单列表页的情况
  57. Product::query()->find($v['product_id'])->update(['stock' => $v['num']]);
  58. }
  59. }
  60. }
  61. //超时订单设置为已取消 TODO 测试阶段暂时注释
  62. // Order::query()->whereIn('id', $timeout_ids)->update(['status' => Status::CANCEL]);
  63. return $this->success($order_list);
  64. }
  65. //提交订单
  66. public function create(Request $request)
  67. {
  68. $formData = $request->only(['id', 'name', 'mobile', 'pay_type', 'num']);
  69. $formData = array_map(fn($v) => trim($v), $formData); //过滤,删除首尾空
  70. //表单验证
  71. $request->validate([
  72. 'id' => ['required', 'regex:/^\d+$/'],
  73. 'name' => ['required', 'between:2,20'],
  74. 'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/'],
  75. 'pay_type' => ['required', 'in:0,1,2'],
  76. 'num' => ['required', 'min:1'],
  77. ], [
  78. 'id.required' => '未指定产品ID',
  79. 'name.required' => '请输入联系人姓名',
  80. 'mobile.required' => '请输入联系手机号',
  81. 'id.regex' => '产品ID错误',
  82. 'name.between' => '联系人姓名在2~20字符之间',
  83. 'mobile.regex' => '请输入11位手机号',
  84. 'pay_type.required' => '请选择支付方式',
  85. 'pay_type.in' => '不存在此支付方式',
  86. 'num.required' => '请输入购买数量',
  87. 'num.min' => '购买数量输入错误',
  88. ]);
  89. $ap = AgentProduct::query()
  90. ->where('id', $formData['id'])
  91. ->with('coupon')
  92. ->with('product')
  93. ->first();
  94. if (!$ap || !$ap->product) {
  95. $this->error('产品不存在');
  96. }
  97. if ($ap->product->stock < $formData['num']) {
  98. $this->error('对不起,库存不足');
  99. }
  100. $coupon_ids = [];
  101. if ($ap->coupon) {
  102. foreach ($ap->coupon as $v) {
  103. $coupon_ids[] = $v['id'];
  104. }
  105. }
  106. DB::beginTransaction();
  107. try {
  108. $price = $this->calc($ap, $formData['num']);
  109. $title = $ap->product->title; //产品标题
  110. //代理商产品表增加销量
  111. // $ap->increment('sale', $formData['num']); TODO 支付成功之后再增加销量
  112. //供应商产品表加销量、减库存
  113. // $ap->product->sale += $formData['num']; TODO 支付成功之后再增加销量
  114. $ap->product->stock -= $formData['num'];
  115. $ap->product->save();
  116. // 存入订单表
  117. $order = Order::query()->create([
  118. 'user_id' => $this->user_id,
  119. 'order_no' => $this->getOrderNo(),
  120. 'num' => $formData['num'],
  121. 'price' => $price,
  122. 'name' => $formData['name'],
  123. 'mobile' => $formData['mobile'],
  124. 'title' => $title,
  125. 'picture' => $ap->product->picture,
  126. 'agent_product_id' => $ap->id,
  127. 'product_id' => $ap->product_id,
  128. 'status' => Status::UNPAID,
  129. 'pay_type' => $formData['pay_type'],
  130. 'coupon_id' => join(',', $coupon_ids),
  131. ]);
  132. //资金流水
  133. UserMoneyLog::query()->create([
  134. 'user_id' => $this->user_id,
  135. 'agent_id' => $this->agent_id,
  136. 'money' => -$price,
  137. 'order_id' => $order->id,
  138. 'type' => 1,
  139. 'desc' => '购买产品:' . $title,
  140. 'created_at' => time(), //已关闭模型自动写入时间
  141. ]);
  142. DB::commit();
  143. } catch (\Exception $e) {
  144. DB::rollBack();
  145. return $e->getMessage();
  146. }
  147. return $this->success();
  148. }
  149. //申请退款
  150. public function refund(Request $request)
  151. {
  152. $formData = $request->only(['id', 'desc', 'pictures']);
  153. $request->validate([
  154. 'id' => 'required|integer',
  155. 'desc' => 'required|string',
  156. 'pictures' => 'nullable|array',
  157. ], [
  158. '*.required' => '内容输入不完整',
  159. 'pictures.array' => '图片必须是数组',
  160. ]);
  161. //去掉图片地址前的域名
  162. $host = env('APP_URL');
  163. foreach ($formData['pictures'] as &$v) {
  164. $v = str_replace($host, '', $v);
  165. }
  166. //TODO 需要后台处理
  167. $order = Order::find($formData['id']);
  168. if (!in_array($order->status, [Status::PAY_EARNEST, Status::PAID, Status::PAY_RETAINAGE])) {
  169. return $this->error('当前订单状态不允许退款');
  170. }
  171. $order->status = Status::REFUNDING;
  172. $order->refund_info = [
  173. 'desc' => strip_tags($formData['desc']),
  174. 'pictures' => $formData['pictures'] ?? [],
  175. ];
  176. $order->save();
  177. return $this->success();
  178. }
  179. //获取应付金额
  180. public function getPrice(Request $request)
  181. {
  182. $id = (int)$request->input('id');
  183. $num = (float)$request->input('num');
  184. if (!$num || $num < 1) {
  185. return $this->error('未指定产品数量');
  186. }
  187. $agent_product = AgentProduct::query()
  188. ->with('coupon:agent_product_id,type,detail,agent_id,start_at,end_at')
  189. ->find($id);
  190. $final_price = $this->calc($agent_product, $num);
  191. return $this->success(['price' => $final_price]);
  192. }
  193. //订单支付
  194. public function pay()
  195. {
  196. $id = (int)request()->input('id');
  197. //订单信息
  198. $order = Order::find($id);
  199. if (!$order) {
  200. return $this->error('订单不存在');
  201. }
  202. //用户openid
  203. $openid = User::query()->find($this->user_id)->value('openid');
  204. //代理商信息
  205. $agent = Agent::find($this->agent_id);
  206. $config = config('wechat.payment.default');
  207. $config = array_merge($config, [
  208. 'app_id' => $agent->appid,
  209. 'mch_id' => $agent->mchid,
  210. 'key' => $agent->mchkey,
  211. ]);
  212. $app = Factory::payment($config);
  213. $result = $app->order->unify([
  214. 'body' => $order->title,
  215. 'out_trade_no' => $order->order_no,
  216. 'total_fee' => $order->price, //TODO 需要区分定金和全款
  217. 'notify_url' => route('wxpay_notify'), // 支付结果通知网址,如果不设置则会使用配置里的默认地址
  218. 'trade_type' => 'JSAPI',
  219. 'openid' => $openid,
  220. ]);
  221. $jssdk = $app->jssdk;
  222. $config = $jssdk->bridgeConfig($result['prepay_id'], false); // 返回数组
  223. return $this->success($config);
  224. }
  225. //订单详情
  226. public function show()
  227. {
  228. $id = (int)request()->input('id');
  229. $fields = ['id', 'order_no', 'agent_product_id', 'num', 'price', 'title', 'picture',
  230. 'status', 'pay_type', 'coupon_id', 'paid_money', 'paid_at', 'refund_info', 'created_at'];
  231. $order = Order::query()
  232. ->where('user_id', $this->user_id)
  233. ->find($id, $fields);
  234. if (!$order) {
  235. return $this->error('订单不存在');
  236. }
  237. $order->coupon = Coupon::query()
  238. ->whereIn('id', $order->coupon_id)
  239. ->where(['agent_id' => $this->agent_id, 'agent_product_id' => $order->agent_product_id,])
  240. ->get(['tag']);
  241. return $this->success($order);
  242. }
  243. /**
  244. * 计算最终价格(扣除优惠券之后的价格)
  245. * @param $agent_product
  246. * @param $num
  247. * @return float
  248. */
  249. private function calc($agent_product, $num)
  250. {
  251. $total_price = $agent_product->price * $num;
  252. //没有任何优惠券时直接返回最终价
  253. if ($agent_product->coupon->isEmpty()) {
  254. return $total_price;
  255. }
  256. $coupon = $agent_product->coupon->toArray();
  257. foreach ($coupon as $v) {
  258. // TODO 未判断优惠券有效期
  259. if ($v['type'] == 1 && !empty($v['detail']['full']) && !empty($v['detail']['reduction'])) { //满减
  260. if ($total_price >= $v['detail']['full']) {
  261. $total_price -= $v['detail']['reduction'];
  262. }
  263. } else if ($v['type'] == 2 && !empty($v['detail']['discount'])) { //打折
  264. $total_price *= $v['detail']['discount'];
  265. }
  266. }
  267. return round($total_price, 2);
  268. }
  269. // 生成订单号
  270. private function getOrderNo(): string
  271. {
  272. list($micro, $sec) = explode(' ', microtime());
  273. $micro = str_pad(floor($micro * 1000000), 6, 0, STR_PAD_LEFT);
  274. return date('YmdHis', $sec) . $micro . mt_rand(1000, 9999);
  275. }
  276. }