PaymentService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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 payCart(array $data, int $userId): SupportCollection
  206. {
  207. $cart = Cart::query()
  208. ->with(['items.schedule.client', 'items.schedule.provider'])
  209. ->findOrFail($data['cart_id']);
  210. $schedules = $this->cartSchedules($cart);
  211. if ($schedules->contains(fn (Schedule $schedule) => $schedule->client?->user_id !== $userId)) {
  212. throw new AuthorizationException;
  213. }
  214. $this->validateCartSchedules($schedules, $data['payment_method']);
  215. $payments = $schedules->map(fn (Schedule $schedule) => $this->payAcceptedSchedule(
  216. schedule: $schedule,
  217. paymentMethod: $data['payment_method'],
  218. clientPaymentMethodId: $data['client_payment_method_id'] ?? null,
  219. options: [
  220. 'phone' => $data['phone'] ?? null,
  221. 'card_id' => $data['card_id'] ?? null,
  222. ],
  223. ));
  224. $this->syncCartStatusAfterPayments($cart);
  225. return $payments;
  226. }
  227. */
  228. //
  229. public function getOrCreatePixPayment(Schedule $schedule): Payment
  230. {
  231. $existingPayment = Payment::query()
  232. ->where('schedule_id', $schedule->id)
  233. ->where('payment_method', 'pix')
  234. ->whereIn('status', [
  235. PaymentStatusEnum::PENDING->value,
  236. PaymentStatusEnum::PROCESSING->value,
  237. PaymentStatusEnum::AUTHORIZED->value,
  238. PaymentStatusEnum::PAID->value,
  239. ])
  240. ->latest('id')
  241. ->first();
  242. if ($existingPayment && $this->isExpiredPixPayment($existingPayment)) {
  243. $existingPayment->forceFill([
  244. 'status' => PaymentStatusEnum::FAILED,
  245. 'failed_at' => Carbon::now(),
  246. 'failure_message' => 'Pagamento Pix expirado.',
  247. ])->save();
  248. PaymentSplit::query()
  249. ->where('payment_id', $existingPayment->id)
  250. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  251. $existingPayment = null;
  252. }
  253. if ($existingPayment) {
  254. if ($this->isIncompleteGatewayPayment($existingPayment)) {
  255. $existingPayment->forceFill([
  256. 'status' => PaymentStatusEnum::FAILED,
  257. 'failed_at' => Carbon::now(),
  258. 'failure_message' => 'Pagamento pendente sem retorno do gateway.',
  259. ])->save();
  260. PaymentSplit::query()
  261. ->where('payment_id', $existingPayment->id)
  262. ->update(['status' => PaymentSplitStatusEnum::FAILED]);
  263. } else {
  264. $this->syncScheduleStatusAfterPayment($schedule, $existingPayment);
  265. return $existingPayment;
  266. }
  267. }
  268. return $this->payAcceptedSchedule(
  269. schedule: $schedule,
  270. paymentMethod: 'pix',
  271. );
  272. }
  273. //
  274. private function isExpiredPixPayment(Payment $payment): bool
  275. {
  276. if ($payment->payment_method !== 'pix') {
  277. return false;
  278. }
  279. if ($payment->status === PaymentStatusEnum::PAID) {
  280. return false;
  281. }
  282. return $payment->expires_at !== null
  283. && $payment->expires_at->isPast();
  284. }
  285. private function isIncompleteGatewayPayment(Payment $payment): bool
  286. {
  287. return $payment->status === PaymentStatusEnum::PENDING
  288. && empty($payment->gateway_entity_reference)
  289. && empty($payment->gateway_operation_reference)
  290. && empty($payment->gateway_payload);
  291. }
  292. public function syncScheduleStatusAfterPayment(Schedule $schedule, Payment $payment): void
  293. {
  294. if ($payment->status !== PaymentStatusEnum::PAID) {
  295. return;
  296. }
  297. if ($schedule->status !== 'paid') {
  298. $schedule->update(['status' => 'paid']);
  299. }
  300. $this->syncCartsForSchedule($schedule);
  301. }
  302. private function validateCartSchedules(SupportCollection $schedules, string $paymentMethod): void
  303. {
  304. if ($schedules->isEmpty()) {
  305. throw new \InvalidArgumentException('Carrinho precisa ter ao menos um agendamento.');
  306. }
  307. if (! in_array($paymentMethod, ['credit_card', 'pix'], true)) {
  308. throw new \InvalidArgumentException('Forma de pagamento invalida.');
  309. }
  310. $clientIds = $schedules->pluck('client_id')->unique()->values();
  311. if ($clientIds->count() !== 1) {
  312. throw new \InvalidArgumentException('Todos os agendamentos do carrinho precisam ser do mesmo cliente.');
  313. }
  314. $schedules->each(function (Schedule $schedule): void {
  315. $schedule->loadMissing(['client', 'provider', 'customSchedule.serviceType']);
  316. if ($schedule->status !== 'accepted') {
  317. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa estar aceito para ser pago.");
  318. }
  319. if (! $schedule->provider_id || ! $schedule->provider) {
  320. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa ter prestador confirmado para gerar pagamento.");
  321. }
  322. if ((float) $schedule->total_amount <= 0) {
  323. throw new \InvalidArgumentException("Agendamento {$schedule->id} precisa ter valor maior que zero para gerar pagamento.");
  324. }
  325. if (empty($schedule->provider->recipient_id)) {
  326. throw new \InvalidArgumentException("Prestador do agendamento {$schedule->id} precisa ter recipient_id do Pagar.me para receber split.");
  327. }
  328. $existingPayment = Payment::query()
  329. ->where('schedule_id', $schedule->id)
  330. ->whereIn('status', [
  331. PaymentStatusEnum::PENDING->value,
  332. PaymentStatusEnum::PROCESSING->value,
  333. PaymentStatusEnum::AUTHORIZED->value,
  334. PaymentStatusEnum::PAID->value,
  335. ])
  336. ->latest('id')
  337. ->first();
  338. if ($existingPayment) {
  339. throw new \InvalidArgumentException("Ja existe um pagamento em andamento para o agendamento {$schedule->id}.");
  340. }
  341. });
  342. }
  343. //
  344. private function cartSchedules(Cart $cart): SupportCollection
  345. {
  346. $schedules = $cart->items
  347. ->map(fn ($item) => $item->schedule)
  348. ->filter()
  349. ->values();
  350. if ($schedules->isEmpty() || $schedules->count() !== $cart->items->count()) {
  351. throw new \InvalidArgumentException('Um ou mais agendamentos nao foram encontrados.');
  352. }
  353. return $schedules;
  354. }
  355. private function syncCartsForSchedule(Schedule $schedule): void
  356. {
  357. Cart::query()
  358. ->whereHas('items', fn ($query) => $query->where('schedule_id', $schedule->id))
  359. ->with('items')
  360. ->get()
  361. ->each(fn (Cart $cart) => $this->syncCartStatusAfterPayments($cart));
  362. }
  363. private function syncCartStatusAfterPayments(Cart $cart): void
  364. {
  365. $cart->loadMissing('items');
  366. $scheduleIds = $cart->items
  367. ->pluck('schedule_id')
  368. ->filter()
  369. ->unique()
  370. ->values();
  371. if ($scheduleIds->isEmpty()) {
  372. return;
  373. }
  374. $paidSchedulesCount = Payment::query()
  375. ->whereIn('schedule_id', $scheduleIds)
  376. ->where('status', PaymentStatusEnum::PAID->value)
  377. ->distinct('schedule_id')
  378. ->count('schedule_id');
  379. if ($paidSchedulesCount !== $scheduleIds->count()) {
  380. return;
  381. }
  382. if ($cart->status !== CartStatusEnum::PAID) {
  383. $cart->update(['status' => CartStatusEnum::PAID->value]);
  384. }
  385. }
  386. public function syncSchedulesStatusAfterPayment(Payment $payment): void
  387. {
  388. $payment->loadMissing('schedules');
  389. if ($payment->schedules->isEmpty()) {
  390. if ($payment->schedule) {
  391. $this->syncScheduleStatusAfterPayment($payment->schedule, $payment);
  392. }
  393. return;
  394. }
  395. $payment->schedules->each(fn (Schedule $schedule) => $this->syncScheduleStatusAfterPayment($schedule, $payment));
  396. }
  397. //
  398. private function cartPaymentTotals(SupportCollection $schedules, string $paymentMethod): array
  399. {
  400. return $schedules->reduce(function (array $totals, Schedule $schedule) use ($paymentMethod) {
  401. $amounts = $this->pagarmePaymentService->calculatePaymentAmounts(
  402. serviceAmount: (float) $schedule->total_amount,
  403. paymentMethod: $paymentMethod,
  404. );
  405. return [
  406. 'service_amount' => $totals['service_amount'] + $amounts['service_amount'],
  407. 'platform_fee_amount' => $totals['platform_fee_amount'] + $amounts['platform_fee_amount'],
  408. 'gross_amount' => $totals['gross_amount'] + $amounts['gross_amount'],
  409. ];
  410. }, [
  411. 'service_amount' => 0,
  412. 'platform_fee_amount' => 0,
  413. 'gross_amount' => 0,
  414. ]);
  415. }
  416. }