PaymentService.php 17 KB

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