OrderService.php 84 KB

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