OrderService.php 81 KB

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