OrderService.php 91 KB

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