OrderService.php 101 KB

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