OrderService.php 110 KB

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