PaymentService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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\Database\Eloquent\Collection;
  14. use Illuminate\Support\Str;
  15. class PaymentService
  16. {
  17. public function __construct(
  18. private readonly PagarmePaymentService $pagarmePaymentService,
  19. ) {}
  20. public function getAll(): Collection
  21. {
  22. return Payment::query()
  23. ->with(['client.user', 'provider.user', 'schedule'])
  24. ->orderBy('created_at', 'desc')
  25. ->get();
  26. }
  27. public function findById(int $id): ?Payment
  28. {
  29. return Payment::query()
  30. ->with(['client.user', 'provider.user', 'schedule'])
  31. ->find($id);
  32. }
  33. public function create(array $data): Payment
  34. {
  35. return Payment::create($data);
  36. }
  37. public function update(int $id, array $data): ?Payment
  38. {
  39. $model = $this->findById($id);
  40. if (! $model) {
  41. return null;
  42. }
  43. $model->update($data);
  44. return $model->fresh();
  45. }
  46. public function delete(int $id): bool
  47. {
  48. $model = $this->findById($id);
  49. if (! $model) {
  50. return false;
  51. }
  52. return $model->delete();
  53. }
  54. //
  55. public function platformFees(): array
  56. {
  57. return $this->pagarmePaymentService->platformFeeRates();
  58. }
  59. //
  60. public function payAcceptedSchedule(
  61. Schedule $schedule, string $paymentMethod, ?int $clientPaymentMethodId = null, array $options = []
  62. ): Payment {
  63. $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
  64. if ($schedule->status !== 'accepted') {
  65. throw new \InvalidArgumentException('Agendamento precisa estar aceito para ser pago.');
  66. }
  67. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  68. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  69. }
  70. if (! $schedule->provider_id || ! $schedule->provider) {
  71. throw new \InvalidArgumentException('Agendamento precisa ter prestador confirmado para gerar pagamento.');
  72. }
  73. if ((float) $schedule->total_amount <= 0) {
  74. throw new \InvalidArgumentException('Agendamento precisa ter valor maior que zero para gerar pagamento.');
  75. }
  76. if (empty($schedule->provider->recipient_id)) {
  77. throw new \InvalidArgumentException('Prestador precisa ter recipient_id do Pagar.me para receber split.');
  78. }
  79. $existingPayment = Payment::query()
  80. ->where('schedule_id', $schedule->id)
  81. ->whereIn('status', [
  82. PaymentStatusEnum::PENDING->value,
  83. PaymentStatusEnum::PROCESSING->value,
  84. PaymentStatusEnum::AUTHORIZED->value,
  85. PaymentStatusEnum::PAID->value,
  86. ])
  87. ->latest('id')
  88. ->first();
  89. if ($existingPayment) {
  90. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  91. $existingPayment->forceFill([
  92. 'status' => PaymentStatusEnum::FAILED,
  93. 'failed_at' => now(),
  94. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  95. ])->save();
  96. }
  97. elseif ($this->isExpiredPixPayment($existingPayment)) {
  98. $existingPayment->forceFill([
  99. 'status' => PaymentStatusEnum::FAILED,
  100. 'failed_at' => now(),
  101. 'failure_message' => 'Pagamento Pix expirado.',
  102. ])->save();
  103. PaymentSplit::query()
  104. ->where('payment_id', $existingPayment->id)
  105. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  106. }
  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. schedule: $schedule,
  141. );
  142. $payment = Payment::create([
  143. 'schedule_id' => $schedule->id,
  144. 'client_id' => $schedule->client_id,
  145. 'provider_id' => $schedule->provider_id,
  146. 'client_payment_method_id' => $paymentMethod === 'credit_card' ? ($clientPaymentMethod?->id ?? null) : null,
  147. 'gateway_provider' => 'pagarme',
  148. 'gateway_code' => 'payment-'.(string) Str::uuid(),
  149. 'payment_method' => $paymentMethod,
  150. 'status' => PaymentStatusEnum::PENDING,
  151. 'gross_amount' => $amounts['gross_amount'],
  152. 'gateway_fee_amount' => 0,
  153. 'platform_fee_amount' => $amounts['platform_fee_amount'],
  154. 'net_amount' => $amounts['gross_amount'],
  155. 'currency' => 'BRL',
  156. 'installments' => 1,
  157. 'expires_at' => $paymentMethod === 'pix' ? Carbon::now()->addMinutes(30) : null,
  158. 'metadata' => [
  159. 'service_amount' => number_format($amounts['service_amount'], 2, '.', ''),
  160. 'platform_fee' => number_format($amounts['platform_fee_amount'], 2, '.', ''),
  161. ],
  162. ]);
  163. PaymentSplit::create([
  164. 'payment_id' => $payment->id,
  165. 'provider_id' => $schedule->provider_id,
  166. 'gateway_provider' => 'pagarme',
  167. 'gateway_transfer_target_reference' => $schedule->provider->recipient_id,
  168. 'gateway_transfer_target_label' => 'recipient',
  169. 'status' => PaymentSplitStatusEnum::PENDING,
  170. 'gross_amount' => $serviceAmount,
  171. 'gateway_fee_amount' => 0,
  172. 'net_amount' => $serviceAmount,
  173. 'metadata' => [
  174. 'schedule_id' => (string) $schedule->id,
  175. ],
  176. ]);
  177. $schedule->ensureCustomerPhone($options['phone'] ?? null);
  178. try {
  179. $orderResponse = $this->pagarmePaymentService->processPayment(
  180. payment: $payment,
  181. schedule: $schedule,
  182. paymentMethod: $paymentMethod,
  183. cardId: $cardId,
  184. options: $options,
  185. );
  186. } catch (\Throwable $e) {
  187. $payment->forceFill([
  188. 'status' => PaymentStatusEnum::FAILED,
  189. 'failed_at' => now(),
  190. 'failure_message' => $e->getMessage(),
  191. ])->save();
  192. PaymentSplit::query()
  193. ->where('payment_id', $payment->id)
  194. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  195. throw $e;
  196. }
  197. $payment = $this->pagarmePaymentService->applyGatewayResponseToPayment($payment, $orderResponse);
  198. $this->syncScheduleStatusAfterPayment($schedule, $payment);
  199. return $payment;
  200. }
  201. //
  202. public function getOrCreatePixPayment(Schedule $schedule): Payment
  203. {
  204. $existingPayment = Payment::query()
  205. ->where('schedule_id', $schedule->id)
  206. ->where('payment_method', 'pix')
  207. ->whereIn('status', [
  208. PaymentStatusEnum::PENDING->value,
  209. PaymentStatusEnum::PROCESSING->value,
  210. PaymentStatusEnum::AUTHORIZED->value,
  211. PaymentStatusEnum::PAID->value,
  212. ])
  213. ->latest('id')
  214. ->first();
  215. if ($existingPayment && $this->isExpiredPixPayment($existingPayment)) {
  216. $existingPayment->forceFill([
  217. 'status' => PaymentStatusEnum::FAILED,
  218. 'failed_at' => Carbon::now(),
  219. 'failure_message' => 'Pagamento Pix expirado.',
  220. ])->save();
  221. PaymentSplit::query()
  222. ->where('payment_id', $existingPayment->id)
  223. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  224. $existingPayment = null;
  225. }
  226. if ($existingPayment) {
  227. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  228. $existingPayment->forceFill([
  229. 'status' => PaymentStatusEnum::FAILED,
  230. 'failed_at' => Carbon::now(),
  231. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  232. ])->save();
  233. PaymentSplit::query()
  234. ->where('payment_id', $existingPayment->id)
  235. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  236. } else {
  237. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  238. return $existingPayment;
  239. }
  240. }
  241. return $this->payAcceptedSchedule(
  242. schedule: $schedule,
  243. paymentMethod: 'pix',
  244. );
  245. }
  246. //
  247. private function isExpiredPixPayment(Payment $payment): bool
  248. {
  249. if ($payment->payment_method !== 'pix') {
  250. return false;
  251. }
  252. if ($payment->status === PaymentStatusEnum::PAID) {
  253. return false;
  254. }
  255. return $payment->expires_at !== null
  256. && $payment->expires_at->isPast();
  257. }
  258. private function isIncompleteGatewayPayment(Payment $payment): bool
  259. {
  260. return $payment->status === PaymentStatusEnum::PENDING
  261. && empty($payment->gateway_entity_reference)
  262. && empty($payment->gateway_operation_reference)
  263. && empty($payment->gateway_payload);
  264. }
  265. public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
  266. {
  267. if ($payment->status !== PaymentStatusEnum::PAID) {
  268. return;
  269. }
  270. if ($schedule->status !== 'paid') {
  271. $schedule->update(['status' => 'paid']);
  272. }
  273. $this->syncCartsForSchedule($schedule);
  274. }
  275. private function syncCartsForSchedule(Schedule $schedule): void
  276. {
  277. Cart::query()
  278. ->whereHas('items', fn ($query) => $query->where('schedule_id', $schedule->id))
  279. ->with('items')
  280. ->get()
  281. ->each(fn (Cart $cart) => $this->syncCartStatusAfterPayments($cart));
  282. }
  283. private function syncCartStatusAfterPayments(Cart $cart): void
  284. {
  285. $cart->loadMissing('items');
  286. $scheduleIds = $cart->items
  287. ->pluck('schedule_id')
  288. ->filter()
  289. ->unique()
  290. ->values();
  291. if ($scheduleIds->isEmpty()) {
  292. return;
  293. }
  294. $paidSchedulesCount = Payment::query()
  295. ->whereIn('schedule_id', $scheduleIds)
  296. ->where('status', PaymentStatusEnum::PAID->value)
  297. ->distinct('schedule_id')
  298. ->count('schedule_id');
  299. if ($paidSchedulesCount !== $scheduleIds->count()) {
  300. return;
  301. }
  302. if ($cart->status !== CartStatusEnum::PAID) {
  303. $cart->update(['status' => CartStatusEnum::PAID->value]);
  304. }
  305. }
  306. }