OrderService.php 108 KB

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