OrderService.php 103 KB

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