|
|
@@ -0,0 +1,75 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+namespace App\Jobs;
|
|
|
+
|
|
|
+use App\Models\FranchiseeAccountReceive;
|
|
|
+use App\Enums\ReceivableStatus;
|
|
|
+use App\Services\Integrations\Asaas\AsaasClient;
|
|
|
+use App\Services\Integrations\Asaas\AsaasCustomerService;
|
|
|
+use Illuminate\Bus\Queueable;
|
|
|
+use Illuminate\Contracts\Queue\ShouldQueue;
|
|
|
+use Illuminate\Foundation\Bus\Dispatchable;
|
|
|
+use Illuminate\Queue\InteractsWithQueue;
|
|
|
+use Illuminate\Queue\SerializesModels;
|
|
|
+use Exception;
|
|
|
+use Illuminate\Support\Facades\Log;
|
|
|
+
|
|
|
+class SyncFranchiseeChargeJob implements ShouldQueue
|
|
|
+{
|
|
|
+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
|
|
+
|
|
|
+ public $receive;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Create a new job instance.
|
|
|
+ */
|
|
|
+ public function __construct(FranchiseeAccountReceive $receive)
|
|
|
+ {
|
|
|
+ $this->receive = $receive;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Execute the job.
|
|
|
+ */
|
|
|
+ public function handle(AsaasClient $client, AsaasCustomerService $customerService): void
|
|
|
+ {
|
|
|
+ // 1. Garantir que a Unidade é um Customer na conta-mãe do Asaas
|
|
|
+ $unit = $this->receive->unit;
|
|
|
+ if (!$unit) {
|
|
|
+ Log::error("Recebível #{$this->receive->id} sem Unidade vinculada. Abortando integração.");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ try {
|
|
|
+ $asaasCustomerId = $customerService->ensureFranchiseeCustomer($unit);
|
|
|
+ $this->receive->update(['asaas_customer_id' => $asaasCustomerId]);
|
|
|
+
|
|
|
+ // 2. Gerar a cobrança no Asaas
|
|
|
+ $payload = [
|
|
|
+ 'customer' => $asaasCustomerId,
|
|
|
+ 'billingType' => 'UNDEFINED', // Deixa o pagador escolher PIX/Boleto
|
|
|
+ 'value' => (float) $this->receive->value,
|
|
|
+ 'dueDate' => $this->receive->due_date->format('Y-m-d'),
|
|
|
+ 'description' => $this->receive->history ?? 'Cobrança Ginástica do Cérebro (TBR)',
|
|
|
+ 'externalReference' => (string) $this->receive->id, // Para conciliarmos no webhook depois
|
|
|
+ ];
|
|
|
+
|
|
|
+ $response = $client->post('/payments', $payload);
|
|
|
+
|
|
|
+ // 3. Atualiza o banco com o link do boleto
|
|
|
+ $this->receive->update([
|
|
|
+ 'asaas_id' => $response['id'],
|
|
|
+ 'invoice_url' => $response['invoiceUrl'],
|
|
|
+ 'billing_type' => $response['billingType'] ?? 'UNDEFINED',
|
|
|
+ 'status' => ReceivableStatus::AWAITING_PAYMENT,
|
|
|
+ 'asaas_status' => $response['status'],
|
|
|
+ ]);
|
|
|
+
|
|
|
+ Log::info("Cobrança do Asaas gerada com sucesso para Recebível #{$this->receive->id}");
|
|
|
+
|
|
|
+ } catch (Exception $e) {
|
|
|
+ Log::error("Erro ao gerar cobrança no Asaas para Recebível #{$this->receive->id}: " . $e->getMessage());
|
|
|
+ throw $e; // Re-joga a exceção para que o Job tente novamente depois
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|