OrderService.php 92 KB

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