OrderService.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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 cancelOrder($userId, $orderId)
  201. {
  202. return DB::transaction(function () use ($userId, $orderId) {
  203. try {
  204. $user = MemberUser::where('id', $userId)->firstOrFail();
  205. $order = $user->orders()->find($orderId);
  206. if (! $order) {
  207. throw new Exception('订单不存在');
  208. }
  209. // 判断订单状态
  210. if ($order->state == 'wait_receive') { // 已接单
  211. // 扣除20%费用
  212. $deductAmount = ($order->payment_amount + $order->balance_amount - $order->traffic_amount) * 0.2;
  213. $this->handleRefund($user, $order, $deductAmount, false);
  214. } elseif ($order->state == 'on_the_way') { // 已出发
  215. // 扣除50%费用并扣除路费
  216. $deductAmount = ($order->payment_amount + $order->balance_amount - $order->traffic_amount) * 0.5;
  217. $this->handleRefund($user, $order, $deductAmount, true);
  218. } elseif ($order->state == 'wait_pay') {
  219. // 待支付状态直接取消,无需退款
  220. } else {
  221. throw new Exception('当前订单状态不允许取消');
  222. }
  223. // 添加订单取消记录
  224. OrderRecord::create([
  225. 'order_id' => $orderId,
  226. 'object_id' => $userId,
  227. 'object_type' => MemberUser::class,
  228. 'state' => 'cancel',
  229. 'remark' => '用户取消订单',
  230. ]);
  231. // 修改订单状态
  232. $order->state = 'cancel';
  233. $order->save();
  234. return ['message' => '订单已取消'];
  235. } catch (Exception $e) {
  236. Log::error('取消订单失败:', [
  237. 'message' => $e->getMessage(),
  238. 'user_id' => $userId,
  239. 'order_id' => $orderId,
  240. ]);
  241. throw $e;
  242. }
  243. });
  244. }
  245. /**
  246. * 处理退款
  247. */
  248. private function handleRefund($user, $order, $deductAmount, $deductTrafficFee)
  249. {
  250. // 计算实际退款金额
  251. $refundAmount = $order->payment_amount + $order->balance_amount;
  252. if ($deductTrafficFee) {
  253. $refundAmount -= $order->traffic_amount;
  254. // 记录技师路费收入
  255. // ...
  256. }
  257. $refundAmount -= $deductAmount;
  258. // 优先从余额支付金额中扣除
  259. $balanceRefund = min($order->balance_amount, $refundAmount);
  260. if ($balanceRefund > 0) {
  261. // 添加钱包退款记录
  262. $refundRecord = $user->wallet->refundRecords()->create([
  263. 'refund_method' => 'balance',
  264. 'total_refund_amount' => $order->payment_amount + $order->balance_amount,
  265. 'actual_refund_amount' => '0.00',
  266. 'wallet_balance_refund_amount' => $balanceRefund,
  267. 'recharge_balance_refund_amount' => '0.00',
  268. 'remark' => '订单取消退还余额',
  269. 'order_id' => $order->id,
  270. ]);
  271. // 添加钱包交易记录
  272. $user->wallet->transRecords()->create([
  273. 'amount' => $balanceRefund,
  274. 'owner_type' => $refundRecord::class,
  275. 'owner_id' => $refundRecord->id,
  276. 'remark' => '订单取消退还余额',
  277. 'trans_type' => 'income',
  278. 'storage_type' => 'balance',
  279. 'amount' => $balanceRefund,
  280. 'before_balance' => $user->wallet->total_balance,
  281. 'after_balance' => $user->wallet->total_balance + $balanceRefund,
  282. 'before_recharge_balance' => '0.00',
  283. 'after_recharge_balance' => '0.00',
  284. 'trans_time' => now(),
  285. 'state' => 'success',
  286. ]);
  287. $user->wallet->increment('total_balance', $balanceRefund);
  288. $user->wallet->increment('available_balance', $balanceRefund);
  289. $user->wallet->save();
  290. }
  291. // 剩余退款金额从支付金额中退还
  292. $paymentRefund = $refundAmount - $balanceRefund;
  293. if ($paymentRefund > 0) {
  294. // 添加钱包退款记录
  295. $refundRecord = $user->wallet->refundRecords()->create([
  296. 'refund_method' => 'balance',
  297. 'total_refund_amount' => $order->payment_amount + $order->balance_amount,
  298. 'actual_refund_amount' => '0.00',
  299. 'wallet_balance_refund_amount' => $balanceRefund,
  300. 'recharge_balance_refund_amount' => '0.00',
  301. 'remark' => '订单取消退还余额',
  302. 'order_id' => $order->id,
  303. ]);
  304. // 添加钱包交易记录
  305. $user->wallet->transRecords()->create([
  306. 'amount' => $balanceRefund,
  307. 'owner_type' => $refundRecord::class,
  308. 'owner_id' => $refundRecord->id,
  309. 'remark' => '订单取消退还余额',
  310. 'trans_type' => 'income',
  311. 'storage_type' => 'balance',
  312. 'amount' => $balanceRefund,
  313. 'before_balance' => $user->wallet->total_balance,
  314. 'after_balance' => $user->wallet->total_balance + $balanceRefund,
  315. 'before_recharge_balance' => '0.00',
  316. 'after_recharge_balance' => '0.00',
  317. 'trans_time' => now(),
  318. 'state' => 'success',
  319. ]);
  320. $user->wallet->increment('total_balance', $paymentRefund);
  321. $user->wallet->increment('available_balance', $paymentRefund);
  322. $user->wallet->save();
  323. }
  324. // 记录平台收入
  325. if ($deductAmount > 0) {
  326. // TODO: 添加平台收入记录
  327. // PlatformIncome::create([...]);
  328. }
  329. }
  330. /**
  331. * 结束订单
  332. */
  333. public function finishOrder($userId, $orderId)
  334. {
  335. return DB::transaction(function () use ($userId, $orderId) {
  336. try {
  337. // 1. 参数校验
  338. $order = Order::where('user_id', $userId)
  339. ->where('id', $orderId)
  340. ->where('state', 'service_ing') // 订单状态必须是服务中
  341. ->firstOrFail();
  342. if (! $order) {
  343. throw new Exception('订单不能结束');
  344. }
  345. // 2. 创建订单历史记录
  346. OrderRecord::create([
  347. 'order_id' => $orderId,
  348. 'object_id' => $userId,
  349. 'object_type' => MemberUser::class,
  350. 'state' => 'finish',
  351. 'remark' => '服务完成',
  352. ]);
  353. // 3. 修改订单状态为服务结束
  354. $order->state = 'service_end';
  355. $order->save();
  356. return ['message' => '订单已完成'];
  357. } catch (Exception $e) {
  358. Log::error('结束订单失败:', [
  359. 'message' => $e->getMessage(),
  360. 'user_id' => $userId,
  361. 'order_id' => $orderId,
  362. ]);
  363. throw $e;
  364. }
  365. });
  366. }
  367. /**
  368. * 确认技师离开
  369. */
  370. public function confirmLeave($userId, $orderId)
  371. {
  372. return DB::transaction(function () use ($userId, $orderId) {
  373. try {
  374. // 1. 参数校验
  375. $order = Order::where('user_id', $userId)
  376. ->where('id', $orderId)
  377. ->where('state', 'service_end') // 订单状态必须是服务结束
  378. ->firstOrFail();
  379. if (! $order) {
  380. throw new Exception('订单不能撤离');
  381. }
  382. // 2. 添加订单撤离记录
  383. OrderRecord::create([
  384. 'order_id' => $orderId,
  385. 'object_id' => $userId,
  386. 'object_type' => MemberUser::class,
  387. 'state' => 'leave',
  388. 'remark' => '技师已离开',
  389. ]);
  390. // 3. 修改订单状态为撤离
  391. $order->state = 'leave';
  392. $order->save();
  393. return ['message' => '已确认技师离开'];
  394. } catch (Exception $e) {
  395. Log::error('确认技师离开失败:', [
  396. 'message' => $e->getMessage(),
  397. 'user_id' => $userId,
  398. 'order_id' => $orderId,
  399. ]);
  400. throw $e;
  401. }
  402. });
  403. }
  404. /**
  405. * 获取订单列表
  406. */
  407. public function getOrderList($user_id)
  408. {
  409. $user = MemberUser::find($user_id);
  410. return $user->orders()
  411. ->with([
  412. 'coach.info:id,nickname,avatar,gender',
  413. ])
  414. ->orderBy('created_at', 'desc')
  415. ->paginate(10);
  416. }
  417. /**
  418. * 获取订单详情
  419. */
  420. public function getOrderDetail($userId, $orderId)
  421. {
  422. $user = MemberUser::find($userId);
  423. return $user->orders()->with([
  424. 'coach.info:id,nickname,avatar,gender',
  425. 'records' => function ($query) {
  426. $query->orderBy('created_at', 'asc');
  427. },
  428. ])
  429. ->firstOrFail();
  430. }
  431. /**
  432. * 订单退款
  433. */
  434. public function refundOrder($orderId)
  435. {
  436. $userId = Auth::id();
  437. return DB::transaction(function () use ($orderId, $userId) {
  438. // 查询并锁定订单
  439. $order = Order::where('id', $orderId)
  440. ->where('user_id', $userId)
  441. ->where('state', 'pending')
  442. ->lockForUpdate()
  443. ->firstOrFail();
  444. // 更新订单状态
  445. $order->state = 'refunded';
  446. $order->save();
  447. // 添加订单记录
  448. OrderRecord::create([
  449. 'order_id' => $orderId,
  450. 'object_id' => $userId,
  451. 'object_type' => 'user',
  452. 'state' => 'refund',
  453. 'remark' => '订单退款',
  454. ]);
  455. // 创建退款记录
  456. WalletRefundRecord::create([
  457. 'order_id' => $orderId,
  458. 'user_id' => $userId,
  459. 'amount' => $order->total_amount,
  460. 'state' => 'success',
  461. ]);
  462. return ['message' => '退款成功'];
  463. });
  464. }
  465. /**
  466. * 获取代理商配置
  467. */
  468. public function getAgentConfig($agentId)
  469. {
  470. $agent = AgentInfo::where('id', $agentId)
  471. ->where('state', 'enable')
  472. ->firstOrFail();
  473. // $config = AgentConfig::where('agent_id', $agentId)->firstOrFail();
  474. return [
  475. // 'min_distance' => $config->min_distance,
  476. // 'min_fee' => $config->min_fee,
  477. // 'per_km_fee' => $config->per_km_fee
  478. ];
  479. }
  480. /**
  481. * 获取技师配置
  482. */
  483. public function getCoachConfig($coachId)
  484. {
  485. $coach = CoachUser::where('id', $coachId)
  486. ->where('state', 'enable')
  487. ->where('auth_state', 'passed')
  488. ->firstOrFail();
  489. // $config = CoachConfig::where('coach_id', $coachId)->firstOrFail();
  490. return [
  491. // 'delivery_fee_type' => $config->delivery_fee_type,
  492. // 'charge_delivery_fee' => $config->charge_delivery_fee
  493. ];
  494. }
  495. /**
  496. * 计算路费金额
  497. */
  498. public function calculateDeliveryFee($coachId, $projectId, $agentId, $distance)
  499. {
  500. // 查询技师数据
  501. $coach = CoachUser::where('state', 'enable')
  502. ->whereHas('info', function ($query) {
  503. $query->where('state', 'approved');
  504. })
  505. ->whereHas('real', function ($query) {
  506. $query->where('state', 'approved');
  507. })
  508. ->whereHas('qual', function ($query) {
  509. $query->where('state', 'approved');
  510. })
  511. ->find($coachId);
  512. if (! $coach) {
  513. throw new Exception('技师不存在');
  514. }
  515. // 查询技师项目
  516. $coachProject = $coach->projects()
  517. ->where('state', 'enable')
  518. ->where('project_id', $projectId)
  519. ->first();
  520. if (! $coachProject) {
  521. throw new Exception('项目不存在');
  522. }
  523. // 技师免收路费
  524. if ($coachProject->traffic_fee_type == 'free') {
  525. return 0;
  526. }
  527. // 查询代理商
  528. $agent = AgentInfo::where('state', 'enable')->find($agentId);
  529. if ($agent) {
  530. $agentProject = $agent->projects()
  531. ->where('state', 'enable')
  532. ->where('project_id', $projectId)
  533. ->first();
  534. if (! $agentProject) {
  535. throw new Exception('代理商项目不存在');
  536. }
  537. $config = $agent->projectConfig;
  538. } else {
  539. // 系统配置
  540. $config = SysConfig::where('key', 'delivery_fee')->firstOrFail();
  541. dd('暂停处理');
  542. }
  543. $fee = 0;
  544. if ($distance <= $config->min_distance) {
  545. $fee = $config->min_fee;
  546. } else {
  547. $extraDistance = $distance - $config->min_distance;
  548. $fee = $config->min_fee + ($extraDistance * $config->per_km_fee);
  549. }
  550. return $coachProject->delivery_fee_type == 'round_trip' ? $fee * 2 : $fee;
  551. }
  552. /**
  553. * 计算订单金额
  554. */
  555. public function calculateOrderAmount($userId, $addressId, $coachId, $projectId, $agentId, $useBalance = false)
  556. {
  557. // 参数校验
  558. $user = MemberUser::find($userId);
  559. if (! $user) {
  560. throw new Exception('用户不存在');
  561. }
  562. if ($user->state != 'enable') {
  563. throw new Exception('用户状态异常');
  564. }
  565. // 查询地址
  566. $address = $user->address()->find($addressId);
  567. // 查询技师数据
  568. $coach = CoachUser::where('state', 'enable')
  569. ->whereHas('info', function ($query) {
  570. $query->where('state', 'approved');
  571. })
  572. ->whereHas('real', function ($query) {
  573. $query->where('state', 'approved');
  574. })
  575. ->whereHas('qual', function ($query) {
  576. $query->where('state', 'approved');
  577. })
  578. ->with(['info:id,nickname,avatar,gender'])
  579. ->find($coachId);
  580. if (! $coach) {
  581. throw new Exception('技师不存在');
  582. }
  583. // 查询技师项目
  584. $coachProject = $coach->projects()
  585. ->where('state', 'enable')
  586. ->where('project_id', $projectId)
  587. ->first();
  588. if (! $coachProject) {
  589. throw new Exception('项目不存在');
  590. }
  591. // 查询项目
  592. $project = $coachProject->basicInfo;
  593. if (! $project) {
  594. throw new Exception('项目不存在');
  595. }
  596. if ($project->state != 'enable') {
  597. throw new Exception('项目状态异常');
  598. }
  599. // 查询代理商
  600. $agent = AgentInfo::where('state', 'enable')->find($agentId);
  601. if ($agent) {
  602. $agentProject = $agent->projects()
  603. ->where('state', 'enable')
  604. ->where('project_id', $projectId)
  605. ->first();
  606. if (! $agentProject) {
  607. throw new Exception('代理商项目不在');
  608. }
  609. $project->price = $agentProject->price;
  610. $project->duration = $agentProject->duration;
  611. $project->distance = $address->distance;
  612. }
  613. // 计算金额
  614. $projectAmount = $project->price;
  615. $deliveryFee = $this->calculateDeliveryFee($coachId, $projectId, $agentId, $address?->distance);
  616. // $tipAmount = request()->has('order_id') ? Order::find(request()->input('order_id'))->tip_amount : 0;
  617. $couponAmount = 0;
  618. if (request()->has('coupon_id')) {
  619. // $coupon = Coupon::where('id', request()->input('coupon_id'))
  620. // ->where('state', 'enable')
  621. // ->firstOrFail();
  622. // $couponAmount = $coupon->amount;
  623. }
  624. $totalAmount = $projectAmount + $deliveryFee - $couponAmount;
  625. $balanceAmount = 0;
  626. $payAmount = $totalAmount;
  627. if ($useBalance) {
  628. $wallet = $user->wallet;
  629. if ($wallet && $wallet->available_balance >= $totalAmount) {
  630. $balanceAmount = $totalAmount;
  631. $payAmount = 0;
  632. } elseif ($wallet) {
  633. $balanceAmount = $wallet->available_balance;
  634. $payAmount = $totalAmount - $balanceAmount;
  635. }
  636. }
  637. return [
  638. 'total_amount' => $totalAmount,
  639. 'balance_amount' => $balanceAmount,
  640. 'pay_amount' => $payAmount,
  641. 'coupon_amount' => $couponAmount,
  642. // 'tip_amount' => $tipAmount,
  643. 'project_amount' => $projectAmount,
  644. 'delivery_fee' => $deliveryFee,
  645. ];
  646. }
  647. /**
  648. * 加钟
  649. */
  650. public function addTime($userId, $orderId)
  651. {
  652. $order = Order::where('id', $orderId)
  653. ->where('user_id', $userId)
  654. ->firstOrFail();
  655. return $this->createOrder($userId, $order->project_id, $order->address_id, $order->coach_id, 0, $orderId);
  656. }
  657. /**
  658. * 指定技师
  659. */
  660. public function assignCoach($userId, $orderId, $coachId)
  661. {
  662. return DB::transaction(function () use ($userId, $orderId, $coachId) {
  663. // 参数校验
  664. $user = MemberUser::where('id', $userId)
  665. ->where('state', 'enable')
  666. ->firstOrFail();
  667. $order = Order::where('id', $orderId)
  668. ->where('user_id', $userId)
  669. ->whereIn('state', [0, 1, 6])
  670. ->firstOrFail();
  671. $coach = CoachUser::where('id', $coachId)
  672. ->where('state', 'enable')
  673. ->where('auth_state', 'passed')
  674. ->firstOrFail();
  675. // $schedule = CoachSchedule::where('coach_id', $coachId)
  676. // ->where('date', date('Y-m-d'))
  677. // ->where('state', 'free')
  678. // ->firstOrFail();
  679. // 修改订单
  680. $order->coach_id = $coachId;
  681. if ($order->state == 'created') {
  682. $amounts = $this->calculateOrderAmount($userId, $order->address_id, $coachId, $order->project_id, $order->agent_id, $order->payment_type == 'balance');
  683. $order->total_amount = $amounts['total_amount'];
  684. $order->balance_amount = $amounts['balance_amount'];
  685. $order->pay_amount = $amounts['pay_amount'];
  686. $order->coupon_amount = $amounts['coupon_amount'];
  687. // $order->tip_amount = $amounts['tip_amount'];
  688. $order->project_amount = $amounts['project_amount'];
  689. $order->delivery_fee = $amounts['delivery_fee'];
  690. if ($order->payment_type == 'balance') {
  691. $order->state = 'paid';
  692. }
  693. }
  694. if ($order->state == 'paid') {
  695. $order->state = 'assigned';
  696. }
  697. $order->save();
  698. // 创建订单历史
  699. OrderRecord::create([
  700. 'order_id' => $order->id,
  701. 'type' => 'assigned',
  702. 'user_id' => $userId,
  703. 'coach_id' => $coachId,
  704. ]);
  705. OrderRecord::create([
  706. 'order_id' => $order->id,
  707. 'type' => 'accepted',
  708. 'user_id' => $userId,
  709. 'coach_id' => $coachId,
  710. 'remark' => '抢单成功',
  711. ]);
  712. // 更新抢单池
  713. OrderGrabRecord::where('order_id', $orderId)
  714. ->update(['state' => 'success', 'coach_id' => $coachId]);
  715. // 更新排班
  716. // $schedule->state = 'busy';
  717. // $schedule->save();
  718. return true;
  719. });
  720. }
  721. }