| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725 |
- <?php
- namespace App\Services;
- use App\Enums\CartStatusEnum;
- use App\Enums\PaymentSplitStatusEnum;
- use App\Enums\PaymentStatusEnum;
- use App\Models\Cart;
- use App\Models\ClientPaymentMethod;
- use App\Models\Payment;
- use App\Models\PaymentSplit;
- use App\Models\Schedule;
- use App\Services\Pagarme\PagarmePaymentService;
- use Carbon\Carbon;
- use Illuminate\Auth\Access\AuthorizationException;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Support\Collection as SupportCollection;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Str;
- class PaymentService
- {
- public function __construct(
- private readonly PagarmePaymentService $pagarmePaymentService,
- ) {}
- public function getAll(): Collection
- {
- return Payment::query()
- ->with(['client.user', 'provider.user', 'schedule', 'cart.items.schedule'])
- ->orderBy('created_at', 'desc')
- ->get();
- }
- public function findById(int $id): ?Payment
- {
- return Payment::query()
- ->with(['client.user', 'provider.user', 'schedule', 'cart.items.schedule'])
- ->find($id);
- }
- public function create(array $data): Payment
- {
- return Payment::create($data);
- }
- public function update(int $id, array $data): ?Payment
- {
- $model = $this->findById($id);
- if (! $model) {
- return null;
- }
- $model->update($data);
- return $model->fresh();
- }
- public function delete(int $id): bool
- {
- $model = $this->findById($id);
- if (! $model) {
- return false;
- }
- return $model->delete();
- }
- //
- public function platformFees(): array
- {
- return $this->pagarmePaymentService->platformFeeRates();
- }
- //
- public function payAcceptedSchedule(
- Schedule $schedule, string $paymentMethod, ?int $clientPaymentMethodId = null, array $options = []
- ): Payment {
- $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
- if ($schedule->status !== 'accepted') {
- throw new \InvalidArgumentException('Agendamento precisa estar aceito para ser pago.');
- }
- if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
- throw new \InvalidArgumentException('Forma de pagamento invalida.');
- }
- if (! $schedule->provider_id || ! $schedule->provider) {
- throw new \InvalidArgumentException('Agendamento precisa ter prestador confirmado para gerar pagamento.');
- }
- if ((float) $schedule->total_amount <= 0) {
- throw new \InvalidArgumentException('Agendamento precisa ter valor maior que zero para gerar pagamento.');
- }
- if (empty($schedule->provider->recipient_id)) {
- throw new \InvalidArgumentException('Prestador precisa ter recipient_id do Pagar.me para receber split.');
- }
- $this->ensureScheduleCanBePaidIndividually($schedule);
- $existingPayment = Payment::query()
- ->where('schedule_id', $schedule->id)
- ->whereIn('status', [
- PaymentStatusEnum::PENDING->value,
- PaymentStatusEnum::PROCESSING->value,
- PaymentStatusEnum::AUTHORIZED->value,
- PaymentStatusEnum::PAID->value,
- ])
- ->latest('id')
- ->first();
- if ($existingPayment) {
- if ($this->isIncompleteGatewayPayment($existingPayment)) {
- $existingPayment->forceFill([
- 'status' => PaymentStatusEnum::FAILED,
- 'failed_at' => now(),
- 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
- ])->save();
- }
- elseif ($this->isExpiredPixPayment($existingPayment)) {
- $existingPayment->forceFill([
- 'status' => PaymentStatusEnum::FAILED,
- 'failed_at' => now(),
- 'failure_message' => 'Pagamento Pix expirado.',
- ])->save();
- PaymentSplit::query()
- ->where('payment_id', $existingPayment->id)
- ->update(['status' => PaymentSplitStatusEnum::FAILED]);
- }
- else {
- if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== PaymentStatusEnum::PAID) {
- throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este agendamento.');
- }
- $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
- return $existingPayment;
- }
- }
- $clientPaymentMethod = null;
- $cardId = null;
- if ($paymentMethod === 'credit_card') {
- if (! $clientPaymentMethodId && empty($options['card_id'])) {
- throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
- }
- if ($clientPaymentMethodId) {
- $clientPaymentMethod = ClientPaymentMethod::query()
- ->where('client_id', $schedule->client_id)
- ->where('id', $clientPaymentMethodId)
- ->where('is_active', true)
- ->first();
- if (! $clientPaymentMethod) {
- throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
- }
- }
- $cardId = $options['card_id'] ?? $clientPaymentMethod?->gateway_card_id ?? null;
- if (empty($cardId)) {
- throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
- }
- }
- $serviceAmount = (float) $schedule->total_amount;
- $amounts = $this->pagarmePaymentService->calculatePaymentAmounts(
- serviceAmount: $serviceAmount,
- paymentMethod: $paymentMethod,
- schedule: $schedule,
- );
- $payment = Payment::create([
- 'schedule_id' => $schedule->id,
- 'client_id' => $schedule->client_id,
- 'provider_id' => $schedule->provider_id,
- 'client_payment_method_id' => $paymentMethod === 'credit_card' ? ($clientPaymentMethod?->id ?? null) : null,
- 'gateway_provider' => 'pagarme',
- 'gateway_code' => 'payment-'.(string) Str::uuid(),
- 'payment_method' => $paymentMethod,
- 'status' => PaymentStatusEnum::PENDING,
- 'gross_amount' => $amounts['gross_amount'],
- 'gateway_fee_amount' => 0,
- 'platform_fee_amount' => $amounts['platform_fee_amount'],
- 'net_amount' => $amounts['gross_amount'],
- 'currency' => 'BRL',
- 'installments' => 1,
- 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
- 'metadata' => [
- 'service_amount' => number_format($amounts['service_amount'], 2, '.', ''),
- 'platform_fee' => number_format($amounts['platform_fee_amount'], 2, '.', ''),
- ],
- ]);
- PaymentSplit::create([
- 'payment_id' => $payment->id,
- 'provider_id' => $schedule->provider_id,
- 'gateway_provider' => 'pagarme',
- 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
- 'gateway_transfer_target_label' => 'recipient',
- 'status' => PaymentSplitStatusEnum::PENDING,
- 'gross_amount' => $serviceAmount,
- 'gateway_fee_amount' => 0,
- 'net_amount' => $serviceAmount,
- 'metadata' => [
- 'schedule_id' => (string) $schedule->id,
- ],
- ]);
- $schedule->ensureCustomerPhone($options['phone'] ?? null);
- try {
- $orderResponse = $this->pagarmePaymentService->processPayment(
- payment: $payment,
- schedule: $schedule,
- paymentMethod: $paymentMethod,
- cardId: $cardId,
- options: $options,
- );
- } catch (\Throwable $e) {
- $payment->forceFill([
- 'status' => PaymentStatusEnum::FAILED,
- 'failed_at' => now(),
- 'failure_message' => $e->getMessage(),
- ])->save();
- PaymentSplit::query()
- ->where('payment_id', $payment->id)
- ->update(['status' => PaymentSplitStatusEnum::FAILED]);
- throw $e;
- }
- $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
- $this->syncScheduleStatusAfterPayment($schedule, $payment);
- return $payment;
- }
- public function payCart(
- Cart $cart,
- int $userId,
- string $paymentMethod,
- ?int $clientPaymentMethodId = null,
- array $options = [],
- ): Payment {
- if ($cart->client?->user_id !== $userId) {
- throw new AuthorizationException;
- }
- if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
- throw new \InvalidArgumentException('Forma de pagamento invalida.');
- }
- $paymentData = DB::transaction(function () use (
- $cart,
- $userId,
- $paymentMethod,
- $clientPaymentMethodId,
- $options,
- ): array {
- $cart = Cart::query()
- ->lockForUpdate()
- ->with(['client', 'provider', 'items.schedule.client', 'items.schedule.provider', 'items.schedule.customSchedule.serviceType'])
- ->findOrFail($cart->id);
- if ($cart->client?->user_id !== $userId) {
- throw new AuthorizationException;
- }
- $schedules = $cart->items->pluck('schedule')->filter()->values();
- $this->validateCartForPayment($cart, $schedules);
- $existingPayment = Payment::query()
- ->where('cart_id', $cart->id)
- ->whereIn('status', [
- PaymentStatusEnum::PENDING->value,
- PaymentStatusEnum::PROCESSING->value,
- PaymentStatusEnum::AUTHORIZED->value,
- PaymentStatusEnum::PAID->value,
- ])
- ->latest('id')
- ->first();
- if ($existingPayment) {
- if ($this->isExpiredPixPayment($existingPayment)) {
- $existingPayment->forceFill([
- 'status' => PaymentStatusEnum::FAILED,
- 'failed_at' => now(),
- 'failure_message' => 'Pagamento Pix expirado.',
- ])->save();
- PaymentSplit::query()
- ->where('payment_id', $existingPayment->id)
- ->update(['status' => PaymentSplitStatusEnum::FAILED]);
- } elseif ($this->isStaleIncompleteGatewayPayment($existingPayment)) {
- if ($existingPayment->payment_method !== $paymentMethod) {
- throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este carrinho.');
- }
- [, $cardId] = $this->resolveCard(
- clientId: $cart->client_id,
- paymentMethod: $paymentMethod,
- clientPaymentMethodId: $clientPaymentMethodId ?? $existingPayment->client_payment_method_id,
- cardId: $options['card_id'] ?? null,
- );
- $this->cartPaymentTotals($schedules, $paymentMethod);
- return [
- 'payment' => $existingPayment,
- 'schedules' => $schedules,
- 'cardId' => $cardId,
- ];
- } else {
- if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== PaymentStatusEnum::PAID) {
- throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este carrinho.');
- }
- return ['existing' => $existingPayment];
- }
- }
- if ($cart->status !== CartStatusEnum::OPEN) {
- throw new \InvalidArgumentException('Carrinho precisa estar aberto para ser pago.');
- }
- [$clientPaymentMethod, $cardId] = $this->resolveCard(
- clientId: $cart->client_id,
- paymentMethod: $paymentMethod,
- clientPaymentMethodId: $clientPaymentMethodId,
- cardId: $options['card_id'] ?? null,
- );
- $totals = $this->cartPaymentTotals($schedules, $paymentMethod);
- $payment = Payment::create([
- 'schedule_id' => null,
- 'cart_id' => $cart->id,
- 'client_id' => $cart->client_id,
- 'provider_id' => $cart->provider_id,
- 'client_payment_method_id' => $paymentMethod === 'credit_card' ? $clientPaymentMethod?->id : null,
- 'gateway_provider' => 'pagarme',
- 'gateway_code' => 'payment-'.(string) Str::uuid(),
- 'payment_method' => $paymentMethod,
- 'status' => PaymentStatusEnum::PENDING,
- 'gross_amount' => $totals['gross_amount'],
- 'gateway_fee_amount' => 0,
- 'platform_fee_amount' => $totals['platform_fee_amount'],
- 'net_amount' => $totals['gross_amount'],
- 'currency' => 'BRL',
- 'installments' => 1,
- 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
- 'metadata' => [
- 'cart_id' => (string) $cart->id,
- 'schedule_ids' => $schedules->pluck('id')->map(fn ($id) => (string) $id)->all(),
- 'service_amount' => number_format($totals['service_amount'], 2, '.', ''),
- 'platform_fee' => number_format($totals['platform_fee_amount'], 2, '.', ''),
- ],
- ]);
- PaymentSplit::create([
- 'payment_id' => $payment->id,
- 'provider_id' => $cart->provider_id,
- 'gateway_provider' => 'pagarme',
- 'gateway_transfer_target_reference' => $cart->provider->recipient_id,
- 'gateway_transfer_target_label' => 'recipient',
- 'status' => PaymentSplitStatusEnum::PENDING,
- 'gross_amount' => $totals['service_amount'],
- 'gateway_fee_amount' => 0,
- 'net_amount' => $totals['service_amount'],
- 'metadata' => [
- 'cart_id' => (string) $cart->id,
- 'schedule_ids' => $schedules->pluck('id')->map(fn ($id) => (string) $id)->all(),
- ],
- ]);
- return compact('payment', 'schedules', 'cardId');
- });
- if (isset($paymentData['existing'])) {
- $existingPayment = $paymentData['existing'];
- $this->syncPaymentTargets($existingPayment);
- return $existingPayment->fresh(['client.user', 'provider.user', 'cart.items.schedule']);
- }
- /** @var Payment $payment */
- $payment = $paymentData['payment'];
- /** @var SupportCollection $schedules */
- $schedules = $paymentData['schedules'];
- try {
- $schedules->first()->ensureCustomerPhone($options['phone'] ?? null);
- $orderResponse = $this->pagarmePaymentService->processCartPayment(
- payment: $payment,
- schedules: $schedules,
- paymentMethod: $paymentMethod,
- cardId: $paymentData['cardId'],
- options: $options,
- );
- } catch (\Throwable $e) {
- $this->failPayment($payment, $e->getMessage());
- throw $e;
- }
- $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
- $this->syncPaymentTargets($payment);
- return $payment->fresh(['client.user', 'provider.user', 'cart.items.schedule']);
- }
- //
- public function getOrCreatePixPayment(Schedule $schedule): Payment
- {
- $this->ensureScheduleCanBePaidIndividually($schedule);
- $existingPayment = Payment::query()
- ->where('schedule_id', $schedule->id)
- ->where('payment_method', 'pix')
- ->whereIn('status', [
- PaymentStatusEnum::PENDING->value,
- PaymentStatusEnum::PROCESSING->value,
- PaymentStatusEnum::AUTHORIZED->value,
- PaymentStatusEnum::PAID->value,
- ])
- ->latest('id')
- ->first();
- if ($existingPayment && $this->isExpiredPixPayment($existingPayment)) {
- $existingPayment->forceFill([
- 'status' => PaymentStatusEnum::FAILED,
- 'failed_at' => Carbon::now(),
- 'failure_message' => 'Pagamento Pix expirado.',
- ])->save();
- PaymentSplit::query()
- ->where('payment_id', $existingPayment->id)
- ->update(['status' => PaymentSplitStatusEnum::FAILED]);
- $existingPayment = null;
- }
- if ($existingPayment) {
- if ($this->isIncompleteGatewayPayment($existingPayment)) {
- $existingPayment->forceFill([
- 'status' => PaymentStatusEnum::FAILED,
- 'failed_at' => Carbon::now(),
- 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
- ])->save();
- PaymentSplit::query()
- ->where('payment_id', $existingPayment->id)
- ->update(['status' => PaymentSplitStatusEnum::FAILED]);
- } else {
- $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
- return $existingPayment;
- }
- }
- return $this->payAcceptedSchedule(
- schedule: $schedule,
- paymentMethod: 'pix',
- );
- }
- //
- private function isExpiredPixPayment(Payment $payment): bool
- {
- if ($payment->payment_method !== 'pix') {
- return false;
- }
- if ($payment->status === PaymentStatusEnum::PAID) {
- return false;
- }
- return $payment->expires_at !== null
- && $payment->expires_at->isPast();
- }
- private function isIncompleteGatewayPayment(Payment $payment): bool
- {
- return $payment->status === PaymentStatusEnum::PENDING
- && empty($payment->gateway_entity_reference)
- && empty($payment->gateway_operation_reference)
- && empty($payment->gateway_payload);
- }
- private function isStaleIncompleteGatewayPayment(Payment $payment): bool
- {
- return $this->isIncompleteGatewayPayment($payment)
- && ($payment->created_at?->lte(now()->subMinutes(5)) ?? false);
- }
- public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
- {
- if ($payment->status !== PaymentStatusEnum::PAID) {
- return;
- }
- if ($schedule->status !== 'paid') {
- $schedule->update(['status' => 'paid']);
- }
- $this->syncCartsForSchedule($schedule);
- }
- public function syncPaymentTargets(Payment $payment): void
- {
- if ($payment->status !== PaymentStatusEnum::PAID) {
- return;
- }
- if ($payment->cart_id) {
- DB::transaction(function () use ($payment): void {
- $cart = Cart::query()->lockForUpdate()->with('items')->find($payment->cart_id);
- if (! $cart) {
- return;
- }
- $scheduleIds = $cart->items->pluck('schedule_id')->filter()->unique();
- Schedule::query()
- ->whereIn('id', $scheduleIds)
- ->where('status', 'accepted')
- ->update(['status' => 'paid']);
- if ($cart->status !== CartStatusEnum::PAID) {
- $cart->update(['status' => CartStatusEnum::PAID->value]);
- }
- });
- return;
- }
- $payment->loadMissing('schedule');
- if ($payment->schedule) {
- $this->syncScheduleStatusAfterPayment($payment->schedule, $payment);
- }
- }
- private function syncCartsForSchedule(Schedule $schedule): void
- {
- Cart::query()
- ->whereHas('items', fn ($query) => $query->where('schedule_id', $schedule->id))
- ->with('items')
- ->get()
- ->each(fn (Cart $cart) => $this->syncCartStatusAfterPayments($cart));
- }
- private function syncCartStatusAfterPayments(Cart $cart): void
- {
- $cart->loadMissing('items');
- $scheduleIds = $cart->items
- ->pluck('schedule_id')
- ->filter()
- ->unique()
- ->values();
- if ($scheduleIds->isEmpty()) {
- return;
- }
- $paidSchedulesCount = Schedule::query()
- ->whereIn('id', $scheduleIds)
- ->where('status', 'paid')
- ->count();
- if ($paidSchedulesCount !== $scheduleIds->count()) {
- return;
- }
- if ($cart->status !== CartStatusEnum::PAID) {
- $cart->update(['status' => CartStatusEnum::PAID->value]);
- }
- }
- private function validateCartForPayment(Cart $cart, SupportCollection $schedules): void
- {
- if (! in_array($cart->status, [CartStatusEnum::OPEN, CartStatusEnum::PAID], true)) {
- throw new \InvalidArgumentException('Carrinho precisa estar aberto para ser pago.');
- }
- if ($schedules->isEmpty()) {
- throw new \InvalidArgumentException('Carrinho precisa ter ao menos um agendamento.');
- }
- $providerIds = $schedules->pluck('provider_id')->filter()->unique()->values();
- $clientIds = $schedules->pluck('client_id')->unique()->values();
- if (! $cart->provider_id || $providerIds->count() !== 1 || (int) $providerIds->first() !== $cart->provider_id) {
- throw new \InvalidArgumentException('Todos os agendamentos do carrinho precisam ser do mesmo prestador.');
- }
- if ($clientIds->count() !== 1 || (int) $clientIds->first() !== $cart->client_id) {
- throw new \InvalidArgumentException('Todos os agendamentos do carrinho precisam ser do mesmo cliente.');
- }
- if (empty($cart->provider?->recipient_id)) {
- throw new \InvalidArgumentException('Prestador precisa ter recipient_id do Pagar.me para receber split.');
- }
- foreach ($schedules as $schedule) {
- $expectedStatus = $cart->status === CartStatusEnum::PAID ? 'paid' : 'accepted';
- if ($schedule->status !== $expectedStatus) {
- throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa estar aceito para o carrinho ser pago.");
- }
- if ((float) $schedule->total_amount <= 0) {
- throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa ter valor maior que zero para gerar pagamento.");
- }
- }
- }
- private function resolveCard(
- int $clientId,
- string $paymentMethod,
- ?int $clientPaymentMethodId,
- ?string $cardId,
- ): array {
- if ($paymentMethod !== 'credit_card') {
- return [null, null];
- }
- if (! $clientPaymentMethodId && empty($cardId)) {
- throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
- }
- $clientPaymentMethod = $clientPaymentMethodId
- ? ClientPaymentMethod::query()
- ->where('client_id', $clientId)
- ->where('id', $clientPaymentMethodId)
- ->where('is_active', true)
- ->first()
- : null;
- if ($clientPaymentMethodId && ! $clientPaymentMethod) {
- throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
- }
- $cardId = $cardId ?: $clientPaymentMethod?->gateway_card_id;
- if (empty($cardId)) {
- throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
- }
- return [$clientPaymentMethod, $cardId];
- }
- private function cartPaymentTotals(SupportCollection $schedules, string $paymentMethod): array
- {
- return $schedules->reduce(function (array $totals, Schedule $schedule) use ($paymentMethod): array {
- $amounts = $this->pagarmePaymentService->calculatePaymentAmounts(
- serviceAmount: (float) $schedule->total_amount,
- paymentMethod: $paymentMethod,
- schedule: $schedule,
- );
- $schedule->setAttribute('payment_gross_amount', $amounts['gross_amount']);
- return [
- 'service_amount' => round($totals['service_amount'] + $amounts['service_amount'], 2),
- 'platform_fee_amount' => round($totals['platform_fee_amount'] + $amounts['platform_fee_amount'], 2),
- 'gross_amount' => round($totals['gross_amount'] + $amounts['gross_amount'], 2),
- ];
- }, [
- 'service_amount' => 0.0,
- 'platform_fee_amount' => 0.0,
- 'gross_amount' => 0.0,
- ]);
- }
- private function failPayment(Payment $payment, string $message): void
- {
- $payment->forceFill([
- 'status' => PaymentStatusEnum::FAILED,
- 'failed_at' => now(),
- 'failure_message' => $message,
- ])->save();
- PaymentSplit::query()
- ->where('payment_id', $payment->id)
- ->update(['status' => PaymentSplitStatusEnum::FAILED]);
- }
- private function ensureScheduleCanBePaidIndividually(Schedule $schedule): void
- {
- $belongsToMultiItemCart = Cart::query()
- ->where('status', CartStatusEnum::OPEN->value)
- ->whereHas('items', fn ($query) => $query->where('schedule_id', $schedule->id))
- ->whereHas('items', null, '>', 1)
- ->exists();
- if ($belongsToMultiItemCart) {
- throw new \InvalidArgumentException('Agendamento pertencente a carrinho com múltiplos itens deve ser pago pelo checkout do carrinho.');
- }
- }
- }
|