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

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