client = $client; } /** * Garante que a Franquia exista como Customer (Cliente) na conta-mãe. * Retorna o ID do cliente no Asaas (cus_xxxxxx). */ public function ensureFranchiseeCustomer(Unit $unit): string { $cpfCnpj = preg_replace('/[^0-9]/', '', $unit->cnpj); if (empty($cpfCnpj)) { throw new Exception("Unidade {$unit->fantasy_name} não possui CNPJ para ser cobrada."); } // 1. Tenta buscar no Asaas se já existe o customer com esse CNPJ $existing = $this->client->get('/customers', ['cpfCnpj' => $cpfCnpj]); if (isset($existing['data']) && count($existing['data']) > 0) { return $existing['data'][0]['id']; } // 2. Se não existe, cria um novo $payload = [ 'name' => $unit->social_reason ?? $unit->fantasy_name ?? 'Franquia', 'cpfCnpj' => $cpfCnpj, 'email' => $unit->email, 'postalCode' => preg_replace('/[^0-9]/', '', $unit->postal_code), 'address' => $unit->street, 'addressNumber' => $unit->address_number ?? 'S/N', 'province' => $unit->neighborhood, ]; // Só envia telefone se for um número que pareça válido (10 a 11 dígitos), // para não travar a API do Asaas com lixo do cadastro. $mobilePhone = preg_replace('/[^0-9]/', '', $unit->cell_number ?? $unit->phone_number ?? ''); if (strlen($mobilePhone) >= 10 && strlen($mobilePhone) <= 11) { $payload['mobilePhone'] = $mobilePhone; } $response = $this->client->post('/customers', $payload); return $response['id']; } }