1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160 |
- <?php
- namespace App\Services\Client;
- use Exception;
- use Carbon\Carbon;
- use App\Models\Order;
- use App\Models\Project;
- use App\Enums\OrderType;
- use App\Enums\UserStatus;
- use App\Models\AgentInfo;
- use App\Models\CoachUser;
- use App\Enums\OrderSource;
- use App\Enums\OrderStatus;
- use App\Models\MemberUser;
- use App\Models\OrderRecord;
- use App\Enums\PaymentMethod;
- use App\Enums\ProjectStatus;
- use App\Models\CoachLocation;
- use App\Models\MemberAddress;
- use App\Enums\TransactionType;
- use App\Enums\TechnicianStatus;
- use App\Models\OrderGrabRecord;
- use App\Enums\OrderRecordStatus;
- use Illuminate\Support\Facades\DB;
- use App\Enums\TechnicianAuthStatus;
- use App\Models\WalletPaymentRecord;
- use Illuminate\Support\Facades\Log;
- use App\Enums\OrderGrabRecordStatus;
- use Illuminate\Support\Facades\Auth;
- use App\Enums\TechnicianLocationType;
- use Illuminate\Support\Facades\Redis;
- use SimpleSoftwareIO\QrCode\Facades\QrCode;
- use Illuminate\Database\Eloquent\Collection;
- use App\Services\Client\Traits\HandlesPayments;
- use App\Services\Client\Traits\HandlesOrderRecords;
- use App\Services\Client\Traits\ValidatesServiceTime;
- use App\Services\Client\Traits\CalculatesOrderAmounts;
- use App\Models\CoachStatistic;
- use App\Models\FinanceRecord;
- use App\Models\OrderRefundRecord;
- use App\Enums\PaymentType;
- use App\Enums\TransactionStatus;
- use App\Enums\TechnicianWorkStatus;
- readonly class OrderService
- {
- use CalculatesOrderAmounts;
- use HandlesOrderRecords;
- use HandlesPayments;
- use ValidatesServiceTime;
- public function __construct(
- private AgentService $agentService,
- private ProjectService $projectService,
- private CoachService $coachService,
- private WalletService $walletService
- ) {}
- /**
- * 订单初始化
- *
- * @param int $userId 用户ID
- * @param array $data 订单数据
- * @return array 初始化的订单信息
- *
- * @throws \Exception
- *
- * 逻辑描述:
- * 1. 验证初始化参数(project_id、coach_id)
- * 2. 获取用户信息(包含钱包和地址)
- * 3. 获取区域编码(从地址或参数)
- * 4. 验证技师状态并获取可用时间
- * 5. 获取项目详情(含价格)
- * 6. 计算订单金额(含路费)
- * 7. 返回初始化数据(钱包、技师、项目、地址、金额、可用时间)
- */
- public function initialize(int $userId, array $data): array
- {
- // 参数验证
- $this->validateInitializeData($data);
- return DB::transaction(function () use ($userId, $data) {
- // 获取用户信息
- $user = $this->getUserWithWalletAndAddress($userId);
- // 获取区域编码
- $areaCode = $this->getAreaCode($user->address, $data);
- // 获取技师信息
- $coach = $this->validateCoach($data['coach_id']);
- // 计算距离和获取技师位置
- [$distance, $coachLocation] = $this->calculateDistanceAndLocation(
- userId: $userId,
- coachId: $coach->id,
- inputData: $data,
- userAddress: $user->address
- );
- // 设置技师的距离和位置信息
- $coach->distance = $distance;
- if ($coachLocation) {
- $coach->location = $coachLocation;
- }
- // 获取技师可用时间
- $availableTimeSlots = $this->coachService->getSchedule($coach->id);
- // 获取项目信息
- $project = $this->getProjectDetail($data['project_id'], $areaCode);
- // 计算订单金额
- $amounts = $this->calculateOrderAmount(
- userId: $userId,
- addressId: $user->address?->id ?? 0,
- coachId: $data['coach_id'],
- projectId: $data['project_id'],
- agentId: $project->agent_id,
- useBalance: false,
- distance: $distance,
- lat: $data['latitude'] ?? ($user->address?->latitude ?? 0),
- lng: $data['longitude'] ?? ($user->address?->longitude ?? 0)
- );
- return [
- 'wallet' => $user->wallet,
- 'coach' => $coach,
- 'project' => $project,
- 'address' => $user->address,
- 'amounts' => $amounts,
- 'availableTimeSlots' => $availableTimeSlots,
- ];
- });
- }
- /**
- * 计算距离并获取技师位置信息
- *
- * 计算逻辑优先级:
- * 1. 使用前端传入的距离
- * 2. 使用用户默认地址计算
- * 3. 使用前端传入的经纬度计算
- *
- * @param int $userId 用户ID
- * @param int $coachId 技师ID
- * @param array $inputData 输入数据
- * @param ?object $userAddress 用户默认地址
- * @return array{0: float, 1: ?array} [距离, 位置信息]
- */
- private function calculateDistanceAndLocation(
- int $userId,
- int $coachId,
- array $inputData,
- ?object $userAddress
- ): array {
- // 1. 如果前端直接传入距离,直接使用
- if (isset($inputData['distance'])) {
- return [$inputData['distance'], null];
- }
- // 2. 确定用户坐标来源
- $userCoordinates = $this->getUserCoordinates($inputData, $userAddress);
- if (!$userCoordinates) {
- return [0.0, null];
- }
- // 3. 计算距离和获取位置
- return $this->calculateDistanceFromCoordinates(
- userId: $userId,
- coachId: $coachId,
- longitude: $userCoordinates['longitude'],
- latitude: $userCoordinates['latitude']
- );
- }
- /**
- * 获取用户坐标
- *
- * @return array{longitude: float, latitude: float}|null
- */
- private function getUserCoordinates(array $inputData, ?object $userAddress): ?array
- {
- // 优先使用默认地址
- if ($userAddress && $userAddress->latitude && $userAddress->longitude) {
- return [
- 'longitude' => $userAddress->longitude,
- 'latitude' => $userAddress->latitude
- ];
- }
- // 其次使用前端传入的坐标
- if (isset($inputData['latitude']) && isset($inputData['longitude'])) {
- return [
- 'longitude' => $inputData['longitude'],
- 'latitude' => $inputData['latitude']
- ];
- }
- return null;
- }
- /**
- * 根据坐标计算距离和获取技师位置
- *
- * @param int $userId 用户ID
- * @param int $coachId 技师ID
- * @param float $longitude 经度
- * @param float $latitude 纬度
- * @return array{0: float, 1: ?array} [距离, 位置信息]
- */
- private function calculateDistanceFromCoordinates(
- int $userId,
- int $coachId,
- float $longitude,
- float $latitude
- ): array {
- // 临时存储用户位置用于计算
- $userLocationKey = "user_{$userId}_temp_location";
- Redis::geoadd(
- 'coach_locations',
- $longitude,
- $latitude,
- $userLocationKey
- );
- try {
- $distances = [];
- // 计算与技师两个位置点的距离
- foreach ([TechnicianLocationType::COMMON, TechnicianLocationType::CURRENT] as $locationType) {
- $locationKey = "{$coachId}_{$locationType->value}";
- $distance = Redis::geodist('coach_locations', $userLocationKey, $locationKey, 'km');
- if ($distance !== null) {
- $distances[] = [
- 'distance' => (float)$distance,
- 'key' => $locationKey,
- 'type' => $locationType->value
- ];
- }
- }
- // 如果没有有效距离,返回默认值
- if (empty($distances)) {
- return [0.0, null];
- }
- // 获取最小距离的记录
- $minDistance = array_reduce($distances, function ($carry, $item) {
- if (!$carry || $item['distance'] < $carry['distance']) {
- return $item;
- }
- return $carry;
- });
- // 从 Redis 获取原始位置信息
- $originalLocation = Redis::hget(
- "coach_location_original:{$coachId}",
- "type_{$minDistance['type']}"
- );
- if ($originalLocation) {
- $locationData = json_decode($originalLocation, true);
- return [
- $minDistance['distance'],
- [
- 'longitude' => (float)$locationData['longitude'],
- 'latitude' => (float)$locationData['latitude']
- ]
- ];
- }
- // 如果没有原始数据,则从数据库获取
- $location = CoachLocation::where('coach_id', $coachId)
- ->where('type', $minDistance['type'])
- ->latest()
- ->first();
- return [
- $minDistance['distance'],
- $location ? [
- 'longitude' => (float)$location->longitude,
- 'latitude' => (float)$location->latitude
- ] : null
- ];
- } finally {
- // 清理临时数据
- Redis::zrem('coach_locations', $userLocationKey);
- }
- }
- /**
- * 验证初始化数据
- *
- * 逻辑描述:
- * 1. 验证项目ID不能为空
- * 2. 验证技师ID不能为空
- */
- private function validateInitializeData(array $data): void
- {
- abort_if(empty($data['project_id']), 400, '项目ID不能为空');
- abort_if(empty($data['coach_id']), 400, '技师ID不能为空');
- }
- /**
- * 获取用户信息(包含钱包和地址)
- *
- * 逻辑描述:
- * 1. 查询用户信息(关联钱包和地址)
- * 2. 验证用户状态是否正常
- * 3. 返回用户信息
- */
- private function getUserWithWalletAndAddress(int $userId): MemberUser
- {
- $user = MemberUser::with(['wallet', 'address'])
- ->where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->first();
- abort_if(! $user, 400, '用户状态异常');
- return $user;
- }
- /**
- * 获取区域编码
- *
- * 逻辑描述:
- * 1. 优先使用地址中的区域编码
- * 2. 其次使用参数中的区域编码
- * 3. 验证区域编码不能为空
- */
- private function getAreaCode(?object $address, array $data): string
- {
- $areaCode = $address?->area_code ?? ($data['area_code'] ?? null);
- abort_if(empty($areaCode), 400, '区域编码不能为空');
- return $areaCode;
- }
- /**
- * 获取项目详情
- *
- * 逻辑描述:
- * 1. 调用项目服务获取详情
- * 2. 验证项目是否存在
- * 3. 返回项目信息
- */
- private function getProjectDetail(int $projectId, string $areaCode): Project
- {
- $project = $this->projectService->getProjectDetail($projectId, $areaCode);
- abort_if(! $project, 400, '项目不存在');
- return $project;
- }
- /**
- * 记录错误日志
- *
- * 逻辑描述:
- * 1. 记录错误信息
- * 2. 记录上下文数据
- * 3. 记录错误堆栈
- */
- private function logError(string $message, Exception $e, array $context = []): void
- {
- Log::error($message, [
- ...$context,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- }
- /**
- * 创建订单
- *
- * @param array{
- * user_id: int,
- * project_id: int,
- * coach_id: ?int,
- * address_id: int,
- * service_time: string,
- * remark: ?string,
- * use_balance: bool,
- * agent_id: ?int,
- * distance: float,
- * payment_type: int,
- * type: int,
- * } $data 订单数据
- * @return array{
- * order_id: int,
- * order_no: string,
- * total_amount: float,
- * balance_amount: float,
- * pay_amount: float
- * }
- *
- * @throws \Exception
- *
- * 逻辑描述:
- * 1. 验证基础数据(用户状态、项目状态、服务时间、技师状态等)
- * 2. 计算订单金额(项目价格、路费、优惠等)
- * 3. 处理加钟订单特殊逻辑(使用原订单地址和技师)
- * 4. 获取服务地址信息
- * 5. 创建订单数据
- * 6. 创建订单相关记录
- * 7. 处理余额支付(如果是余额支付)
- * 8. 发送订单创建通知
- * 9. 返回订单信息
- */
- public function createOrder(int $userId, array $data): array
- {
- return DB::transaction(function () use ($userId, $data) {
- try {
- // 转换时间格式
- if (!empty($data['service_time'])) {
- $data['service_time'] = Carbon::parse($data['service_time'])->format('Y-m-d H:i:s');
- }
- // 1. 验证基础数据
- $this->validateOrderData($userId, $data);
- // 2. 计算订单金额
- $amounts = $this->calculateOrderAmount(
- userId: $userId,
- addressId: $data['address_id'] ?? null,
- coachId: $data['coach_id'] ?? null,
- projectId: $data['project_id'],
- agentId: $data['agent_id'] ?? null,
- useBalance: $data['use_balance'] ?? false,
- distance: $data['distance'] ?? 0
- );
- // 加钟订单使用原订单地址和技师ID
- if (! empty($data['order_id'])) {
- $order = Order::findOrFail($data['order_id']);
- // 验证订单状态
- abort_if(
- ! in_array($order->state, [
- OrderStatus::PAID->value,
- OrderStatus::ACCEPTED->value,
- OrderStatus::SERVICE_START->value,
- OrderStatus::SERVICING->value,
- ]),
- 422,
- '原订单状态不允许加钟'
- );
- $data['address_id'] = $order->address_id;
- $data['coach_id'] = $order->coach_id;
- $data['service_time'] = $order->service_end_time;
- }
- // 3. 获取地址
- $address = MemberUser::find($userId)->addresses()
- ->where('id', $data['address_id'])
- ->first();
- abort_if(! $address, 404, '收货地址不存在');
- // 3. 创建订单
- $order = $this->createOrderData(['user_id' => $userId, ...$data], $amounts, $address);
- // 4. 创建订单相关记录
- $this->createRelatedRecords($order);
- // 5. 检测支付类型,自动进行余额支付
- if ($order->payment_type == PaymentMethod::BALANCE->value) {
- // 处理余额支付
- if ($amounts['balance_amount'] > 0) {
- $this->processBalancePayment($order);
- }
- // 更改订单状态
- $order->state = OrderStatus::PAID->value;
- $order->service_start_time = $data['service_time'];
- $order->service_end_time = Carbon::parse($data['service_time'])
- ->addMinutes($order->project->duration);
- $order->save();
- // 创建订单相关记录
- $this->createRelatedRecords($order);
- }
- // 6. 发送通知
- $this->notifyOrderCreated($order);
- $result = [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'total_amount' => $amounts['total_amount'],
- 'balance_amount' => $amounts['balance_amount'],
- 'pay_amount' => $amounts['pay_amount'],
- ];
- // 7. 如果是微信支付,获取支付参数
- if ($order->payment_type == PaymentMethod::WECHAT->value) {
- $paymentService = app(PaymentService::class);
- $result['wx_payment'] = $paymentService->getPaymentConfig($order->id);
- }
- return $result;
- } catch (Exception $e) {
- $this->logError('创建订单失败', $e, $data);
- throw $e;
- }
- });
- }
- /**
- * 验证订单创建数据
- */
- private function validateOrderData(int $userId, array $data): void
- {
- // 验证用户状态
- $user = MemberUser::where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->first();
- abort_if(! $user, 404, '用户不存在');
- abort_if($user->state != UserStatus::OPEN->value, 403, '用户状态异常');
- // 验证项目状态
- $project = Project::where('id', $data['project_id'])->first();
- abort_if(! $project, 404, '服务项目不存在');
- abort_if($project->state != ProjectStatus::OPEN->value, 403, '服务项目未开放');
- // 验证服务时间和技师状态
- if (! empty($data['service_time']) && ! empty($data['coach_id'])) {
- $this->validateServiceTimeParams($data['coach_id'], $data['service_time']);
- }
- }
- /**
- * 创建订单数据
- */
- private function createOrderData(array $data, array $amounts, object $address): Order
- {
- // 获取项目信息和服务时长
- $project = Project::findOrFail($data['project_id']);
- $serviceDuration = $project->duration;
- return Order::create([
- 'order_no' => $this->generateOrderNo(),
- 'user_id' => $data['user_id'],
- 'project_id' => $data['project_id'],
- 'coach_id' => $data['coach_id'] ?? null,
- 'agent_id' => $data['agent_id'] ?? null,
- 'address_id' => $data['address_id'],
- 'service_time' => $data['service_time'] ?? null,
- 'project_duration' => $serviceDuration, // 添加服务时长记录
- 'remark' => $data['remark'] ?? '',
- 'total_amount' => $amounts['total_amount'],
- 'balance_amount' => $amounts['balance_amount'],
- 'pay_amount' => $amounts['pay_amount'],
- 'traffic_amount' => $amounts['delivery_fee'],
- 'project_amount' => $amounts['project_amount'],
- 'discount_amount' => $amounts['coupon_amount'],
- 'state' => OrderStatus::CREATED->value,
- // 如果余额支付且未使用优惠券且未支付金额,则使用余额支付,否则使用传入的支付方式
- 'payment_type' => $amounts['balance_amount'] > 0 && $amounts['pay_amount'] == 0
- ? PaymentMethod::BALANCE->value
- : $data['payment_type'],
- 'latitude' => $address->latitude,
- 'longitude' => $address->longitude,
- 'location' => $address->location,
- 'address' => $address->detail,
- 'area_code' => $address->area_code,
- 'type' => $data['order_type'],
- 'distance' => $data['distance'] ?? 0,
- ]);
- }
- private function createOrderRecord(Order $order, int $objectId, string $objectType, OrderRecordStatus $status, string $remark): OrderRecord
- {
- return OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $objectId,
- 'object_type' => $objectType,
- 'state' => $status->value,
- 'remark' => $remark,
- ]);
- }
- /**
- * 生成订单号
- */
- private function generateOrderNo(): string
- {
- return 'O' . date('YmdHis') . str_pad(random_int(1, 9999), 4, '0', STR_PAD_LEFT);
- }
- /**
- * 处理余额支付
- */
- private function processBalancePayment(Order $order): void
- {
- $user = MemberUser::find($order->user_id);
- abort_if(! $user, 404, sprintf('用户[%d]不存在', $order->user_id));
- $wallet = $user->wallet;
- abort_if(
- $wallet->available_balance < $order->balance_amount,
- 400,
- sprintf(
- '用户[%d]可用余额[%.2f]不足,需要[%.2f]',
- $user->id,
- $wallet->available_balance,
- $order->balance_amount
- )
- );
- // 扣除余额
- if ($order->balance_amount > 0) {
- $this->walletService->deduct(
- userId: $user->id,
- amount: $order->balance_amount,
- type: TransactionType::PAYMENT->value,
- objectId: $order->id,
- remark: sprintf('订单[%s]余额支付', $order->order_no)
- );
- }
- }
- /**
- * 创建订单相关记录
- */
- private function createRelatedRecords(Order $order): void
- {
- // 创建订单状态记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => $order->state,
- 'remark' => $order->state === OrderStatus::PAID->value
- ? '余额支付成功'
- : '订单创建成功',
- ]);
- }
- /**
- * 发送订单创建通知
- */
- private function notifyOrderCreated(Order $order): void
- {
- // TODO: 实现订单创建通知
- // 1. 通知用户
- // event(new OrderCreatedEvent($order));
- }
- /**
- * 获取订单地址
- */
- private function getOrderAddress(MemberUser $user, array $data, OrderType $orderType): object
- {
- // 加钟订单使用原订单地址
- if ($orderType === OrderType::OVERTIME) {
- $originalOrder = $this->getOriginalOrder($user, $data['order_id']);
- $data['address_id'] = $originalOrder->address_id;
- }
- abort_if(empty($data['address_id']), 400, '地址ID不能为空');
- return $user->addresses()
- ->where('id', $data['address_id'])
- ->firstOrFail();
- }
- /**
- * 验证支付方式和余额
- */
- private function validatePayment(MemberUser $user, array $data, array $amounts): void
- {
- abort_if($amounts['total_amount'] <= 0, 400, '订单金额异常');
- if ($data['payment_type'] === PaymentMethod::BALANCE->value) {
- $wallet = $user->wallet;
- abort_if($wallet->available_balance < $amounts['balance_amount'], 400, '可用余额不足');
- }
- }
- /**
- * 判断是否需要处理余额支付
- */
- private function shouldHandleBalancePayment(Order $order, OrderType $orderType): bool
- {
- return $order->payment_type === PaymentMethod::BALANCE->value
- && $orderType !== OrderType::GRAB;
- }
- /**
- * 验证技师状态
- */
- private function validateCoach(int $coachId): CoachUser
- {
- $coach = CoachUser::query()
- ->with(['info'])
- ->where('id', $coachId)
- ->where('state', TechnicianStatus::ACTIVE->value)
- ->first();
- abort_if(! $coach, 400, '技师不存在或未激活');
- abort_if(
- ! $coach->info || $coach->info->state !== TechnicianAuthStatus::PASSED->value,
- 400,
- '技师未通过认证'
- );
- return $coach;
- }
- // 提取方法:获取原始订单
- private function getOriginalOrder($user, $orderId): Order
- {
- $originalOrder = $user->orders->where('id', $orderId)
- ->whereIn('state', [OrderStatus::SERVICING->value, OrderStatus::COMPLETED->value])
- ->firstOrFail();
- return $originalOrder;
- }
- // 提取方法:准备加钟订单数据
- private function prepareAddTimeData($originalOrder, $data): array
- {
- if ($originalOrder->state == OrderStatus::SERVICING->value) {
- $startTime = now();
- } else {
- $startTime = now();
- }
- return [
- ...$data,
- 'order_id' => $data['order_id'],
- 'address_id' => $originalOrder->address_id,
- 'service_time' => $startTime,
- 'coach_id' => $originalOrder->coach_id,
- ];
- }
- /**
- * 取消订单
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @param string|null $reason 取消原因
- * @return array{message: string}
- *
- * @throws \Exception
- */
- public function cancelOrder(int $userId, int $orderId, ?string $reason = null): array
- {
- return DB::transaction(function () use ($userId, $orderId, $reason) {
- try {
- // 1. 验证订单状态
- $order = $this->validateOrderForCancel($userId, $orderId);
- // 2. 计算退款金额
- $refundAmounts = $this->calculateCancelAmount($order);
- // 3. 更新订单状态为已取消
- $this->updateOrderCancelStatus($order);
- // 4. 创建取消记录
- $this->createCancelRecords($order, $reason);
- // 5. 处理退款
- $this->processCancelRefund($order, $refundAmounts);
- // 6. 更新订单退款状态
- $this->updateOrderRefundStatus($order);
- // 7. 发送取消通知
- $this->notifyCancel($order);
- return ['message' => '订单取消成功'];
- } catch (Exception $e) {
- $this->logError('取消订单失败', $e, [
- 'user_id' => $userId,
- 'order_id' => $orderId,
- 'reason' => $reason,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 验证订单取消条件
- */
- private function validateOrderForCancel(int $userId, int $orderId): Order
- {
- // 获取并锁定订单
- $order = Order::where('id', $orderId)
- ->whereIn('state', [
- OrderStatus::PAID->value, // 已支付
- OrderStatus::ACCEPTED->value, // 已接单
- OrderStatus::DEPARTED->value, // 已出发
- OrderStatus::REJECTED->value, // 技师拒单
- ])
- ->lockForUpdate()
- ->firstOrFail();
- // 验证订单所属用户
- abort_if($order->user_id !== $userId, 403, '无权操作此订单');
- // 验证订单是否已取消
- abort_if($order->state === OrderStatus::CANCELLED->value, 400, '订单已取消');
- return $order;
- }
- /**
- * 计算取消费用
- *
- * @return array{
- * total_refund: float,
- * balance_refund: float,
- * payment_refund: float,
- * penalty_amount: float
- * }
- */
- private function calculateCancelAmount(Order $order): array
- {
- // 计算违约金
- $penaltyAmount = $this->calculatePenaltyAmount($order);
- // 计算退款金额分配
- return $this->calculateRefundDistribution($order, $penaltyAmount);
- }
- /**
- * 计算违约金
- *
- * @return array{
- * total_penalty: float,
- * coach_fee: float,
- * platform_traffic_fee: float,
- * platform_penalty: float
- * }
- */
- private function calculatePenaltyAmount(Order $order): array
- {
- // 根据订单状态计算违约金
- return match ($order->state) {
- // 已出发状态:扣除路费(90%给技师,10%给平台),剩余金额再扣除20%
- OrderStatus::DEPARTED->value => $this->calculateDepartedPenalty($order),
- // 其他状态(已支付、已接单等):不收取违约金
- default => [
- 'total_penalty' => 0,
- 'coach_fee' => 0,
- 'platform_traffic_fee' => 0,
- 'platform_penalty' => 0
- ]
- };
- }
- /**
- * 计算已出发状态的违约金
- * 规则:
- * 1. 路费分配:90%给技师,10%给平台
- * 2. 剩余金额的20%作为平台违约金
- *
- * @return array{
- * total_penalty: float, // 总违约金
- * coach_fee: float, // 技师获得的路费
- * platform_traffic_fee: float, // 平台获得的路费分成
- * platform_penalty: float // 平台获得的违约金
- * }
- */
- private function calculateDepartedPenalty(Order $order): array
- {
- // 获取路费
- $trafficFee = $order->traffic_fee ?? 0;
- // 路费分配:90%给技师,10%给平台
- $coachFee = bcmul($trafficFee, '0.9', 2); // 技师获得的路费
- $platformTrafficFee = bcsub($trafficFee, $coachFee, 2); // 平台获得的路费分成
- // 计算扣除路费后的剩余金额
- $remainingAmount = bcsub($order->total_amount, $trafficFee, 2);
- // 剩余金额的20%作为平台违约金
- $platformPenalty = bcmul($remainingAmount, '0.2', 2);
- // 总违约金 = 路费 + 平台违约金
- $totalPenalty = bcadd($trafficFee, $platformPenalty, 2);
- return [
- 'total_penalty' => $totalPenalty, // 总违约金
- 'coach_fee' => $coachFee, // 技师获得的路费
- 'platform_traffic_fee' => $platformTrafficFee, // 平台获得的路费分成
- 'platform_penalty' => $platformPenalty // 平台获得的违约金
- ];
- }
- /**
- * 计算退款金额分配
- *
- * @return array{
- * total_refund: float,
- * balance_refund: float,
- * payment_refund: float,
- * penalty_amount: float,
- * coach_fee: float,
- * platform_traffic_fee: float,
- * platform_penalty: float
- * }
- */
- private function calculateRefundDistribution(Order $order, array $penaltyInfo): array
- {
- // 计算实际可退金额(总金额减去违约金)
- $totalRefund = bcsub($order->total_amount, $penaltyInfo['total_penalty'], 2);
- // 优先退还用户使用的余额部分
- $balanceRefund = min($order->balance_amount, $totalRefund);
- // 剩余部分退还到支付账户
- $paymentRefund = bcsub($totalRefund, $balanceRefund, 2);
- return [
- 'total_refund' => $totalRefund,
- 'balance_refund' => $balanceRefund,
- 'payment_refund' => $paymentRefund,
- 'penalty_amount' => $penaltyInfo['total_penalty'],
- 'coach_fee' => $penaltyInfo['coach_fee'],
- 'platform_traffic_fee' => $penaltyInfo['platform_traffic_fee'],
- 'platform_penalty' => $penaltyInfo['platform_penalty'],
- ];
- }
- /**
- * 处理取消退款
- */
- private function processCancelRefund(Order $order, array $refundAmounts): void
- {
- try {
- // 1. 处理余额退款
- if ($refundAmounts['balance_refund'] > 0) {
- $this->processBalanceCancelRefund($order, $refundAmounts['balance_refund']);
- }
- // 2. 处理支付退款
- if ($refundAmounts['payment_refund'] > 0) {
- $refundResult = $this->processPaymentCancelRefund($order, $refundAmounts['payment_refund']);
- // 3. 创建退款记录
- $refundRecord = OrderRefundRecord::create([
- 'order_id' => $order->id,
- 'total_refund_amount' => $refundAmounts['total_refund'],
- 'balance_refund_amount' => $refundAmounts['balance_refund'],
- 'payment_refund_amount' => $refundAmounts['payment_refund'],
- 'penalty_amount' => $refundAmounts['penalty_amount'], // 这里使用 penalty_amount 而不是 penalty
- 'coach_fee' => $refundAmounts['coach_fee'],
- 'platform_traffic_fee' => $refundAmounts['platform_traffic_fee'],
- 'platform_penalty' => $refundAmounts['platform_penalty'],
- 'refund_no' => $refundResult['refund_no'],
- 'transaction_id' => $order->transaction_id,
- 'state' => TransactionStatus::SUCCESS->value, // 使用成功状态枚举值
- 'remark' => '订单取消退款'
- ]);
- }
- } catch (\Exception $e) {
- Log::error('处理退款失败', [
- 'order_id' => $order->id,
- 'refund_amounts' => $refundAmounts,
- 'error' => $e->getMessage()
- ]);
- throw $e;
- }
- }
- /**
- * 处理余额退款
- */
- private function processBalanceCancelRefund(Order $order, float $amount): void
- {
- $wallet = $order->user->wallet;
- // 更新钱包余额
- $wallet->increment('total_balance', $amount);
- $wallet->increment('available_balance', $amount);
- // 创建钱包交易记录
- $wallet->transRecords()->create([
- 'amount' => $amount,
- 'trans_type' => TransactionType::REFUND->value, // 使用退款枚举值
- 'owner_type' => Order::class,
- 'owner_id' => $order->id,
- 'remark' => '订单取消退款',
- 'before_balance' => $wallet->total_balance - $amount,
- 'after_balance' => $wallet->total_balance,
- 'state' => TransactionStatus::SUCCESS->value, // 使用成功状态枚举值
- ]);
- // 创建订单记录
- $order->records()->create([
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::REFUNDING->value,
- 'remark' => '余额退款'
- ]);
- }
- /**
- * 处理支付退款
- */
- private function processPaymentCancelRefund(Order $order, float $amount): array
- {
- try {
- // 调用支付服务处理退款
- $paymentService = app(PaymentService::class);
- $result = $paymentService->refund(
- $order->transaction_id,
- $amount,
- $order->pay_amount,
- '订单取消退款'
- );
- if (!$result['success']) {
- throw new \Exception($result['message']);
- }
- // 创建订单记录
- $order->records()->create([
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::REFUNDING->value,
- 'remark' => '微信支付退款'
- ]);
- return $result;
- } catch (\Exception $e) {
- Log::error('订单退款失败', [
- 'order_id' => $order->id,
- 'amount' => $amount,
- 'error' => $e->getMessage()
- ]);
- throw $e;
- }
- }
- /**
- * 更新订单取消状态
- */
- private function updateOrderCancelStatus(Order $order): void
- {
- $order->update([
- 'state' => OrderStatus::CANCELLED->value,
- ]);
- }
- /**
- * 创建取消记录
- */
- private function createCancelRecords(Order $order, ?string $reason): void
- {
- // 创建订单状态记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => Auth::id(),
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::CANCELLED->value,
- 'remark' => "用户取消订单:{$reason}",
- ]);
- }
- /**
- * 发送取消通知
- */
- private function notifyCancel(Order $order): void
- {
- // TODO: 实现取消通知逻辑
- // 1. 知用户
- // event(new OrderCancelledEvent($order));
- // 2. 通知技师
- if ($order->coach_id) {
- // event(new OrderCancelledToCoachEvent($order));
- }
- }
- /**
- * 结束订单
- */
- public function finishOrder(int $userId, int $orderId): array
- {
- return DB::transaction(function () use ($userId, $orderId) {
- try {
- // 1. 验证用户和订单
- $order = $this->validateOrderForFinish($userId, $orderId);
- // 2. 验证技师状
- $coach = $this->validateCoach($order->coach_id);
- // 3. 检测并更新技师状态
- // 如果技师状态为忙碌,则更新为空闲
- if ($coach->work_status === TechnicianWorkStatus::BUSY->value) {
- $coach->update([
- 'work_status' => TechnicianWorkStatus::FREE->value
- ]);
- }
- // 4. 完成订单
- $this->completeOrder($order, $userId);
- // 5. 知技师
- // event(new OrderFinishedEvent($order));
- return ['message' => '订单已完成'];
- } catch (Exception $e) {
- $this->logFinishOrderError($e, $userId, $orderId);
- throw $e;
- }
- });
- }
- /**
- * 验证订单完成条件
- */
- private function validateOrderForFinish(int $userId, int $orderId): Order
- {
- // 验证用户状态
- $user = MemberUser::where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->firstOrFail();
- // 验证订单状态
- $order = Order::where('user_id', $userId)
- ->where('id', $orderId)
- ->where('state', OrderStatus::SERVICING->value)
- ->lockForUpdate()
- ->firstOrFail();
- return $order;
- }
- /**
- * 完成订单
- */
- private function completeOrder(Order $order, int $userId): void
- {
- // 1. 创建订单记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::COMPLETED->value,
- 'remark' => '服务完成',
- ]);
- // 2. 更新订单状态
- $order->state = OrderStatus::SERVICE_END->value;
- $order->service_end_time = now();
- $order->save();
- }
- /**
- * 记录订单完成错误日志
- */
- private function logFinishOrderError(Exception $e, int $userId, int $orderId): void
- {
- Log::error('结束订单失败:', [
- 'message' => $e->getMessage(),
- 'user_id' => $userId,
- 'order_id' => $orderId,
- 'trace' => $e->getTraceAsString(),
- ]);
- }
- /**
- * 确认技师离开
- */
- public function confirmLeave(int $userId, int $orderId): array
- {
- return DB::transaction(function () use ($userId, $orderId) {
- try {
- // 1. 参数校验
- $order = Order::where('user_id', $userId)
- ->where('id', $orderId)
- ->where('state', OrderStatus::SERVICE_END->value) // 订单状态必须是服务结束
- ->firstOrFail();
- if (! $order) {
- throw new Exception('订单不能撤离');
- }
- // 2. 添加订单撤离记录
- OrderRecord::create([
- 'order_id' => $orderId,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::LEFT->value,
- 'remark' => '技师已离开',
- ]);
- // 3. 修改订单状态为撤离
- $order->state = OrderStatus::LEAVING->value;
- $order->save();
- return ['message' => '已确技师离开'];
- } catch (Exception $e) {
- Log::error('确认技师离开失败:', [
- 'message' => $e->getMessage(),
- 'user_id' => $userId,
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 获取用户订单列表
- *
- * @param int $userId 用户ID
- * @param int $tab 标签页 0:全部 1:待支付 2:进行中 3:已完成 4:已取消
- * @return array
- */
- public function getOrderList(int $userId, int $tab = 0)
- {
- // 1. 验证用户
- $user = $this->validateUserForQuery($userId);
- // 2. 构建基础查询
- $query = $this->buildOrderListQuery($user);
- // 3. 获取状态过滤条件
- $states = $this->getOrderStatesByTab($tab);
- // 4. 加载关联数据并分页
- return $this->paginateOrderList($query, [
- 'states' => $states
- ]);
- }
- /**
- * 分页获取订单列表
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @param array $filters 过滤条件
- */
- private function paginateOrderList($query, array $filters = [])
- {
- // 从请求中获取分页参数
- $perPage = request('per_page', 10);
- $page = request('page', 1);
- // 应用状态过滤
- if (!empty($filters['states'])) {
- $query->whereIn('state', $filters['states']);
- }
- // 按创建时间降序排序并分页
- $paginatedOrders = $query->orderBy('created_at', 'desc')
- ->paginate(
- perPage: $perPage,
- page: $page
- );
- // 格式化订单数据
- $formattedOrders = $paginatedOrders->map(function ($order) {
- return $this->formatOrderListItem($order);
- });
- return [
- 'items' => $formattedOrders,
- 'total' => $paginatedOrders->total(),
- ];
- }
- /**
- * 根据标签页获取订单状态
- */
- private function getOrderStatesByTab(int $tab): array
- {
- return match ($tab) {
- 1 => [OrderStatus::CREATED->value, OrderStatus::PAYMENT_FAILED->value], // 待付款
- 2 => [ // 进行中
- OrderStatus::PAID->value,
- OrderStatus::ASSIGNED->value,
- OrderStatus::ACCEPTED->value,
- OrderStatus::DEPARTED->value,
- OrderStatus::ARRIVED->value,
- OrderStatus::SERVICE_START->value,
- OrderStatus::SERVICING->value,
- OrderStatus::SERVICE_END->value,
- OrderStatus::LEAVING->value,
- ],
- 3 => [OrderStatus::COMPLETED->value], // 已完成
- 4 => [OrderStatus::LEFT->value], // 待评价
- 5 => [ // 已取消
- OrderStatus::CANCELLED->value,
- OrderStatus::REFUNDED->value,
- OrderStatus::REJECTED->value,
- OrderStatus::REFUNDING->value,
- OrderStatus::REFUND_FAILED->value,
- ],
- default => [], // 全部订单
- };
- }
- /**
- * 验证用户查询权限
- */
- private function validateUserForQuery(int $userId): MemberUser
- {
- return MemberUser::where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->firstOrFail();
- }
- /**
- * 构建订单列表基础查询
- */
- private function buildOrderListQuery(MemberUser $user)
- {
- return $user->orders()
- ->whereNull('user_deleted_at') // 不显示用户已删除的订单
- ->with([
- 'coach' => function ($query) {
- $query->with(['info' => function ($q) {
- $q->select(['id', 'coach_id', 'nickname', 'avatar', 'gender']);
- }]);
- },
- 'project:id,title,subtitle,duration,cover',
- 'records' => function ($query) {
- $query->orderBy('created_at', 'desc')
- ->select(['id', 'order_id', 'state', 'remark', 'created_at']);
- },
- // 'evaluation:id,order_id,score,content,created_at',
- ]);
- }
- /**
- * 格式化订单列表项
- */
- private function formatOrderListItem(Order $order): array
- {
- return [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'state' => $order->state,
- 'state_text' => OrderStatus::fromValue($order->state)->label(),
- 'type' => $order->type,
- 'type_text' => OrderType::fromValue($order->type)?->label(),
- 'source' => $order->source,
- 'source_text' => OrderSource::fromValue($order->source)?->label(),
- 'total_amount' => $order->total_amount, // 订单总金额
- 'balance_amount' => $order->balance_amount, // 余额支付金额
- 'pay_amount' => $order->pay_amount, // 实付金额
- 'payment_type' => $order->payment_type, // 支付方式
- 'payment_type_text' => $order->payment_type ? PaymentMethod::fromValue($order->payment_type)->label() : null, // 支付方式文本
- 'discount_amount' => $order->discount_amount, // 优惠金额
- 'traffic_amount' => $order->traffic_amount, // 路费金额
- 'service_time' => $order->service_time,
- 'service_start_time' => $order->service_start_time instanceof \Carbon\Carbon // 服务开始时间
- ? $order->service_start_time->toDateTimeString()
- : $order->service_start_time,
- 'service_end_time' => $order->service_end_time instanceof \Carbon\Carbon // 服务结束时间
- ? $order->service_end_time->toDateTimeString()
- : $order->service_end_time,
- 'created_at' => $order->created_at->toDateTimeString(),
- 'coach' => $order->coach ? [
- 'id' => $order->coach->id,
- 'nickname' => $order->coach->info->nickname,
- 'avatar' => $order->coach->info->avatar,
- ] : null,
- 'project' => $order->project ? [
- 'id' => $order->project->id,
- 'title' => $order->project->title,
- 'subtitle' => $order->project->subtitle,
- 'duration' => $order->project->duration,
- 'cover_image' => $order->project->cover_image,
- ] : null,
- 'address' => $order->address ? [
- 'location' => $order->location,
- 'address' => $order->address,
- ] : null,
- 'latest_record' => $order->records->first() ? [
- 'state' => $order->records->first()->state,
- 'remark' => $order->records->first()->remark,
- 'created_at' => $order->records->first()->created_at->format('Y-m-d H:i:s'),
- ] : null,
- 'evaluation' => $order->evaluation ? [
- 'score' => $order->evaluation->score,
- 'content' => $order->evaluation->content,
- ] : null,
- ];
- }
- /**
- * 获取订单详情
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @return array 订单详情
- *
- * @throws \Exception
- */
- public function getOrderDetail(int $userId, int $orderId): array
- {
- try {
- // 1. 验证订单权限
- $order = $this->validateOrderAccess($userId, $orderId);
- // 2. 加载订单关联数据
- $order->load([
- 'coach.info' => function ($query) {
- $query->select(['id', 'coach_id', 'nickname', 'avatar', 'gender']);
- },
- 'project:id,title,subtitle,duration,cover',
- 'records' => function ($query) {
- $query->orderBy('created_at', 'desc')
- ->select(['id', 'order_id', 'state', 'remark', 'created_at']);
- },
- // 'evaluation' => function ($query) {
- // $query->select(['id', 'order_id', 'score', 'content', 'images', 'created_at']);
- // },
- ]);
- // 3. 格式化返回数据
- return $this->formatOrderDetail($order);
- } catch (Exception $e) {
- $this->logError('获取订单详情失败', $e, [
- 'user_id' => $userId,
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- }
- /**
- * 验证订单访问权限
- */
- private function validateOrderAccess(int $userId, int $orderId): Order
- {
- return Order::where('id', $orderId)
- ->where('user_id', $userId)
- ->firstOrFail();
- }
- /**
- * 格式化订单详情数据
- */
- private function formatOrderDetail(Order $order): array
- {
- return [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'state' => $order->state,
- 'state_text' => OrderStatus::fromValue($order->state)->label(),
- 'total_amount' => $order->total_amount,
- 'balance_amount' => $order->balance_amount,
- 'pay_amount' => $order->pay_amount,
- 'delivery_fee' => $order->delivery_fee,
- 'project_amount' => $order->project_amount,
- 'coupon_amount' => $order->coupon_amount,
- 'service_time' => $order->service_time,
- 'service_start_time' => $order->service_start_time instanceof \Carbon\Carbon // 服务开始时间
- ? $order->service_start_time->toDateTimeString()
- : $order->service_start_time,
- 'service_end_time' => $order->service_end_time instanceof \Carbon\Carbon // 服务结束时间
- ? $order->service_end_time->toDateTimeString()
- : $order->service_end_time,
- 'created_at' => $order->created_at->toDateTimeString(),
- 'remark' => $order->remark,
- 'distance' => $order->distance ?? 0,
- 'coach' => $order->coach ? [
- 'id' => $order->coach->id,
- 'nickname' => $order->coach->info->nickname,
- 'avatar' => $order->coach->info->avatar,
- 'gender' => $order->coach->info->gender,
- 'score' => $order->coach->info?->score,
- ] : null,
- 'project' => $order->project ? [
- 'id' => $order->project->id,
- 'title' => $order->project->title,
- 'subtitle' => $order->project->subtitle,
- 'duration' => $order->project->duration,
- 'cover' => $order->project->cover,
- ] : null,
- 'address' => $order->address ? [
- 'id' => $order->address_id,
- 'location' => $order->location,
- 'address' => $order->address,
- ] : null,
- 'records' => $order->records->map(function ($record) {
- return [
- 'id' => $record->id,
- 'state' => $record->state,
- 'remark' => $record->remark,
- 'created_at' => $record->created_at->format('Y-m-d H:i:s'),
- ];
- })->toArray(),
- // 'evaluation' => $order->evaluation ? [
- // 'score' => $order->evaluation->score,
- // 'content' => $order->evaluation->content,
- // 'images' => $order->evaluation->images,
- // 'created_at' => $order->evaluation->created_at->format('Y-m-d H:i:s'),
- // ] : null,
- ];
- }
- /**
- * 应用订单过滤条件
- */
- private function applyOrderFilters($query, array $filters): void
- {
- // 按状态数组筛选
- if (!empty($filters['states'])) {
- $query->whereIn('state', $filters['states']);
- }
- // 按时间范围筛选
- if (! empty($filters['start_date'])) {
- $query->where('created_at', '>=', $filters['start_date']);
- }
- if (! empty($filters['end_date'])) {
- $query->where('created_at', '<=', $filters['end_date']);
- }
- // 按服务类型筛选
- if (! empty($filters['project_id'])) {
- $query->where('project_id', $filters['project_id']);
- }
- // 按技师筛选
- if (! empty($filters['coach_id'])) {
- $query->where('coach_id', $filters['coach_id']);
- }
- // 按订单号搜索
- if (! empty($filters['order_no'])) {
- $query->where('order_no', 'like', "%{$filters['order_no']}%");
- }
- }
- /**
- * 订单退款
- *
- * @param int $orderId 订单ID
- * @return array{message: string}
- *
- * @throws \Exception
- */
- public function refundOrder(int $orderId): array
- {
- return DB::transaction(function () use ($orderId) {
- try {
- // 1. 验证订单状态
- $order = $this->validateOrderForRefund($orderId);
- // 2. 计算退款金额
- $refundAmounts = $this->calculateRefundAmount($order);
- // 3. 处理退款
- $this->processRefund($order, $refundAmounts);
- // 4. 更新订单状态
- $this->updateOrderRefundStatus($order);
- // 5. 记录退款操作
- $this->createRefundRecords($order, $refundAmounts);
- // 6. 通知相关方
- $this->notifyRefund($order);
- return ['message' => '退款申请成功'];
- } catch (Exception $e) {
- $this->logError('订单退款失败', $e, [
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 验证订单退款条件
- */
- private function validateOrderForRefund(int $orderId): Order
- {
- // 获取并锁定订单,防止并发操作
- $order = Order::where('id', $orderId)
- ->whereIn('state', [
- OrderStatus::PAID->value,
- OrderStatus::ACCEPTED->value,
- OrderStatus::DEPARTED->value,
- ])
- ->lockForUpdate()
- ->firstOrFail();
- // 验证当前用户是否为订单所有者
- $user = Auth::user();
- abort_if($order->user_id !== $user->id, 403, '无权操作此订单');
- // 检查订单是否已经退款
- abort_if($order->state === OrderStatus::REFUNDED->value, 400, '订单已退款');
- return $order;
- }
- /**
- * 计算退款金额
- */
- private function calculateRefundAmount(Order $order): array
- {
- // 计算违约金
- $penaltyAmount = $this->calculatePenaltyAmount($order);
- // 计算退款金额分配
- return $this->calculateRefundDistribution($order, $penaltyAmount);
- }
- /**
- * 处理退款操作
- */
- private function processRefund(Order $order, array $refundAmounts): void
- {
- // 处理余额退款部分
- if ($refundAmounts['balance_refund'] > 0) {
- $this->processBalanceRefund($order, $refundAmounts['balance_refund']);
- }
- // 处理支付退款部分
- if ($refundAmounts['payment_refund'] > 0) {
- $this->processPaymentRefund($order, $refundAmounts['payment_refund']);
- }
- }
- /**
- * 处理余额退款
- */
- private function processBalanceRefund(Order $order, float $amount): void
- {
- $wallet = $order->user->wallet;
- // 增加用户钱包总余额
- $wallet->increment('total_balance', $amount);
- // 增加可用余额
- $wallet->increment('available_balance', $amount);
- // 创建退款交易记录
- $wallet->transRecords()->create([
- 'amount' => $amount,
- 'trans_type' => TransactionType::REFUND->value, // 使用退款枚举值
- 'owner_type' => Order::class,
- 'owner_id' => $order->id,
- 'remark' => '订单退款',
- 'before_balance' => $wallet->total_balance - $amount,
- 'after_balance' => $wallet->total_balance,
- 'state' => TransactionStatus::SUCCESS->value, // 使用成功状态枚举值
- ]);
- }
- /**
- * 处理支付退款
- */
- private function processPaymentRefund(Order $order, float $amount): void
- {
- // TODO: 实现第三方支付退款逻辑
- // $paymentService = app(PaymentService::class);
- // $paymentService->refund($order->payment_no, $amount);
- }
- /**
- * 更新订单退款状态
- *
- * @param Order $order 订单对象
- * @return void
- */
- private function updateOrderRefundStatus(Order $order): void
- {
- // 根据支付方式更新订单状态
- if ($order->payment_type === PaymentMethod::BALANCE->value) {
- // 余额支付直接更新为退款成功
- $order->update([
- 'state' => OrderStatus::REFUNDED->value,
- 'refund_time' => now(),
- ]);
- // 创建退款成功记录
- $order->records()->create([
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::REFUNDED->value,
- 'remark' => '退款成功'
- ]);
- } else {
- // 微信支付更新为退款中
- $order->update([
- 'state' => OrderStatus::REFUNDING->value
- ]);
- // 创建退款中记录
- $order->records()->create([
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::REFUNDING->value,
- 'remark' => '退款处理中'
- ]);
- }
- }
- /**
- * 创建退款记录
- */
- private function createRefundRecords(Order $order, array $refundAmounts): void
- {
- // 创建退款记录
- $refundRecord = $order->refundRecords()->create([
- 'total_refund_amount' => $refundAmounts['total_refund'],
- 'balance_refund_amount' => $refundAmounts['balance_refund'],
- 'payment_refund_amount' => $refundAmounts['payment_refund'],
- 'deduct_amount' => $refundAmounts['deduct_amount'],
- 'state' => 'success',
- 'remark' => '用户申请退款',
- ]);
- // 创建订单状态记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => Auth::id(),
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::REFUNDING->value,
- 'remark' => '订单退款中',
- ]);
- }
- /**
- * 发送退款通知
- */
- private function notifyRefund(Order $order): void
- {
- // TODO: 实现退款通知逻辑
- // 1. 通知用户
- // event(new OrderRefundedEvent($order));
- // 2. 通知技师
- if ($order->coach_id) {
- // event(new OrderRefundedToCoachEvent($order));
- }
- }
- /**
- * 获取代理商配置
- */
- public function getAgentConfig(int $agentId): array
- {
- $agent = AgentInfo::where('id', $agentId)
- ->where('state', 'enable')
- ->firstOrFail();
- // $config = AgentConfig::where('agent_id', $agentId)->firstOrFail();
- return [
- // 'min_distance' => $config->min_distance,
- // 'min_fee' => $config->min_fee,
- // 'per_km_fee' => $config->per_km_fee
- ];
- }
- /**
- * 获取技师配置
- */
- public function getCoachConfig(int $coachId): array
- {
- $coach = CoachUser::where('id', $coachId)
- ->where('state', 'enable')
- ->where('auth_state', 'passed')
- ->firstOrFail();
- // $config = CoachConfig::where('coach_id', $coachId)->firstOrFail();
- return [
- // 'delivery_fee_type' => $config->delivery_fee_type,
- // 'charge_delivery_fee' => $config->charge_delivery_fee
- ];
- }
- /**
- * 计算路费
- *
- * @param int $coachId 技师ID
- * @param int $projectId 项目ID
- * @param int|null $agentId 代理商ID
- * @param float $distance 距离(公里)
- * @return float 路费金额
- *
- * @throws \Exception
- */
- public function calculateDeliveryFee(
- int $coachId,
- int $projectId,
- ?int $agentId,
- float $distance
- ): float {
- try {
- // 1. 验证基础参数
- $this->validateDeliveryFeeParams($coachId, $projectId, $distance);
- // 2. 获取计费规则
- $feeRules = $this->getDeliveryFeeRules($coachId, $agentId);
- // 3. 算路费
- return $this->calculateFeeByRules($distance, $feeRules, $coachId, $projectId);
- } catch (Exception $e) {
- $this->logError('计算路费失败', $e, [
- 'coach_id' => $coachId,
- 'project_id' => $projectId,
- 'agent_id' => $agentId,
- 'distance' => $distance,
- ]);
- throw $e;
- }
- }
- /**
- * 验证路费计算参数
- */
- private function validateDeliveryFeeParams(int $coachId, int $projectId, float $distance): void
- {
- // 验证技师状态
- $coach = $this->validateCoach($coachId);
- // 验证项目状态
- $project = Project::where('id', $projectId)
- ->where('state', ProjectStatus::OPEN->value)
- ->firstOrFail();
- // 验证距离有效性
- abort_if($distance < 0, 400, '距离计算错误');
- }
- /**
- * 获取路费计算规则
- *
- * @return array{
- * min_distance: float,
- * min_fee: float,
- * per_km_fee: float,
- * max_distance: float,
- * max_fee: float,
- * free_distance: float
- * }
- */
- private function getDeliveryFeeRules(int $coachId, ?int $agentId): array
- {
- // 1. 获取系统默认规则
- $defaultRules = $this->getDefaultDeliveryFeeRules();
- // 2. 获取代理商规则(如果有)
- $agentRules = $agentId ? $this->getAgentDeliveryFeeRules($agentId) : [];
- // 3. 获取技师个性化规则
- // $coachRules = $this->getCoachDeliveryFeeRules($coachId);
- // 4. 合并规则,优先级:技师 > 代理商 > 系统默认
- return array_merge(
- $defaultRules,
- $agentRules,
- // $coachRules
- );
- }
- /**
- * 获取系统默认路费规则
- */
- private function getDefaultDeliveryFeeRules(): array
- {
- // TODO: 从配置表中获取系统默认路费规则
- return [
- 'min_distance' => 3.0, // 最小计费距离(公里)
- 'min_fee' => 10.0, // 最小路费(元)
- 'per_km_fee' => 3.0, // 每公里费用(元)
- 'max_distance' => 120.0, // 最大服务距离(公里)
- 'max_fee' => 50.0, // 最大路费(元)
- 'free_distance' => 1.0, // 免费服务距离(公里)
- ];
- }
- /**
- * 获取代理商路费规则
- */
- private function getAgentDeliveryFeeRules(int $agentId): array
- {
- // $agentConfig = AgentConfig::where('agent_id', $agentId)
- // ->where('state', 'enable')
- // ->first();
- // if (! $agentConfig) {
- // return [];
- // }
- // return [
- // 'min_distance' => $agentConfig->min_distance,
- // 'min_fee' => $agentConfig->min_fee,
- // 'per_km_fee' => $agentConfig->per_km_fee,
- // 'max_distance' => $agentConfig->max_distance,
- // 'max_fee' => $agentConfig->max_fee,
- // 'free_distance' => $agentConfig->free_distance,
- // ];
- return [];
- }
- /**
- * 获取技师路费规则
- */
- private function getCoachDeliveryFeeRules(int $coachId): array
- {
- // TODO: 从配置表中获取技师个性化路费规则
- // $coachConfig = CoachConfig::where('coach_id', $coachId)
- // ->where('state', 'enable')
- // ->first();
- $coachConfig = null;
- if (! $coachConfig) {
- return [];
- }
- // 如果技师设置了不收取路费
- if (! $coachConfig->charge_delivery_fee) {
- return [
- 'min_fee' => 0,
- 'per_km_fee' => 0,
- 'max_fee' => 0,
- ];
- }
- return [
- 'min_distance' => $coachConfig->min_distance,
- 'min_fee' => $coachConfig->min_fee,
- 'per_km_fee' => $coachConfig->per_km_fee,
- 'max_distance' => $coachConfig->max_distance,
- 'max_fee' => $coachConfig->max_fee,
- 'free_distance' => $coachConfig->free_distance,
- ];
- }
- /**
- * 根据规则计算路费
- *
- * @param float $distance 距离(公里)
- * @param array{
- * min_distance: float, // 最小计费距离(公里)
- * min_fee: float, // 小路费(元)
- * per_km_fee: float, // 每公里费用(元)
- * max_distance: float, // 最大服务距离(公里)
- * max_fee: float, // 最大路费(元)
- * free_distance: float // 免费服务距离(公里)
- * } $rules 计费规则
- * @param int $coachId 技师ID
- * @param int $projectId 项目ID
- * @return float 路费金额(元)
- */
- private function calculateFeeByRules(float $distance, array $rules, int $coachId, int $projectId): float
- {
- // 1. 获取技师项目路费设置
- $coachProject = DB::table('coach_project')
- ->where('coach_id', $coachId)
- ->where('project_id', $projectId)
- ->where('state', 1) // 启用状态
- ->first();
- // 2. 如果技师设置了免路费,直接返回技师设置的固定路费
- if ($coachProject && (int)$coachProject->traffic_fee_type === 0) {
- return 0.00;
- }
- // 3. 检查是否超出最大服务距离
- abort_if(
- $distance > $rules['max_distance'],
- 400,
- sprintf('超出最大服务距离 %.1f 公里', $rules['max_distance'])
- );
- // 4. 检查是否在免费距离内
- if ($distance <= $rules['free_distance']) {
- return 0.00;
- }
- // 5. 计算实际计费距离
- $chargeDistance = max(0, $distance - $rules['free_distance']);
- // 6. 检查是否达到最小计费距离
- if ($chargeDistance < $rules['min_distance']) {
- return $rules['min_fee'];
- }
- // 7. 计算基础路费
- $fee = bcmul($chargeDistance, $rules['per_km_fee'], 2);
- // 8. 应用最小路费限制
- $fee = max($fee, $rules['min_fee']);
- // 9. 应用最大路费限制
- $fee = min($fee, $rules['max_fee']);
- // 10. 如果技师设置了固定路费,使用技师设置的路费
- if ($coachProject && $coachProject->traffic_fee > 0) {
- $fee = (float)$coachProject->traffic_fee;
- }
- // 11. 根据路费类型计算(单程/双程)
- if ($coachProject && $coachProject->traffic_fee_type === 2) { // 2表示双程
- $fee = bcmul($fee, '2', 2); // 双程路费翻倍
- }
- return $fee;
- }
- /**
- * 计算两点之间的距离
- *
- * @param float $lat1 起点纬度
- * @param float $lng1 起点经度
- * @param float $lat2 终点纬度
- * @param float $lng2 终点经度
- * @return float 距离(公里)
- */
- private function getDistance(float $lat1, float $lng1, float $lat2, float $lng2): float
- {
- // 将角度转为弧度
- $radLat1 = deg2rad($lat1);
- $radLat2 = deg2rad($lat2);
- $radLng1 = deg2rad($lng1);
- $radLng2 = deg2rad($lng2);
- // 地球半径(公里)
- $earthRadius = 6371;
- // 计算距离
- $distance = acos(
- sin($radLat1) * sin($radLat2) +
- cos($radLat1) * cos($radLat2) * cos($radLng1 - $radLng2)
- ) * $earthRadius;
- // 保留2位小数
- return round($distance, 2);
- }
- /**
- * 计算订单金额
- *
- * @param int $userId 用户ID
- * @param int|null $addressId 地址ID
- * @param int|null $coachId 技师ID
- * @param int $projectId 项目ID
- * @param int|null $agentId 代理商ID
- * @param bool $useBalance 是否使用余额
- * @param float $distance 距离
- * @param float $lat 纬度
- * @param float $lng 经度
- * @return array{
- * total_amount: float,
- * balance_amount: float,
- * pay_amount: float,
- * coupon_amount: float,
- * project_amount: float,
- * delivery_fee: float
- * }
- *
- * @throws \Exception
- */
- public function calculateOrderAmount(
- int $userId,
- ?int $addressId,
- ?int $coachId,
- int $projectId,
- ?int $agentId = null,
- bool $useBalance = false,
- float $distance = 0,
- float $lat = 0,
- float $lng = 0
- ): array {
- try {
- // 1. 验证用户状态和权限
- $user = $this->validateUserForCalculation($userId);
- // 2. 获取项目信息和价格(包含代理价格)
- $project = $this->getProjectWithPrice($projectId, $agentId);
- // 3. 计算路费(如果有技师)
- $deliveryFee = $this->calculateDeliveryFeeForOrder(
- coachId: $coachId,
- projectId: $projectId,
- agentId: $agentId,
- distance: $distance,
- addressId: $addressId,
- lat: $lat,
- lng: $lng
- );
- // 4. 计算优惠金额(优惠券、活动等)
- $discountAmount = $this->calculateDiscountAmount($projectId, $userId);
- // 5. 计算订单总金额(项目价格 + 路费 - 优惠金额)
- $totalAmount = $this->calculateTotalAmount($project->price, $deliveryFee, $discountAmount);
- // 6. 处理余额支付分配(优先使用余额)
- $paymentAmounts = $this->calculatePaymentDistribution(
- user: $user,
- totalAmount: $totalAmount,
- useBalance: $useBalance
- );
- // 7. 返回计算结果
- return [
- 'total_amount' => $totalAmount, // 订单总金额
- 'balance_amount' => $paymentAmounts['balance_amount'], // 余额支付金额
- 'pay_amount' => $paymentAmounts['pay_amount'], // 需要支付金额
- 'coupon_amount' => $discountAmount, // 优惠金额
- 'project_amount' => $project->price, // 项目原价
- 'delivery_fee' => $deliveryFee, // 路费
- ];
- } catch (Exception $e) {
- // 记录错误日志
- $this->logError('计算订单金额失败', $e, [
- 'user_id' => $userId,
- 'project_id' => $projectId,
- 'coach_id' => $coachId,
- 'address_id' => $addressId,
- ]);
- throw $e;
- }
- }
- /**
- * 验证用户状态
- */
- private function validateUserForCalculation(int $userId): MemberUser
- {
- $user = MemberUser::with('wallet')
- ->where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->first();
- abort_if(! $user, 404, '用户不存在或状态异常');
- return $user;
- }
- /**
- * 获取项目信息和价格
- */
- private function getProjectWithPrice(int $projectId, ?int $agentId): Project
- {
- // 获取基础项目信息
- $project = Project::where('id', $projectId)
- ->where('state', ProjectStatus::OPEN->value)
- ->first();
- abort_if(! $project, 404, '项目不存在或状态异常');
- // 如果有代理商,获取代理商价格
- if ($agentId) {
- $agentProject = $this->getAgentProjectPrice($agentId, $projectId);
- if ($agentProject) {
- $project->price = $agentProject->price;
- }
- }
- return $project;
- }
- /**
- * 获取代理商项目价格
- */
- private function getAgentProjectPrice(int $agentId, int $projectId): ?object
- {
- return DB::table('agent_project')
- ->where('agent_id', $agentId)
- ->where('project_id', $projectId)
- ->where('state', 'enable')
- ->first();
- }
- /**
- * 计算订单路费
- */
- private function calculateDeliveryFeeForOrder(
- ?int $coachId,
- int $projectId,
- ?int $agentId,
- float $distance,
- ?int $addressId,
- ?float $lat,
- ?float $lng
- ): float {
- // 如果没有技师,无需计算路费
- if (! $coachId) {
- return 0;
- }
- if (! $addressId && ! $lat && ! $lng) {
- return 0;
- }
- // 如果距离为0,需要重新计算距离
- if ($distance <= 0) {
- $distance = $this->calculateDistance($coachId, $addressId, $lat, $lng);
- }
- return $this->calculateDeliveryFee($coachId, $projectId, $agentId, $distance);
- }
- /**
- * 获取技师位置信息
- */
- private function getCoachLocation(int $coachId): array
- {
- // 从技师服务获取最新位置信息
- $location = $this->coachService->getLocation($coachId);
- // 如果没有位置信息,返回系统默认位置
- if (empty($location)) {
- return [
- 'latitude' => config('business.default_latitude', 0),
- 'longitude' => config('business.default_longitude', 0),
- ];
- }
- // 格式化位置数据
- return [
- 'latitude' => (float) $location->latitude,
- 'longitude' => (float) $location->longitude,
- ];
- }
- /**
- * 计算技师与服务地址的距离
- */
- private function calculateDistance(int $coachId, int $addressId, float $lat, float $lng): float
- {
- try {
- // 如果提供了地址ID,优先使用地址表中的经纬度
- if ($addressId > 0) {
- $address = MemberAddress::find($addressId);
- // 使用地址的经纬度,如果没有则使用传入的经纬度
- $lat = $address?->latitude ?? $lat;
- $lng = $address?->longitude ?? $lng;
- }
- // 从Redis获取技师的两个位置点信息
- // 获取常用地址位置(如家庭地址)
- $homeLocation = Redis::geopos(
- 'coach_locations',
- $coachId . '_' . TechnicianLocationType::COMMON->value
- );
- // 获取当前实时位置
- $workLocation = Redis::geopos(
- 'coach_locations',
- $coachId . '_' . TechnicianLocationType::CURRENT->value
- );
- $distances = [];
- // 计算与常用地址的距离
- if ($homeLocation && $homeLocation[0]) {
- $distances[] = $this->getDistance($homeLocation[0][1], $homeLocation[0][0], $lat, $lng);
- }
- // 计算与当前位置的距离
- if ($workLocation && $workLocation[0]) {
- $distances[] = $this->getDistance($workLocation[0][1], $workLocation[0][0], $lat, $lng);
- }
- // 如果有有效距离,返回最小值;否则返回0
- return ! empty($distances) ? min($distances) : 0.0;
- } catch (\Exception $e) {
- Log::error('计算距离失败', [
- 'error' => $e->getMessage(),
- 'coach_id' => $coachId,
- 'address_id' => $addressId,
- 'lat' => $lat,
- 'lng' => $lng,
- ]);
- return 0.0;
- }
- }
- /**
- * 计算优惠金额
- */
- private function calculateDiscountAmount(int $projectId, int $userId): float
- {
- $discountAmount = 0;
- // TODO: 实现优惠券、活动等优惠计算逻辑
- return $discountAmount;
- }
- /**
- * 计算订单总金额
- */
- private function calculateTotalAmount(float $projectPrice, float $deliveryFee, float $discountAmount): float
- {
- $totalAmount = bcadd($projectPrice, $deliveryFee, 2);
- $totalAmount = bcsub($totalAmount, $discountAmount, 2);
- return max(0, $totalAmount);
- }
- /**
- * 计算支付金额分配
- *
- * @return array{balance_amount: float, pay_amount: float}
- */
- private function calculatePaymentDistribution(MemberUser $user, float $totalAmount, bool $useBalance): array
- {
- if (! $useBalance || $totalAmount <= 0) {
- return [
- 'balance_amount' => 0,
- 'pay_amount' => $totalAmount,
- ];
- }
- $availableBalance = $user->wallet?->available_balance ?? 0;
- if ($availableBalance >= $totalAmount) {
- return [
- 'balance_amount' => $totalAmount,
- 'pay_amount' => 0,
- ];
- }
- return [
- 'balance_amount' => $availableBalance,
- 'pay_amount' => bcsub($totalAmount, $availableBalance, 2),
- ];
- }
- /**
- * 获取订单抢单池列表
- *
- * @param int $orderId 订单ID
- * @return array 抢单池列表
- */
- public function getOrderGrabList(int $orderId): array
- {
- try {
- // 查询订单信息
- $order = Order::where('id', $orderId)
- ->whereIn('state', [OrderStatus::CREATED->value])
- ->firstOrFail();
- // 查询抢单池表
- $grabList = $order->grabRecords()->with(['coach.info'])->get();
- // 格式化返回数据
- $result = [];
- foreach ($grabList as $grab) {
- $coach = $grab->coach;
- $result[] = [
- 'id' => $grab->id,
- 'coach_id' => $coach->id,
- 'nickname' => $coach->info->nickname,
- 'avatar' => $coach->info->avatar,
- 'distance' => $grab->distance,
- 'created_at' => $grab->created_at->format('Y-m-d H:i:s'),
- ];
- }
- return $result;
- } catch (\Exception $e) {
- Log::error('获取订单抢单池列表失败', [
- 'error' => $e->getMessage(),
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- }
- /**
- * 指定技师
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @param int $coachId 技师ID
- *
- * @throws \Exception
- */
- public function assignCoach(int $userId, int $orderId, int $coachId): bool
- {
- return DB::transaction(function () use ($userId, $orderId, $coachId) {
- try {
- // 1. 验证参数
- $order = $this->validateAssignOrder($userId, $orderId);
- // 2. 验证技师
- $coach = $this->validateCoach($coachId);
- // 3. 检查抢单池状态
- $this->validateGrabPool($order);
- // 4. 更新订单信息
- $this->updateOrderForAssign($order, $coachId);
- // 5. 创建订单记录(指派)
- $this->createAssignRecord($order, $userId);
- // 6. 处理支付
- if ($order->payment_type === PaymentMethod::BALANCE->value) {
- $this->handleBalancePaymentForAssign($order, $userId, $coachId);
- }
- // 7. 发送通知
- $this->notifyAssignment($order, $coach);
- return true;
- } catch (Exception $e) {
- $this->logError('指定技师失败', $e, [
- 'user_id' => $userId,
- 'order_id' => $orderId,
- 'coach_id' => $coachId,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 验证指定技师的订单条件
- */
- private function validateAssignOrder(int $userId, int $orderId): Order
- {
- // 验证用户状态
- $user = MemberUser::where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->firstOrFail();
- // 验证订单状态
- $order = $user->orders()
- ->where('id', $orderId)
- ->whereIn('state', [OrderStatus::CREATED->value, OrderStatus::PAID->value])
- ->lockForUpdate()
- ->firstOrFail();
- return $order;
- }
- /**
- * 验证抢单池状态
- */
- private function validateGrabPool(Order $order): void
- {
- // 检查抢单池是否已有抢单成功记录
- $existsGrabSuccess = $order->grabRecords()
- ->where('state', OrderGrabRecordStatus::SUCCEEDED->value)
- ->exists();
- abort_if($existsGrabSuccess, 400, '该订单已抢单完成');
- }
- /**
- * 更新订单信息
- */
- private function updateOrderForAssign(Order $order, int $coachId): void
- {
- // 修改订单技师
- $order->coach_id = $coachId;
- // 待支付订单需要重新计算金额
- if ($order->state === OrderStatus::CREATED->value) {
- $amounts = $this->calculateOrderAmount(
- userId: $order->user_id,
- addressId: $order->address_id,
- coachId: $coachId,
- projectId: $order->project_id,
- agentId: $order->agent_id,
- useBalance: $order->payment_type === PaymentMethod::BALANCE->value
- );
- // 更新订单金额
- $order->fill([
- 'total_amount' => $amounts['total_amount'],
- 'balance_amount' => $amounts['balance_amount'],
- 'pay_amount' => $amounts['pay_amount'],
- 'discount_amount' => $amounts['coupon_amount'],
- 'project_amount' => $amounts['project_amount'],
- 'traffic_amount' => $amounts['delivery_fee'],
- ]);
- }
- $order->save();
- }
- /**
- * 处理指派订单的余额支付
- */
- private function handleBalancePaymentForAssign(Order $order, int $userId, int $coachId): void
- {
- // 验证余额
- $user = MemberUser::find($userId);
- $wallet = $user->wallet;
- abort_if($wallet->available_balance < $order->balance_amount, 400, '可用余额不足');
- // 扣除余额
- DB::transaction(function () use ($wallet, $order, $userId, $coachId) {
- // 更新钱包余额
- $wallet->decrement('total_balance', $order->balance_amount);
- $wallet->decrement('available_balance', $order->balance_amount);
- // 更新订单状态
- $order->update(['state' => OrderStatus::PAID->value]);
- // 创建钱包支付记录
- $this->createWalletPaymentRecord($order, $wallet);
- // 创建支付成功记录
- $this->createPaymentSuccessRecord($order, $userId);
- // 更新抢单记录
- $this->updateGrabRecords($order->id, $coachId);
- });
- }
- /**
- * 创建钱包支付记录
- */
- private function createWalletPaymentRecord(Order $order, $wallet): void
- {
- WalletPaymentRecord::create([
- 'order_id' => $order->id,
- 'wallet_id' => $wallet->id,
- 'payment_no' => 'B_' . $order->id,
- 'payment_method' => 'balance',
- 'total_amount' => $order->balance_amount,
- 'actual_amount' => 0,
- 'used_wallet_balance' => $order->balance_amount,
- 'used_recharge_balance' => 0,
- 'state' => 'success',
- ]);
- }
- /**
- * 创建支付成功记录
- */
- private function createPaymentSuccessRecord(Order $order, int $userId): void
- {
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::PAID->value,
- 'remark' => '余额支付成功',
- ]);
- }
- /**
- * 更新抢单记录
- */
- private function updateGrabRecords(int $orderId, int $coachId): void
- {
- OrderGrabRecord::where('order_id', $orderId)
- ->update([
- 'state' => OrderGrabRecordStatus::SUCCEEDED->value,
- 'coach_id' => $coachId,
- ]);
- }
- /**
- * 发送指派通知
- */
- private function notifyAssignment(Order $order, CoachUser $coach): void
- {
- // TODO: 实现通知逻辑
- // event(new OrderAssignedEvent($order, $coach));
- }
- /**
- * 生成订单核销码
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @return array{
- * order_id: int,
- * qr_code: string,
- * qr_image: ?string,
- * expired_at: string,
- * state: string
- * } 返回核销码信息
- *
- * @throws \Exception
- */
- public function generateVerificationCode(int $userId, int $orderId): array
- {
- try {
- // 验证订单状态和归属
- $order = $this->validateOrderForVerification($userId, $orderId);
- // 生成核销码数据
- $verificationData = $this->generateVerificationData($order->id);
- // 生成二维码图片
- $qrCodeImage = $this->generateQRCodeImage($verificationData['qr_code']);
- return [
- 'order_id' => $order->id,
- 'qr_code' => $verificationData['qr_code'],
- 'qr_image' => $qrCodeImage,
- 'expired_at' => $verificationData['expired_at'],
- 'state' => $order->state,
- ];
- } catch (Exception $e) {
- $this->logError('生成订单核销码失败', $e, [
- 'user_id' => $userId,
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- }
- /**
- * 验证订单状态和归属
- */
- private function validateOrderForVerification(int $userId, int $orderId): Order
- {
- // 验证用户状态
- $user = MemberUser::where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->firstOrFail();
- // 验证订单状态和归属
- $order = $user->orders()
- ->where('id', $orderId)
- ->whereIn('state', [
- OrderStatus::PAID->value,
- OrderStatus::ACCEPTED->value,
- OrderStatus::DEPARTED->value,
- OrderStatus::ARRIVED->value,
- ])
- ->firstOrFail();
- return $order;
- }
- /**
- * 生成核销码数据
- *
- * @param int $orderId 订单ID
- * @return array{qr_code: string, expired_at: string}
- */
- private function generateVerificationData(int $orderId): array
- {
- // 生成时间戳
- $timestamp = time();
- // 生成签名
- $sign = md5("order_{$orderId}_{$timestamp}_" . config('app.key'));
- // 组装二维码内容
- $qrCode = "order_{$orderId}_{$timestamp}_{$sign}";
- return [
- 'qr_code' => $qrCode,
- 'expired_at' => date('Y-m-d H:i:s', $timestamp + 300), // 5分钟有效期
- ];
- }
- /**
- * 生成二维码图片
- *
- * @param string $content 二维码内容
- * @return string|null Base64编码的图片数据
- */
- private function generateQRCodeImage(string $content): ?string
- {
- // 生成SVG格式的二维码
- $qrCodeImage = QrCode::format('svg')
- ->size(200) // 设置二维码大小为200px
- ->margin(1) // 设置二维码边距为1
- ->errorCorrection('H') // 设置纠错级别为最高级别H
- ->generate($content);
- // 将SVG转为base64
- return 'data:image/svg+xml;base64,' . base64_encode($qrCodeImage);
- }
- /**
- * 验证技师服务时间是否可用
- */
- public function validateServiceTime(int $coachId, string $serviceTime): bool
- {
- try {
- // 1. 验证基础参数(技师状态、时间格式等)
- $this->validateServiceTimeParams($coachId, $serviceTime);
- // 2. 获取技师工作时间安排
- $workSchedule = $this->getCoachWorkSchedule($coachId);
- // 3. 验证是否在工作时间内
- $this->validateWorkingHours($serviceTime, $workSchedule);
- // 4. 检查是否与其他订单时间冲突
- $this->checkTimeConflicts($coachId, $serviceTime);
- return true;
- } catch (Exception $e) {
- // 记录错误日志
- $this->logError('验证服务时间失败', $e, [
- 'coach_id' => $coachId,
- 'service_time' => $serviceTime,
- ]);
- throw $e;
- }
- }
- /**
- * 检查订单时间冲突
- */
- private function checkTimeConflicts(int $coachId, string $serviceTime): void
- {
- $serviceDateTime = Carbon::parse($serviceTime);
- // 获取服务时长配置(默认2小时)
- $serviceDuration = config('business.default_service_duration', 120);
- // 计算本次服务的结束时间
- $serviceEndTime = $serviceDateTime->copy()->addMinutes($serviceDuration);
- // 检查是否与其他订单时间重叠
- $conflictOrder = Order::where('coach_id', $coachId)
- ->whereIn('state', [
- OrderStatus::PAID->value, // 已支付
- OrderStatus::ACCEPTED->value, // 已接单
- OrderStatus::SERVICING->value, // 服务中
- ])
- ->where(function ($query) use ($serviceDateTime, $serviceEndTime) {
- $query->where(function ($q) use ($serviceDateTime) {
- // 检查服务开始时间是否冲突
- $q->where('service_time', '<=', $serviceDateTime)
- ->where('service_end_time', '>', $serviceDateTime);
- })->orWhere(function ($q) use ($serviceEndTime) {
- // 检查服务结束时间是否冲突
- $q->where('service_time', '<', $serviceEndTime)
- ->where('service_end_time', '>=', $serviceEndTime);
- });
- })
- ->first();
- // 如果存在时间冲突,抛出异常
- abort_if(
- $conflictOrder,
- 400,
- '该时间段技师已有其他订单'
- );
- }
- /**
- * 订单评价
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @param array{
- * score: int,
- * content: string,
- * images: ?array,
- * tags: ?array
- * } $data 评价数据
- * @return array{message: string}
- *
- * @throws \Exception
- */
- public function evaluateOrder(int $userId, int $orderId, array $data): array
- {
- return DB::transaction(function () use ($userId, $orderId, $data) {
- try {
- // 1. 验证订单状态
- $order = $this->validateOrderForEvaluation($userId, $orderId);
- // 2. 创建评价记录
- $evaluation = $this->createEvaluation($order, $data);
- // 3. 更新技师评分
- // TODO: 更新技师评分
- $this->updateCoachScore($order->coach_id);
- // 4. 更新订单状态
- $this->updateOrderEvaluationStatus($order);
- // 5. 创建评价奖励
- // TODO: 创建评价奖励
- // $this->createEvaluationReward($order, $evaluation);
- // 6. 发送评价通知
- // $this->notifyEvaluation($order, $evaluation);
- return ['message' => '评价成功'];
- } catch (Exception $e) {
- $this->logError('订单评价失败', $e, [
- 'user_id' => $userId,
- 'order_id' => $orderId,
- 'data' => $data,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 验证订单评价条件
- */
- private function validateOrderForEvaluation(int $userId, int $orderId): Order
- {
- // 获取订单信息
- $order = Order::where('id', $orderId)
- ->where('user_id', $userId)
- ->where('state', OrderStatus::LEFT->value)
- ->firstOrFail();
- // 检查是否已评价
- abort_if(
- $order->evaluation()->exists(),
- 400,
- '订单已评价'
- );
- // 检查评价时效(7天内可评价)
- $evaluationExpireDays = config('business.evaluation_expire_days', 7);
- abort_if(
- $order->finish_time->addDays($evaluationExpireDays)->isPast(),
- 400,
- '评价已过期'
- );
- return $order;
- }
- /**
- * 更新订单评价状态
- */
- private function updateOrderEvaluationStatus(Order $order): void
- {
- // 创建订单记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::EVALUATED->value,
- 'remark' => '用户评价完成',
- ]);
- }
- /**
- * 创建评价奖励
- */
- // private function createEvaluationReward(Order $order, OrderEvaluation $evaluation): void
- // {
- // // 获取评价奖励配置
- // $rewardAmount = config('business.evaluation_reward_amount', 0);
- // if ($rewardAmount <= 0) {
- // return;
- // }
- // // 更新用户钱包
- // $wallet = $order->user->wallet;
- // $wallet->increment('total_balance', $rewardAmount);
- // $wallet->increment('available_balance', $rewardAmount);
- // // 创建奖励记录
- // $wallet->transRecords()->create([
- // 'amount' => $rewardAmount,
- // 'trans_type' => 'evaluation_reward',
- // 'owner_type' => OrderEvaluation::class,
- // 'owner_id' => $evaluation->id,
- // 'remark' => '评价奖励',
- // 'before_balance' => $wallet->total_balance - $rewardAmount,
- // 'after_balance' => $wallet->total_balance,
- // 'state' => 'success',
- // ]);
- // }
- /**
- * 发送评价通知
- */
- // private function notifyEvaluation(Order $order, OrderEvaluation $evaluation): void
- // {
- // // TODO: 实现评价通知逻辑
- // // 1. 通知技师
- // // event(new OrderEvaluatedEvent($order, $evaluation));
- // // 2. 更新评价缓存
- // // Cache::tags(['coach_evaluations'])->forget("coach:{$order->coach_id}");
- // }
- private function getNearbyCoaches(float $lat, float $lng, float $radius = 5.0): Collection
- {
- // 获取在线技师列表
- return CoachUser::query()
- ->with(['info'])
- ->where('state', TechnicianStatus::ACTIVE->value)
- ->whereHas('info', fn($q) => $q->where('state', TechnicianAuthStatus::PASSED->value))
- ->get();
- }
- private function validateCoachForGrab(int $coachId): CoachUser
- {
- $coach = CoachUser::query()
- ->with(['info'])
- ->where('id', $coachId)
- ->where('state', TechnicianStatus::ACTIVE->value)
- ->first();
- abort_if(! $coach, 400, '技师不存在或未激活');
- // 验证技师认证状态
- abort_if(
- ! $coach->info || $coach->info->state !== TechnicianAuthStatus::PASSED->value,
- 400,
- '技师未通过认证'
- );
- return $coach;
- }
- public function getOrder(int $orderId): Order
- {
- $order = Order::find($orderId);
- abort_if(! $order, 404, '订单不存在');
- return $order;
- }
- private function findOrder(int $orderId): Order
- {
- $order = Order::find($orderId);
- abort_if(! $order, 404, sprintf('订单[%d]不存在', $orderId));
- return $order;
- }
- private function getOrderForPayment(int $orderId): Order
- {
- $order = Order::where('id', $orderId)
- ->whereIn('state', [OrderStatus::CREATED->value])
- ->first();
- abort_if(! $order, 404, sprintf('订单[%d]不存在', $orderId));
- abort_if(
- $order->state !== OrderStatus::CREATED->value,
- 422,
- sprintf('订单[%d]状态为[%s],不允许支付', $orderId, $order->state)
- );
- return $order;
- }
- /**
- * 评价订单
- *
- * @param int $userId 用户ID
- * @param array $data 评价数据
- */
- public function rateOrder(int $userId, array $data): void
- {
- // 查找订单并加载关联数据
- $order = Order::query()
- ->where('user_id', $userId)
- ->where('id', $data['order_id'])
- ->first();
- // 检查订单是否存在
- abort_if(!$order, 404, sprintf('订单[%d]不存在', $data['order_id']));
- // 检查订单是否属于当前用户
- abort_if((int)$order->user_id !== $userId, 403, '无权评价此订单');
- // 检查订单状态 - 确保类型一致性比较
- abort_if((int)$order->state !== OrderStatus::LEFT->value, 400, sprintf('订单状态为[%s],不允许评价', $order->state));
- // 检查是否已评价
- abort_if($order->comments()->exists(), 400, '订单已评价');
- // 验证评分范围
- foreach (['service_score', 'appearance_score', 'attitude_score', 'professional_score'] as $scoreField) {
- if (isset($data[$scoreField])) {
- $score = (float)$data[$scoreField];
- abort_if($score < 1 || $score > 5, 400, '评分范围必须在1-5之间');
- }
- }
- DB::transaction(function () use ($order, $data, $userId) {
- // 创建评价记录
- $comment = $order->comments()->create([
- 'user_id' => $userId,
- 'coach_id' => $order->coach_id,
- 'service_score' => isset($data['service_score']) ? (float)$data['service_score'] : 5.0,
- 'appearance_score' => isset($data['appearance_score']) ? (float)$data['appearance_score'] : 5.0,
- 'attitude_score' => isset($data['attitude_score']) ? (float)$data['attitude_score'] : 5.0,
- 'professional_score' => isset($data['professional_score']) ? (float)$data['professional_score'] : 5.0,
- 'tags' => $data['tags'] ?? [],
- 'content' => $data['content'] ?? '',
- 'images' => $data['images'] ?? [],
- ]);
- // 更新订单状态为已完成
- $order->update(['state' => OrderStatus::COMPLETED->value]);
- // 更新技师评分
- $this->updateCoachScore($order->coach_id);
- // 记录订单状态变更
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::EVALUATED->value,
- 'remark' => '用户完成评价',
- ]);
- });
- }
- /**
- * 更新技师评分
- *
- * @param int $coachId 技师ID
- */
- private function updateCoachScore(int $coachId): void
- {
- $coach = CoachUser::find($coachId);
- if (!$coach) {
- return;
- }
- // 计算技师的各维度平均分
- $avgScores = DB::table('order_comments')
- ->where('coach_id', $coachId)
- ->whereExists(function ($query) {
- $query->select(DB::raw(1))
- ->from('order')
- ->whereColumn('order_comments.order_id', 'order.id')
- ->where('order.state', OrderStatus::COMPLETED->value);
- })
- ->select([
- DB::raw('AVG(service_score) as avg_service_score'),
- DB::raw('AVG(appearance_score) as avg_appearance_score'),
- DB::raw('AVG(attitude_score) as avg_attitude_score'),
- DB::raw('AVG(professional_score) as avg_professional_score'),
- DB::raw('COUNT(*) as total_comments')
- ])
- ->first();
- // 获取订单统计
- $orderCounts = DB::table('order')
- ->where('coach_id', $coachId)
- ->select([
- DB::raw('COUNT(*) as total_orders'),
- DB::raw('COUNT(CASE WHEN state = ' . OrderStatus::COMPLETED->value . ' THEN 1 END) as completed_orders')
- ])
- ->first();
- if ($avgScores) {
- // 计算总体平均分
- $overallScore = round(($avgScores->avg_service_score +
- $avgScores->avg_appearance_score +
- $avgScores->avg_attitude_score +
- $avgScores->avg_professional_score) / 4, 1);
- // 更新或创建统计记录
- CoachStatistic::updateOrCreate(
- ['coach_id' => $coachId],
- [
- 'score' => $overallScore,
- 'service_score' => round($avgScores->avg_service_score, 1),
- 'appearance_score' => round($avgScores->avg_appearance_score, 1),
- 'attitude_score' => round($avgScores->avg_attitude_score, 1),
- 'professional_score' => round($avgScores->avg_professional_score, 1),
- 'comment_count' => $avgScores->total_comments,
- 'order_count' => $orderCounts->total_orders,
- 'completed_order_count' => $orderCounts->completed_orders
- ]
- );
- }
- }
- /**
- * 生成退款单号
- * 格式:RF + 年月日时分秒 + 订单ID后4位 + 4位随机数
- * 示例:RF202403151428120001RAND
- *
- * @param Order $order 订单对象
- * @return string 退款单号
- */
- private function generateRefundNo(Order $order): string
- {
- // 获取时间戳
- $timestamp = now()->format('YmdHis');
- // 获取订单ID后4位,不足4位前面补0
- $orderIdSuffix = str_pad(substr($order->id, -4), 4, '0', STR_PAD_LEFT);
- // 生成4位随机数
- $random = str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT);
- // 组合退款单号:前缀 + 时间戳 + 订单ID后缀 + 随机数
- return "RF{$timestamp}{$orderIdSuffix}{$random}";
- }
- /**
- * 用户删除订单
- *
- * 业务逻辑:
- * 1. 验证订单是否存在且属于当前用户
- * 2. 验证订单状态是否允许删除(已完成、已取消等)
- * 3. 更新订单的user_deleted_at字段
- * 4. 记录删除操作
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @return array
- * @throws \Exception
- */
- public function deleteOrder(int $userId, int $orderId): array
- {
- return DB::transaction(function () use ($userId, $orderId) {
- // 验证订单是否存在且属于当前用户
- $order = Order::where('id', $orderId)
- ->where('user_id', $userId)
- ->whereNull('user_deleted_at') // 确保订单未被用户删除
- ->first();
- abort_if(!$order, 404, '订单不存在');
- // 验证订单状态是否允许删除
- // 允许删除未支付、已完成、已取消、已退款等状态的订单
- $allowedStates = [
- OrderStatus::CREATED->value, // 未支付
- OrderStatus::COMPLETED->value, // 已完成
- OrderStatus::CANCELLED->value, // 已取消
- OrderStatus::REFUNDED->value, // 已退款
- ];
- abort_if(!in_array($order->state, $allowedStates), 422, '当前订单状态不允许删除');
- // 标记订单为用户已删除
- $order->update([
- 'user_deleted_at' => now()
- ]);
- // 创建订单记录
- $this->createOrderRecord(
- $order,
- $userId,
- 'user',
- OrderRecordStatus::DELETED,
- '用户删除订单'
- );
- return [
- 'message' => '订单删除成功'
- ];
- });
- }
- }
|