OrderService.php 87 KB

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