1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563 |
- <?php
- namespace App\Services\Client;
- use App\Enums\OrderGrabRecordStatus;
- use App\Enums\OrderRecordStatus;
- use App\Enums\OrderStatus;
- use App\Enums\OrderType;
- use App\Enums\PaymentMethod;
- use App\Enums\ProjectStatus;
- use App\Enums\TechnicianAuthStatus;
- use App\Enums\TechnicianLocationType;
- use App\Enums\TechnicianStatus;
- use App\Enums\TransactionType;
- use App\Enums\UserStatus;
- use App\Models\AgentInfo;
- use App\Models\CoachUser;
- use App\Models\MemberAddress;
- use App\Models\MemberUser;
- use App\Models\Order;
- use App\Models\OrderGrabRecord;
- use App\Models\OrderRecord;
- use App\Models\Project;
- use App\Models\WalletPaymentRecord;
- use App\Services\Client\Traits\CalculatesOrderAmounts;
- use App\Services\Client\Traits\HandlesOrderRecords;
- use App\Services\Client\Traits\HandlesPayments;
- use App\Services\Client\Traits\ValidatesServiceTime;
- use Carbon\Carbon;
- use Exception;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Redis;
- use SimpleSoftwareIO\QrCode\Facades\QrCode;
- 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
- {
- try {
- // 参数验证
- $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']);
- $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: $data['distance'] ?? 0,
- lat: $data['latitude'] ?? 0,
- lng: $data['longitude'] ?? 0
- );
- return [
- 'wallet' => $user->wallet,
- 'coach' => $coach,
- 'project' => $project,
- 'address' => $user->address,
- 'amounts' => $amounts,
- 'availableTimeSlots' => $availableTimeSlots,
- ];
- });
- } catch (Exception $e) {
- $this->logError('订单初始化失败', $e, [
- 'userId' => $userId,
- 'data' => $data,
- ]);
- throw $e;
- }
- }
- /**
- * 验证初始化数据
- *
- * 逻辑描述:
- * 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 {
- // 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->value,
- OrderStatus::SERVICE_ING->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'])
- ->firstOrFail();
- // 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);
- return [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'total_amount' => $amounts['total_amount'],
- 'balance_amount' => $amounts['balance_amount'],
- 'pay_amount' => $amounts['pay_amount'],
- ];
- } 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)
- ->firstOrFail();
- // 验证项目状态
- $project = Project::where('id', $data['project_id'])
- ->where('state', ProjectStatus::OPEN->value)
- ->firstOrFail();
- // 验证服务时间和技师状态
- 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
- {
- 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,
- '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'],
- ]);
- }
- 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
- {
- $wallet = $order->user->wallet;
- // 检查钱包可用余额是否足够
- abort_if($wallet->available_balance < $order->balance_amount, 400, '钱包可用余额不足,无法完成支付');
- // 扣减钱包余额
- $wallet->decrement('total_balance', $order->balance_amount);
- $wallet->decrement('available_balance', $order->balance_amount);
- // 增加冻结金额
- $wallet->increment('frozen_amount', $order->balance_amount);
- // 创建钱包交易记录
- $wallet->transRecords()->create([
- 'amount' => -$order->balance_amount,
- 'trans_type' => TransactionType::PAYMENT->value,
- 'owner_type' => Order::class,
- 'owner_id' => $order->id,
- 'remark' => '订单支付',
- 'before_balance' => $wallet->total_balance + $order->balance_amount,
- 'after_balance' => $wallet->total_balance,
- 'state' => 'success',
- ]);
- }
- /**
- * 创建订单相关记录
- */
- 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));
- // 2. 通知技师(如果有)
- if ($order->coach_id) {
- // event(new OrderAssignedToCoachEvent($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::SERVING->value, OrderStatus::FINISHED->value])
- ->firstOrFail();
- return $originalOrder;
- }
- // 提取方法:准备加钟订单数据
- private function prepareAddTimeData($originalOrder, $data): array
- {
- if ($originalOrder->state == OrderStatus::SERVING->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. 计算取消���用
- $cancelAmounts = $this->calculateCancelAmount($order);
- // 3. 处理退款
- $this->processCancelRefund($order, $cancelAmounts);
- // 4. 更新订单状态
- $this->updateOrderCancelStatus($order);
- // 5. 创建取消记录
- $this->createCancelRecords($order, $cancelAmounts, $reason);
- // 6. 发送取消通知
- $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::CREATED->value,
- OrderStatus::PAID->value,
- OrderStatus::ACCEPTED->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 = 0;
- // 计算违约金(根据订单状态和时间)
- if ($order->state === OrderStatus::ACCEPTED->value) {
- // 已接单取消,收取10%违约金
- $penaltyAmount = bcmul($order->total_amount, '0.1', 2);
- }
- // 计算实际退款金额
- $totalRefund = bcsub($order->total_amount, $penaltyAmount, 2);
- // 分配退款金额(优先退还支付金额)
- $balanceRefund = min($order->balance_amount, $totalRefund);
- $paymentRefund = bcsub($totalRefund, $balanceRefund, 2);
- return [
- 'total_refund' => $totalRefund,
- 'balance_refund' => $balanceRefund,
- 'payment_refund' => $paymentRefund,
- 'penalty_amount' => $penaltyAmount,
- ];
- }
- /**
- * 处理取消退款
- */
- private function processCancelRefund(Order $order, array $cancelAmounts): void
- {
- // 处理余额退款
- if ($cancelAmounts['balance_refund'] > 0) {
- $this->processBalanceCancelRefund($order, $cancelAmounts['balance_refund']);
- }
- // 处理支付退款
- if ($cancelAmounts['payment_refund'] > 0) {
- $this->processPaymentCancelRefund($order, $cancelAmounts['payment_refund']);
- }
- }
- /**
- * 处理余额退款
- */
- 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' => 'cancel_refund',
- 'owner_type' => Order::class,
- 'owner_id' => $order->id,
- 'remark' => '订单取消退款',
- 'before_balance' => $wallet->total_balance - $amount,
- 'after_balance' => $wallet->total_balance,
- 'state' => 'success',
- ]);
- }
- /**
- * 处理支付退款
- */
- private function processPaymentCancelRefund(Order $order, float $amount): void
- {
- // TODO: 实现第三方支付退款逻辑
- // $paymentService = app(PaymentService::class);
- // $paymentService->refund($order->payment_no, $amount);
- }
- /**
- * 更新订单取消状态
- */
- private function updateOrderCancelStatus(Order $order): void
- {
- $order->update([
- 'state' => OrderStatus::CANCELLED->value,
- ]);
- }
- /**
- * 创建取消记录
- */
- private function createCancelRecords(Order $order, array $cancelAmounts, ?string $reason): void
- {
- // TODO: 创建取消记录
- // 创建取消记录
- // $order->cancelRecords()->create([
- // 'total_refund_amount' => $cancelAmounts['total_refund'],
- // 'balance_refund_amount' => $cancelAmounts['balance_refund'],
- // 'payment_refund_amount' => $cancelAmounts['payment_refund'],
- // 'penalty_amount' => $cancelAmounts['penalty_amount'],
- // 'remark' => $reason ?? '',
- // 'state' => 'success',
- // ]);
- // 创建订单状态记录
- 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);
- // 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::SERVING->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::FINISHED->value;
- $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::FINISHED->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::LEFT->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 array{
- * state: ?string,
- * start_date: ?string,
- * end_date: ?string,
- * project_id: ?int,
- * coach_id: ?int,
- * order_no: ?string,
- * per_page: ?int,
- * page: ?int
- * } $filters 过滤条件
- *
- * @throws \Exception
- */
- public function getOrderList(int $userId, array $filters = [])
- {
- try {
- // 1. 验证用户
- $user = $this->validateUserForQuery($userId);
- // 2. 构建基础查询
- $query = $this->buildOrderListQuery($user);
- // 3. 应用过滤条件
- $this->applyOrderFilters($query, $filters);
- // 4. 加载关联数据并分页
- return $this->paginateOrderList($query, $filters);
- } catch (Exception $e) {
- $this->logError('获取订单列表失败', $e, [
- 'user_id' => $userId,
- 'filters' => $filters,
- ]);
- throw $e;
- }
- }
- /**
- * 验证用户查询权限
- */
- 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()
- ->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 paginateOrderList($query, array $filters)
- {
- $paginatedOrders = $query->orderBy('created_at', 'desc')
- ->paginate(
- perPage: $filters['per_page'] ?? 10,
- page: $filters['page'] ?? 1
- );
- $formattedOrders = $paginatedOrders->map(function ($order) {
- return $this->formatOrderListItem($order);
- });
- return [
- 'items' => $formattedOrders,
- 'total' => $paginatedOrders->total(),
- ];
- }
- /**
- * �������化订��列表项
- */
- private function formatOrderListItem(Order $order): array
- {
- return [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'state' => $order->state,
- 'state_description' => $this->getOrderStateDescription($order->state),
- 'total_amount' => $order->total_amount,
- 'service_time' => $order->service_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_description' => $this->getOrderStateDescription($order->state),
- '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,
- 'created_at' => $order->created_at->toDateTimeString(),
- 'remark' => $order->remark,
- '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['state'])) {
- $query->where('state', $filters['state']);
- }
- // 按时间范围筛选
- 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']}%");
- }
- }
- /**
- * 获取订单状态描述
- */
- private function getOrderStateDescription(string $state): string
- {
- return match ($state) {
- OrderStatus::CREATED->value => '待支付',
- OrderStatus::PAID->value => '待接单',
- OrderStatus::ACCEPTED->value => '已接单',
- OrderStatus::DEPARTED->value => '已出发',
- OrderStatus::ARRIVED->value => '已到达',
- OrderStatus::SERVING->value => '服务中',
- OrderStatus::FINISHED->value => '已完成',
- OrderStatus::CANCELLED->value => '已取消',
- OrderStatus::REFUNDED->value => '已退款',
- default => '未知状态',
- };
- }
- /**
- * 订单退款
- *
- * @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
- {
- // 初始化扣除金额
- $deductAmount = 0;
- // 根据订单状态计算违约金
- switch ($order->state) {
- case OrderStatus::ACCEPTED->value:
- // 已接单状态扣除订单金额的20%作为违约金
- $deductAmount = bcmul($order->total_amount, '0.2', 2);
- break;
- case OrderStatus::DEPARTED->value:
- // 已出发状态扣除订单金额的50%作为违约金
- $deductAmount = bcmul($order->total_amount, '0.5', 2);
- break;
- }
- // 计算实际可��金额(总金额减去违约金)
- $totalRefund = bcsub($order->total_amount, $deductAmount, 2);
- // 优先退还用户使用的余额部分
- $balanceRefund = min($order->balance_amount, $totalRefund);
- // 剩余部分退还到支付账户
- $paymentRefund = bcsub($totalRefund, $balanceRefund, 2);
- return [
- 'total_refund' => $totalRefund, // 总退款金额
- 'balance_amount' => $balanceRefund, // 退还到余额的金额
- 'payment_refund' => $paymentRefund, // 退还到支付账户的金额
- 'deduct_amount' => $deductAmount, // 扣除的违约金
- ];
- }
- /**
- * 处理退款操作
- */
- 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' => 'refund',
- 'owner_type' => Order::class,
- 'owner_id' => $order->id,
- 'remark' => '订单退款',
- 'before_balance' => $wallet->total_balance - $amount,
- 'after_balance' => $wallet->total_balance,
- 'state' => 'success',
- ]);
- }
- /**
- * 处理支付退款
- */
- private function processPaymentRefund(Order $order, float $amount): void
- {
- // TODO: 实现第三方支付退款逻辑
- // $paymentService = app(PaymentService::class);
- // $paymentService->refund($order->payment_no, $amount);
- }
- /**
- * 更新订单退款状态
- */
- private function updateOrderRefundStatus(Order $order): void
- {
- $order->update([
- 'state' => OrderStatus::REFUNDED->value,
- 'refund_time' => now(),
- ]);
- }
- /**
- * 创建退款记录
- */
- 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);
- } 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 计费规则
- * @return float 路费金额(元)
- */
- private function calculateFeeByRules(float $distance, array $rules): float
- {
- // 1. 检查是否超出最大服务距离
- abort_if(
- $distance > $rules['max_distance'],
- 400,
- sprintf('超出最大服务距离 %.1f 公里', $rules['max_distance'])
- );
- // 2. 检查是否在免费距离内
- if ($distance <= $rules['free_distance']) {
- return 0;
- }
- // 3. 计算实际计费距离
- $chargeDistance = max(0, $distance - $rules['free_distance']);
- // 4. 检查是否达到最小计费距离
- if ($chargeDistance < $rules['min_distance']) {
- return $rules['min_fee'];
- }
- // 5. 计算基础路费
- $fee = bcmul($chargeDistance, $rules['per_km_fee'], 2);
- // 6. 应用最小路费限制
- $fee = max($fee, $rules['min_fee']);
- // 7. 应用最大路费限制
- $fee = min($fee, $rules['max_fee']);
- 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
- {
- try {
- // 生成PNG格式的二维码
- $qrCodeImage = QrCode::format('png')
- ->size(200) // 设置二维码大小为200px
- ->margin(1) // 设置二维码边距为1
- ->errorCorrection('H') // 设置纠错级别为最高级别H
- ->generate($content);
- // 将PNG转为base64
- return 'data:image/png;base64,'.base64_encode($qrCodeImage);
- } catch (Exception $e) {
- Log::error('生成二维码图片失败:', [
- 'content' => $content,
- 'error' => $e->getMessage(),
- ]);
- return null;
- }
- }
- /**
- * 验证技师服务时间是否可用
- */
- 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::SERVING->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::FINISHED->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 updateCoachScore(int $coachId): void
- // {
- // $coach = CoachUser::findOrFail($coachId);
- // // 计算平均分
- // $avgScore = OrderEvaluation::where('coach_id', $coachId)
- // ->where('state', 'normal')
- // ->avg('score');
- // // 更新技师评分
- // $coach->info()->update([
- // 'score' => round($avgScore, 1),
- // 'evaluation_count' => OrderEvaluation::where('coach_id', $coachId)
- // ->where('state', 'normal')
- // ->count(),
- // ]);
- // }
- /**
- * 更新订单评价状态
- */
- 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;
- }
- }
|