12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588 |
- <?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
- ) {}
-
- 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;
- }
- }
-
- private function validateInitializeData(array $data): void
- {
- abort_if(empty($data['project_id']), 400, '项目ID不能为空');
- abort_if(empty($data['coach_id']), 400, '技师ID不能为空');
- }
-
- 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;
- }
-
- private function getAreaCode(?object $address, array $data): string
- {
- $areaCode = $address?->area_code ?? ($data['area_code'] ?? null);
- abort_if(empty($areaCode), 400, '区域编码不能为空');
- return $areaCode;
- }
-
- private function getProjectDetail(int $projectId, string $areaCode): Project
- {
- $project = $this->projectService->getProjectDetail($projectId, $areaCode);
- abort_if(! $project, 400, '项目不存在');
- return $project;
- }
-
- private function logError(string $message, Exception $e, array $context = []): void
- {
- Log::error($message, [
- ...$context,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- }
-
- public function createOrder(int $userId, array $data): array
- {
- return DB::transaction(function () use ($userId, $data) {
- try {
-
- $this->validateOrderData($userId, $data);
-
- $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
- );
-
- if (! empty($data['order_id'])) {
- $order = Order::findOrFail($data['order_id']);
-
- abort_if(
- ! in_array($order->state, [
- OrderStatus::PAID->value,
- OrderStatus::ACCEPTED->value,
- OrderStatus::STARTED->value,
- OrderStatus::SERVING->value,
- ]),
- 422,
- '原订单状态不允许加钟'
- );
- $data['address_id'] = $order->address_id;
- $data['coach_id'] = $order->coach_id;
- $data['service_time'] = $order->service_end_time;
- }
-
- $address = MemberUser::find($userId)->addresses()
- ->where('id', $data['address_id'])
- ->first();
- abort_if(! $address, 404, '收货地址不存在');
-
- $order = $this->createOrderData(['user_id' => $userId, ...$data], $amounts, $address);
-
- $this->createRelatedRecords($order);
-
- 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);
- }
-
- $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)
- ->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
- {
- 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
- {
- $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
- {
-
-
-
- }
-
- 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,
- ];
- }
-
- public function cancelOrder(int $userId, int $orderId, ?string $reason = null): array
- {
- return DB::transaction(function () use ($userId, $orderId, $reason) {
- try {
-
- $order = $this->validateOrderForCancel($userId, $orderId);
-
- $cancelAmounts = $this->calculateCancelAmount($order);
-
- $this->processCancelRefund($order, $cancelAmounts);
-
- $this->updateOrderCancelStatus($order);
-
- $this->createCancelRecords($order, $cancelAmounts, $reason);
-
- $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;
- }
-
- private function calculateCancelAmount(Order $order): array
- {
- $penaltyAmount = 0;
-
- if ($order->state === OrderStatus::ACCEPTED->value) {
-
- $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
- {
-
-
-
- }
-
- private function updateOrderCancelStatus(Order $order): void
- {
- $order->update([
- 'state' => OrderStatus::CANCELLED->value,
- ]);
- }
-
- private function createCancelRecords(Order $order, array $cancelAmounts, ?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
- {
-
-
-
-
- if ($order->coach_id) {
-
- }
- }
-
- public function finishOrder(int $userId, int $orderId): array
- {
- return DB::transaction(function () use ($userId, $orderId) {
- try {
-
- $order = $this->validateOrderForFinish($userId, $orderId);
-
- $coach = $this->validateCoach($order->coach_id);
-
- $this->completeOrder($order, $userId);
-
-
- 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
- {
-
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::COMPLETED->value,
- 'remark' => '服务完成',
- ]);
-
- $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 {
-
- $order = Order::where('user_id', $userId)
- ->where('id', $orderId)
- ->where('state', OrderStatus::FINISHED->value)
- ->firstOrFail();
- if (! $order) {
- throw new Exception('订单不能撤离');
- }
-
- OrderRecord::create([
- 'order_id' => $orderId,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::LEFT->value,
- 'remark' => '技师已离开',
- ]);
-
- $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;
- }
- });
- }
-
- public function getOrderList(int $userId, array $filters = [])
- {
- try {
-
- $user = $this->validateUserForQuery($userId);
-
- $query = $this->buildOrderListQuery($user);
-
- $this->applyOrderFilters($query, $filters);
-
- 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']);
- },
-
- ]);
- }
-
- 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,
- ];
- }
-
- public function getOrderDetail(int $userId, int $orderId): array
- {
- try {
-
- $order = $this->validateOrderAccess($userId, $orderId);
-
- $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']);
- },
-
-
-
- ]);
-
- 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(),
-
-
-
-
-
-
- ];
- }
-
- 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 => '未知状态',
- };
- }
-
- public function refundOrder(int $orderId): array
- {
- return DB::transaction(function () use ($orderId) {
- try {
-
- $order = $this->validateOrderForRefund($orderId);
-
- $refundAmounts = $this->calculateRefundAmount($order);
-
- $this->processRefund($order, $refundAmounts);
-
- $this->updateOrderRefundStatus($order);
-
- $this->createRefundRecords($order, $refundAmounts);
-
- $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:
-
- $deductAmount = bcmul($order->total_amount, '0.2', 2);
- break;
- case OrderStatus::DEPARTED->value:
-
- $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
- {
-
-
-
- }
-
- 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
- {
-
-
-
-
- if ($order->coach_id) {
-
- }
- }
-
- public function getAgentConfig(int $agentId): array
- {
- $agent = AgentInfo::where('id', $agentId)
- ->where('state', 'enable')
- ->firstOrFail();
-
- return [
-
-
-
- ];
- }
-
- public function getCoachConfig(int $coachId): array
- {
- $coach = CoachUser::where('id', $coachId)
- ->where('state', 'enable')
- ->where('auth_state', 'passed')
- ->firstOrFail();
-
- return [
-
-
- ];
- }
-
- public function calculateDeliveryFee(
- int $coachId,
- int $projectId,
- ?int $agentId,
- float $distance
- ): float {
- try {
-
- $this->validateDeliveryFeeParams($coachId, $projectId, $distance);
-
- $feeRules = $this->getDeliveryFeeRules($coachId, $agentId);
-
- 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, '距离计算错误');
- }
-
- private function getDeliveryFeeRules(int $coachId, ?int $agentId): array
- {
-
- $defaultRules = $this->getDefaultDeliveryFeeRules();
-
- $agentRules = $agentId ? $this->getAgentDeliveryFeeRules($agentId) : [];
-
- $coachRules = $this->getCoachDeliveryFeeRules($coachId);
-
- return array_merge(
- $defaultRules,
- $agentRules,
- $coachRules
- );
- }
-
- private function getDefaultDeliveryFeeRules(): array
- {
-
- 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
- {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- return [];
- }
-
- private function getCoachDeliveryFeeRules(int $coachId): array
- {
-
-
-
-
- $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,
- ];
- }
-
- private function calculateFeeByRules(float $distance, array $rules): float
- {
-
- abort_if(
- $distance > $rules['max_distance'],
- 400,
- sprintf('超出最大服务距离 %.1f 公里', $rules['max_distance'])
- );
-
- if ($distance <= $rules['free_distance']) {
- return 0;
- }
-
- $chargeDistance = max(0, $distance - $rules['free_distance']);
-
- if ($chargeDistance < $rules['min_distance']) {
- return $rules['min_fee'];
- }
-
- $fee = bcmul($chargeDistance, $rules['per_km_fee'], 2);
-
- $fee = max($fee, $rules['min_fee']);
-
- $fee = min($fee, $rules['max_fee']);
- return $fee;
- }
-
- 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;
-
- return round($distance, 2);
- }
-
- 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 {
-
- $user = $this->validateUserForCalculation($userId);
-
- $project = $this->getProjectWithPrice($projectId, $agentId);
-
- $deliveryFee = $this->calculateDeliveryFeeForOrder(
- coachId: $coachId,
- projectId: $projectId,
- agentId: $agentId,
- distance: $distance,
- addressId: $addressId,
- lat: $lat,
- lng: $lng
- );
-
- $discountAmount = $this->calculateDiscountAmount($projectId, $userId);
-
- $totalAmount = $this->calculateTotalAmount($project->price, $deliveryFee, $discountAmount);
-
- $paymentAmounts = $this->calculatePaymentDistribution(
- user: $user,
- totalAmount: $totalAmount,
- useBalance: $useBalance
- );
-
- 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;
- }
-
- 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 {
-
- if ($addressId > 0) {
- $address = MemberAddress::find($addressId);
-
- $lat = $address?->latitude ?? $lat;
- $lng = $address?->longitude ?? $lng;
- }
-
-
- $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);
- }
-
- 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;
-
- 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);
- }
-
- 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),
- ];
- }
-
- 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;
- }
- }
-
- public function assignCoach(int $userId, int $orderId, int $coachId): bool
- {
- return DB::transaction(function () use ($userId, $orderId, $coachId) {
- try {
-
- $order = $this->validateAssignOrder($userId, $orderId);
-
- $coach = $this->validateCoach($coachId);
-
- $this->validateGrabPool($order);
-
- $this->updateOrderForAssign($order, $coachId);
-
- $this->createAssignRecord($order, $userId);
-
- if ($order->payment_type === PaymentMethod::BALANCE->value) {
- $this->handleBalancePaymentForAssign($order, $userId, $coachId);
- }
-
- $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
- {
-
-
- }
-
- 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;
- }
-
- 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),
- ];
- }
-
- private function generateQRCodeImage(string $content): ?string
- {
- try {
-
- $qrCodeImage = QrCode::format('png')
- ->size(200)
- ->margin(1)
- ->errorCorrection('H')
- ->generate($content);
-
- 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 {
-
- $this->validateServiceTimeParams($coachId, $serviceTime);
-
- $workSchedule = $this->getCoachWorkSchedule($coachId);
-
- $this->validateWorkingHours($serviceTime, $workSchedule);
-
- $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);
-
- $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,
- '该时间段技师已有其他订单'
- );
- }
-
- public function evaluateOrder(int $userId, int $orderId, array $data): array
- {
- return DB::transaction(function () use ($userId, $orderId, $data) {
- try {
-
- $order = $this->validateOrderForEvaluation($userId, $orderId);
-
- $evaluation = $this->createEvaluation($order, $data);
-
-
-
-
- $this->updateOrderEvaluationStatus($order);
-
-
-
-
-
- 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,
- '订单已评价'
- );
-
- $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 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;
- }
- }
|