Bläddra i källkod

refactor: add ajustes em recipient service, add formatacao de data de nascimento e normaliza nome do dono da conta bancaria

Gustavo Mantovani 3 veckor sedan
förälder
incheckning
f427581cba

+ 29 - 24
app/Services/AuthService.php

@@ -133,11 +133,11 @@ class AuthService
                 $query->when(! empty($data['email']), function ($q) use ($data) {
                 $query->when(! empty($data['email']), function ($q) use ($data) {
                     $q->where('email', $data['email']);
                     $q->where('email', $data['email']);
                 })
                 })
-                    ->when(! empty($data['phone']), function ($q) use ($data) {
-                        $q->where('phone', $data['phone']);
-                    });
+                ->when(! empty($data['phone']), function ($q) use ($data) {
+                    $q->where('phone', $data['phone']);
+                });
             })
             })
-                ->first();
+            ->first();
 
 
             $isLogin = false;
             $isLogin = false;
 
 
@@ -148,7 +148,8 @@ class AuthService
                     return ['error' => 'wrong_user_type'];
                     return ['error' => 'wrong_user_type'];
                 }
                 }
 
 
-                $user->code           = $code;
+                $user->code = $code;
+
                 $user->validated_code = false;
                 $user->validated_code = false;
 
 
                 $user->save();
                 $user->save();
@@ -211,11 +212,11 @@ class AuthService
                 $query->when(! empty($data['email']), function ($q) use ($data) {
                 $query->when(! empty($data['email']), function ($q) use ($data) {
                     $q->where('email', $data['email']);
                     $q->where('email', $data['email']);
                 })
                 })
-                    ->when(! empty($data['phone']), function ($q) use ($data) {
-                        $q->where('phone', $data['phone']);
-                    });
+                ->when(! empty($data['phone']), function ($q) use ($data) {
+                    $q->where('phone', $data['phone']);
+                });
             })
             })
-                ->first();
+            ->first();
 
 
             $isLogin = false;
             $isLogin = false;
 
 
@@ -234,7 +235,8 @@ class AuthService
                     return ['error' => 'provider_not_accepted'];
                     return ['error' => 'provider_not_accepted'];
                 }
                 }
 
 
-                $user->code           = $code;
+                $user->code = $code;
+
                 $user->validated_code = false;
                 $user->validated_code = false;
 
 
                 $user->save();
                 $user->save();
@@ -283,7 +285,7 @@ class AuthService
     {
     {
         $email = $data['email'] ?? null;
         $email = $data['email'] ?? null;
         $phone = $data['phone'] ?? null;
         $phone = $data['phone'] ?? null;
-        $code  = $data['code'] ?? '';
+        $code  = $data['code']  ?? '';
 
 
         $user = User::where(function ($query) use ($email, $phone) {
         $user = User::where(function ($query) use ($email, $phone) {
             $query->when($email, fn ($q) => $q->where('email', $email))
             $query->when($email, fn ($q) => $q->where('email', $email))
@@ -307,14 +309,14 @@ class AuthService
     {
     {
         $email = $data['email'] ?? null;
         $email = $data['email'] ?? null;
         $phone = $data['phone'] ?? null;
         $phone = $data['phone'] ?? null;
-        $code  = $data['code'] ?? '';
+        $code  = $data['code']  ?? '';
 
 
         $user = User::where(function ($query) use ($email, $phone) {
         $user = User::where(function ($query) use ($email, $phone) {
             $query->when($email, fn ($q) => $q->where('email', $email))
             $query->when($email, fn ($q) => $q->where('email', $email))
                 ->when($phone, fn ($q) => $q->where('phone', $phone));
                 ->when($phone, fn ($q) => $q->where('phone', $phone));
         })
         })
-            ->where('code', $code)
-            ->first();
+        ->where('code', $code)
+        ->first();
 
 
         if (! $user) {
         if (! $user) {
             return false;
             return false;
@@ -343,18 +345,18 @@ class AuthService
     {
     {
         $email = $data['email'] ?? null;
         $email = $data['email'] ?? null;
         $phone = $data['phone'] ?? null;
         $phone = $data['phone'] ?? null;
-        $code  = $data['code'] ?? '';
+        $code  = $data['code']  ?? '';
 
 
         $user = User::where(function ($query) use ($email, $phone) {
         $user = User::where(function ($query) use ($email, $phone) {
             $query->when($email, function ($q) use ($email) {
             $query->when($email, function ($q) use ($email) {
                 $q->where('email', $email);
                 $q->where('email', $email);
             })
             })
-                ->when($phone, function ($q) use ($phone) {
-                    $q->where('phone', $phone);
-                });
+            ->when($phone, function ($q) use ($phone) {
+                $q->where('phone', $phone);
+            });
         })
         })
-            ->where('code', $code)
-            ->first();
+        ->where('code', $code)
+        ->first();
 
 
         if (! $user) {
         if (! $user) {
             return false;
             return false;
@@ -379,11 +381,14 @@ class AuthService
             return null;
             return null;
         }
         }
 
 
-        $deviceId             = Str::uuid()->toString();
-        $accessToken          = $user->createAccessTokenApp($deviceId);
-        $refreshToken         = $user->createRefreshTokenApp($deviceId);
+        $deviceId = Str::uuid()->toString();
+
+        $accessToken  = $user->createAccessTokenApp($deviceId);
+        $refreshToken = $user->createRefreshTokenApp($deviceId);
+
         $user->validated_code = true;
         $user->validated_code = true;
-        $user->code           = null;
+
+        $user->code = null;
 
 
         $user->save();
         $user->save();
 
 

+ 0 - 4
app/Services/Pagarme/PagarmeCustomerService.php

@@ -170,10 +170,6 @@ class PagarmeCustomerService
 
 
     //
     //
 
 
-    /**
-     * @param  array<string, mixed>  $data
-     * @return array<string, mixed>
-     */
     private function filterFilledRecursive(array $data): array
     private function filterFilledRecursive(array $data): array
     {
     {
         $filtered = [];
         $filtered = [];

+ 35 - 39
app/Services/Pagarme/PagarmePaymentService.php

@@ -60,6 +60,8 @@ class PagarmePaymentService
         );
         );
     }
     }
 
 
+    //
+
     public function createOrder(
     public function createOrder(
         Payment $payment, 
         Payment $payment, 
         array   $items,
         array   $items,
@@ -140,11 +142,14 @@ class PagarmePaymentService
         return $order;
         return $order;
     }
     }
 
 
+    //
+
     public function applyGatewayResponseToPayment(Payment $payment, array $orderResponse): Payment
     public function applyGatewayResponseToPayment(Payment $payment, array $orderResponse): Payment
     {
     {
         $charge = $orderResponse['charges'][0] ?? [];
         $charge = $orderResponse['charges'][0] ?? [];
 
 
-        $transaction  = $charge['last_transaction']  ?? [];
+        $transaction = $charge['last_transaction'] ?? [];
+
         $chargeStatus = $charge['status'] ?? null;
         $chargeStatus = $charge['status'] ?? null;
 
 
         $transactionStatus = $transaction['status'] ?? null;
         $transactionStatus = $transaction['status'] ?? null;
@@ -166,26 +171,25 @@ class PagarmePaymentService
         return $payment->fresh();
         return $payment->fresh();
     }
     }
 
 
-    /**
-     * @param  Collection<int, PaymentTransfer>  $transfers
-     * @return array<int, array<string, mixed>>
-     */
+    //
+
     public function buildSplitFromTransfers(Collection $transfers): array
     public function buildSplitFromTransfers(Collection $transfers): array
     {
     {
         return $transfers
         return $transfers
             ->filter(fn (PaymentTransfer $transfer) => ! empty($transfer->gateway_transfer_target_reference))
             ->filter(fn (PaymentTransfer $transfer) => ! empty($transfer->gateway_transfer_target_reference))
             ->map(function (PaymentTransfer $transfer) {
             ->map(function (PaymentTransfer $transfer) {
                 return [
                 return [
-            'amount'       => $this->toGatewayAmountInCents((float) $transfer->gross_amount),
-            'recipient_id' => $transfer->gateway_transfer_target_reference,
-            'type'         => 'flat',
-            'options'      => [
-                'charge_processing_fee' => false,
-                'charge_remainder_fee'  => false,
-                'liable'                => false,
-            ],
-        ];
-    })
+                    'amount'       => $this->toGatewayAmountInCents((float) $transfer->gross_amount),
+                    'recipient_id' => $transfer->gateway_transfer_target_reference,
+                    'type'         => 'flat',
+                    
+                    'options' => [
+                        'charge_processing_fee' => false,
+                        'charge_remainder_fee'  => false,
+                        'liable'                => false,
+                    ],
+                ];
+            })
             ->values()
             ->values()
             ->all();
             ->all();
     }
     }
@@ -274,17 +278,6 @@ class PagarmePaymentService
 
 
     //
     //
 
 
-    private function resolveAuthorizedAt(?string $transactionStatus, array $transaction): ?string
-    {
-        if (in_array($transactionStatus, ['authorized_pending_capture', 'captured', 'partial_capture'], true)) {
-            return $this->filledArrayValue($transaction, 'created_at');
-        }
-
-        return null;
-    }
-
-    //
-
     private function extractFailureCode(array $transaction): ?string
     private function extractFailureCode(array $transaction): ?string
     {
     {
         return $this->filledArrayValue($transaction['gateway_response'] ?? [], 'code');
         return $this->filledArrayValue($transaction['gateway_response'] ?? [], 'code');
@@ -295,10 +288,15 @@ class PagarmePaymentService
         return $this->filledArrayValue($transaction, 'acquirer_message');
         return $this->filledArrayValue($transaction, 'acquirer_message');
     }
     }
 
 
-    /**
-     * @param  array<int, array<string, mixed>>  $items
-     * @return array<int, array<string, mixed>>
-     */
+    private function resolveAuthorizedAt(?string $transactionStatus, array $transaction): ?string
+    {
+        if (in_array($transactionStatus, ['authorized_pending_capture', 'captured', 'partial_capture'], true)) {
+            return $this->filledArrayValue($transaction, 'created_at');
+        }
+
+        return null;
+    }
+
     private function validateItems(array $items): array
     private function validateItems(array $items): array
     {
     {
         return collect($items)
         return collect($items)
@@ -319,6 +317,13 @@ class PagarmePaymentService
             ->all();
             ->all();
     }
     }
 
 
+    //
+
+    private function filled(mixed $value): bool
+    {
+        return $value !== null && $value !== '' && $value !== [];
+    }
+
     private function filledArrayValue(array $data, string $field): ?string
     private function filledArrayValue(array $data, string $field): ?string
     {
     {
         if (! array_key_exists($field, $data) || ! $this->filled($data[$field])) {
         if (! array_key_exists($field, $data) || ! $this->filled($data[$field])) {
@@ -328,10 +333,6 @@ class PagarmePaymentService
         return (string) $data[$field];
         return (string) $data[$field];
     }
     }
 
 
-    /**
-     * @param  array<string, mixed>  $data
-     * @return array<string, mixed>
-     */
     private function filterFilledRecursive(array $data): array
     private function filterFilledRecursive(array $data): array
     {
     {
         $filtered = [];
         $filtered = [];
@@ -349,11 +350,6 @@ class PagarmePaymentService
         return $filtered;
         return $filtered;
     }
     }
 
 
-    private function filled(mixed $value): bool
-    {
-        return $value !== null && $value !== '' && $value !== [];
-    }
-
     //
     //
 
 
     private function mapPaymentStatus(?string $chargeStatus, ?string $transactionStatus): string
     private function mapPaymentStatus(?string $chargeStatus, ?string $transactionStatus): string

+ 104 - 65
app/Services/Pagarme/PagarmeRecipientService.php

@@ -3,8 +3,10 @@
 namespace App\Services\Pagarme;
 namespace App\Services\Pagarme;
 
 
 use App\Models\Provider;
 use App\Models\Provider;
+use Carbon\Carbon;
 use Illuminate\Support\Facades\Http;
 use Illuminate\Support\Facades\Http;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Str;
 
 
 class PagarmeRecipientService
 class PagarmeRecipientService
 {
 {
@@ -14,10 +16,11 @@ class PagarmeRecipientService
             return $provider->recipient_id;
             return $provider->recipient_id;
         }
         }
 
 
-        $bankAccountData = $data['recipient_default_bank_account'];
-        $metadata        = $data['recipient_metadata'] ?? [];
-        $paymentMode     = $data['recipient_payment_mode'];
-        $recipientType   = $data['recipient_type'] ?? 'individual';
+        $bankAccountData                = $data['recipient_default_bank_account'];
+        $bankAccountData['holder_name'] = $this->normalizeBankAccountHolderName($bankAccountData['holder_name']);
+        $metadata                       = $data['recipient_metadata'] ?? [];
+        $paymentMode                    = $data['recipient_payment_mode'];
+        $recipientType                  = $data['recipient_type'] ?? 'individual';
 
 
         $addressParts  = $this->extractAddressParts($data);
         $addressParts  = $this->extractAddressParts($data);
         $monthlyIncome = isset($data['monthly_income']) ? (int) $data['monthly_income'] : 1000;
         $monthlyIncome = isset($data['monthly_income']) ? (int) $data['monthly_income'] : 1000;
@@ -31,7 +34,7 @@ class PagarmeRecipientService
                 'email'                   => $data['recipient_email'],
                 'email'                   => $data['recipient_email'],
                 'document'                => preg_replace('/\D+/', '', $data['recipient_document']),
                 'document'                => preg_replace('/\D+/', '', $data['recipient_document']),
                 'type'                    => $recipientType,
                 'type'                    => $recipientType,
-                'birthdate'               => $data['birth_date'] ?? null,
+                'birthdate'               => $this->formatBirthdate($data['birth_date'] ?? null),
                 'monthly_income'          => $monthlyIncome,
                 'monthly_income'          => $monthlyIncome,
                 'professional_occupation' => $occupation,
                 'professional_occupation' => $occupation,
                 'phone_numbers'           => $this->buildPhoneNumbers($data['phone'] ?? null),
                 'phone_numbers'           => $this->buildPhoneNumbers($data['phone'] ?? null),
@@ -120,8 +123,6 @@ class PagarmeRecipientService
             'recipient_metadata' => $metadata,
             'recipient_metadata' => $metadata,
         ])->save();
         ])->save();
 
 
-        $this->applyAutomaticAnticipationSettings($provider->id, $recipientId);
-
         return $recipientId;
         return $recipientId;
     }
     }
 
 
@@ -139,42 +140,31 @@ class PagarmeRecipientService
 
 
     //
     //
 
 
-    private function pagarmeRequest(int $providerId, string $suffix = 'recipient')
+    private function buildPhoneNumbers(?string $phone): array
     {
     {
-        $secretKey = config('services.pagarme.secret_key');
-
-        if (empty($secretKey)) {
-            Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
+        $digits = preg_replace('/\D+/', '', (string) $phone) ?? '';
 
 
-            throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
+        if (strlen($digits) < 10) {
+            return [[
+                'ddd'    => '11',
+                'number' => '999999999',
+                'type'   => 'mobile',
+            ]];
         }
         }
 
 
-        return Http::withBasicAuth($secretKey, '')
-            ->withHeaders([
-                'Idempotency-Key' => $this->idempotencyKey($providerId, $suffix),
-                'Content-Type'    => 'application/json',
-                'Accept'          => 'application/json',
-            ]);
-    }
-
-    private function applyAutomaticAnticipationSettings(int $providerId, string $recipientId): void
-    {
-        $payload = [
-            'enabled' => false,
-        ];
+        if (str_starts_with($digits, '55')) {
+            $digits = substr($digits, 2);
+        }
 
 
-        $response = $this->pagarmeRequest($providerId, 'auto-anticipation')
-            ->patch($this->pagarmeUrl("/recipients/{$recipientId}/automatic-anticipation-settings"), $payload);
+        $areaCode = substr($digits, 0, 2);
 
 
-        if ($response->failed()) {
-            Log::channel('pagarme')->error('Pagar.me automatic anticipation settings update failed', [
-                'status'  => $response->status(),
-                'body'    => $response->json() ?? $response->body(),
-                'payload' => $payload,
-            ]);
+        $number = substr($digits, 2);
 
 
-            throw new \RuntimeException('Erro ao atualizar antecipação automática do recebedor no Pagar.me.');
-        }
+        return [[
+            'ddd'    => $areaCode,
+            'number' => $number,
+            'type'   => 'mobile',
+        ]];
     }
     }
 
 
     private function extractAddressParts(array $data): array
     private function extractAddressParts(array $data): array
@@ -215,51 +205,100 @@ class PagarmeRecipientService
         ];
         ];
     }
     }
 
 
-    private function buildPhoneNumbers(?string $phone): array
+    //
+
+    private function filterFilledRecursive(array $data): array
     {
     {
-        $digits = preg_replace('/\D+/', '', (string) $phone) ?? '';
+        $filtered = [];
 
 
-        if (strlen($digits) < 10) {
-            return [[
-                'ddd'    => '11',
-                'number' => '999999999',
-                'type'   => 'mobile',
-            ]];
+        foreach ($data as $key => $value) {
+            if (is_array($value)) {
+                $value = $this->filterFilledRecursive($value);
+            }
+
+            if ($value !== null && $value !== '' && $value !== []) {
+                $filtered[$key] = $value;
+            }
         }
         }
 
 
-        if (str_starts_with($digits, '55')) {
-            $digits = substr($digits, 2);
+        return $filtered;
+    }
+
+    private function formatBirthdate(mixed $birthdate): ?string
+    {
+        if ($birthdate === null || $birthdate === '') {
+            return null;
         }
         }
 
 
-        $areaCode = substr($digits, 0, 2);
+        if ($birthdate instanceof \DateTimeInterface) {
+            return Carbon::instance($birthdate)->format('d/m/Y');
+        }
 
 
-        $number = substr($digits, 2);
+        $birthdate = trim((string) $birthdate);
 
 
-        return [[
-            'ddd'    => $areaCode,
-            'number' => $number,
-            'type'   => 'mobile',
-        ]];
+        if (preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $birthdate) === 1) {
+            return $birthdate;
+        }
+
+        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $birthdate) === 1) {
+            return Carbon::createFromFormat('Y-m-d', $birthdate)->format('d/m/Y');
+        }
+
+        return Carbon::parse($birthdate)->format('d/m/Y');
     }
     }
 
 
-    /**
-     * @param  array<string, mixed>  $data
-     * @return array<string, mixed>
-     */
-    private function filterFilledRecursive(array $data): array
+    private function normalizeBankAccountHolderName(string $holderName): string
     {
     {
-        $filtered = [];
+        $holderName = trim(preg_replace('/\s+/', ' ', $holderName) ?? '');
 
 
-        foreach ($data as $key => $value) {
-            if (is_array($value)) {
-                $value = $this->filterFilledRecursive($value);
+        if (Str::length($holderName) < 30) {
+            return $holderName;
+        }
+
+        $parts = explode(' ', $holderName);
+
+        if (count($parts) >= 3) {
+            $firstName = array_shift($parts);
+            $lastName  = array_pop($parts);
+
+            $initials = array_map(
+                static fn (string $part): string => Str::upper(Str::substr($part, 0, 1)),
+                $parts
+            );
+
+            $abbreviated = trim($firstName.' '.implode(' ', $initials).' '.$lastName);
+
+            if (Str::length($abbreviated) < 30) {
+                return $abbreviated;
             }
             }
 
 
-            if ($value !== null && $value !== '' && $value !== []) {
-                $filtered[$key] = $value;
+            $firstAndLast = trim($firstName.' '.$lastName);
+
+            if (Str::length($firstAndLast) < 30) {
+                return $firstAndLast;
             }
             }
         }
         }
 
 
-        return $filtered;
+        return Str::limit($holderName, 29, '');
+    }
+
+    //
+
+    private function pagarmeRequest(int $providerId, string $suffix = 'recipient')
+    {
+        $secretKey = config('services.pagarme.secret_key');
+
+        if (empty($secretKey)) {
+            Log::channel('pagarme')->error('PAGARME_SECRET_KEY is not configured.');
+
+            throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
+        }
+
+        return Http::withBasicAuth($secretKey, '')
+            ->withHeaders([
+                'Idempotency-Key' => $this->idempotencyKey($providerId, $suffix),
+                'Content-Type'    => 'application/json',
+                'Accept'          => 'application/json',
+            ]);
     }
     }
 }
 }