OrderService.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. <?php
  2. namespace App\Services\Client;
  3. use App\Models\AgentConfig;
  4. use App\Models\AgentInfo;
  5. use App\Models\CoachConfig;
  6. use App\Models\CoachSchedule;
  7. use App\Models\CoachUser;
  8. use App\Models\Coupon;
  9. use App\Models\MemberUser;
  10. use App\Models\Order;
  11. use App\Models\OrderGrabRecord;
  12. use App\Models\OrderRecord;
  13. use App\Models\Project;
  14. use App\Models\SysConfig;
  15. use App\Models\User;
  16. use App\Models\WalletRefundRecord;
  17. use Exception;
  18. use Illuminate\Support\Facades\Auth;
  19. use Illuminate\Support\Facades\DB;
  20. use Illuminate\Support\Facades\Log;
  21. class OrderService
  22. {
  23. protected AgentService $agentService;
  24. protected ProjectService $projectService;
  25. public function __construct(
  26. AgentService $agentService,
  27. ProjectService $projectService
  28. ) {
  29. $this->agentService = $agentService;
  30. $this->projectService = $projectService;
  31. }
  32. /**
  33. * 订单初始化
  34. */
  35. public function initialize($userId, $data)
  36. {
  37. $user = MemberUser::find($userId);
  38. if (! $user) {
  39. throw new Exception('用户不存在');
  40. }
  41. if ($user->state != 'enable') {
  42. throw new Exception('用户状态异常');
  43. }
  44. // 查询用户钱包
  45. $wallet = $user->wallet;
  46. // 查询默认地址
  47. $address = $user->address;
  48. $areaCode = $address ? $address->area_code : $data['area_code'];
  49. // 查询技师数据
  50. $coach = CoachUser::where('state', 'enable')
  51. ->whereHas('info', function ($query) {
  52. $query->where('state', 'approved');
  53. })
  54. ->whereHas('real', function ($query) {
  55. $query->where('state', 'approved');
  56. })
  57. ->whereHas('qual', function ($query) {
  58. $query->where('state', 'approved');
  59. })
  60. ->with(['info:id,nickname,avatar,gender'])
  61. ->find($data['coach_id']);
  62. if (! $coach) {
  63. throw new Exception('技师不存在');
  64. }
  65. // 查询技师排班
  66. // $schedule = CoachSchedule::where('coach_id', $coachId)
  67. // ->where('date', date('Y-m-d'))
  68. // ->first();
  69. // // 查询用户优惠券
  70. // $coupons = Coupon::where('user_id', $userId)
  71. // ->where('state', 'enable')
  72. // ->where('expire_time', '>', now())
  73. // ->get();
  74. // 获取项目详情
  75. $project = $this->projectService->getProjectDetail($data['project_id'], $areaCode);
  76. // 计算订单金额
  77. $amounts = $this->calculateOrderAmount($userId, $address?->id, $data['coach_id'], $data['project_id'], $project?->agent_id);
  78. return [
  79. 'wallet' => $wallet,
  80. 'coach' => $coach,
  81. 'project' => $project,
  82. 'address' => $address,
  83. // 'schedule' => $schedule,
  84. 'amounts' => $amounts,
  85. // 'coupons' => $coupons
  86. ];
  87. }
  88. /**
  89. * 创建订单
  90. */
  91. public function createOrder($userId, array $data)
  92. {
  93. try {
  94. return DB::transaction(function () use ($userId, $data) {
  95. // 1. 参数校验
  96. $user = MemberUser::where('id', $userId)
  97. ->where('state', 'enable')
  98. ->firstOrFail();
  99. $address = $user->addresses()
  100. ->where('id', $data['address_id'])
  101. ->firstOrFail();
  102. // 查询技师及其认证状态
  103. $coach = CoachUser::where('id', $data['coach_id'])
  104. ->where('state', 'enable')
  105. ->whereHas('info', function ($query) {
  106. $query->where('state', 'approved');
  107. })
  108. ->whereHas('qual', function ($query) {
  109. $query->where('state', 'approved');
  110. })
  111. ->whereHas('real', function ($query) {
  112. $query->where('state', 'approved');
  113. })
  114. ->firstOrFail();
  115. $project = Project::where('id', $data['project_id'])
  116. ->where('state', 'enable')
  117. ->firstOrFail();
  118. // 2. 创建订单
  119. $orderType = isset($data['order_id']) ? 'add_time' : 'normal';
  120. // 计算订单金额
  121. $amounts = $this->calculateOrderAmount(
  122. $userId,
  123. $data['address_id'],
  124. $data['coach_id'],
  125. $data['project_id'],
  126. $project->agent_id,
  127. $data['use_balance'] ?? false
  128. );
  129. $order = new Order;
  130. $order->user_id = $userId;
  131. $order->project_id = $data['project_id'];
  132. $order->coach_id = $data['coach_id'];
  133. $order->type = $orderType;
  134. $order->state = 'wait_pay';
  135. $order->source = 'platform';
  136. $order->total_amount = $amounts['total_amount'];
  137. $order->balance_amount = $amounts['balance_amount'];
  138. $order->pay_amount = $amounts['pay_amount'];
  139. $order->project_amount = $amounts['project_amount'];
  140. $order->traffic_amount = $orderType == 'add_time' ? 0 : $amounts['delivery_fee'];
  141. $order->payment_type = ($data['use_balance'] && $amounts['pay_amount'] == 0) ? 'balance' : null;
  142. $order->service_time = $data['service_time'];
  143. // 从用户地址获取位置信息
  144. $order->longitude = $address->longitude; // 经度
  145. $order->latitude = $address->latitude; // 纬度
  146. $order->location = $address->location; // 定位地址
  147. $order->address = $address->address; // 详细地址
  148. $order->area_code = $address->area_code; // 行政区划代码
  149. $order->save();
  150. // 3. 创建订单记录
  151. OrderRecord::create([
  152. 'order_id' => $order->id,
  153. 'object_id' => $userId,
  154. 'object_type' => MemberUser::class,
  155. 'state' => $orderType == 'add_time' ? 'add_time' : 'create',
  156. 'remark' => $orderType == 'add_time' ? '加钟订单' : '创建订单',
  157. ]);
  158. // 4. 余额支付处理
  159. if ($order->payment_type == 'balance') {
  160. $order->state = 'wait_receive';
  161. $order->save();
  162. // 创建订单支付记录
  163. OrderRecord::create([
  164. 'order_id' => $order->id,
  165. 'object_id' => $userId,
  166. 'object_type' => MemberUser::class,
  167. 'state' => 'pay',
  168. 'remark' => '余额支付',
  169. ]);
  170. // 扣除用户钱包总余额
  171. $user->wallet->decrement('total_balance', $order->balance_amount);
  172. // 扣除用户钱包可用余额
  173. $user->wallet->decrement('available_balance', $order->balance_amount);
  174. $user->wallet->save();
  175. // 创建技师排班
  176. // CoachSchedule::create([
  177. // 'coach_id' => $data['coach_id'],
  178. // 'date' => date('Y-m-d'),
  179. // 'state' => 'busy',
  180. // ]);
  181. // TODO: 发送抢单通知
  182. }
  183. return [
  184. 'order_id' => $order->id,
  185. 'payment_type' => $order->payment_type,
  186. ];
  187. });
  188. } catch (Exception $e) {
  189. Log::error('创建订单失败:', [
  190. 'message' => $e->getMessage(),
  191. 'user_id' => $userId,
  192. 'data' => $data,
  193. ]);
  194. throw $e;
  195. }
  196. }
  197. /**
  198. * 结束订单
  199. */
  200. public function finishOrder($userId, $orderId)
  201. {
  202. return DB::transaction(function () use ($userId, $orderId) {
  203. $order = Order::where('user_id', $userId)
  204. ->where('id', $orderId)
  205. ->first();
  206. if (! $order) {
  207. throw new Exception('订单不存在');
  208. }
  209. // 添加订单结束记录
  210. OrderRecord::create([
  211. 'order_id' => $orderId,
  212. 'user_id' => $userId,
  213. 'state' => 'finish',
  214. 'remark' => '服务完成',
  215. ]);
  216. // 修改订单状态
  217. $order->state = 'finished';
  218. $order->save();
  219. return ['message' => '订单已完成'];
  220. });
  221. }
  222. /**
  223. * 确认技师离开
  224. */
  225. public function confirmLeave($userId, $orderId)
  226. {
  227. return DB::transaction(function () use ($userId, $orderId) {
  228. $order = Order::where('user_id', $userId)
  229. ->where('id', $orderId)
  230. ->first();
  231. if (! $order) {
  232. throw new Exception('订单不存在');
  233. }
  234. // 添加订单撤离记录
  235. OrderRecord::create([
  236. 'order_id' => $orderId,
  237. 'user_id' => $userId,
  238. 'state' => 'leave',
  239. 'remark' => '技师已离开',
  240. ]);
  241. // 修改订单状态
  242. $order->state = 'allow_leave';
  243. $order->save();
  244. return ['message' => '已确认技师离开'];
  245. });
  246. }
  247. /**
  248. * 取消订单
  249. */
  250. public function cancelOrder($userId, $orderId)
  251. {
  252. return DB::transaction(function () use ($userId, $orderId) {
  253. $order = Order::where('user_id', $userId)
  254. ->where('id', $orderId)
  255. ->first();
  256. if (! $order) {
  257. throw new Exception('订单不存在');
  258. }
  259. // 添加订单取消记录
  260. OrderRecord::create([
  261. 'order_id' => $orderId,
  262. 'user_id' => $userId,
  263. 'state' => 'cancel',
  264. 'remark' => '用户取消订单',
  265. ]);
  266. // 修改订单状态
  267. $order->state = 'cancelled';
  268. $order->save();
  269. return ['message' => '订单已取消'];
  270. });
  271. }
  272. /**
  273. * 获取订单列表
  274. */
  275. public function getOrderList()
  276. {
  277. $userId = Auth::id();
  278. return Order::where('user_id', $userId)
  279. ->with([
  280. 'project:id,title,cover,price',
  281. 'coach:id,name,avatar',
  282. 'agent:id,company_name',
  283. 'address:id,address',
  284. ])
  285. ->orderBy('created_at', 'desc')
  286. ->paginate(10);
  287. }
  288. /**
  289. * 获取订单详情
  290. */
  291. public function getOrderDetail($orderId)
  292. {
  293. $userId = Auth::id();
  294. return Order::where('id', $orderId)
  295. ->where('user_id', $userId)
  296. ->with([
  297. 'project:id,title,cover,price,duration',
  298. 'coach:id,name,avatar,mobile',
  299. 'agent:id,company_name',
  300. 'address:id,address,latitude,longitude',
  301. 'records' => function ($query) {
  302. $query->orderBy('created_at', 'asc');
  303. },
  304. ])
  305. ->firstOrFail();
  306. }
  307. /**
  308. * 订单退款
  309. */
  310. public function refundOrder($orderId)
  311. {
  312. $userId = Auth::id();
  313. return DB::transaction(function () use ($orderId, $userId) {
  314. // 查询并锁定订单
  315. $order = Order::where('id', $orderId)
  316. ->where('user_id', $userId)
  317. ->where('state', 'pending')
  318. ->lockForUpdate()
  319. ->firstOrFail();
  320. // 更新订单状态
  321. $order->state = 'refunded';
  322. $order->save();
  323. // 添加订单记录
  324. OrderRecord::create([
  325. 'order_id' => $orderId,
  326. 'object_id' => $userId,
  327. 'object_type' => 'user',
  328. 'state' => 'refund',
  329. 'remark' => '订单退款',
  330. ]);
  331. // 创建退款记录
  332. WalletRefundRecord::create([
  333. 'order_id' => $orderId,
  334. 'user_id' => $userId,
  335. 'amount' => $order->total_amount,
  336. 'state' => 'success',
  337. ]);
  338. return ['message' => '退款成功'];
  339. });
  340. }
  341. /**
  342. * 获取代理商配置
  343. */
  344. public function getAgentConfig($agentId)
  345. {
  346. $agent = AgentInfo::where('id', $agentId)
  347. ->where('state', 'enable')
  348. ->firstOrFail();
  349. // $config = AgentConfig::where('agent_id', $agentId)->firstOrFail();
  350. return [
  351. // 'min_distance' => $config->min_distance,
  352. // 'min_fee' => $config->min_fee,
  353. // 'per_km_fee' => $config->per_km_fee
  354. ];
  355. }
  356. /**
  357. * 获取技师配置
  358. */
  359. public function getCoachConfig($coachId)
  360. {
  361. $coach = CoachUser::where('id', $coachId)
  362. ->where('state', 'enable')
  363. ->where('auth_state', 'passed')
  364. ->firstOrFail();
  365. // $config = CoachConfig::where('coach_id', $coachId)->firstOrFail();
  366. return [
  367. // 'delivery_fee_type' => $config->delivery_fee_type,
  368. // 'charge_delivery_fee' => $config->charge_delivery_fee
  369. ];
  370. }
  371. /**
  372. * 计算路费金额
  373. */
  374. public function calculateDeliveryFee($coachId, $projectId, $agentId, $distance)
  375. {
  376. // 查询技师数据
  377. $coach = CoachUser::where('state', 'enable')
  378. ->whereHas('info', function ($query) {
  379. $query->where('state', 'approved');
  380. })
  381. ->whereHas('real', function ($query) {
  382. $query->where('state', 'approved');
  383. })
  384. ->whereHas('qual', function ($query) {
  385. $query->where('state', 'approved');
  386. })
  387. ->find($coachId);
  388. if (! $coach) {
  389. throw new Exception('技师不存在');
  390. }
  391. // 查询技师项目
  392. $coachProject = $coach->projects()
  393. ->where('state', 'enable')
  394. ->where('project_id', $projectId)
  395. ->first();
  396. if (! $coachProject) {
  397. throw new Exception('项目不存在');
  398. }
  399. // 技师免收路费
  400. if ($coachProject->traffic_fee_type == 'free') {
  401. return 0;
  402. }
  403. // 查询代理商
  404. $agent = AgentInfo::where('state', 'enable')->find($agentId);
  405. if ($agent) {
  406. $agentProject = $agent->projects()
  407. ->where('state', 'enable')
  408. ->where('project_id', $projectId)
  409. ->first();
  410. if (! $agentProject) {
  411. throw new Exception('代理商项目不存在');
  412. }
  413. $config = $agent->projectConfig;
  414. } else {
  415. // 系统配置
  416. $config = SysConfig::where('key', 'delivery_fee')->firstOrFail();
  417. dd('暂停处理');
  418. }
  419. $fee = 0;
  420. if ($distance <= $config->min_distance) {
  421. $fee = $config->min_fee;
  422. } else {
  423. $extraDistance = $distance - $config->min_distance;
  424. $fee = $config->min_fee + ($extraDistance * $config->per_km_fee);
  425. }
  426. return $coachProject->delivery_fee_type == 'round_trip' ? $fee * 2 : $fee;
  427. }
  428. /**
  429. * 计算订单金额
  430. */
  431. public function calculateOrderAmount($userId, $addressId, $coachId, $projectId, $agentId, $useBalance = false)
  432. {
  433. // 参数校验
  434. $user = MemberUser::find($userId);
  435. if (! $user) {
  436. throw new Exception('用户不存在');
  437. }
  438. if ($user->state != 'enable') {
  439. throw new Exception('用户状态异常');
  440. }
  441. // 查询地址
  442. $address = $user->address()->find($addressId);
  443. // 查询技师数据
  444. $coach = CoachUser::where('state', 'enable')
  445. ->whereHas('info', function ($query) {
  446. $query->where('state', 'approved');
  447. })
  448. ->whereHas('real', function ($query) {
  449. $query->where('state', 'approved');
  450. })
  451. ->whereHas('qual', function ($query) {
  452. $query->where('state', 'approved');
  453. })
  454. ->with(['info:id,nickname,avatar,gender'])
  455. ->find($coachId);
  456. if (! $coach) {
  457. throw new Exception('技师不存在');
  458. }
  459. // 查询技师项目
  460. $coachProject = $coach->projects()
  461. ->where('state', 'enable')
  462. ->where('project_id', $projectId)
  463. ->first();
  464. if (! $coachProject) {
  465. throw new Exception('项目不存在');
  466. }
  467. // 查询项目
  468. $project = $coachProject->basicInfo;
  469. if (! $project) {
  470. throw new Exception('项目不存在');
  471. }
  472. if ($project->state != 'enable') {
  473. throw new Exception('项目状态异常');
  474. }
  475. // 查询代理商
  476. $agent = AgentInfo::where('state', 'enable')->find($agentId);
  477. if ($agent) {
  478. $agentProject = $agent->projects()
  479. ->where('state', 'enable')
  480. ->where('project_id', $projectId)
  481. ->first();
  482. if (! $agentProject) {
  483. throw new Exception('代理商项目不存在');
  484. }
  485. $project->price = $agentProject->price;
  486. $project->duration = $agentProject->duration;
  487. $project->distance = $address->distance;
  488. }
  489. // 计算金额
  490. $projectAmount = $project->price;
  491. $deliveryFee = $this->calculateDeliveryFee($coachId, $projectId, $agentId, $address?->distance);
  492. // $tipAmount = request()->has('order_id') ? Order::find(request()->input('order_id'))->tip_amount : 0;
  493. $couponAmount = 0;
  494. if (request()->has('coupon_id')) {
  495. // $coupon = Coupon::where('id', request()->input('coupon_id'))
  496. // ->where('state', 'enable')
  497. // ->firstOrFail();
  498. // $couponAmount = $coupon->amount;
  499. }
  500. $totalAmount = $projectAmount + $deliveryFee - $couponAmount;
  501. $balanceAmount = 0;
  502. $payAmount = $totalAmount;
  503. if ($useBalance) {
  504. $wallet = $user->wallet;
  505. if ($wallet && $wallet->available_balance >= $totalAmount) {
  506. $balanceAmount = $totalAmount;
  507. $payAmount = 0;
  508. } elseif ($wallet) {
  509. $balanceAmount = $wallet->available_balance;
  510. $payAmount = $totalAmount - $balanceAmount;
  511. }
  512. }
  513. return [
  514. 'total_amount' => $totalAmount,
  515. 'balance_amount' => $balanceAmount,
  516. 'pay_amount' => $payAmount,
  517. 'coupon_amount' => $couponAmount,
  518. // 'tip_amount' => $tipAmount,
  519. 'project_amount' => $projectAmount,
  520. 'delivery_fee' => $deliveryFee,
  521. ];
  522. }
  523. /**
  524. * 加钟
  525. */
  526. public function addTime($userId, $orderId)
  527. {
  528. $order = Order::where('id', $orderId)
  529. ->where('user_id', $userId)
  530. ->firstOrFail();
  531. return $this->createOrder($userId, $order->project_id, $order->address_id, $order->coach_id, 0, $orderId);
  532. }
  533. /**
  534. * 指定技师
  535. */
  536. public function assignCoach($userId, $orderId, $coachId)
  537. {
  538. return DB::transaction(function () use ($userId, $orderId, $coachId) {
  539. // 参数校验
  540. $user = MemberUser::where('id', $userId)
  541. ->where('state', 'enable')
  542. ->firstOrFail();
  543. $order = Order::where('id', $orderId)
  544. ->where('user_id', $userId)
  545. ->whereIn('state', [0, 1, 6])
  546. ->firstOrFail();
  547. $coach = CoachUser::where('id', $coachId)
  548. ->where('state', 'enable')
  549. ->where('auth_state', 'passed')
  550. ->firstOrFail();
  551. // $schedule = CoachSchedule::where('coach_id', $coachId)
  552. // ->where('date', date('Y-m-d'))
  553. // ->where('state', 'free')
  554. // ->firstOrFail();
  555. // 修改订单
  556. $order->coach_id = $coachId;
  557. if ($order->state == 'created') {
  558. $amounts = $this->calculateOrderAmount($userId, $order->address_id, $coachId, $order->project_id, $order->agent_id, $order->payment_type == 'balance');
  559. $order->total_amount = $amounts['total_amount'];
  560. $order->balance_amount = $amounts['balance_amount'];
  561. $order->pay_amount = $amounts['pay_amount'];
  562. $order->coupon_amount = $amounts['coupon_amount'];
  563. // $order->tip_amount = $amounts['tip_amount'];
  564. $order->project_amount = $amounts['project_amount'];
  565. $order->delivery_fee = $amounts['delivery_fee'];
  566. if ($order->payment_type == 'balance') {
  567. $order->state = 'paid';
  568. }
  569. }
  570. if ($order->state == 'paid') {
  571. $order->state = 'assigned';
  572. }
  573. $order->save();
  574. // 创建订单历史
  575. OrderRecord::create([
  576. 'order_id' => $order->id,
  577. 'type' => 'assigned',
  578. 'user_id' => $userId,
  579. 'coach_id' => $coachId,
  580. ]);
  581. OrderRecord::create([
  582. 'order_id' => $order->id,
  583. 'type' => 'accepted',
  584. 'user_id' => $userId,
  585. 'coach_id' => $coachId,
  586. 'remark' => '抢单成功',
  587. ]);
  588. // 更新抢单池
  589. OrderGrabRecord::where('order_id', $orderId)
  590. ->update(['state' => 'success', 'coach_id' => $coachId]);
  591. // 更新排班
  592. // $schedule->state = 'busy';
  593. // $schedule->save();
  594. return true;
  595. });
  596. }
  597. }