PaymentService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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\Str;
  17. class PaymentService
  18. {
  19. public function __construct(
  20. private readonly PagarmePaymentService $pagarmePaymentService,
  21. ) {}
  22. public function getAll(): Collection
  23. {
  24. return Payment::query()
  25. ->with(['client.user', 'provider.user', 'schedule'])
  26. ->orderBy('created_at', 'desc')
  27. ->get();
  28. }
  29. public function findById(int $id): ?Payment
  30. {
  31. return Payment::query()
  32. ->with(['client.user', 'provider.user', 'schedule'])
  33. ->find($id);
  34. }
  35. public function create(array $data): Payment
  36. {
  37. return Payment::create($data);
  38. }
  39. public function update(int $id, array $data): ?Payment
  40. {
  41. $model = $this->findById($id);
  42. if (! $model) {
  43. return null;
  44. }
  45. $model->update($data);
  46. return $model->fresh();
  47. }
  48. public function delete(int $id): bool
  49. {
  50. $model = $this->findById($id);
  51. if (! $model) {
  52. return false;
  53. }
  54. return $model->delete();
  55. }
  56. //
  57. public function platformFees(): array
  58. {
  59. return $this->pagarmePaymentService->platformFeeRates();
  60. }
  61. //
  62. public function payAcceptedSchedule(
  63. Schedule $schedule, string $paymentMethod, ?int $clientPaymentMethodId = null, array $options = []
  64. ): Payment {
  65. $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
  66. if ($schedule->status !== 'accepted') {
  67. throw new \InvalidArgumentException('Agendamento precisa estar aceito para ser pago.');
  68. }
  69. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  70. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  71. }
  72. if (! $schedule->provider_id || ! $schedule->provider) {
  73. throw new \InvalidArgumentException('Agendamento precisa ter prestador confirmado para gerar pagamento.');
  74. }
  75. if ((float) $schedule->total_amount <= 0) {
  76. throw new \InvalidArgumentException('Agendamento precisa ter valor maior que zero para gerar pagamento.');
  77. }
  78. if (empty($schedule->provider->recipient_id)) {
  79. throw new \InvalidArgumentException('Prestador precisa ter recipient_id do Pagar.me para receber split.');
  80. }
  81. $existingPayment = Payment::query()
  82. ->where('schedule_id', $schedule->id)
  83. ->whereIn('status', [
  84. PaymentStatusEnum::PENDING->value,
  85. PaymentStatusEnum::PROCESSING->value,
  86. PaymentStatusEnum::AUTHORIZED->value,
  87. PaymentStatusEnum::PAID->value,
  88. ])
  89. ->latest('id')
  90. ->first();
  91. if ($existingPayment) {
  92. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  93. $existingPayment->forceFill([
  94. 'status' => PaymentStatusEnum::FAILED,
  95. 'failed_at' => now(),
  96. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  97. ])->save();
  98. } elseif ($this->isExpiredPixPayment($existingPayment)) {
  99. $existingPayment->forceFill([
  100. 'status' => PaymentStatusEnum::FAILED,
  101. 'failed_at' => now(),
  102. 'failure_message' => 'Pagamento Pix expirado.',
  103. ])->save();
  104. PaymentSplit::query()
  105. ->where('payment_id', $existingPayment->id)
  106. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  107. } else {
  108. if ($existingPayment->payment_method !== $paymentMethod && $existingPayment->status !== PaymentStatusEnum::PAID) {
  109. throw new \InvalidArgumentException('Ja existe um pagamento em andamento para este agendamento.');
  110. }
  111. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  112. return $existingPayment;
  113. }
  114. }
  115. $clientPaymentMethod = null;
  116. $cardId = null;
  117. if ($paymentMethod === 'credit_card') {
  118. if (! $clientPaymentMethodId && empty($options['card_id'])) {
  119. throw new \InvalidArgumentException('Cartao de pagamento ou card_id e obrigatorio.');
  120. }
  121. if ($clientPaymentMethodId) {
  122. $clientPaymentMethod = ClientPaymentMethod::query()
  123. ->where('client_id', $schedule->client_id)
  124. ->where('id', $clientPaymentMethodId)
  125. ->where('is_active', true)
  126. ->first();
  127. if (! $clientPaymentMethod) {
  128. throw new \InvalidArgumentException('Cartao de pagamento nao encontrado ou inativo para este cliente.');
  129. }
  130. }
  131. $cardId = $options['card_id'] ?? $clientPaymentMethod?->gateway_card_id ?? null;
  132. if (empty($cardId)) {
  133. throw new \InvalidArgumentException('Cartao de pagamento invalido ou sem gateway_card_id do Pagar.me.');
  134. }
  135. }
  136. $serviceAmount = (float) $schedule->total_amount;
  137. $amounts = $this->pagarmePaymentService->calculatePaymentAmounts(
  138. serviceAmount: $serviceAmount,
  139. paymentMethod: $paymentMethod,
  140. );
  141. $payment = Payment::create([
  142. 'schedule_id' => $schedule->id,
  143. 'client_id' => $schedule->client_id,
  144. 'provider_id' => $schedule->provider_id,
  145. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? ($clientPaymentMethod?->id ?? null) : null,
  146. 'gateway_provider' => 'pagarme',
  147. 'gateway_code' => 'payment-'.(string) Str::uuid(),
  148. 'payment_method' => $paymentMethod,
  149. 'status' => PaymentStatusEnum::PENDING,
  150. 'gross_amount' => $amounts['gross_amount'],
  151. 'gateway_fee_amount' => 0,
  152. 'platform_fee_amount' => $amounts['platform_fee_amount'],
  153. 'net_amount' => $amounts['gross_amount'],
  154. 'currency' => 'BRL',
  155. 'installments' => 1,
  156. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  157. 'metadata' => [
  158. 'service_amount' => number_format($amounts['service_amount'], 2, '.', ''),
  159. 'platform_fee' => number_format($amounts['platform_fee_amount'], 2, '.', ''),
  160. ],
  161. ]);
  162. PaymentSplit::create([
  163. 'payment_id' => $payment->id,
  164. 'provider_id' => $schedule->provider_id,
  165. 'gateway_provider' => 'pagarme',
  166. 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
  167. 'gateway_transfer_target_label' => 'recipient',
  168. 'status' => PaymentSplitStatusEnum::PENDING,
  169. 'gross_amount' => $serviceAmount,
  170. 'gateway_fee_amount' => 0,
  171. 'net_amount' => $serviceAmount,
  172. 'metadata' => [
  173. 'schedule_id' => (string) $schedule->id,
  174. ],
  175. ]);
  176. $schedule->ensureCustomerPhone($options['phone'] ?? null);
  177. try {
  178. $orderResponse = $this->pagarmePaymentService->processPayment(
  179. payment: $payment,
  180. schedule: $schedule,
  181. paymentMethod: $paymentMethod,
  182. cardId: $cardId,
  183. options: $options,
  184. );
  185. } catch (\Throwable $e) {
  186. $payment->forceFill([
  187. 'status' => PaymentStatusEnum::FAILED,
  188. 'failed_at' => now(),
  189. 'failure_message' => $e->getMessage(),
  190. ])->save();
  191. PaymentSplit::query()
  192. ->where('payment_id', $payment->id)
  193. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  194. throw $e;
  195. }
  196. $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  197. $this->syncScheduleStatusAfterPayment($schedule, $payment);
  198. return $payment;
  199. }
  200. public function payCart(array $data, int $userId): SupportCollection
  201. {
  202. $cart = Cart::query()
  203. ->with(['items.schedule.client', 'items.schedule.provider'])
  204. ->findOrFail($data['cart_id']);
  205. $schedules = $this->cartSchedules($cart);
  206. if ($schedules->contains(fn (Schedule $schedule) => $schedule->client?->user_id !== $userId)) {
  207. throw new AuthorizationException;
  208. }
  209. $this->validateCartSchedules($schedules, $data['payment_method']);
  210. $payments = $schedules->map(fn (Schedule $schedule) => $this->payAcceptedSchedule(
  211. schedule: $schedule,
  212. paymentMethod: $data['payment_method'],
  213. clientPaymentMethodId: $data['client_payment_method_id'] ?? null,
  214. options: [
  215. 'phone' => $data['phone'] ?? null,
  216. 'card_id' => $data['card_id'] ?? null,
  217. ],
  218. ));
  219. $this->syncCartStatusAfterPayments($cart);
  220. return $payments;
  221. }
  222. //
  223. public function getOrCreatePixPayment(Schedule $schedule): Payment
  224. {
  225. $existingPayment = Payment::query()
  226. ->where('schedule_id', $schedule->id)
  227. ->where('payment_method', 'pix')
  228. ->whereIn('status', [
  229. PaymentStatusEnum::PENDING->value,
  230. PaymentStatusEnum::PROCESSING->value,
  231. PaymentStatusEnum::AUTHORIZED->value,
  232. PaymentStatusEnum::PAID->value,
  233. ])
  234. ->latest('id')
  235. ->first();
  236. if ($existingPayment && $this->isExpiredPixPayment($existingPayment)) {
  237. $existingPayment->forceFill([
  238. 'status' => PaymentStatusEnum::FAILED,
  239. 'failed_at' => Carbon::now(),
  240. 'failure_message' => 'Pagamento Pix expirado.',
  241. ])->save();
  242. PaymentSplit::query()
  243. ->where('payment_id', $existingPayment->id)
  244. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  245. $existingPayment = null;
  246. }
  247. if ($existingPayment) {
  248. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  249. $existingPayment->forceFill([
  250. 'status' => PaymentStatusEnum::FAILED,
  251. 'failed_at' => Carbon::now(),
  252. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  253. ])->save();
  254. PaymentSplit::query()
  255. ->where('payment_id', $existingPayment->id)
  256. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  257. } else {
  258. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  259. return $existingPayment;
  260. }
  261. }
  262. return $this->payAcceptedSchedule(
  263. schedule: $schedule,
  264. paymentMethod: 'pix',
  265. );
  266. }
  267. //
  268. private function isExpiredPixPayment(Payment $payment): bool
  269. {
  270. if ($payment->payment_method !== 'pix') {
  271. return false;
  272. }
  273. if ($payment->status === PaymentStatusEnum::PAID) {
  274. return false;
  275. }
  276. return $payment->expires_at !== null
  277. && $payment->expires_at->isPast();
  278. }
  279. private function isIncompleteGatewayPayment(Payment $payment): bool
  280. {
  281. return $payment->status === PaymentStatusEnum::PENDING
  282. && empty($payment->gateway_entity_reference)
  283. && empty($payment->gateway_operation_reference)
  284. && empty($payment->gateway_payload);
  285. }
  286. public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
  287. {
  288. if ($payment->status !== PaymentStatusEnum::PAID) {
  289. return;
  290. }
  291. if ($schedule->status !== 'paid') {
  292. $schedule->update(['status' => 'paid']);
  293. }
  294. $this->syncCartsForSchedule($schedule);
  295. }
  296. private function validateCartSchedules(SupportCollection $schedules, string $paymentMethod): void
  297. {
  298. if ($schedules->isEmpty()) {
  299. throw new \InvalidArgumentException('Carrinho precisa ter ao menos um agendamento.');
  300. }
  301. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  302. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  303. }
  304. $clientIds = $schedules->pluck('client_id')->unique()->values();
  305. if ($clientIds->count() !== 1) {
  306. throw new \InvalidArgumentException('Todos os agendamentos do carrinho precisam ser do mesmo cliente.');
  307. }
  308. $schedules->each(function (Schedule $schedule): void {
  309. $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
  310. if ($schedule->status !== 'accepted') {
  311. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa estar aceito para ser pago.");
  312. }
  313. if (! $schedule->provider_id || ! $schedule->provider) {
  314. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa ter prestador confirmado para gerar pagamento.");
  315. }
  316. if ((float) $schedule->total_amount <= 0) {
  317. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa ter valor maior que zero para gerar pagamento.");
  318. }
  319. if (empty($schedule->provider->recipient_id)) {
  320. throw new \InvalidArgumentException("Prestador do agendamento {$schedule->id} precisa ter recipient_id do Pagar.me para receber split.");
  321. }
  322. $existingPayment = Payment::query()
  323. ->where('schedule_id', $schedule->id)
  324. ->whereIn('status', [
  325. PaymentStatusEnum::PENDING->value,
  326. PaymentStatusEnum::PROCESSING->value,
  327. PaymentStatusEnum::AUTHORIZED->value,
  328. PaymentStatusEnum::PAID->value,
  329. ])
  330. ->latest('id')
  331. ->first();
  332. if ($existingPayment) {
  333. throw new \InvalidArgumentException("Ja existe um pagamento em andamento para o agendamento {$schedule->id}.");
  334. }
  335. });
  336. }
  337. //
  338. private function cartSchedules(Cart $cart): SupportCollection
  339. {
  340. $schedules = $cart->items
  341. ->map(fn ($item) => $item->schedule)
  342. ->filter()
  343. ->values();
  344. if ($schedules->isEmpty() || $schedules->count() !== $cart->items->count()) {
  345. throw new \InvalidArgumentException('Um ou mais agendamentos nao foram encontrados.');
  346. }
  347. return $schedules;
  348. }
  349. private function syncCartsForSchedule(Schedule $schedule): void
  350. {
  351. Cart::query()
  352. ->whereHas('items', fn ($query) => $query->where('schedule_id', $schedule->id))
  353. ->with('items')
  354. ->get()
  355. ->each(fn (Cart $cart) => $this->syncCartStatusAfterPayments($cart));
  356. }
  357. private function syncCartStatusAfterPayments(Cart $cart): void
  358. {
  359. $cart->loadMissing('items');
  360. $scheduleIds = $cart->items
  361. ->pluck('schedule_id')
  362. ->filter()
  363. ->unique()
  364. ->values();
  365. if ($scheduleIds->isEmpty()) {
  366. return;
  367. }
  368. $paidSchedulesCount = Payment::query()
  369. ->whereIn('schedule_id', $scheduleIds)
  370. ->where('status', PaymentStatusEnum::PAID->value)
  371. ->distinct('schedule_id')
  372. ->count('schedule_id');
  373. if ($paidSchedulesCount !== $scheduleIds->count()) {
  374. return;
  375. }
  376. if ($cart->status !== CartStatusEnum::PAID) {
  377. $cart->update(['status' => CartStatusEnum::PAID->value]);
  378. }
  379. }
  380. }