OrderService.php 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563
  1. <?php
  2. namespace App\Services\Client;
  3. use App\Enums\OrderGrabRecordStatus;
  4. use App\Enums\OrderRecordStatus;
  5. use App\Enums\OrderStatus;
  6. use App\Enums\OrderType;
  7. use App\Enums\PaymentMethod;
  8. use App\Enums\ProjectStatus;
  9. use App\Enums\TechnicianAuthStatus;
  10. use App\Enums\TechnicianLocationType;
  11. use App\Enums\TechnicianStatus;
  12. use App\Enums\TransactionType;
  13. use App\Enums\UserStatus;
  14. use App\Models\AgentInfo;
  15. use App\Models\CoachUser;
  16. use App\Models\MemberAddress;
  17. use App\Models\MemberUser;
  18. use App\Models\Order;
  19. use App\Models\OrderGrabRecord;
  20. use App\Models\OrderRecord;
  21. use App\Models\Project;
  22. use App\Models\WalletPaymentRecord;
  23. use App\Services\Client\Traits\CalculatesOrderAmounts;
  24. use App\Services\Client\Traits\HandlesOrderRecords;
  25. use App\Services\Client\Traits\HandlesPayments;
  26. use App\Services\Client\Traits\ValidatesServiceTime;
  27. use Carbon\Carbon;
  28. use Exception;
  29. use Illuminate\Database\Eloquent\Collection;
  30. use Illuminate\Support\Facades\Auth;
  31. use Illuminate\Support\Facades\DB;
  32. use Illuminate\Support\Facades\Log;
  33. use Illuminate\Support\Facades\Redis;
  34. use SimpleSoftwareIO\QrCode\Facades\QrCode;
  35. readonly class OrderService
  36. {
  37. use CalculatesOrderAmounts;
  38. use HandlesOrderRecords;
  39. use HandlesPayments;
  40. use ValidatesServiceTime;
  41. public function __construct(
  42. private AgentService $agentService,
  43. private ProjectService $projectService,
  44. private CoachService $coachService,
  45. private WalletService $walletService
  46. ) {}
  47. /**
  48. * 订单初始化
  49. *
  50. * @param int $userId 用户ID
  51. * @param array $data 订单数据
  52. * @return array 初始化的订单信息
  53. *
  54. * @throws \Exception
  55. *
  56. * 逻辑描述:
  57. * 1. 验证初始化参数(project_id、coach_id)
  58. * 2. 获取用户信息(包含钱包和地址)
  59. * 3. 获取区域编码(从地址或参数)
  60. * 4. 验证技师状态并获取可用时间
  61. * 5. 获取项目详情(含价格)
  62. * 6. 计算订单金额(含路费)
  63. * 7. 返回初始化数据(钱包、技师、项目、地址、金额、可用时间)
  64. */
  65. public function initialize(int $userId, array $data): array
  66. {
  67. try {
  68. // 参数验证
  69. $this->validateInitializeData($data);
  70. return DB::transaction(function () use ($userId, $data) {
  71. // 获取用户信息
  72. $user = $this->getUserWithWalletAndAddress($userId);
  73. // 获取区域编码
  74. $areaCode = $this->getAreaCode($user->address, $data);
  75. // 获取技师信息和可用时间
  76. $coach = $this->validateCoach($data['coach_id']);
  77. $availableTimeSlots = $this->coachService->getSchedule($coach->id);
  78. // 获取项目信息
  79. $project = $this->getProjectDetail($data['project_id'], $areaCode);
  80. // 计算订单金额
  81. $amounts = $this->calculateOrderAmount(
  82. userId: $userId,
  83. addressId: $user->address?->id ?? 0,
  84. coachId: $data['coach_id'],
  85. projectId: $data['project_id'],
  86. agentId: $project->agent_id,
  87. useBalance: false,
  88. distance: $data['distance'] ?? 0,
  89. lat: $data['latitude'] ?? 0,
  90. lng: $data['longitude'] ?? 0
  91. );
  92. return [
  93. 'wallet' => $user->wallet,
  94. 'coach' => $coach,
  95. 'project' => $project,
  96. 'address' => $user->address,
  97. 'amounts' => $amounts,
  98. 'availableTimeSlots' => $availableTimeSlots,
  99. ];
  100. });
  101. } catch (Exception $e) {
  102. $this->logError('订单初始化失败', $e, [
  103. 'userId' => $userId,
  104. 'data' => $data,
  105. ]);
  106. throw $e;
  107. }
  108. }
  109. /**
  110. * 验证初始化数据
  111. *
  112. * 逻辑描述:
  113. * 1. 验证项目ID不能为空
  114. * 2. 验证技师ID不能为空
  115. */
  116. private function validateInitializeData(array $data): void
  117. {
  118. abort_if(empty($data['project_id']), 400, '项目ID不能为空');
  119. abort_if(empty($data['coach_id']), 400, '技师ID不能为空');
  120. }
  121. /**
  122. * 获取用户信息(包含钱包和地址)
  123. *
  124. * 逻辑描述:
  125. * 1. 查询用户信息(关联钱包和地址)
  126. * 2. 验证用户状态是否正常
  127. * 3. 返回用户信息
  128. */
  129. private function getUserWithWalletAndAddress(int $userId): MemberUser
  130. {
  131. $user = MemberUser::with(['wallet', 'address'])
  132. ->where('id', $userId)
  133. ->where('state', UserStatus::OPEN->value)
  134. ->first();
  135. abort_if(! $user, 400, '用户状态异常');
  136. return $user;
  137. }
  138. /**
  139. * 获取区域编码
  140. *
  141. * 逻辑描述:
  142. * 1. 优先使用地址中的区域编码
  143. * 2. 其次使用参数中的区域编码
  144. * 3. 验证区域编码不能为空
  145. */
  146. private function getAreaCode(?object $address, array $data): string
  147. {
  148. $areaCode = $address?->area_code ?? ($data['area_code'] ?? null);
  149. abort_if(empty($areaCode), 400, '区域编码不能为空');
  150. return $areaCode;
  151. }
  152. /**
  153. * 获取项目详情
  154. *
  155. * 逻辑描述:
  156. * 1. 调用项目服务获取详情
  157. * 2. 验证项目是否存在
  158. * 3. 返回项目信息
  159. */
  160. private function getProjectDetail(int $projectId, string $areaCode): Project
  161. {
  162. $project = $this->projectService->getProjectDetail($projectId, $areaCode);
  163. abort_if(! $project, 400, '项目不存在');
  164. return $project;
  165. }
  166. /**
  167. * 记录错误日志
  168. *
  169. * 逻辑描述:
  170. * 1. 记录错误信息
  171. * 2. 记录上下文数据
  172. * 3. 记录错误堆栈
  173. */
  174. private function logError(string $message, Exception $e, array $context = []): void
  175. {
  176. Log::error($message, [
  177. ...$context,
  178. 'error' => $e->getMessage(),
  179. 'trace' => $e->getTraceAsString(),
  180. ]);
  181. }
  182. /**
  183. * 创建订单
  184. *
  185. * @param array{
  186. * user_id: int,
  187. * project_id: int,
  188. * coach_id: ?int,
  189. * address_id: int,
  190. * service_time: string,
  191. * remark: ?string,
  192. * use_balance: bool,
  193. * agent_id: ?int,
  194. * distance: float,
  195. * payment_type: int,
  196. * type: int,
  197. * } $data 订单数据
  198. * @return array{
  199. * order_id: int,
  200. * order_no: string,
  201. * total_amount: float,
  202. * balance_amount: float,
  203. * pay_amount: float
  204. * }
  205. *
  206. * @throws \Exception
  207. *
  208. * 逻辑描述:
  209. * 1. 验证基础数据(用户状态、项目状态、服务时间、技师状态等)
  210. * 2. 计算订单金额(项目价格、路费、优惠等)
  211. * 3. 处理加钟订单特殊逻辑(使用原订单地址和技师)
  212. * 4. 获取服务地址信息
  213. * 5. 创建订单数据
  214. * 6. 创建订单相关记录
  215. * 7. 处理余额支付(如果是余额支付)
  216. * 8. 发送订单创建通知
  217. * 9. 返回订单信息
  218. */
  219. public function createOrder(int $userId, array $data): array
  220. {
  221. return DB::transaction(function () use ($userId, $data) {
  222. try {
  223. // 1. 验证基础数据
  224. $this->validateOrderData($userId, $data);
  225. // 2. 计算订单金额
  226. $amounts = $this->calculateOrderAmount(
  227. userId: $userId,
  228. addressId: $data['address_id'] ?? null,
  229. coachId: $data['coach_id'] ?? null,
  230. projectId: $data['project_id'],
  231. agentId: $data['agent_id'] ?? null,
  232. useBalance: $data['use_balance'] ?? false,
  233. distance: $data['distance'] ?? 0
  234. );
  235. // 加钟订单使用原订单地址和技师ID
  236. if (!empty($data['order_id'])) {
  237. $order = Order::findOrFail($data['order_id']);
  238. // 验证订单状态
  239. abort_if(
  240. !in_array($order->state, [
  241. OrderStatus::PAID->value,
  242. OrderStatus::ACCEPTED->value,
  243. OrderStatus::SERVICE->value,
  244. OrderStatus::SERVICE_ING->value,
  245. ]),
  246. 422,
  247. '原订单状态不允许加钟'
  248. );
  249. $data['address_id'] = $order->address_id;
  250. $data['coach_id'] = $order->coach_id;
  251. $data['service_time'] = $order->service_end_time;
  252. }
  253. // 3. 获取地址
  254. $address = MemberUser::find($userId)->addresses()
  255. ->where('id', $data['address_id'])
  256. ->firstOrFail();
  257. // 3. 创建订单
  258. $order = $this->createOrderData(['user_id' => $userId, ...$data], $amounts, $address);
  259. // 4. 创建订单相关记录
  260. $this->createRelatedRecords($order);
  261. // 5. 检测支付类型,自动进行余额支付
  262. if ($order->payment_type == PaymentMethod::BALANCE->value) {
  263. // 处理余额支付
  264. if ($amounts['balance_amount'] > 0) {
  265. $this->processBalancePayment($order);
  266. }
  267. // 更改订单状态
  268. $order->state = OrderStatus::PAID->value;
  269. $order->service_start_time = $data['service_time'];
  270. $order->service_end_time = Carbon::parse($data['service_time'])
  271. ->addMinutes($order->project->duration);
  272. $order->save();
  273. // 创建订单相关记录
  274. $this->createRelatedRecords($order);
  275. }
  276. // 6. 发送通知
  277. $this->notifyOrderCreated($order);
  278. return [
  279. 'order_id' => $order->id,
  280. 'order_no' => $order->order_no,
  281. 'total_amount' => $amounts['total_amount'],
  282. 'balance_amount' => $amounts['balance_amount'],
  283. 'pay_amount' => $amounts['pay_amount'],
  284. ];
  285. } catch (Exception $e) {
  286. $this->logError('创建订单失败', $e, $data);
  287. throw $e;
  288. }
  289. });
  290. }
  291. /**
  292. * 验证订单创建数据
  293. */
  294. private function validateOrderData(int $userId, array $data): void
  295. {
  296. // 验证用户状态
  297. $user = MemberUser::where('id', $userId)
  298. ->where('state', UserStatus::OPEN->value)
  299. ->firstOrFail();
  300. // 验证项目状态
  301. $project = Project::where('id', $data['project_id'])
  302. ->where('state', ProjectStatus::OPEN->value)
  303. ->firstOrFail();
  304. // 验证服务时间和技师状态
  305. if (! empty($data['service_time']) && ! empty($data['coach_id'])) {
  306. $this->validateServiceTimeParams($data['coach_id'], $data['service_time']);
  307. }
  308. }
  309. /**
  310. * 创建订单数据
  311. */
  312. private function createOrderData(array $data, array $amounts, object $address): Order
  313. {
  314. return Order::create([
  315. 'order_no' => $this->generateOrderNo(),
  316. 'user_id' => $data['user_id'],
  317. 'project_id' => $data['project_id'],
  318. 'coach_id' => $data['coach_id'] ?? null,
  319. 'agent_id' => $data['agent_id'] ?? null,
  320. 'address_id' => $data['address_id'],
  321. 'service_time' => $data['service_time'] ?? null,
  322. 'remark' => $data['remark'] ?? '',
  323. 'total_amount' => $amounts['total_amount'],
  324. 'balance_amount' => $amounts['balance_amount'],
  325. 'pay_amount' => $amounts['pay_amount'],
  326. 'traffic_amount' => $amounts['delivery_fee'],
  327. 'project_amount' => $amounts['project_amount'],
  328. 'discount_amount' => $amounts['coupon_amount'],
  329. 'state' => OrderStatus::CREATED->value,
  330. // 如果余额支付且未使用优惠券且未支付金额,则使用余额支付,否则使用传入的支付方式
  331. 'payment_type' => $amounts['balance_amount'] > 0 && $amounts['pay_amount'] == 0
  332. ? PaymentMethod::BALANCE->value
  333. : $data['payment_type'],
  334. 'latitude' => $address->latitude,
  335. 'longitude' => $address->longitude,
  336. 'location' => $address->location,
  337. 'address' => $address->detail,
  338. 'area_code' => $address->area_code,
  339. 'type' => $data['order_type'],
  340. ]);
  341. }
  342. private function createOrderRecord(Order $order, int $objectId, string $objectType, OrderRecordStatus $status, string $remark): OrderRecord
  343. {
  344. return OrderRecord::create([
  345. 'order_id' => $order->id,
  346. 'object_id' => $objectId,
  347. 'object_type' => $objectType,
  348. 'state' => $status->value,
  349. 'remark' => $remark,
  350. ]);
  351. }
  352. /**
  353. * 生成订单号
  354. */
  355. private function generateOrderNo(): string
  356. {
  357. return 'O'.date('YmdHis').str_pad(random_int(1, 9999), 4, '0', STR_PAD_LEFT);
  358. }
  359. /**
  360. * 处理余额支付
  361. */
  362. private function processBalancePayment(Order $order): void
  363. {
  364. $wallet = $order->user->wallet;
  365. // 检查钱包可用余额是否足够
  366. abort_if($wallet->available_balance < $order->balance_amount, 400, '钱包可用余额不足,无法完成支付');
  367. // 扣减钱包余额
  368. $wallet->decrement('total_balance', $order->balance_amount);
  369. $wallet->decrement('available_balance', $order->balance_amount);
  370. // 增加冻结金额
  371. $wallet->increment('frozen_amount', $order->balance_amount);
  372. // 创建钱包交易记录
  373. $wallet->transRecords()->create([
  374. 'amount' => -$order->balance_amount,
  375. 'trans_type' => TransactionType::PAYMENT->value,
  376. 'owner_type' => Order::class,
  377. 'owner_id' => $order->id,
  378. 'remark' => '订单支付',
  379. 'before_balance' => $wallet->total_balance + $order->balance_amount,
  380. 'after_balance' => $wallet->total_balance,
  381. 'state' => 'success',
  382. ]);
  383. }
  384. /**
  385. * 创建订单相关记录
  386. */
  387. private function createRelatedRecords(Order $order): void
  388. {
  389. // 创建订单状态记录
  390. OrderRecord::create([
  391. 'order_id' => $order->id,
  392. 'object_id' => $order->user_id,
  393. 'object_type' => MemberUser::class,
  394. 'state' => $order->state,
  395. 'remark' => $order->state === OrderStatus::PAID->value
  396. ? '余额支付成功'
  397. : '订单创建成功',
  398. ]);
  399. }
  400. /**
  401. * 发送订单创建通知
  402. */
  403. private function notifyOrderCreated(Order $order): void
  404. {
  405. // TODO: 实现订单创建通������
  406. // 1. 通知用户
  407. // event(new OrderCreatedEvent($order));
  408. // 2. 通知技师(如果有)
  409. if ($order->coach_id) {
  410. // event(new OrderAssignedToCoachEvent($order));
  411. }
  412. }
  413. /**
  414. * 获取订单地址
  415. */
  416. private function getOrderAddress(MemberUser $user, array $data, OrderType $orderType): object
  417. {
  418. // 加钟订单使用原订单地址
  419. if ($orderType === OrderType::OVERTIME) {
  420. $originalOrder = $this->getOriginalOrder($user, $data['order_id']);
  421. $data['address_id'] = $originalOrder->address_id;
  422. }
  423. abort_if(empty($data['address_id']), 400, '地址ID不能为空');
  424. return $user->addresses()
  425. ->where('id', $data['address_id'])
  426. ->firstOrFail();
  427. }
  428. /**
  429. * 验证支付方式和余额
  430. */
  431. private function validatePayment(MemberUser $user, array $data, array $amounts): void
  432. {
  433. abort_if($amounts['total_amount'] <= 0, 400, '订单金额异常');
  434. if ($data['payment_type'] === PaymentMethod::BALANCE->value) {
  435. $wallet = $user->wallet;
  436. abort_if($wallet->available_balance < $amounts['balance_amount'], 400, '可用余额不足');
  437. }
  438. }
  439. /**
  440. * 判断是否需要处理余额支付
  441. */
  442. private function shouldHandleBalancePayment(Order $order, OrderType $orderType): bool
  443. {
  444. return $order->payment_type === PaymentMethod::BALANCE->value
  445. && $orderType !== OrderType::GRAB;
  446. }
  447. /**
  448. * 验证技师状态
  449. */
  450. private function validateCoach(int $coachId): CoachUser
  451. {
  452. $coach = CoachUser::query()
  453. ->with(['info'])
  454. ->where('id', $coachId)
  455. ->where('state', TechnicianStatus::ACTIVE->value)
  456. ->first();
  457. abort_if(! $coach, 400, '技师不存在或未激活');
  458. abort_if(! $coach->info || $coach->info->state !== TechnicianAuthStatus::PASSED->value,
  459. 400, '技师未通过认证');
  460. return $coach;
  461. }
  462. // 提取方法:获取原始订单
  463. private function getOriginalOrder($user, $orderId): Order
  464. {
  465. $originalOrder = $user->orders->where('id', $orderId)
  466. ->whereIn('state', [OrderStatus::SERVING->value, OrderStatus::FINISHED->value])
  467. ->firstOrFail();
  468. return $originalOrder;
  469. }
  470. // 提取方法:准备加钟订单数据
  471. private function prepareAddTimeData($originalOrder, $data): array
  472. {
  473. if ($originalOrder->state == OrderStatus::SERVING->value) {
  474. $startTime = now();
  475. } else {
  476. $startTime = now();
  477. }
  478. return [
  479. ...$data,
  480. 'order_id' => $data['order_id'],
  481. 'address_id' => $originalOrder->address_id,
  482. 'service_time' => $startTime,
  483. 'coach_id' => $originalOrder->coach_id,
  484. ];
  485. }
  486. /**
  487. * 取消订单
  488. *
  489. * @param int $userId 用户ID
  490. * @param int $orderId 订单ID
  491. * @param string|null $reason 取消原因
  492. * @return array{message: string}
  493. *
  494. * @throws \Exception
  495. */
  496. public function cancelOrder(int $userId, int $orderId, ?string $reason = null): array
  497. {
  498. return DB::transaction(function () use ($userId, $orderId, $reason) {
  499. try {
  500. // 1. 验证订单状态
  501. $order = $this->validateOrderForCancel($userId, $orderId);
  502. // 2. 计算取消���用
  503. $cancelAmounts = $this->calculateCancelAmount($order);
  504. // 3. 处理退款
  505. $this->processCancelRefund($order, $cancelAmounts);
  506. // 4. 更新订单状态
  507. $this->updateOrderCancelStatus($order);
  508. // 5. 创建取消记录
  509. $this->createCancelRecords($order, $cancelAmounts, $reason);
  510. // 6. 发送取消通知
  511. $this->notifyCancel($order);
  512. return ['message' => '订单取消成功'];
  513. } catch (Exception $e) {
  514. $this->logError('取消订单失败', $e, [
  515. 'user_id' => $userId,
  516. 'order_id' => $orderId,
  517. 'reason' => $reason,
  518. ]);
  519. throw $e;
  520. }
  521. });
  522. }
  523. /**
  524. * 验证订单取消条件
  525. */
  526. private function validateOrderForCancel(int $userId, int $orderId): Order
  527. {
  528. // 获取并锁定订单
  529. $order = Order::where('id', $orderId)
  530. ->whereIn('state', [
  531. OrderStatus::CREATED->value,
  532. OrderStatus::PAID->value,
  533. OrderStatus::ACCEPTED->value,
  534. ])
  535. ->lockForUpdate()
  536. ->firstOrFail();
  537. // 验证订单所属用户
  538. abort_if($order->user_id !== $userId, 403, '无权操作此订单');
  539. // 验证订单是否已取消
  540. abort_if($order->state === OrderStatus::CANCELLED->value, 400, '订单已取消');
  541. return $order;
  542. }
  543. /**
  544. * 计算取消费用
  545. *
  546. * @return array{
  547. * total_refund: float,
  548. * balance_refund: float,
  549. * payment_refund: float,
  550. * penalty_amount: float
  551. * }
  552. */
  553. private function calculateCancelAmount(Order $order): array
  554. {
  555. $penaltyAmount = 0;
  556. // 计算违约金(根据订单状态和时间)
  557. if ($order->state === OrderStatus::ACCEPTED->value) {
  558. // 已接单取消,收取10%违约金
  559. $penaltyAmount = bcmul($order->total_amount, '0.1', 2);
  560. }
  561. // 计算实际退款金额
  562. $totalRefund = bcsub($order->total_amount, $penaltyAmount, 2);
  563. // 分配退款金额(优先退还支付金额)
  564. $balanceRefund = min($order->balance_amount, $totalRefund);
  565. $paymentRefund = bcsub($totalRefund, $balanceRefund, 2);
  566. return [
  567. 'total_refund' => $totalRefund,
  568. 'balance_refund' => $balanceRefund,
  569. 'payment_refund' => $paymentRefund,
  570. 'penalty_amount' => $penaltyAmount,
  571. ];
  572. }
  573. /**
  574. * 处理取消退款
  575. */
  576. private function processCancelRefund(Order $order, array $cancelAmounts): void
  577. {
  578. // 处理余额退款
  579. if ($cancelAmounts['balance_refund'] > 0) {
  580. $this->processBalanceCancelRefund($order, $cancelAmounts['balance_refund']);
  581. }
  582. // 处理支付退款
  583. if ($cancelAmounts['payment_refund'] > 0) {
  584. $this->processPaymentCancelRefund($order, $cancelAmounts['payment_refund']);
  585. }
  586. }
  587. /**
  588. * 处理余额退款
  589. */
  590. private function processBalanceCancelRefund(Order $order, float $amount): void
  591. {
  592. $wallet = $order->user->wallet;
  593. // 更新钱包余额
  594. $wallet->increment('total_balance', $amount);
  595. $wallet->increment('available_balance', $amount);
  596. // 创建钱包交易记录
  597. $wallet->transRecords()->create([
  598. 'amount' => $amount,
  599. 'trans_type' => 'cancel_refund',
  600. 'owner_type' => Order::class,
  601. 'owner_id' => $order->id,
  602. 'remark' => '订单取消退款',
  603. 'before_balance' => $wallet->total_balance - $amount,
  604. 'after_balance' => $wallet->total_balance,
  605. 'state' => 'success',
  606. ]);
  607. }
  608. /**
  609. * 处理支付退款
  610. */
  611. private function processPaymentCancelRefund(Order $order, float $amount): void
  612. {
  613. // TODO: 实现第三方支付退款逻辑
  614. // $paymentService = app(PaymentService::class);
  615. // $paymentService->refund($order->payment_no, $amount);
  616. }
  617. /**
  618. * 更新订单取消状态
  619. */
  620. private function updateOrderCancelStatus(Order $order): void
  621. {
  622. $order->update([
  623. 'state' => OrderStatus::CANCELLED->value,
  624. ]);
  625. }
  626. /**
  627. * 创建取消记录
  628. */
  629. private function createCancelRecords(Order $order, array $cancelAmounts, ?string $reason): void
  630. {
  631. // TODO: 创建取消记录
  632. // 创建取消记录
  633. // $order->cancelRecords()->create([
  634. // 'total_refund_amount' => $cancelAmounts['total_refund'],
  635. // 'balance_refund_amount' => $cancelAmounts['balance_refund'],
  636. // 'payment_refund_amount' => $cancelAmounts['payment_refund'],
  637. // 'penalty_amount' => $cancelAmounts['penalty_amount'],
  638. // 'remark' => $reason ?? '',
  639. // 'state' => 'success',
  640. // ]);
  641. // 创建订单状态记录
  642. OrderRecord::create([
  643. 'order_id' => $order->id,
  644. 'object_id' => Auth::id(),
  645. 'object_type' => MemberUser::class,
  646. 'state' => OrderRecordStatus::CANCELLED->value,
  647. 'remark' => "用户取消订单:{$reason}",
  648. ]);
  649. }
  650. /**
  651. * 发送取消通知
  652. */
  653. private function notifyCancel(Order $order): void
  654. {
  655. // TODO: 实现取消通知逻辑
  656. // 1. ��知用户
  657. // event(new OrderCancelledEvent($order));
  658. // 2. 通知技师
  659. if ($order->coach_id) {
  660. // event(new OrderCancelledToCoachEvent($order));
  661. }
  662. }
  663. /**
  664. * 结束订单
  665. */
  666. public function finishOrder(int $userId, int $orderId): array
  667. {
  668. return DB::transaction(function () use ($userId, $orderId) {
  669. try {
  670. // 1. 验证用户和订单
  671. $order = $this->validateOrderForFinish($userId, $orderId);
  672. // 2. 验证技师状���
  673. $coach = $this->validateCoach($order->coach_id);
  674. // 4. 完成订单
  675. $this->completeOrder($order, $userId);
  676. // 5. ���知技师
  677. // event(new OrderFinishedEvent($order));
  678. return ['message' => '订单已完成'];
  679. } catch (Exception $e) {
  680. $this->logFinishOrderError($e, $userId, $orderId);
  681. throw $e;
  682. }
  683. });
  684. }
  685. /**
  686. * 验证订单完成条件
  687. */
  688. private function validateOrderForFinish(int $userId, int $orderId): Order
  689. {
  690. // 验证用户状态
  691. $user = MemberUser::where('id', $userId)
  692. ->where('state', UserStatus::OPEN->value)
  693. ->firstOrFail();
  694. // 验证订单状态
  695. $order = Order::where('user_id', $userId)
  696. ->where('id', $orderId)
  697. ->where('state', OrderStatus::SERVING->value)
  698. ->lockForUpdate()
  699. ->firstOrFail();
  700. return $order;
  701. }
  702. /**
  703. * 完成订单
  704. */
  705. private function completeOrder(Order $order, int $userId): void
  706. {
  707. // 1. 创建订单记录
  708. OrderRecord::create([
  709. 'order_id' => $order->id,
  710. 'object_id' => $userId,
  711. 'object_type' => MemberUser::class,
  712. 'state' => OrderRecordStatus::COMPLETED->value,
  713. 'remark' => '服务完成',
  714. ]);
  715. // 2. 更新订单状态
  716. $order->state = OrderStatus::FINISHED->value;
  717. $order->save();
  718. }
  719. /**
  720. * 记录订单完成错误日志
  721. */
  722. private function logFinishOrderError(Exception $e, int $userId, int $orderId): void
  723. {
  724. Log::error('结束订单失败:', [
  725. 'message' => $e->getMessage(),
  726. 'user_id' => $userId,
  727. 'order_id' => $orderId,
  728. 'trace' => $e->getTraceAsString(),
  729. ]);
  730. }
  731. /**
  732. * 确认技师离开
  733. */
  734. public function confirmLeave(int $userId, int $orderId): array
  735. {
  736. return DB::transaction(function () use ($userId, $orderId) {
  737. try {
  738. // 1. 参数校验
  739. $order = Order::where('user_id', $userId)
  740. ->where('id', $orderId)
  741. ->where('state', OrderStatus::FINISHED->value) // 订单状态必须是服务结束
  742. ->firstOrFail();
  743. if (! $order) {
  744. throw new Exception('订单不能撤离');
  745. }
  746. // 2. 添加订单撤离记录
  747. OrderRecord::create([
  748. 'order_id' => $orderId,
  749. 'object_id' => $userId,
  750. 'object_type' => MemberUser::class,
  751. 'state' => OrderRecordStatus::LEFT->value,
  752. 'remark' => '技师已离开',
  753. ]);
  754. // 3. 修改订单状态为撤离
  755. $order->state = OrderStatus::LEFT->value;
  756. $order->save();
  757. return ['message' => '已确技师离开'];
  758. } catch (Exception $e) {
  759. Log::error('确认技师离开失败:', [
  760. 'message' => $e->getMessage(),
  761. 'user_id' => $userId,
  762. 'order_id' => $orderId,
  763. ]);
  764. throw $e;
  765. }
  766. });
  767. }
  768. /**
  769. * 获取订单列表
  770. *
  771. * @param int $userId 用户ID
  772. * @param array{
  773. * state: ?string,
  774. * start_date: ?string,
  775. * end_date: ?string,
  776. * project_id: ?int,
  777. * coach_id: ?int,
  778. * order_no: ?string,
  779. * per_page: ?int,
  780. * page: ?int
  781. * } $filters 过滤条件
  782. *
  783. * @throws \Exception
  784. */
  785. public function getOrderList(int $userId, array $filters = [])
  786. {
  787. try {
  788. // 1. 验证用户
  789. $user = $this->validateUserForQuery($userId);
  790. // 2. 构建基础查询
  791. $query = $this->buildOrderListQuery($user);
  792. // 3. 应用过滤条件
  793. $this->applyOrderFilters($query, $filters);
  794. // 4. 加载关联数据并分页
  795. return $this->paginateOrderList($query, $filters);
  796. } catch (Exception $e) {
  797. $this->logError('获取订单列表失败', $e, [
  798. 'user_id' => $userId,
  799. 'filters' => $filters,
  800. ]);
  801. throw $e;
  802. }
  803. }
  804. /**
  805. * 验证用户查询权限
  806. */
  807. private function validateUserForQuery(int $userId): MemberUser
  808. {
  809. return MemberUser::where('id', $userId)
  810. ->where('state', UserStatus::OPEN->value)
  811. ->firstOrFail();
  812. }
  813. /**
  814. * 构建订单列表基础查询
  815. */
  816. private function buildOrderListQuery(MemberUser $user)
  817. {
  818. return $user->orders()
  819. ->with([
  820. 'coach' => function ($query) {
  821. $query->with(['info' => function ($q) {
  822. $q->select(['id', 'coach_id', 'nickname', 'avatar', 'gender']);
  823. }]);
  824. },
  825. 'project:id,title,subtitle,duration,cover',
  826. 'records' => function ($query) {
  827. $query->orderBy('created_at', 'desc')
  828. ->select(['id', 'order_id', 'state', 'remark', 'created_at']);
  829. },
  830. // 'evaluation:id,order_id,score,content,created_at',
  831. ]);
  832. }
  833. /**
  834. * 分页获取订单列表
  835. */
  836. private function paginateOrderList($query, array $filters)
  837. {
  838. $paginatedOrders = $query->orderBy('created_at', 'desc')
  839. ->paginate(
  840. perPage: $filters['per_page'] ?? 10,
  841. page: $filters['page'] ?? 1
  842. );
  843. $formattedOrders = $paginatedOrders->map(function ($order) {
  844. return $this->formatOrderListItem($order);
  845. });
  846. return [
  847. 'items' => $formattedOrders,
  848. 'total' => $paginatedOrders->total(),
  849. ];
  850. }
  851. /**
  852. * �������化订��列表项
  853. */
  854. private function formatOrderListItem(Order $order): array
  855. {
  856. return [
  857. 'order_id' => $order->id,
  858. 'order_no' => $order->order_no,
  859. 'state' => $order->state,
  860. 'state_description' => $this->getOrderStateDescription($order->state),
  861. 'total_amount' => $order->total_amount,
  862. 'service_time' => $order->service_time,
  863. 'created_at' => $order->created_at->toDateTimeString(),
  864. 'coach' => $order->coach ? [
  865. 'id' => $order->coach->id,
  866. 'nickname' => $order->coach->info->nickname,
  867. 'avatar' => $order->coach->info->avatar,
  868. ] : null,
  869. 'project' => $order->project ? [
  870. 'id' => $order->project->id,
  871. 'title' => $order->project->title,
  872. 'subtitle' => $order->project->subtitle,
  873. 'duration' => $order->project->duration,
  874. 'cover_image' => $order->project->cover_image,
  875. ] : null,
  876. 'address' => $order->address ? [
  877. 'location' => $order->location,
  878. 'address' => $order->address,
  879. ] : null,
  880. 'latest_record' => $order->records->first() ? [
  881. 'state' => $order->records->first()->state,
  882. 'remark' => $order->records->first()->remark,
  883. 'created_at' => $order->records->first()->created_at->format('Y-m-d H:i:s'),
  884. ] : null,
  885. 'evaluation' => $order->evaluation ? [
  886. 'score' => $order->evaluation->score,
  887. 'content' => $order->evaluation->content,
  888. ] : null,
  889. ];
  890. }
  891. /**
  892. * 获取订单详情
  893. *
  894. * @param int $userId 用户ID
  895. * @param int $orderId 订单ID
  896. * @return array 订单详情
  897. *
  898. * @throws \Exception
  899. */
  900. public function getOrderDetail(int $userId, int $orderId): array
  901. {
  902. try {
  903. // 1. 验证订单权限
  904. $order = $this->validateOrderAccess($userId, $orderId);
  905. // 2. 加载订单关联数据
  906. $order->load([
  907. 'coach.info' => function ($query) {
  908. $query->select(['id', 'coach_id', 'nickname', 'avatar', 'gender']);
  909. },
  910. 'project:id,title,subtitle,duration,cover',
  911. 'records' => function ($query) {
  912. $query->orderBy('created_at', 'desc')
  913. ->select(['id', 'order_id', 'state', 'remark', 'created_at']);
  914. },
  915. // 'evaluation' => function ($query) {
  916. // $query->select(['id', 'order_id', 'score', 'content', 'images', 'created_at']);
  917. // },
  918. ]);
  919. // 3. 格式化返回数据
  920. return $this->formatOrderDetail($order);
  921. } catch (Exception $e) {
  922. $this->logError('获取订单详情失败', $e, [
  923. 'user_id' => $userId,
  924. 'order_id' => $orderId,
  925. ]);
  926. throw $e;
  927. }
  928. }
  929. /**
  930. * 验证订单访问权限
  931. */
  932. private function validateOrderAccess(int $userId, int $orderId): Order
  933. {
  934. return Order::where('id', $orderId)
  935. ->where('user_id', $userId)
  936. ->firstOrFail();
  937. }
  938. /**
  939. * 格式化订单详情数据
  940. */
  941. private function formatOrderDetail(Order $order): array
  942. {
  943. return [
  944. 'order_id' => $order->id,
  945. 'order_no' => $order->order_no,
  946. 'state' => $order->state,
  947. 'state_description' => $this->getOrderStateDescription($order->state),
  948. 'total_amount' => $order->total_amount,
  949. 'balance_amount' => $order->balance_amount,
  950. 'pay_amount' => $order->pay_amount,
  951. 'delivery_fee' => $order->delivery_fee,
  952. 'project_amount' => $order->project_amount,
  953. 'coupon_amount' => $order->coupon_amount,
  954. 'service_time' => $order->service_time,
  955. 'created_at' => $order->created_at->toDateTimeString(),
  956. 'remark' => $order->remark,
  957. 'coach' => $order->coach ? [
  958. 'id' => $order->coach->id,
  959. 'nickname' => $order->coach->info->nickname,
  960. 'avatar' => $order->coach->info->avatar,
  961. 'gender' => $order->coach->info->gender,
  962. 'score' => $order->coach->info?->score,
  963. ] : null,
  964. 'project' => $order->project ? [
  965. 'id' => $order->project->id,
  966. 'title' => $order->project->title,
  967. 'subtitle' => $order->project->subtitle,
  968. 'duration' => $order->project->duration,
  969. 'cover' => $order->project->cover,
  970. ] : null,
  971. 'address' => $order->address ? [
  972. 'id' => $order->address_id,
  973. 'location' => $order->location,
  974. 'address' => $order->address,
  975. ] : null,
  976. 'records' => $order->records->map(function ($record) {
  977. return [
  978. 'id' => $record->id,
  979. 'state' => $record->state,
  980. 'remark' => $record->remark,
  981. 'created_at' => $record->created_at->format('Y-m-d H:i:s'),
  982. ];
  983. })->toArray(),
  984. // 'evaluation' => $order->evaluation ? [
  985. // 'score' => $order->evaluation->score,
  986. // 'content' => $order->evaluation->content,
  987. // 'images' => $order->evaluation->images,
  988. // 'created_at' => $order->evaluation->created_at->format('Y-m-d H:i:s'),
  989. // ] : null,
  990. ];
  991. }
  992. /**
  993. * 应用订单过滤条件
  994. */
  995. private function applyOrderFilters($query, array $filters): void
  996. {
  997. // 按状态筛选
  998. if (! empty($filters['state'])) {
  999. $query->where('state', $filters['state']);
  1000. }
  1001. // 按时间范围筛选
  1002. if (! empty($filters['start_date'])) {
  1003. $query->where('created_at', '>=', $filters['start_date']);
  1004. }
  1005. if (! empty($filters['end_date'])) {
  1006. $query->where('created_at', '<=', $filters['end_date']);
  1007. }
  1008. // 按服务类型筛选
  1009. if (! empty($filters['project_id'])) {
  1010. $query->where('project_id', $filters['project_id']);
  1011. }
  1012. // 按技师筛选
  1013. if (! empty($filters['coach_id'])) {
  1014. $query->where('coach_id', $filters['coach_id']);
  1015. }
  1016. // 按订单号搜索
  1017. if (! empty($filters['order_no'])) {
  1018. $query->where('order_no', 'like', "%{$filters['order_no']}%");
  1019. }
  1020. }
  1021. /**
  1022. * 获取订单状态描述
  1023. */
  1024. private function getOrderStateDescription(string $state): string
  1025. {
  1026. return match ($state) {
  1027. OrderStatus::CREATED->value => '待支付',
  1028. OrderStatus::PAID->value => '待接单',
  1029. OrderStatus::ACCEPTED->value => '已接单',
  1030. OrderStatus::DEPARTED->value => '已出发',
  1031. OrderStatus::ARRIVED->value => '已到达',
  1032. OrderStatus::SERVING->value => '服务中',
  1033. OrderStatus::FINISHED->value => '已完成',
  1034. OrderStatus::CANCELLED->value => '已取消',
  1035. OrderStatus::REFUNDED->value => '已退款',
  1036. default => '未知状态',
  1037. };
  1038. }
  1039. /**
  1040. * 订单退款
  1041. *
  1042. * @param int $orderId 订单ID
  1043. * @return array{message: string}
  1044. *
  1045. * @throws \Exception
  1046. */
  1047. public function refundOrder(int $orderId): array
  1048. {
  1049. return DB::transaction(function () use ($orderId) {
  1050. try {
  1051. // 1. 验证订单状态
  1052. $order = $this->validateOrderForRefund($orderId);
  1053. // 2. 计算退款金额
  1054. $refundAmounts = $this->calculateRefundAmount($order);
  1055. // 3. 处理退款
  1056. $this->processRefund($order, $refundAmounts);
  1057. // 4. 更新订单状态
  1058. $this->updateOrderRefundStatus($order);
  1059. // 5. 记录退款操作
  1060. $this->createRefundRecords($order, $refundAmounts);
  1061. // 6. 通知相关方
  1062. $this->notifyRefund($order);
  1063. return ['message' => '退款成功'];
  1064. } catch (Exception $e) {
  1065. $this->logError('订单退款失败', $e, [
  1066. 'order_id' => $orderId,
  1067. ]);
  1068. throw $e;
  1069. }
  1070. });
  1071. }
  1072. /**
  1073. * 验证订单退款条件
  1074. */
  1075. private function validateOrderForRefund(int $orderId): Order
  1076. {
  1077. // 获取并锁定订单,防止并发操作
  1078. $order = Order::where('id', $orderId)
  1079. ->whereIn('state', [
  1080. OrderStatus::PAID->value,
  1081. OrderStatus::ACCEPTED->value,
  1082. OrderStatus::DEPARTED->value,
  1083. ])
  1084. ->lockForUpdate()
  1085. ->firstOrFail();
  1086. // 验证当前用户是否为订单所有者
  1087. $user = Auth::user();
  1088. abort_if($order->user_id !== $user->id, 403, '无权操作此订单');
  1089. // 检查订单是否已经退款
  1090. abort_if($order->state === OrderStatus::REFUNDED->value, 400, '订单已退款');
  1091. return $order;
  1092. }
  1093. /**
  1094. * 计算退款金额
  1095. */
  1096. private function calculateRefundAmount(Order $order): array
  1097. {
  1098. // 初始化扣除金额
  1099. $deductAmount = 0;
  1100. // 根据订单状态计算违约金
  1101. switch ($order->state) {
  1102. case OrderStatus::ACCEPTED->value:
  1103. // 已接单状态扣除订单金额的20%作为违约金
  1104. $deductAmount = bcmul($order->total_amount, '0.2', 2);
  1105. break;
  1106. case OrderStatus::DEPARTED->value:
  1107. // 已出发状态扣除订单金额的50%作为违约金
  1108. $deductAmount = bcmul($order->total_amount, '0.5', 2);
  1109. break;
  1110. }
  1111. // 计算实际可��金额(总金额减去违约金)
  1112. $totalRefund = bcsub($order->total_amount, $deductAmount, 2);
  1113. // 优先退还用户使用的余额部分
  1114. $balanceRefund = min($order->balance_amount, $totalRefund);
  1115. // 剩余部分退还到支付账户
  1116. $paymentRefund = bcsub($totalRefund, $balanceRefund, 2);
  1117. return [
  1118. 'total_refund' => $totalRefund, // 总退款金额
  1119. 'balance_amount' => $balanceRefund, // 退还到余额的金额
  1120. 'payment_refund' => $paymentRefund, // 退还到支付账户的金额
  1121. 'deduct_amount' => $deductAmount, // 扣除的违约金
  1122. ];
  1123. }
  1124. /**
  1125. * 处理退款操作
  1126. */
  1127. private function processRefund(Order $order, array $refundAmounts): void
  1128. {
  1129. // 处理余额退款部分
  1130. if ($refundAmounts['balance_refund'] > 0) {
  1131. $this->processBalanceRefund($order, $refundAmounts['balance_refund']);
  1132. }
  1133. // 处理支付退款部分
  1134. if ($refundAmounts['payment_refund'] > 0) {
  1135. $this->processPaymentRefund($order, $refundAmounts['payment_refund']);
  1136. }
  1137. }
  1138. /**
  1139. * 处理余额退款
  1140. */
  1141. private function processBalanceRefund(Order $order, float $amount): void
  1142. {
  1143. $wallet = $order->user->wallet;
  1144. // 增加用户钱包总余额
  1145. $wallet->increment('total_balance', $amount);
  1146. // 增加可用余额
  1147. $wallet->increment('available_balance', $amount);
  1148. // 创建退款交易记录
  1149. $wallet->transRecords()->create([
  1150. 'amount' => $amount,
  1151. 'trans_type' => 'refund',
  1152. 'owner_type' => Order::class,
  1153. 'owner_id' => $order->id,
  1154. 'remark' => '订单退款',
  1155. 'before_balance' => $wallet->total_balance - $amount,
  1156. 'after_balance' => $wallet->total_balance,
  1157. 'state' => 'success',
  1158. ]);
  1159. }
  1160. /**
  1161. * 处理支付退款
  1162. */
  1163. private function processPaymentRefund(Order $order, float $amount): void
  1164. {
  1165. // TODO: 实现第三方支付退款逻辑
  1166. // $paymentService = app(PaymentService::class);
  1167. // $paymentService->refund($order->payment_no, $amount);
  1168. }
  1169. /**
  1170. * 更新订单退款状态
  1171. */
  1172. private function updateOrderRefundStatus(Order $order): void
  1173. {
  1174. $order->update([
  1175. 'state' => OrderStatus::REFUNDED->value,
  1176. 'refund_time' => now(),
  1177. ]);
  1178. }
  1179. /**
  1180. * 创建退款记录
  1181. */
  1182. private function createRefundRecords(Order $order, array $refundAmounts): void
  1183. {
  1184. // 创建退款记录
  1185. $refundRecord = $order->refundRecords()->create([
  1186. 'total_refund_amount' => $refundAmounts['total_refund'],
  1187. 'balance_refund_amount' => $refundAmounts['balance_refund'],
  1188. 'payment_refund_amount' => $refundAmounts['payment_refund'],
  1189. 'deduct_amount' => $refundAmounts['deduct_amount'],
  1190. 'state' => 'success',
  1191. 'remark' => '用户申请退款',
  1192. ]);
  1193. // 创建订单状态记录
  1194. OrderRecord::create([
  1195. 'order_id' => $order->id,
  1196. 'object_id' => Auth::id(),
  1197. 'object_type' => MemberUser::class,
  1198. 'state' => OrderRecordStatus::REFUNDING->value,
  1199. 'remark' => '订单退款中',
  1200. ]);
  1201. }
  1202. /**
  1203. * 发送退款通知
  1204. */
  1205. private function notifyRefund(Order $order): void
  1206. {
  1207. // TODO: 实现退款通知逻辑
  1208. // 1. 通知用户
  1209. // event(new OrderRefundedEvent($order));
  1210. // 2. 通知技师
  1211. if ($order->coach_id) {
  1212. // event(new OrderRefundedToCoachEvent($order));
  1213. }
  1214. }
  1215. /**
  1216. * 获取代理商配置
  1217. */
  1218. public function getAgentConfig(int $agentId): array
  1219. {
  1220. $agent = AgentInfo::where('id', $agentId)
  1221. ->where('state', 'enable')
  1222. ->firstOrFail();
  1223. // $config = AgentConfig::where('agent_id', $agentId)->firstOrFail();
  1224. return [
  1225. // 'min_distance' => $config->min_distance,
  1226. // 'min_fee' => $config->min_fee,
  1227. // 'per_km_fee' => $config->per_km_fee
  1228. ];
  1229. }
  1230. /**
  1231. * 获取技师配置
  1232. */
  1233. public function getCoachConfig(int $coachId): array
  1234. {
  1235. $coach = CoachUser::where('id', $coachId)
  1236. ->where('state', 'enable')
  1237. ->where('auth_state', 'passed')
  1238. ->firstOrFail();
  1239. // $config = CoachConfig::where('coach_id', $coachId)->firstOrFail();
  1240. return [
  1241. // 'delivery_fee_type' => $config->delivery_fee_type,
  1242. // 'charge_delivery_fee' => $config->charge_delivery_fee
  1243. ];
  1244. }
  1245. /**
  1246. * 计算路费
  1247. *
  1248. * @param int $coachId 技师ID
  1249. * @param int $projectId 项目ID
  1250. * @param int|null $agentId 代理商ID
  1251. * @param float $distance 距离(公里)
  1252. * @return float 路费金额
  1253. *
  1254. * @throws \Exception
  1255. */
  1256. public function calculateDeliveryFee(
  1257. int $coachId,
  1258. int $projectId,
  1259. ?int $agentId,
  1260. float $distance
  1261. ): float {
  1262. try {
  1263. // 1. 验证基础参数
  1264. $this->validateDeliveryFeeParams($coachId, $projectId, $distance);
  1265. // 2. 获取计费规则
  1266. $feeRules = $this->getDeliveryFeeRules($coachId, $agentId);
  1267. // 3. 计算路费
  1268. return $this->calculateFeeByRules($distance, $feeRules);
  1269. } catch (Exception $e) {
  1270. $this->logError('计算路费失败', $e, [
  1271. 'coach_id' => $coachId,
  1272. 'project_id' => $projectId,
  1273. 'agent_id' => $agentId,
  1274. 'distance' => $distance,
  1275. ]);
  1276. throw $e;
  1277. }
  1278. }
  1279. /**
  1280. * 验证路费计算参数
  1281. */
  1282. private function validateDeliveryFeeParams(int $coachId, int $projectId, float $distance): void
  1283. {
  1284. // 验证技师状态
  1285. $coach = $this->validateCoach($coachId);
  1286. // 验证项目状态
  1287. $project = Project::where('id', $projectId)
  1288. ->where('state', ProjectStatus::OPEN->value)
  1289. ->firstOrFail();
  1290. // 验证距离有效性
  1291. abort_if($distance < 0, 400, '距离计算错误');
  1292. }
  1293. /**
  1294. * 获取路费计算规则
  1295. *
  1296. * @return array{
  1297. * min_distance: float,
  1298. * min_fee: float,
  1299. * per_km_fee: float,
  1300. * max_distance: float,
  1301. * max_fee: float,
  1302. * free_distance: float
  1303. * }
  1304. */
  1305. private function getDeliveryFeeRules(int $coachId, ?int $agentId): array
  1306. {
  1307. // 1. 获取系统默认规则
  1308. $defaultRules = $this->getDefaultDeliveryFeeRules();
  1309. // 2. 获取代理商规则(如果有)
  1310. $agentRules = $agentId ? $this->getAgentDeliveryFeeRules($agentId) : [];
  1311. // 3. 获取技师个性化规则
  1312. $coachRules = $this->getCoachDeliveryFeeRules($coachId);
  1313. // 4. 合并规则,优先级:技师 > 代理商 > 系统默认
  1314. return array_merge(
  1315. $defaultRules,
  1316. $agentRules,
  1317. $coachRules
  1318. );
  1319. }
  1320. /**
  1321. * 获取系统默认路费规则
  1322. */
  1323. private function getDefaultDeliveryFeeRules(): array
  1324. {
  1325. // TODO: 从配置表中获取系统默认路费规则
  1326. return [
  1327. 'min_distance' => 3.0, // 最小计费距离(公里)
  1328. 'min_fee' => 10.0, // 最小路费(元)
  1329. 'per_km_fee' => 3.0, // 每公里费用(元)
  1330. 'max_distance' => 120.0, // 最大服务距离(公里)
  1331. 'max_fee' => 50.0, // 最大路费(元)
  1332. 'free_distance' => 1.0, // 免费服务距离(公里)
  1333. ];
  1334. }
  1335. /**
  1336. * 获取代理商路费规则
  1337. */
  1338. private function getAgentDeliveryFeeRules(int $agentId): array
  1339. {
  1340. // $agentConfig = AgentConfig::where('agent_id', $agentId)
  1341. // ->where('state', 'enable')
  1342. // ->first();
  1343. // if (! $agentConfig) {
  1344. // return [];
  1345. // }
  1346. // return [
  1347. // 'min_distance' => $agentConfig->min_distance,
  1348. // 'min_fee' => $agentConfig->min_fee,
  1349. // 'per_km_fee' => $agentConfig->per_km_fee,
  1350. // 'max_distance' => $agentConfig->max_distance,
  1351. // 'max_fee' => $agentConfig->max_fee,
  1352. // 'free_distance' => $agentConfig->free_distance,
  1353. // ];
  1354. return [];
  1355. }
  1356. /**
  1357. * 获取技师路费规则
  1358. */
  1359. private function getCoachDeliveryFeeRules(int $coachId): array
  1360. {
  1361. // TODO: 从配置表中获取技师个性化路费规则
  1362. // $coachConfig = CoachConfig::where('coach_id', $coachId)
  1363. // ->where('state', 'enable')
  1364. // ->first();
  1365. $coachConfig = null;
  1366. if (! $coachConfig) {
  1367. return [];
  1368. }
  1369. // 如果技师设置了不收取路费
  1370. if (! $coachConfig->charge_delivery_fee) {
  1371. return [
  1372. 'min_fee' => 0,
  1373. 'per_km_fee' => 0,
  1374. 'max_fee' => 0,
  1375. ];
  1376. }
  1377. return [
  1378. 'min_distance' => $coachConfig->min_distance,
  1379. 'min_fee' => $coachConfig->min_fee,
  1380. 'per_km_fee' => $coachConfig->per_km_fee,
  1381. 'max_distance' => $coachConfig->max_distance,
  1382. 'max_fee' => $coachConfig->max_fee,
  1383. 'free_distance' => $coachConfig->free_distance,
  1384. ];
  1385. }
  1386. /**
  1387. * 根据规则计算路费
  1388. *
  1389. * @param float $distance 距离(公里)
  1390. * @param array{
  1391. * min_distance: float, // 最小计费距离(公里)
  1392. * min_fee: float, // ���小路费(元)
  1393. * per_km_fee: float, // 每公里费用(元)
  1394. * max_distance: float, // 最大服务距离(公里)
  1395. * max_fee: float, // 最大路费(元)
  1396. * free_distance: float // 免费服务距离(公里)
  1397. * } $rules 计费规则
  1398. * @return float 路费金额(元)
  1399. */
  1400. private function calculateFeeByRules(float $distance, array $rules): float
  1401. {
  1402. // 1. 检查是否超出最大服务距离
  1403. abort_if(
  1404. $distance > $rules['max_distance'],
  1405. 400,
  1406. sprintf('超出最大服务距离 %.1f 公里', $rules['max_distance'])
  1407. );
  1408. // 2. 检查是否在免费距离内
  1409. if ($distance <= $rules['free_distance']) {
  1410. return 0;
  1411. }
  1412. // 3. 计算实际计费距离
  1413. $chargeDistance = max(0, $distance - $rules['free_distance']);
  1414. // 4. 检查是否达到最小计费距离
  1415. if ($chargeDistance < $rules['min_distance']) {
  1416. return $rules['min_fee'];
  1417. }
  1418. // 5. 计算基础路费
  1419. $fee = bcmul($chargeDistance, $rules['per_km_fee'], 2);
  1420. // 6. 应用最小路费限制
  1421. $fee = max($fee, $rules['min_fee']);
  1422. // 7. 应用最大路费限制
  1423. $fee = min($fee, $rules['max_fee']);
  1424. return $fee;
  1425. }
  1426. /**
  1427. * 计算两点之间的距离
  1428. *
  1429. * @param float $lat1 起点纬度
  1430. * @param float $lng1 起点经度
  1431. * @param float $lat2 终点纬度
  1432. * @param float $lng2 终点经度
  1433. * @return float 距离(公里)
  1434. */
  1435. private function getDistance(float $lat1, float $lng1, float $lat2, float $lng2): float
  1436. {
  1437. // 将角度转为弧度
  1438. $radLat1 = deg2rad($lat1);
  1439. $radLat2 = deg2rad($lat2);
  1440. $radLng1 = deg2rad($lng1);
  1441. $radLng2 = deg2rad($lng2);
  1442. // 地球半径(公里)
  1443. $earthRadius = 6371;
  1444. // 计算距离
  1445. $distance = acos(
  1446. sin($radLat1) * sin($radLat2) +
  1447. cos($radLat1) * cos($radLat2) * cos($radLng1 - $radLng2)
  1448. ) * $earthRadius;
  1449. // 保留2位小数
  1450. return round($distance, 2);
  1451. }
  1452. /**
  1453. * 计算订单金额
  1454. *
  1455. * @param int $userId 用户ID
  1456. * @param int|null $addressId 地址ID
  1457. * @param int|null $coachId 技师ID
  1458. * @param int $projectId 项目ID
  1459. * @param int|null $agentId 代理商ID
  1460. * @param bool $useBalance 是否使用余额
  1461. * @param float $distance 距离
  1462. * @param float $lat 纬度
  1463. * @param float $lng 经度
  1464. * @return array{
  1465. * total_amount: float,
  1466. * balance_amount: float,
  1467. * pay_amount: float,
  1468. * coupon_amount: float,
  1469. * project_amount: float,
  1470. * delivery_fee: float
  1471. * }
  1472. *
  1473. * @throws \Exception
  1474. */
  1475. public function calculateOrderAmount(
  1476. int $userId,
  1477. ?int $addressId,
  1478. ?int $coachId,
  1479. int $projectId,
  1480. ?int $agentId = null,
  1481. bool $useBalance = false,
  1482. float $distance = 0,
  1483. float $lat = 0,
  1484. float $lng = 0
  1485. ): array {
  1486. try {
  1487. // 1. 验证用户状态和权限
  1488. $user = $this->validateUserForCalculation($userId);
  1489. // 2. 获取项目信息和价格(包含代理���价格)
  1490. $project = $this->getProjectWithPrice($projectId, $agentId);
  1491. // 3. 计算路费(如果有技师)
  1492. $deliveryFee = $this->calculateDeliveryFeeForOrder(
  1493. coachId: $coachId,
  1494. projectId: $projectId,
  1495. agentId: $agentId,
  1496. distance: $distance,
  1497. addressId: $addressId,
  1498. lat: $lat,
  1499. lng: $lng
  1500. );
  1501. // 4. 计算优惠金额(优惠券、活动等)
  1502. $discountAmount = $this->calculateDiscountAmount($projectId, $userId);
  1503. // 5. 计算订单总金额(项目价格 + 路费 - 优惠金额)
  1504. $totalAmount = $this->calculateTotalAmount($project->price, $deliveryFee, $discountAmount);
  1505. // 6. 处理余额支付分配(优先使用余额)
  1506. $paymentAmounts = $this->calculatePaymentDistribution(
  1507. user: $user,
  1508. totalAmount: $totalAmount,
  1509. useBalance: $useBalance
  1510. );
  1511. // 7. 返回计算结果
  1512. return [
  1513. 'total_amount' => $totalAmount, // 订单总金额
  1514. 'balance_amount' => $paymentAmounts['balance_amount'], // 余额支付金额
  1515. 'pay_amount' => $paymentAmounts['pay_amount'], // 需要支付金额
  1516. 'coupon_amount' => $discountAmount, // 优惠金额
  1517. 'project_amount' => $project->price, // 项目原价
  1518. 'delivery_fee' => $deliveryFee, // 路费
  1519. ];
  1520. } catch (Exception $e) {
  1521. // 记录错误日志
  1522. $this->logError('计算订单金额失败', $e, [
  1523. 'user_id' => $userId,
  1524. 'project_id' => $projectId,
  1525. 'coach_id' => $coachId,
  1526. 'address_id' => $addressId,
  1527. ]);
  1528. throw $e;
  1529. }
  1530. }
  1531. /**
  1532. * 验证用户状态
  1533. */
  1534. private function validateUserForCalculation(int $userId): MemberUser
  1535. {
  1536. $user = MemberUser::with('wallet')
  1537. ->where('id', $userId)
  1538. ->where('state', UserStatus::OPEN->value)
  1539. ->first();
  1540. abort_if(! $user, 404, '用户不存在或状态异常');
  1541. return $user;
  1542. }
  1543. /**
  1544. * 获取项目信息和价格
  1545. */
  1546. private function getProjectWithPrice(int $projectId, ?int $agentId): Project
  1547. {
  1548. // 获取基础项目信息
  1549. $project = Project::where('id', $projectId)
  1550. ->where('state', ProjectStatus::OPEN->value)
  1551. ->first();
  1552. abort_if(! $project, 404, '项目不���在或���态异常');
  1553. // 如果有代理商,获取代理商价格
  1554. if ($agentId) {
  1555. $agentProject = $this->getAgentProjectPrice($agentId, $projectId);
  1556. if ($agentProject) {
  1557. $project->price = $agentProject->price;
  1558. }
  1559. }
  1560. return $project;
  1561. }
  1562. /**
  1563. * 获取代理商项目价格
  1564. */
  1565. private function getAgentProjectPrice(int $agentId, int $projectId): ?object
  1566. {
  1567. return DB::table('agent_project')
  1568. ->where('agent_id', $agentId)
  1569. ->where('project_id', $projectId)
  1570. ->where('state', 'enable')
  1571. ->first();
  1572. }
  1573. /**
  1574. * 计算订单路费
  1575. */
  1576. private function calculateDeliveryFeeForOrder(
  1577. ?int $coachId,
  1578. int $projectId,
  1579. ?int $agentId,
  1580. float $distance,
  1581. ?int $addressId,
  1582. ?float $lat,
  1583. ?float $lng
  1584. ): float {
  1585. // 如果没有技师,无需计算路费
  1586. if (! $coachId) {
  1587. return 0;
  1588. }
  1589. if (! $addressId && ! $lat && ! $lng) {
  1590. return 0;
  1591. }
  1592. // 如果距离为0,需要重新计算距离
  1593. if ($distance <= 0) {
  1594. $distance = $this->calculateDistance($coachId, $addressId, $lat, $lng);
  1595. }
  1596. return $this->calculateDeliveryFee($coachId, $projectId, $agentId, $distance);
  1597. }
  1598. /**
  1599. * 获取技师位置信息
  1600. */
  1601. private function getCoachLocation(int $coachId): array
  1602. {
  1603. // 从技师服务获取最新位置信息
  1604. $location = $this->coachService->getLocation($coachId);
  1605. // 如果没有位置信息,返回系统默认位置
  1606. if (empty($location)) {
  1607. return [
  1608. 'latitude' => config('business.default_latitude', 0),
  1609. 'longitude' => config('business.default_longitude', 0),
  1610. ];
  1611. }
  1612. // 格式化位置数据
  1613. return [
  1614. 'latitude' => (float) $location->latitude,
  1615. 'longitude' => (float) $location->longitude,
  1616. ];
  1617. }
  1618. /**
  1619. * 计算技师与服务地址的距离
  1620. */
  1621. private function calculateDistance(int $coachId, int $addressId, float $lat, float $lng): float
  1622. {
  1623. try {
  1624. // 如果提供了地址ID,优先使用地址表中的经纬度
  1625. if ($addressId > 0) {
  1626. $address = MemberAddress::find($addressId);
  1627. // 使用地址的经纬度,如果没有则使用传入的经纬度
  1628. $lat = $address?->latitude ?? $lat;
  1629. $lng = $address?->longitude ?? $lng;
  1630. }
  1631. // 从Redis获取技师的两个位置点信息
  1632. // 获取常用地址位置(如家庭地址)
  1633. $homeLocation = Redis::geopos(
  1634. 'coach_locations',
  1635. $coachId.'_'.TechnicianLocationType::COMMON->value
  1636. );
  1637. // 获取当前实时位置
  1638. $workLocation = Redis::geopos(
  1639. 'coach_locations',
  1640. $coachId.'_'.TechnicianLocationType::CURRENT->value
  1641. );
  1642. $distances = [];
  1643. // 计算与常用地址的距离
  1644. if ($homeLocation && $homeLocation[0]) {
  1645. $distances[] = $this->getDistance($homeLocation[0][1], $homeLocation[0][0], $lat, $lng);
  1646. }
  1647. // 计算与当前位置的距离
  1648. if ($workLocation && $workLocation[0]) {
  1649. $distances[] = $this->getDistance($workLocation[0][1], $workLocation[0][0], $lat, $lng);
  1650. }
  1651. // 如果有有效距离,返回最小值;否则返回0
  1652. return ! empty($distances) ? min($distances) : 0.0;
  1653. } catch (\Exception $e) {
  1654. Log::error('计算距离失败', [
  1655. 'error' => $e->getMessage(),
  1656. 'coach_id' => $coachId,
  1657. 'address_id' => $addressId,
  1658. 'lat' => $lat,
  1659. 'lng' => $lng,
  1660. ]);
  1661. return 0.0;
  1662. }
  1663. }
  1664. /**
  1665. * 计算优惠金额
  1666. */
  1667. private function calculateDiscountAmount(int $projectId, int $userId): float
  1668. {
  1669. $discountAmount = 0;
  1670. // TODO: 实现优惠券、活动等优惠计算逻辑
  1671. return $discountAmount;
  1672. }
  1673. /**
  1674. * 计算订单总金额
  1675. */
  1676. private function calculateTotalAmount(float $projectPrice, float $deliveryFee, float $discountAmount): float
  1677. {
  1678. $totalAmount = bcadd($projectPrice, $deliveryFee, 2);
  1679. $totalAmount = bcsub($totalAmount, $discountAmount, 2);
  1680. return max(0, $totalAmount);
  1681. }
  1682. /**
  1683. * 计算支付金额分配
  1684. *
  1685. * @return array{balance_amount: float, pay_amount: float}
  1686. */
  1687. private function calculatePaymentDistribution(MemberUser $user, float $totalAmount, bool $useBalance): array
  1688. {
  1689. if (! $useBalance || $totalAmount <= 0) {
  1690. return [
  1691. 'balance_amount' => 0,
  1692. 'pay_amount' => $totalAmount,
  1693. ];
  1694. }
  1695. $availableBalance = $user->wallet?->available_balance ?? 0;
  1696. if ($availableBalance >= $totalAmount) {
  1697. return [
  1698. 'balance_amount' => $totalAmount,
  1699. 'pay_amount' => 0,
  1700. ];
  1701. }
  1702. return [
  1703. 'balance_amount' => $availableBalance,
  1704. 'pay_amount' => bcsub($totalAmount, $availableBalance, 2),
  1705. ];
  1706. }
  1707. /**
  1708. * 获取订单抢单池列表
  1709. *
  1710. * @param int $orderId 订单ID
  1711. * @return array 抢单池列表
  1712. */
  1713. public function getOrderGrabList(int $orderId): array
  1714. {
  1715. try {
  1716. // 查询��单信息
  1717. $order = Order::where('id', $orderId)
  1718. ->whereIn('state', [OrderStatus::CREATED->value])
  1719. ->firstOrFail();
  1720. // 查询抢单池列表
  1721. $grabList = $order->grabRecords()->with(['coach.info'])->get();
  1722. // 格式化返回数据
  1723. $result = [];
  1724. foreach ($grabList as $grab) {
  1725. $coach = $grab->coach;
  1726. $result[] = [
  1727. 'id' => $grab->id,
  1728. 'coach_id' => $coach->id,
  1729. 'nickname' => $coach->info->nickname,
  1730. 'avatar' => $coach->info->avatar,
  1731. 'distance' => $grab->distance,
  1732. 'created_at' => $grab->created_at->format('Y-m-d H:i:s'),
  1733. ];
  1734. }
  1735. return $result;
  1736. } catch (\Exception $e) {
  1737. Log::error('获取订单抢单池列表失败', [
  1738. 'error' => $e->getMessage(),
  1739. 'order_id' => $orderId,
  1740. ]);
  1741. throw $e;
  1742. }
  1743. }
  1744. /**
  1745. * 指定技师
  1746. *
  1747. * @param int $userId 用户ID
  1748. * @param int $orderId 订单ID
  1749. * @param int $coachId 技师ID
  1750. *
  1751. * @throws \Exception
  1752. */
  1753. public function assignCoach(int $userId, int $orderId, int $coachId): bool
  1754. {
  1755. return DB::transaction(function () use ($userId, $orderId, $coachId) {
  1756. try {
  1757. // 1. 验证参数
  1758. $order = $this->validateAssignOrder($userId, $orderId);
  1759. // 2. 验证技师
  1760. $coach = $this->validateCoach($coachId);
  1761. // 3. 检查抢单池状态
  1762. $this->validateGrabPool($order);
  1763. // 4. 更新订单信息
  1764. $this->updateOrderForAssign($order, $coachId);
  1765. // 5. 创建订单记录(指派)
  1766. $this->createAssignRecord($order, $userId);
  1767. // 6. 处理支付
  1768. if ($order->payment_type === PaymentMethod::BALANCE->value) {
  1769. $this->handleBalancePaymentForAssign($order, $userId, $coachId);
  1770. }
  1771. // 7. 发送通知
  1772. $this->notifyAssignment($order, $coach);
  1773. return true;
  1774. } catch (Exception $e) {
  1775. $this->logError('指定技师失败', $e, [
  1776. 'user_id' => $userId,
  1777. 'order_id' => $orderId,
  1778. 'coach_id' => $coachId,
  1779. ]);
  1780. throw $e;
  1781. }
  1782. });
  1783. }
  1784. /**
  1785. * 验证指定技师的订单条件
  1786. */
  1787. private function validateAssignOrder(int $userId, int $orderId): Order
  1788. {
  1789. // 验证用户状态
  1790. $user = MemberUser::where('id', $userId)
  1791. ->where('state', UserStatus::OPEN->value)
  1792. ->firstOrFail();
  1793. // 验证订单状态
  1794. $order = $user->orders()
  1795. ->where('id', $orderId)
  1796. ->whereIn('state', [OrderStatus::CREATED->value, OrderStatus::PAID->value])
  1797. ->lockForUpdate()
  1798. ->firstOrFail();
  1799. return $order;
  1800. }
  1801. /**
  1802. * 验证抢单池状态
  1803. */
  1804. private function validateGrabPool(Order $order): void
  1805. {
  1806. // 检查抢单池是否已有抢单成功记录
  1807. $existsGrabSuccess = $order->grabRecords()
  1808. ->where('state', OrderGrabRecordStatus::SUCCEEDED->value)
  1809. ->exists();
  1810. abort_if($existsGrabSuccess, 400, '该订单已抢单完成');
  1811. }
  1812. /**
  1813. * 更新订单信息
  1814. */
  1815. private function updateOrderForAssign(Order $order, int $coachId): void
  1816. {
  1817. // 修改订单技师
  1818. $order->coach_id = $coachId;
  1819. // 待支付订单需要重新计算金额
  1820. if ($order->state === OrderStatus::CREATED->value) {
  1821. $amounts = $this->calculateOrderAmount(
  1822. userId: $order->user_id,
  1823. addressId: $order->address_id,
  1824. coachId: $coachId,
  1825. projectId: $order->project_id,
  1826. agentId: $order->agent_id,
  1827. useBalance: $order->payment_type === PaymentMethod::BALANCE->value
  1828. );
  1829. // 更新订单金额
  1830. $order->fill([
  1831. 'total_amount' => $amounts['total_amount'],
  1832. 'balance_amount' => $amounts['balance_amount'],
  1833. 'pay_amount' => $amounts['pay_amount'],
  1834. 'discount_amount' => $amounts['coupon_amount'],
  1835. 'project_amount' => $amounts['project_amount'],
  1836. 'traffic_amount' => $amounts['delivery_fee'],
  1837. ]);
  1838. }
  1839. $order->save();
  1840. }
  1841. /**
  1842. * 处理指派订单的余额支付
  1843. */
  1844. private function handleBalancePaymentForAssign(Order $order, int $userId, int $coachId): void
  1845. {
  1846. // 验证余额
  1847. $user = MemberUser::find($userId);
  1848. $wallet = $user->wallet;
  1849. abort_if($wallet->available_balance < $order->balance_amount, 400, '可���余额不足');
  1850. // 扣除余额
  1851. DB::transaction(function () use ($wallet, $order, $userId, $coachId) {
  1852. // 更新钱包余额
  1853. $wallet->decrement('total_balance', $order->balance_amount);
  1854. $wallet->decrement('available_balance', $order->balance_amount);
  1855. // 更新订单状态
  1856. $order->update(['state' => OrderStatus::PAID->value]);
  1857. // 创建钱包支付记录
  1858. $this->createWalletPaymentRecord($order, $wallet);
  1859. // 创建支付成功记录
  1860. $this->createPaymentSuccessRecord($order, $userId);
  1861. // 更新抢单记录
  1862. $this->updateGrabRecords($order->id, $coachId);
  1863. });
  1864. }
  1865. /**
  1866. * 创建钱包支付记录
  1867. */
  1868. private function createWalletPaymentRecord(Order $order, $wallet): void
  1869. {
  1870. WalletPaymentRecord::create([
  1871. 'order_id' => $order->id,
  1872. 'wallet_id' => $wallet->id,
  1873. 'payment_no' => 'B_'.$order->id,
  1874. 'payment_method' => 'balance',
  1875. 'total_amount' => $order->balance_amount,
  1876. 'actual_amount' => 0,
  1877. 'used_wallet_balance' => $order->balance_amount,
  1878. 'used_recharge_balance' => 0,
  1879. 'state' => 'success',
  1880. ]);
  1881. }
  1882. /**
  1883. * 创建支付成功记录
  1884. */
  1885. private function createPaymentSuccessRecord(Order $order, int $userId): void
  1886. {
  1887. OrderRecord::create([
  1888. 'order_id' => $order->id,
  1889. 'object_id' => $userId,
  1890. 'object_type' => MemberUser::class,
  1891. 'state' => OrderRecordStatus::PAID->value,
  1892. 'remark' => '余额支付成功',
  1893. ]);
  1894. }
  1895. /**
  1896. * 更新抢单记录
  1897. */
  1898. private function updateGrabRecords(int $orderId, int $coachId): void
  1899. {
  1900. OrderGrabRecord::where('order_id', $orderId)
  1901. ->update([
  1902. 'state' => OrderGrabRecordStatus::SUCCEEDED->value,
  1903. 'coach_id' => $coachId,
  1904. ]);
  1905. }
  1906. /**
  1907. * 发送指派通知
  1908. */
  1909. private function notifyAssignment(Order $order, CoachUser $coach): void
  1910. {
  1911. // TODO: 实现通知逻辑
  1912. // event(new OrderAssignedEvent($order, $coach));
  1913. }
  1914. /**
  1915. * 生成订单核销码
  1916. *
  1917. * @param int $userId 用户ID
  1918. * @param int $orderId 订单ID
  1919. * @return array{
  1920. * order_id: int,
  1921. * qr_code: string,
  1922. * qr_image: ?string,
  1923. * expired_at: string,
  1924. * state: string
  1925. * } 返回核销码信息
  1926. *
  1927. * @throws \Exception
  1928. */
  1929. public function generateVerificationCode(int $userId, int $orderId): array
  1930. {
  1931. try {
  1932. // 验证订单状态和归属
  1933. $order = $this->validateOrderForVerification($userId, $orderId);
  1934. // 生成核销码数据
  1935. $verificationData = $this->generateVerificationData($order->id);
  1936. // 生成二维码图片
  1937. $qrCodeImage = $this->generateQRCodeImage($verificationData['qr_code']);
  1938. return [
  1939. 'order_id' => $order->id,
  1940. 'qr_code' => $verificationData['qr_code'],
  1941. 'qr_image' => $qrCodeImage,
  1942. 'expired_at' => $verificationData['expired_at'],
  1943. 'state' => $order->state,
  1944. ];
  1945. } catch (Exception $e) {
  1946. $this->logError('生成订单核销码失败', $e, [
  1947. 'user_id' => $userId,
  1948. 'order_id' => $orderId,
  1949. ]);
  1950. throw $e;
  1951. }
  1952. }
  1953. /**
  1954. * 验证订单状态和归属
  1955. */
  1956. private function validateOrderForVerification(int $userId, int $orderId): Order
  1957. {
  1958. // 验证用户状态
  1959. $user = MemberUser::where('id', $userId)
  1960. ->where('state', UserStatus::OPEN->value)
  1961. ->firstOrFail();
  1962. // 验证订单状态和归属
  1963. $order = $user->orders()
  1964. ->where('id', $orderId)
  1965. ->whereIn('state', [
  1966. OrderStatus::PAID->value,
  1967. OrderStatus::ACCEPTED->value,
  1968. OrderStatus::DEPARTED->value,
  1969. OrderStatus::ARRIVED->value,
  1970. ])
  1971. ->firstOrFail();
  1972. return $order;
  1973. }
  1974. /**
  1975. * 生成核销码数据
  1976. *
  1977. * @param int $orderId 订单ID
  1978. * @return array{qr_code: string, expired_at: string}
  1979. */
  1980. private function generateVerificationData(int $orderId): array
  1981. {
  1982. // 生成时间戳
  1983. $timestamp = time();
  1984. // 生成签名
  1985. $sign = md5("order_{$orderId}_{$timestamp}_".config('app.key'));
  1986. // 组装二维码内容
  1987. $qrCode = "order_{$orderId}_{$timestamp}_{$sign}";
  1988. return [
  1989. 'qr_code' => $qrCode,
  1990. 'expired_at' => date('Y-m-d H:i:s', $timestamp + 300), // 5分钟有效期
  1991. ];
  1992. }
  1993. /**
  1994. * 生成二维码图片
  1995. *
  1996. * @param string $content 二维码内容
  1997. * @return string|null Base64编码的图片数据
  1998. */
  1999. private function generateQRCodeImage(string $content): ?string
  2000. {
  2001. try {
  2002. // 生成PNG格式的二维码
  2003. $qrCodeImage = QrCode::format('png')
  2004. ->size(200) // 设置二维码大小为200px
  2005. ->margin(1) // 设置二维码边距为1
  2006. ->errorCorrection('H') // 设置纠错级别为最高级别H
  2007. ->generate($content);
  2008. // 将PNG转为base64
  2009. return 'data:image/png;base64,'.base64_encode($qrCodeImage);
  2010. } catch (Exception $e) {
  2011. Log::error('生成二维码图片失败:', [
  2012. 'content' => $content,
  2013. 'error' => $e->getMessage(),
  2014. ]);
  2015. return null;
  2016. }
  2017. }
  2018. /**
  2019. * 验证技师服务时间是否可用
  2020. */
  2021. public function validateServiceTime(int $coachId, string $serviceTime): bool
  2022. {
  2023. try {
  2024. // 1. 验证基础参数(技师状态、时间格式等)
  2025. $this->validateServiceTimeParams($coachId, $serviceTime);
  2026. // 2. 获取技师工作时间安排
  2027. $workSchedule = $this->getCoachWorkSchedule($coachId);
  2028. // 3. 验证是否在工作时间内
  2029. $this->validateWorkingHours($serviceTime, $workSchedule);
  2030. // 4. 检查是否与其他订单时间冲突
  2031. $this->checkTimeConflicts($coachId, $serviceTime);
  2032. return true;
  2033. } catch (Exception $e) {
  2034. // 记录错误日志
  2035. $this->logError('验证服务时间失败', $e, [
  2036. 'coach_id' => $coachId,
  2037. 'service_time' => $serviceTime,
  2038. ]);
  2039. throw $e;
  2040. }
  2041. }
  2042. /**
  2043. * 检查订单时间冲突
  2044. */
  2045. private function checkTimeConflicts(int $coachId, string $serviceTime): void
  2046. {
  2047. $serviceDateTime = Carbon::parse($serviceTime);
  2048. // 获取服务时长配置(默认2小时)
  2049. $serviceDuration = config('business.default_service_duration', 120);
  2050. // 计算本次服务的结束时间
  2051. $serviceEndTime = $serviceDateTime->copy()->addMinutes($serviceDuration);
  2052. // 检查是否与其他订单时间重叠
  2053. $conflictOrder = Order::where('coach_id', $coachId)
  2054. ->whereIn('state', [
  2055. OrderStatus::PAID->value, // 已支付
  2056. OrderStatus::ACCEPTED->value, // 已接单
  2057. OrderStatus::SERVING->value, // 服务中
  2058. ])
  2059. ->where(function ($query) use ($serviceDateTime, $serviceEndTime) {
  2060. $query->where(function ($q) use ($serviceDateTime) {
  2061. // 检查服务开始时间是否冲突
  2062. $q->where('service_time', '<=', $serviceDateTime)
  2063. ->where('service_end_time', '>', $serviceDateTime);
  2064. })->orWhere(function ($q) use ($serviceEndTime) {
  2065. // 检查服务结束时间是否冲突
  2066. $q->where('service_time', '<', $serviceEndTime)
  2067. ->where('service_end_time', '>=', $serviceEndTime);
  2068. });
  2069. })
  2070. ->first();
  2071. // 如果存在时间冲突,抛出异常
  2072. abort_if(
  2073. $conflictOrder,
  2074. 400,
  2075. '该时间段技师已有其他订单'
  2076. );
  2077. }
  2078. /**
  2079. * 订单评价
  2080. *
  2081. * @param int $userId 用户ID
  2082. * @param int $orderId 订单ID
  2083. * @param array{
  2084. * score: int,
  2085. * content: string,
  2086. * images: ?array,
  2087. * tags: ?array
  2088. * } $data 评价数据
  2089. * @return array{message: string}
  2090. *
  2091. * @throws \Exception
  2092. */
  2093. public function evaluateOrder(int $userId, int $orderId, array $data): array
  2094. {
  2095. return DB::transaction(function () use ($userId, $orderId, $data) {
  2096. try {
  2097. // 1. 验证订单状态
  2098. $order = $this->validateOrderForEvaluation($userId, $orderId);
  2099. // 2. 创建评价记录
  2100. $evaluation = $this->createEvaluation($order, $data);
  2101. // 3. 更新技师评分
  2102. // TODO: 更新技师评分
  2103. // $this->updateCoachScore($order->coach_id);
  2104. // 4. 更新订单状态
  2105. $this->updateOrderEvaluationStatus($order);
  2106. // 5. 创建评价奖励
  2107. // TODO: 创建评价奖励
  2108. // $this->createEvaluationReward($order, $evaluation);
  2109. // 6. 发送评价通知
  2110. // $this->notifyEvaluation($order, $evaluation);
  2111. return ['message' => '评价成功'];
  2112. } catch (Exception $e) {
  2113. $this->logError('订单评价失败', $e, [
  2114. 'user_id' => $userId,
  2115. 'order_id' => $orderId,
  2116. 'data' => $data,
  2117. ]);
  2118. throw $e;
  2119. }
  2120. });
  2121. }
  2122. /**
  2123. * 验证订单评价条件
  2124. */
  2125. private function validateOrderForEvaluation(int $userId, int $orderId): Order
  2126. {
  2127. // 获取订单信息
  2128. $order = Order::where('id', $orderId)
  2129. ->where('user_id', $userId)
  2130. ->where('state', OrderStatus::FINISHED->value)
  2131. ->firstOrFail();
  2132. // 检查是否已评价
  2133. abort_if(
  2134. $order->evaluation()->exists(),
  2135. 400,
  2136. '订单已评价'
  2137. );
  2138. // 检查评价时效(7天内可评价)
  2139. $evaluationExpireDays = config('business.evaluation_expire_days', 7);
  2140. abort_if(
  2141. $order->finish_time->addDays($evaluationExpireDays)->isPast(),
  2142. 400,
  2143. '评价已过期'
  2144. );
  2145. return $order;
  2146. }
  2147. /**
  2148. * 更新技师评分
  2149. */
  2150. // private function updateCoachScore(int $coachId): void
  2151. // {
  2152. // $coach = CoachUser::findOrFail($coachId);
  2153. // // 计算平均分
  2154. // $avgScore = OrderEvaluation::where('coach_id', $coachId)
  2155. // ->where('state', 'normal')
  2156. // ->avg('score');
  2157. // // 更新技师评分
  2158. // $coach->info()->update([
  2159. // 'score' => round($avgScore, 1),
  2160. // 'evaluation_count' => OrderEvaluation::where('coach_id', $coachId)
  2161. // ->where('state', 'normal')
  2162. // ->count(),
  2163. // ]);
  2164. // }
  2165. /**
  2166. * 更新订单评价状态
  2167. */
  2168. private function updateOrderEvaluationStatus(Order $order): void
  2169. {
  2170. // 创建订单记录
  2171. OrderRecord::create([
  2172. 'order_id' => $order->id,
  2173. 'object_id' => $order->user_id,
  2174. 'object_type' => MemberUser::class,
  2175. 'state' => OrderRecordStatus::EVALUATED->value,
  2176. 'remark' => '用户评价完成',
  2177. ]);
  2178. }
  2179. /**
  2180. * 创建评价奖励
  2181. */
  2182. // private function createEvaluationReward(Order $order, OrderEvaluation $evaluation): void
  2183. // {
  2184. // // 获取评价奖励配置
  2185. // $rewardAmount = config('business.evaluation_reward_amount', 0);
  2186. // if ($rewardAmount <= 0) {
  2187. // return;
  2188. // }
  2189. // // 更新用户钱包
  2190. // $wallet = $order->user->wallet;
  2191. // $wallet->increment('total_balance', $rewardAmount);
  2192. // $wallet->increment('available_balance', $rewardAmount);
  2193. // // 创建奖励记录
  2194. // $wallet->transRecords()->create([
  2195. // 'amount' => $rewardAmount,
  2196. // 'trans_type' => 'evaluation_reward',
  2197. // 'owner_type' => OrderEvaluation::class,
  2198. // 'owner_id' => $evaluation->id,
  2199. // 'remark' => '评价奖励',
  2200. // 'before_balance' => $wallet->total_balance - $rewardAmount,
  2201. // 'after_balance' => $wallet->total_balance,
  2202. // 'state' => 'success',
  2203. // ]);
  2204. // }
  2205. /**
  2206. * 发送评价通知
  2207. */
  2208. // private function notifyEvaluation(Order $order, OrderEvaluation $evaluation): void
  2209. // {
  2210. // // TODO: 实现评价通知逻辑
  2211. // // 1. 通知技师
  2212. // // event(new OrderEvaluatedEvent($order, $evaluation));
  2213. // // 2. 更新评价缓存
  2214. // // Cache::tags(['coach_evaluations'])->forget("coach:{$order->coach_id}");
  2215. // }
  2216. private function getNearbyCoaches(float $lat, float $lng, float $radius = 5.0): Collection
  2217. {
  2218. // 获取在线技师列表
  2219. return CoachUser::query()
  2220. ->with(['info'])
  2221. ->where('state', TechnicianStatus::ACTIVE->value)
  2222. ->whereHas('info', fn ($q) => $q->where('state', TechnicianAuthStatus::PASSED->value))
  2223. ->get();
  2224. }
  2225. private function validateCoachForGrab(int $coachId): CoachUser
  2226. {
  2227. $coach = CoachUser::query()
  2228. ->with(['info'])
  2229. ->where('id', $coachId)
  2230. ->where('state', TechnicianStatus::ACTIVE->value)
  2231. ->first();
  2232. abort_if(! $coach, 400, '技师不存在或未激活');
  2233. // 验证技师认证状态
  2234. abort_if(! $coach->info || $coach->info->state !== TechnicianAuthStatus::PASSED->value,
  2235. 400, '技师未通过认证');
  2236. return $coach;
  2237. }
  2238. }