OrderService.php 87 KB

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