PaymentService.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\CartStatusEnum;
  4. use App\Enums\PaymentSplitStatusEnum;
  5. use App\Enums\PaymentStatusEnum;
  6. use App\Models\Cart;
  7. use App\Models\ClientPaymentMethod;
  8. use App\Models\Payment;
  9. use App\Models\PaymentSplit;
  10. use App\Models\Schedule;
  11. use App\Services\Pagarme\PagarmePaymentService;
  12. use Carbon\Carbon;
  13. use Illuminate\Auth\Access\AuthorizationException;
  14. use Illuminate\Database\Eloquent\Collection;
  15. use Illuminate\Support\Collection as SupportCollection;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Str;
  18. class PaymentService
  19. {
  20. public function __construct(
  21. private readonly PagarmePaymentService $pagarmePaymentService,
  22. ) {}
  23. public function getAll(): Collection
  24. {
  25. return Payment::query()
  26. ->with(['client.user', 'provider.user', 'schedule', 'cart.items.schedule'])
  27. ->orderBy('created_at', 'desc')
  28. ->get();
  29. }
  30. public function findById(int $id): ?Payment
  31. {
  32. return Payment::query()
  33. ->with(['client.user', 'provider.user', 'schedule', 'cart.items.schedule'])
  34. ->find($id);
  35. }
  36. public function create(array $data): Payment
  37. {
  38. return Payment::create($data);
  39. }
  40. public function update(int $id, array $data): ?Payment
  41. {
  42. $model = $this->findById($id);
  43. if (! $model) {
  44. return null;
  45. }
  46. $model->update($data);
  47. return $model->fresh();
  48. }
  49. public function delete(int $id): bool
  50. {
  51. $model = $this->findById($id);
  52. if (! $model) {
  53. return false;
  54. }
  55. return $model->delete();
  56. }
  57. //
  58. public function platformFees(): array
  59. {
  60. return $this->pagarmePaymentService->platformFeeRates();
  61. }
  62. //
  63. public function payAcceptedSchedule(
  64. Schedule $schedule, string $paymentMethod, ?int $clientPaymentMethodId = null, array $options = []
  65. ): Payment {
  66. $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
  67. if ($schedule->status !== 'accepted') {
  68. throw new \InvalidArgumentException('Agendamento precisa estar aceito para ser pago.');
  69. }
  70. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  71. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  72. }
  73. if (! $schedule->provider_id || ! $schedule->provider) {
  74. throw new \InvalidArgumentException('Agendamento precisa ter prestador confirmado para gerar pagamento.');
  75. }
  76. if ((float) $schedule->total_amount <= 0) {
  77. throw new \InvalidArgumentException('Agendamento precisa ter valor maior que zero para gerar pagamento.');
  78. }
  79. if (empty($schedule->provider->recipient_id)) {
  80. throw new \InvalidArgumentException('Prestador precisa ter recipient_id do Pagar.me para receber split.');
  81. }
  82. $this->ensureScheduleCanBePaidIndividually($schedule);
  83. $existingPayment = Payment::query()
  84. ->where('schedule_id', $schedule->id)
  85. ->whereIn('status', [
  86. PaymentStatusEnum::PENDING->value,
  87. PaymentStatusEnum::PROCESSING->value,
  88. PaymentStatusEnum::AUTHORIZED->value,
  89. PaymentStatusEnum::PAID->value,
  90. ])
  91. ->latest('id')
  92. ->first();
  93. if ($existingPayment) {
  94. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  95. $existingPayment->forceFill([
  96. 'status' => PaymentStatusEnum::FAILED,
  97. 'failed_at' => now(),
  98. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  99. ])->save();
  100. }
  101. elseif ($this->isExpiredPixPayment($existingPayment)) {
  102. $existingPayment->forceFill([
  103. 'status' => PaymentStatusEnum::FAILED,
  104. 'failed_at' => now(),
  105. 'failure_message' => 'Pagamento Pix expirado.',
  106. ])->save();
  107. PaymentSplit::query()
  108. ->where('payment_id', $existingPayment->id)
  109. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  110. }
  111. else {
  112. if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== PaymentStatusEnum::PAID) {
  113. throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este agendamento.');
  114. }
  115. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  116. return $existingPayment;
  117. }
  118. }
  119. $clientPaymentMethod = null;
  120. $cardId = null;
  121. if ($paymentMethod === 'credit_card') {
  122. if (! $clientPaymentMethodId && empty($options['card_id'])) {
  123. throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
  124. }
  125. if ($clientPaymentMethodId) {
  126. $clientPaymentMethod = ClientPaymentMethod::query()
  127. ->where('client_id', $schedule->client_id)
  128. ->where('id', $clientPaymentMethodId)
  129. ->where('is_active', true)
  130. ->first();
  131. if (! $clientPaymentMethod) {
  132. throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
  133. }
  134. }
  135. $cardId = $options['card_id'] ?? $clientPaymentMethod?->gateway_card_id ?? null;
  136. if (empty($cardId)) {
  137. throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
  138. }
  139. }
  140. $serviceAmount = (float) $schedule->total_amount;
  141. $amounts = $this->pagarmePaymentService->calculatePaymentAmounts(
  142. serviceAmount: $serviceAmount,
  143. paymentMethod: $paymentMethod,
  144. schedule: $schedule,
  145. );
  146. $payment = Payment::create([
  147. 'schedule_id' => $schedule->id,
  148. 'client_id' => $schedule->client_id,
  149. 'provider_id' => $schedule->provider_id,
  150. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? ($clientPaymentMethod?->id ?? null) : null,
  151. 'gateway_provider' => 'pagarme',
  152. 'gateway_code' => 'payment-'.(string) Str::uuid(),
  153. 'payment_method' => $paymentMethod,
  154. 'status' => PaymentStatusEnum::PENDING,
  155. 'gross_amount' => $amounts['gross_amount'],
  156. 'gateway_fee_amount' => 0,
  157. 'platform_fee_amount' => $amounts['platform_fee_amount'],
  158. 'net_amount' => $amounts['gross_amount'],
  159. 'currency' => 'BRL',
  160. 'installments' => 1,
  161. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  162. 'metadata' => [
  163. 'service_amount' => number_format($amounts['service_amount'], 2, '.', ''),
  164. 'platform_fee' => number_format($amounts['platform_fee_amount'], 2, '.', ''),
  165. ],
  166. ]);
  167. PaymentSplit::create([
  168. 'payment_id' => $payment->id,
  169. 'provider_id' => $schedule->provider_id,
  170. 'gateway_provider' => 'pagarme',
  171. 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
  172. 'gateway_transfer_target_label' => 'recipient',
  173. 'status' => PaymentSplitStatusEnum::PENDING,
  174. 'gross_amount' => $serviceAmount,
  175. 'gateway_fee_amount' => 0,
  176. 'net_amount' => $serviceAmount,
  177. 'metadata' => [
  178. 'schedule_id' => (string) $schedule->id,
  179. ],
  180. ]);
  181. $schedule->ensureCustomerPhone($options['phone'] ?? null);
  182. try {
  183. $orderResponse = $this->pagarmePaymentService->processPayment(
  184. payment: $payment,
  185. schedule: $schedule,
  186. paymentMethod: $paymentMethod,
  187. cardId: $cardId,
  188. options: $options,
  189. );
  190. } catch (\Throwable $e) {
  191. $payment->forceFill([
  192. 'status' => PaymentStatusEnum::FAILED,
  193. 'failed_at' => now(),
  194. 'failure_message' => $e->getMessage(),
  195. ])->save();
  196. PaymentSplit::query()
  197. ->where('payment_id', $payment->id)
  198. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  199. throw $e;
  200. }
  201. $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  202. $this->syncScheduleStatusAfterPayment($schedule, $payment);
  203. return $payment;
  204. }
  205. public function payCart(
  206. Cart $cart,
  207. int $userId,
  208. string $paymentMethod,
  209. ?int $clientPaymentMethodId = null,
  210. array $options = [],
  211. ): Payment {
  212. if ($cart->client?->user_id !== $userId) {
  213. throw new AuthorizationException;
  214. }
  215. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  216. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  217. }
  218. $paymentData = DB::transaction(function () use (
  219. $cart,
  220. $userId,
  221. $paymentMethod,
  222. $clientPaymentMethodId,
  223. $options,
  224. ): array {
  225. $cart = Cart::query()
  226. ->lockForUpdate()
  227. ->with(['client', 'provider', 'items.schedule.client', 'items.schedule.provider', 'items.schedule.customSchedule.serviceType'])
  228. ->findOrFail($cart->id);
  229. if ($cart->client?->user_id !== $userId) {
  230. throw new AuthorizationException;
  231. }
  232. $schedules = $cart->items->pluck('schedule')->filter()->values();
  233. $this->validateCartForPayment($cart, $schedules);
  234. $existingPayment = Payment::query()
  235. ->where('cart_id', $cart->id)
  236. ->whereIn('status', [
  237. PaymentStatusEnum::PENDING->value,
  238. PaymentStatusEnum::PROCESSING->value,
  239. PaymentStatusEnum::AUTHORIZED->value,
  240. PaymentStatusEnum::PAID->value,
  241. ])
  242. ->latest('id')
  243. ->first();
  244. if ($existingPayment) {
  245. if ($this->isExpiredPixPayment($existingPayment)) {
  246. $existingPayment->forceFill([
  247. 'status' => PaymentStatusEnum::FAILED,
  248. 'failed_at' => now(),
  249. 'failure_message' => 'Pagamento Pix expirado.',
  250. ])->save();
  251. PaymentSplit::query()
  252. ->where('payment_id', $existingPayment->id)
  253. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  254. } elseif ($this->isStaleIncompleteGatewayPayment($existingPayment)) {
  255. if ($existingPayment->payment_method !== $paymentMethod) {
  256. throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este carrinho.');
  257. }
  258. [, $cardId] = $this->resolveCard(
  259. clientId: $cart->client_id,
  260. paymentMethod: $paymentMethod,
  261. clientPaymentMethodId: $clientPaymentMethodId ?? $existingPayment->client_payment_method_id,
  262. cardId: $options['card_id'] ?? null,
  263. );
  264. $this->cartPaymentTotals($schedules, $paymentMethod);
  265. return [
  266. 'payment' => $existingPayment,
  267. 'schedules' => $schedules,
  268. 'cardId' => $cardId,
  269. ];
  270. } else {
  271. if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== PaymentStatusEnum::PAID) {
  272. throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este carrinho.');
  273. }
  274. return ['existing' => $existingPayment];
  275. }
  276. }
  277. if ($cart->status !== CartStatusEnum::OPEN) {
  278. throw new \InvalidArgumentException('Carrinho precisa estar aberto para ser pago.');
  279. }
  280. [$clientPaymentMethod, $cardId] = $this->resolveCard(
  281. clientId: $cart->client_id,
  282. paymentMethod: $paymentMethod,
  283. clientPaymentMethodId: $clientPaymentMethodId,
  284. cardId: $options['card_id'] ?? null,
  285. );
  286. $totals = $this->cartPaymentTotals($schedules, $paymentMethod);
  287. $payment = Payment::create([
  288. 'schedule_id' => null,
  289. 'cart_id' => $cart->id,
  290. 'client_id' => $cart->client_id,
  291. 'provider_id' => $cart->provider_id,
  292. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? $clientPaymentMethod?->id : null,
  293. 'gateway_provider' => 'pagarme',
  294. 'gateway_code' => 'payment-'.(string) Str::uuid(),
  295. 'payment_method' => $paymentMethod,
  296. 'status' => PaymentStatusEnum::PENDING,
  297. 'gross_amount' => $totals['gross_amount'],
  298. 'gateway_fee_amount' => 0,
  299. 'platform_fee_amount' => $totals['platform_fee_amount'],
  300. 'net_amount' => $totals['gross_amount'],
  301. 'currency' => 'BRL',
  302. 'installments' => 1,
  303. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  304. 'metadata' => [
  305. 'cart_id' => (string) $cart->id,
  306. 'schedule_ids' => $schedules->pluck('id')->map(fn ($id) => (string) $id)->all(),
  307. 'service_amount' => number_format($totals['service_amount'], 2, '.', ''),
  308. 'platform_fee' => number_format($totals['platform_fee_amount'], 2, '.', ''),
  309. ],
  310. ]);
  311. PaymentSplit::create([
  312. 'payment_id' => $payment->id,
  313. 'provider_id' => $cart->provider_id,
  314. 'gateway_provider' => 'pagarme',
  315. 'gateway_transfer_target_reference' => $cart->provider->recipient_id,
  316. 'gateway_transfer_target_label' => 'recipient',
  317. 'status' => PaymentSplitStatusEnum::PENDING,
  318. 'gross_amount' => $totals['service_amount'],
  319. 'gateway_fee_amount' => 0,
  320. 'net_amount' => $totals['service_amount'],
  321. 'metadata' => [
  322. 'cart_id' => (string) $cart->id,
  323. 'schedule_ids' => $schedules->pluck('id')->map(fn ($id) => (string) $id)->all(),
  324. ],
  325. ]);
  326. return compact('payment', 'schedules', 'cardId');
  327. });
  328. if (isset($paymentData['existing'])) {
  329. $existingPayment = $paymentData['existing'];
  330. $this->syncPaymentTargets($existingPayment);
  331. return $existingPayment->fresh(['client.user', 'provider.user', 'cart.items.schedule']);
  332. }
  333. /** @var Payment $payment */
  334. $payment = $paymentData['payment'];
  335. /** @var SupportCollection $schedules */
  336. $schedules = $paymentData['schedules'];
  337. try {
  338. $schedules->first()->ensureCustomerPhone($options['phone'] ?? null);
  339. $orderResponse = $this->pagarmePaymentService->processCartPayment(
  340. payment: $payment,
  341. schedules: $schedules,
  342. paymentMethod: $paymentMethod,
  343. cardId: $paymentData['cardId'],
  344. options: $options,
  345. );
  346. } catch (\Throwable $e) {
  347. $this->failPayment($payment, $e->getMessage());
  348. throw $e;
  349. }
  350. $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  351. $this->syncPaymentTargets($payment);
  352. return $payment->fresh(['client.user', 'provider.user', 'cart.items.schedule']);
  353. }
  354. //
  355. public function getOrCreatePixPayment(Schedule $schedule): Payment
  356. {
  357. $this->ensureScheduleCanBePaidIndividually($schedule);
  358. $existingPayment = Payment::query()
  359. ->where('schedule_id', $schedule->id)
  360. ->where('payment_method', 'pix')
  361. ->whereIn('status', [
  362. PaymentStatusEnum::PENDING->value,
  363. PaymentStatusEnum::PROCESSING->value,
  364. PaymentStatusEnum::AUTHORIZED->value,
  365. PaymentStatusEnum::PAID->value,
  366. ])
  367. ->latest('id')
  368. ->first();
  369. if ($existingPayment && $this->isExpiredPixPayment($existingPayment)) {
  370. $existingPayment->forceFill([
  371. 'status' => PaymentStatusEnum::FAILED,
  372. 'failed_at' => Carbon::now(),
  373. 'failure_message' => 'Pagamento Pix expirado.',
  374. ])->save();
  375. PaymentSplit::query()
  376. ->where('payment_id', $existingPayment->id)
  377. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  378. $existingPayment = null;
  379. }
  380. if ($existingPayment) {
  381. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  382. $existingPayment->forceFill([
  383. 'status' => PaymentStatusEnum::FAILED,
  384. 'failed_at' => Carbon::now(),
  385. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  386. ])->save();
  387. PaymentSplit::query()
  388. ->where('payment_id', $existingPayment->id)
  389. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  390. } else {
  391. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  392. return $existingPayment;
  393. }
  394. }
  395. return $this->payAcceptedSchedule(
  396. schedule: $schedule,
  397. paymentMethod: 'pix',
  398. );
  399. }
  400. //
  401. private function isExpiredPixPayment(Payment $payment): bool
  402. {
  403. if ($payment->payment_method !== 'pix') {
  404. return false;
  405. }
  406. if ($payment->status === PaymentStatusEnum::PAID) {
  407. return false;
  408. }
  409. return $payment->expires_at !== null
  410. && $payment->expires_at->isPast();
  411. }
  412. private function isIncompleteGatewayPayment(Payment $payment): bool
  413. {
  414. return $payment->status === PaymentStatusEnum::PENDING
  415. && empty($payment->gateway_entity_reference)
  416. && empty($payment->gateway_operation_reference)
  417. && empty($payment->gateway_payload);
  418. }
  419. private function isStaleIncompleteGatewayPayment(Payment $payment): bool
  420. {
  421. return $this->isIncompleteGatewayPayment($payment)
  422. && ($payment->created_at?->lte(now()->subMinutes(5)) ?? false);
  423. }
  424. public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
  425. {
  426. if ($payment->status !== PaymentStatusEnum::PAID) {
  427. return;
  428. }
  429. if ($schedule->status !== 'paid') {
  430. $schedule->update(['status' => 'paid']);
  431. }
  432. $this->syncCartsForSchedule($schedule);
  433. }
  434. public function syncPaymentTargets(Payment $payment): void
  435. {
  436. if ($payment->status !== PaymentStatusEnum::PAID) {
  437. return;
  438. }
  439. if ($payment->cart_id) {
  440. DB::transaction(function () use ($payment): void {
  441. $cart = Cart::query()->lockForUpdate()->with('items')->find($payment->cart_id);
  442. if (! $cart) {
  443. return;
  444. }
  445. $scheduleIds = $cart->items->pluck('schedule_id')->filter()->unique();
  446. Schedule::query()
  447. ->whereIn('id', $scheduleIds)
  448. ->where('status', 'accepted')
  449. ->update(['status' => 'paid']);
  450. if ($cart->status !== CartStatusEnum::PAID) {
  451. $cart->update(['status' => CartStatusEnum::PAID->value]);
  452. }
  453. });
  454. return;
  455. }
  456. $payment->loadMissing('schedule');
  457. if ($payment->schedule) {
  458. $this->syncScheduleStatusAfterPayment($payment->schedule, $payment);
  459. }
  460. }
  461. private function syncCartsForSchedule(Schedule $schedule): void
  462. {
  463. Cart::query()
  464. ->whereHas('items', fn ($query) => $query->where('schedule_id', $schedule->id))
  465. ->with('items')
  466. ->get()
  467. ->each(fn (Cart $cart) => $this->syncCartStatusAfterPayments($cart));
  468. }
  469. private function syncCartStatusAfterPayments(Cart $cart): void
  470. {
  471. $cart->loadMissing('items');
  472. $scheduleIds = $cart->items
  473. ->pluck('schedule_id')
  474. ->filter()
  475. ->unique()
  476. ->values();
  477. if ($scheduleIds->isEmpty()) {
  478. return;
  479. }
  480. $paidSchedulesCount = Schedule::query()
  481. ->whereIn('id', $scheduleIds)
  482. ->where('status', 'paid')
  483. ->count();
  484. if ($paidSchedulesCount !== $scheduleIds->count()) {
  485. return;
  486. }
  487. if ($cart->status !== CartStatusEnum::PAID) {
  488. $cart->update(['status' => CartStatusEnum::PAID->value]);
  489. }
  490. }
  491. private function validateCartForPayment(Cart $cart, SupportCollection $schedules): void
  492. {
  493. if (! in_array($cart->status, [CartStatusEnum::OPEN, CartStatusEnum::PAID], true)) {
  494. throw new \InvalidArgumentException('Carrinho precisa estar aberto para ser pago.');
  495. }
  496. if ($schedules->isEmpty()) {
  497. throw new \InvalidArgumentException('Carrinho precisa ter ao menos um agendamento.');
  498. }
  499. $providerIds = $schedules->pluck('provider_id')->filter()->unique()->values();
  500. $clientIds = $schedules->pluck('client_id')->unique()->values();
  501. if (! $cart->provider_id || $providerIds->count() !== 1 || (int) $providerIds->first() !== $cart->provider_id) {
  502. throw new \InvalidArgumentException('Todos os agendamentos do carrinho precisam ser do mesmo prestador.');
  503. }
  504. if ($clientIds->count() !== 1 || (int) $clientIds->first() !== $cart->client_id) {
  505. throw new \InvalidArgumentException('Todos os agendamentos do carrinho precisam ser do mesmo cliente.');
  506. }
  507. if (empty($cart->provider?->recipient_id)) {
  508. throw new \InvalidArgumentException('Prestador precisa ter recipient_id do Pagar.me para receber split.');
  509. }
  510. foreach ($schedules as $schedule) {
  511. $expectedStatus = $cart->status === CartStatusEnum::PAID ? 'paid' : 'accepted';
  512. if ($schedule->status !== $expectedStatus) {
  513. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa estar aceito para o carrinho ser pago.");
  514. }
  515. if ((float) $schedule->total_amount <= 0) {
  516. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa ter valor maior que zero para gerar pagamento.");
  517. }
  518. }
  519. }
  520. private function resolveCard(
  521. int $clientId,
  522. string $paymentMethod,
  523. ?int $clientPaymentMethodId,
  524. ?string $cardId,
  525. ): array {
  526. if ($paymentMethod !== 'credit_card') {
  527. return [null, null];
  528. }
  529. if (! $clientPaymentMethodId && empty($cardId)) {
  530. throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
  531. }
  532. $clientPaymentMethod = $clientPaymentMethodId
  533. ? ClientPaymentMethod::query()
  534. ->where('client_id', $clientId)
  535. ->where('id', $clientPaymentMethodId)
  536. ->where('is_active', true)
  537. ->first()
  538. : null;
  539. if ($clientPaymentMethodId && ! $clientPaymentMethod) {
  540. throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
  541. }
  542. $cardId = $cardId ?: $clientPaymentMethod?->gateway_card_id;
  543. if (empty($cardId)) {
  544. throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
  545. }
  546. return [$clientPaymentMethod, $cardId];
  547. }
  548. private function cartPaymentTotals(SupportCollection $schedules, string $paymentMethod): array
  549. {
  550. return $schedules->reduce(function (array $totals, Schedule $schedule) use ($paymentMethod): array {
  551. $amounts = $this->pagarmePaymentService->calculatePaymentAmounts(
  552. serviceAmount: (float) $schedule->total_amount,
  553. paymentMethod: $paymentMethod,
  554. schedule: $schedule,
  555. );
  556. $schedule->setAttribute('payment_gross_amount', $amounts['gross_amount']);
  557. return [
  558. 'service_amount' => round($totals['service_amount'] + $amounts['service_amount'], 2),
  559. 'platform_fee_amount' => round($totals['platform_fee_amount'] + $amounts['platform_fee_amount'], 2),
  560. 'gross_amount' => round($totals['gross_amount'] + $amounts['gross_amount'], 2),
  561. ];
  562. }, [
  563. 'service_amount' => 0.0,
  564. 'platform_fee_amount' => 0.0,
  565. 'gross_amount' => 0.0,
  566. ]);
  567. }
  568. private function failPayment(Payment $payment, string $message): void
  569. {
  570. $payment->forceFill([
  571. 'status' => PaymentStatusEnum::FAILED,
  572. 'failed_at' => now(),
  573. 'failure_message' => $message,
  574. ])->save();
  575. PaymentSplit::query()
  576. ->where('payment_id', $payment->id)
  577. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  578. }
  579. private function ensureScheduleCanBePaidIndividually(Schedule $schedule): void
  580. {
  581. $belongsToMultiItemCart = Cart::query()
  582. ->where('status', CartStatusEnum::OPEN->value)
  583. ->whereHas('items', fn ($query) => $query->where('schedule_id', $schedule->id))
  584. ->whereHas('items', null, '>', 1)
  585. ->exists();
  586. if ($belongsToMultiItemCart) {
  587. throw new \InvalidArgumentException('Agendamento pertencente a carrinho com múltiplos itens deve ser pago pelo checkout do carrinho.');
  588. }
  589. }
  590. }