PaymentService.php 17 KB

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