OrderService.php 101 KB

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