asaas: Tier 1 Fase A foundation — migrations + service + edge function stubs
DESIGN_ASAAS_GATEWAY.md documenta arquitetura. Schema novo: 2 migrations (tables + RLS) cobrindo asaas_customers + asaas_payments + asaas_webhook_events. Client service asaasGatewayService.js no features/financeiro. 3 Edge Function stubs (create-payment-record, cancel-payment, sync-payment) — webhook financial_records eh Fase B. Bloqueadores Fase B (implementacao real): user precisa criar conta Asaas, gerar API keys, configurar webhook, setar ENV vars no Supabase. Decisao modelo de negocio (A/B/C) tambem pendente. Stops marcados claramente no DESIGN. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,138 @@
|
|||||||
|
-- ============================================================================
|
||||||
|
-- Asaas Gateway — Tier 1 (cobrança de paciente) — schema foundation
|
||||||
|
-- ----------------------------------------------------------------------------
|
||||||
|
-- Cria 3 tabelas novas + adiciona 4 colunas em payment_settings.
|
||||||
|
-- Schema preparado pra Fase 3 do ROADMAP (gateway de pagamento).
|
||||||
|
--
|
||||||
|
-- ⚠️ Não habilita o gateway sozinho. Requer:
|
||||||
|
-- - Edge Functions deployadas
|
||||||
|
-- - API keys configuradas em payment_settings
|
||||||
|
-- - Webhook setado no dashboard Asaas
|
||||||
|
--
|
||||||
|
-- Ver: development/02-auditoria/DESIGN_ASAAS_GATEWAY.md
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
-- 1. asaas_customers — mapping patient ↔ Asaas customer
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS public.asaas_customers (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id uuid NOT NULL,
|
||||||
|
patient_id uuid NOT NULL REFERENCES public.patients(id) ON DELETE CASCADE,
|
||||||
|
asaas_customer_id text NOT NULL,
|
||||||
|
environment text NOT NULL DEFAULT 'sandbox' CHECK (environment IN ('sandbox', 'prod')),
|
||||||
|
-- dados cacheados (sincronizados quando atualizar patient)
|
||||||
|
name text NOT NULL,
|
||||||
|
email text,
|
||||||
|
cpf_cnpj text,
|
||||||
|
phone text,
|
||||||
|
address jsonb,
|
||||||
|
created_at timestamptz DEFAULT now() NOT NULL,
|
||||||
|
updated_at timestamptz DEFAULT now() NOT NULL,
|
||||||
|
deleted_at timestamptz,
|
||||||
|
CONSTRAINT asaas_customers_unique_per_env UNIQUE (tenant_id, patient_id, environment)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE public.asaas_customers IS
|
||||||
|
'Mapping de pacientes para Asaas customers (1:1 por environment). Cacheado pra evitar re-criação a cada cobrança.';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_asaas_customers_lookup
|
||||||
|
ON public.asaas_customers (tenant_id, patient_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
-- 2. asaas_payments — 1 row por cobrança gerada
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS public.asaas_payments (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id uuid NOT NULL,
|
||||||
|
financial_record_id uuid NOT NULL REFERENCES public.financial_records(id) ON DELETE CASCADE,
|
||||||
|
asaas_customer_id uuid REFERENCES public.asaas_customers(id),
|
||||||
|
asaas_payment_id text NOT NULL,
|
||||||
|
asaas_invoice_id text,
|
||||||
|
environment text NOT NULL DEFAULT 'sandbox' CHECK (environment IN ('sandbox', 'prod')),
|
||||||
|
billing_type text NOT NULL CHECK (billing_type IN ('PIX', 'BOLETO', 'CREDIT_CARD', 'UNDEFINED')),
|
||||||
|
status text NOT NULL,
|
||||||
|
value numeric(10, 2) NOT NULL,
|
||||||
|
net_value numeric(10, 2),
|
||||||
|
due_date date NOT NULL,
|
||||||
|
payment_date timestamptz,
|
||||||
|
invoice_url text,
|
||||||
|
payment_url text,
|
||||||
|
bank_slip_url text,
|
||||||
|
pix_qr_code text,
|
||||||
|
pix_copy_paste text,
|
||||||
|
created_at timestamptz DEFAULT now() NOT NULL,
|
||||||
|
updated_at timestamptz DEFAULT now() NOT NULL,
|
||||||
|
cancelled_at timestamptz,
|
||||||
|
CONSTRAINT asaas_payments_unique_per_env UNIQUE (asaas_payment_id, environment)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE public.asaas_payments IS
|
||||||
|
'Cobranças geradas no Asaas. Status raw do Asaas; mapeamento pra financial_records.status acontece no JS.';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_asaas_payments_record
|
||||||
|
ON public.asaas_payments (financial_record_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_asaas_payments_lookup
|
||||||
|
ON public.asaas_payments (tenant_id, status, due_date)
|
||||||
|
WHERE cancelled_at IS NULL;
|
||||||
|
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
-- 3. asaas_webhook_events — idempotência + audit
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS public.asaas_webhook_events (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
event_id text,
|
||||||
|
event_type text NOT NULL,
|
||||||
|
asaas_payment_id text,
|
||||||
|
payload jsonb NOT NULL,
|
||||||
|
processed_at timestamptz,
|
||||||
|
processing_error text,
|
||||||
|
received_at timestamptz DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE public.asaas_webhook_events IS
|
||||||
|
'Audit + idempotência de webhooks Asaas. event_id usado pra dedupe (Asaas faz retry).';
|
||||||
|
|
||||||
|
-- event_id UNIQUE quando preenchido (Asaas nem sempre manda)
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_asaas_webhook_events_event_id
|
||||||
|
ON public.asaas_webhook_events (event_id)
|
||||||
|
WHERE event_id IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_asaas_webhook_events_payment
|
||||||
|
ON public.asaas_webhook_events (asaas_payment_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_asaas_webhook_events_unprocessed
|
||||||
|
ON public.asaas_webhook_events (received_at)
|
||||||
|
WHERE processed_at IS NULL;
|
||||||
|
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
-- 4. payment_settings — colunas pra config Asaas por tenant
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
-- API keys plaintext nesta migration. Em produção, mover pra pgsodium/Vault.
|
||||||
|
|
||||||
|
ALTER TABLE public.payment_settings
|
||||||
|
ADD COLUMN IF NOT EXISTS asaas_api_key_sandbox text,
|
||||||
|
ADD COLUMN IF NOT EXISTS asaas_api_key_prod text,
|
||||||
|
ADD COLUMN IF NOT EXISTS asaas_environment text DEFAULT 'sandbox'
|
||||||
|
CHECK (asaas_environment IN ('sandbox', 'prod')),
|
||||||
|
ADD COLUMN IF NOT EXISTS asaas_webhook_token text,
|
||||||
|
ADD COLUMN IF NOT EXISTS asaas_enabled boolean DEFAULT false NOT NULL;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN public.payment_settings.asaas_api_key_sandbox IS
|
||||||
|
'API key Asaas SANDBOX. PLAINTEXT por enquanto — migrar pra Vault em prod.';
|
||||||
|
COMMENT ON COLUMN public.payment_settings.asaas_api_key_prod IS
|
||||||
|
'API key Asaas PRODUÇÃO. PLAINTEXT por enquanto — migrar pra Vault em prod.';
|
||||||
|
COMMENT ON COLUMN public.payment_settings.asaas_environment IS
|
||||||
|
'Qual key usar: sandbox (testes) ou prod (real). Default sandbox por segurança.';
|
||||||
|
COMMENT ON COLUMN public.payment_settings.asaas_webhook_token IS
|
||||||
|
'Token customizado pra webhook receiver validar. Setar mesmo valor no dashboard Asaas.';
|
||||||
|
COMMENT ON COLUMN public.payment_settings.asaas_enabled IS
|
||||||
|
'Flag que controla se gateway Asaas está habilitado pro tenant. Default false (opt-in).';
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
-- ============================================================================
|
||||||
|
-- Asaas Gateway — RLS policies
|
||||||
|
-- ----------------------------------------------------------------------------
|
||||||
|
-- Owner-scoped: cada terapeuta vê só os customers/payments do seu tenant.
|
||||||
|
-- INSERT/UPDATE bloqueado client-side — só Edge Functions (service role)
|
||||||
|
-- podem escrever. Browser só lê (pra exibir QR code, status, etc).
|
||||||
|
--
|
||||||
|
-- API keys em payment_settings: já tem RLS (não duplica).
|
||||||
|
-- ============================================================================
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
-- asaas_customers
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
ALTER TABLE public.asaas_customers ENABLE ROW LEVEL SECURITY;
|
||||||
|
|
||||||
|
CREATE POLICY asaas_customers_member_select
|
||||||
|
ON public.asaas_customers FOR SELECT TO authenticated
|
||||||
|
USING (public.is_tenant_member(tenant_id));
|
||||||
|
|
||||||
|
-- INSERT/UPDATE/DELETE bloqueados — Edge Functions usam service_role que bypassa RLS
|
||||||
|
CREATE POLICY asaas_customers_no_client_write
|
||||||
|
ON public.asaas_customers FOR INSERT TO authenticated
|
||||||
|
WITH CHECK (false);
|
||||||
|
CREATE POLICY asaas_customers_no_client_update
|
||||||
|
ON public.asaas_customers FOR UPDATE TO authenticated
|
||||||
|
USING (false);
|
||||||
|
CREATE POLICY asaas_customers_no_client_delete
|
||||||
|
ON public.asaas_customers FOR DELETE TO authenticated
|
||||||
|
USING (false);
|
||||||
|
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
-- asaas_payments
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
ALTER TABLE public.asaas_payments ENABLE ROW LEVEL SECURITY;
|
||||||
|
|
||||||
|
CREATE POLICY asaas_payments_member_select
|
||||||
|
ON public.asaas_payments FOR SELECT TO authenticated
|
||||||
|
USING (public.is_tenant_member(tenant_id));
|
||||||
|
|
||||||
|
CREATE POLICY asaas_payments_no_client_write
|
||||||
|
ON public.asaas_payments FOR INSERT TO authenticated
|
||||||
|
WITH CHECK (false);
|
||||||
|
CREATE POLICY asaas_payments_no_client_update
|
||||||
|
ON public.asaas_payments FOR UPDATE TO authenticated
|
||||||
|
USING (false);
|
||||||
|
CREATE POLICY asaas_payments_no_client_delete
|
||||||
|
ON public.asaas_payments FOR DELETE TO authenticated
|
||||||
|
USING (false);
|
||||||
|
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
-- asaas_webhook_events
|
||||||
|
-- ──────────────────────────────────────────────────────────────────────────
|
||||||
|
-- Audit table — saas_admin lê pra debug. Members não veem.
|
||||||
|
ALTER TABLE public.asaas_webhook_events ENABLE ROW LEVEL SECURITY;
|
||||||
|
|
||||||
|
CREATE POLICY asaas_webhook_events_saas_admin_select
|
||||||
|
ON public.asaas_webhook_events FOR SELECT TO authenticated
|
||||||
|
USING (public.is_saas_admin());
|
||||||
|
|
||||||
|
CREATE POLICY asaas_webhook_events_no_client_write
|
||||||
|
ON public.asaas_webhook_events FOR INSERT TO authenticated
|
||||||
|
WITH CHECK (false);
|
||||||
|
CREATE POLICY asaas_webhook_events_no_update
|
||||||
|
ON public.asaas_webhook_events FOR UPDATE TO authenticated
|
||||||
|
USING (false);
|
||||||
|
CREATE POLICY asaas_webhook_events_no_delete
|
||||||
|
ON public.asaas_webhook_events FOR DELETE TO authenticated
|
||||||
|
USING (false);
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
# Design — Asaas Gateway (Tier 1: Cobrança de Paciente · PIX + Boleto)
|
||||||
|
|
||||||
|
> **Data:** 2026-05-21
|
||||||
|
> **Tipo:** Design doc + foundation (sem credenciais reais ainda)
|
||||||
|
> **Resolve:** Item #1-#3 da Fase 1 do ROADMAP (Monetização)
|
||||||
|
> **Decisões confirmadas:** Tier 1 primeiro (paciente paga terapeuta) · PIX + Boleto · Approach foundation com stops
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Estado atual
|
||||||
|
|
||||||
|
### 1.1 O que JÁ EXISTE no projeto
|
||||||
|
|
||||||
|
- **Edge Function `asaas-webhook`** (`supabase/functions/asaas-webhook/index.ts`) — porém só lida com `whatsapp_credit_purchases`. Token `ASAAS_WEBHOOK_TOKEN` validado.
|
||||||
|
- **Edge Function `create-whatsapp-credit-charge`** — cria cobrança Asaas para créditos WhatsApp. Pattern de chamada à API Asaas estabelecido.
|
||||||
|
- **Tabela `whatsapp_credit_purchases`** com coluna `asaas_payment_id`. Modelo: 1 purchase ↔ 1 Asaas payment.
|
||||||
|
- **Coluna `financial_records.payment_link`** (migration 20260514000001) — espera o URL Asaas quando integração existir.
|
||||||
|
- **Tabela `payment_settings`** com pix_chave, deposito_*, etc — config manual de pagamento por owner (NÃO é Asaas).
|
||||||
|
- **Asaas mencionado em 9 arquivos client** — todos relacionados a WhatsApp credits ou docs.
|
||||||
|
|
||||||
|
### 1.2 O que FALTA pra patient billing
|
||||||
|
|
||||||
|
- Schema: tabelas `asaas_customers` (mapping patient → Asaas customer) e `asaas_payments` (1 row por cobrança gerada)
|
||||||
|
- Schema: ENCRYPTED storage da API key Asaas por tenant (se modelo B — ver §3)
|
||||||
|
- Edge Function `asaas-create-customer-patient` — upsert customer no Asaas
|
||||||
|
- Edge Function `asaas-create-payment-record` — gera cobrança a partir de financial_record
|
||||||
|
- Edge Function `asaas-cancel-payment` — cancela
|
||||||
|
- Edge Function `asaas-webhook` ESTENDIDA — handler pra eventos de financial_records (atualmente só whatsapp_credit_purchases)
|
||||||
|
- Cliente JS: `asaasGatewayService.js` em `features/financeiro/services/`
|
||||||
|
- UI: botão "Gerar cobrança Asaas" no record do `financial_records` (não escopo desta sessão)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Arquitetura
|
||||||
|
|
||||||
|
### 2.1 Camadas
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────┐
|
||||||
|
│ Browser (Vue) │
|
||||||
|
│ ├ asaasGatewayService.js │
|
||||||
|
│ │ • createPaymentForRecord(recordId, opts) │ ← invoca Edge Function via supabase.functions.invoke
|
||||||
|
│ │ • cancelPayment(asaasPaymentId) │
|
||||||
|
│ │ • getPaymentInfo(asaasPaymentId) │
|
||||||
|
└─────────────────────────────────────────────────┘
|
||||||
|
↓
|
||||||
|
┌─────────────────────────────────────────────────┐
|
||||||
|
│ Supabase Edge Functions (Deno) │
|
||||||
|
│ ├ asaas-create-customer-patient │
|
||||||
|
│ │ • Recebe patient_id │
|
||||||
|
│ │ • Upsert asaas_customers (cache) │
|
||||||
|
│ │ • Chama Asaas POST /customers │
|
||||||
|
│ ├ asaas-create-payment-record │
|
||||||
|
│ │ • Recebe financial_record_id + method │
|
||||||
|
│ │ • Garante customer existe (cascade) │
|
||||||
|
│ │ • Chama Asaas POST /payments │
|
||||||
|
│ │ • Salva asaas_payments + update financial_records.payment_link │
|
||||||
|
│ ├ asaas-cancel-payment │
|
||||||
|
│ │ • Asaas DELETE /payments/:id │
|
||||||
|
│ └ asaas-webhook (EXTENDER) │
|
||||||
|
│ • Adiciona handler pra events linkados a │
|
||||||
|
│ financial_records (não só credits) │
|
||||||
|
└─────────────────────────────────────────────────┘
|
||||||
|
↓
|
||||||
|
┌─────────────────────────────────────────────────┐
|
||||||
|
│ Asaas REST API (sandbox/prod) │
|
||||||
|
└─────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Por que Edge Functions e não client-side?
|
||||||
|
|
||||||
|
**Crítico:** API key do Asaas NUNCA pode chegar ao browser. Browser vê script + DevTools = key vaza = qualquer pessoa cria cobrança em nome da plataforma/tenant. Edge Functions rodam server-side, key fica em env vars do Supabase.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Modelo de negócio (DECISÃO PENDENTE)
|
||||||
|
|
||||||
|
**Quem detém a conta Asaas que recebe o dinheiro?**
|
||||||
|
|
||||||
|
### Opção A — Plataforma (marketplace)
|
||||||
|
- 1 conta Asaas global da plataforma AgenciaPsi
|
||||||
|
- Plataforma recebe TUDO + repassa pra terapeutas (split payment ou reconciliação manual)
|
||||||
|
- Asaas tem feature de SubAccounts/Split — pode ser configurado
|
||||||
|
- **Pros:** simples, 1 chave ENV no Supabase
|
||||||
|
- **Cons:** plataforma fica como intermediadora financeira (regulatório + impostos + compliance)
|
||||||
|
|
||||||
|
### Opção B — Tenant-level (recommended pra MVP solo-therapist)
|
||||||
|
- Cada tenant tem SUA conta Asaas
|
||||||
|
- API key encrypted em `payment_settings.asaas_api_key` (Supabase Vault ou pgsodium)
|
||||||
|
- Terapeuta recebe direto na própria conta
|
||||||
|
- Edge Function lê chave do tenant requisitante
|
||||||
|
- **Pros:** sem complexidade regulatória pra plataforma
|
||||||
|
- **Cons:** terapeuta precisa configurar Asaas próprio (UX onboarding)
|
||||||
|
|
||||||
|
### Opção C — Híbrido
|
||||||
|
- Plataforma cobra mensalidade SaaS via SUA Asaas (Tier 2 — fora desta sessão)
|
||||||
|
- Terapeuta cobra paciente via SUA Asaas (Tier 1)
|
||||||
|
- 2 contas em mundos separados
|
||||||
|
|
||||||
|
**Recomendação desta sessão:** **Opção B (Tenant-level)** pra Tier 1. Tier 2 (SaaS subscriptions) decide depois — pode ser A com mesma infra.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Schema additions
|
||||||
|
|
||||||
|
### 4.1 Tabela `asaas_customers`
|
||||||
|
|
||||||
|
Mapping patient ↔ Asaas customer. Cacheado (não recriar a cada cobrança).
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE public.asaas_customers (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id uuid NOT NULL,
|
||||||
|
patient_id uuid NOT NULL REFERENCES patients(id) ON DELETE CASCADE,
|
||||||
|
asaas_customer_id text NOT NULL,
|
||||||
|
-- ambiente: sandbox ou prod (mesmo patient pode ter ambos)
|
||||||
|
environment text NOT NULL DEFAULT 'prod' CHECK (environment IN ('sandbox', 'prod')),
|
||||||
|
-- dados cacheados (sincronizados quando atualizar)
|
||||||
|
name text NOT NULL,
|
||||||
|
email text,
|
||||||
|
cpf_cnpj text,
|
||||||
|
phone text,
|
||||||
|
address jsonb,
|
||||||
|
-- audit
|
||||||
|
created_at timestamptz DEFAULT now() NOT NULL,
|
||||||
|
updated_at timestamptz DEFAULT now() NOT NULL,
|
||||||
|
deleted_at timestamptz,
|
||||||
|
UNIQUE (tenant_id, patient_id, environment)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_asaas_customers_lookup
|
||||||
|
ON public.asaas_customers (tenant_id, patient_id)
|
||||||
|
WHERE deleted_at IS NULL;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Tabela `asaas_payments`
|
||||||
|
|
||||||
|
1 row por cobrança Asaas gerada. Link com financial_record.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE public.asaas_payments (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id uuid NOT NULL,
|
||||||
|
financial_record_id uuid NOT NULL REFERENCES financial_records(id) ON DELETE CASCADE,
|
||||||
|
asaas_customer_id uuid REFERENCES asaas_customers(id),
|
||||||
|
asaas_payment_id text NOT NULL,
|
||||||
|
asaas_invoice_id text,
|
||||||
|
environment text NOT NULL DEFAULT 'prod' CHECK (environment IN ('sandbox', 'prod')),
|
||||||
|
billing_type text NOT NULL CHECK (billing_type IN ('PIX', 'BOLETO', 'CREDIT_CARD', 'UNDEFINED')),
|
||||||
|
status text NOT NULL, -- raw Asaas status; mapeamento pra financial_records.status no JS
|
||||||
|
value numeric(10, 2) NOT NULL,
|
||||||
|
net_value numeric(10, 2),
|
||||||
|
due_date date NOT NULL,
|
||||||
|
payment_date timestamptz,
|
||||||
|
invoice_url text,
|
||||||
|
payment_url text, -- URL pra paciente abrir e pagar
|
||||||
|
bank_slip_url text, -- PDF boleto
|
||||||
|
pix_qr_code text, -- base64 do QR
|
||||||
|
pix_copy_paste text, -- payload PIX
|
||||||
|
-- audit
|
||||||
|
created_at timestamptz DEFAULT now() NOT NULL,
|
||||||
|
updated_at timestamptz DEFAULT now() NOT NULL,
|
||||||
|
cancelled_at timestamptz,
|
||||||
|
UNIQUE (asaas_payment_id, environment)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_asaas_payments_record
|
||||||
|
ON public.asaas_payments (financial_record_id);
|
||||||
|
CREATE INDEX idx_asaas_payments_lookup
|
||||||
|
ON public.asaas_payments (tenant_id, status, due_date);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Tabela `asaas_webhook_events`
|
||||||
|
|
||||||
|
Idempotência + audit. Cada webhook recebido vai aqui ANTES de processar.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE public.asaas_webhook_events (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
event_id text, -- id que Asaas mandar (se mandar)
|
||||||
|
event_type text NOT NULL, -- PAYMENT_RECEIVED, PAYMENT_OVERDUE, etc
|
||||||
|
asaas_payment_id text, -- pra linkar com asaas_payments
|
||||||
|
payload jsonb NOT NULL, -- raw event pra debug
|
||||||
|
processed_at timestamptz, -- quando processou; NULL = pendente/falha
|
||||||
|
processing_error text,
|
||||||
|
received_at timestamptz DEFAULT now() NOT NULL,
|
||||||
|
UNIQUE (event_id) DEFERRABLE INITIALLY DEFERRED
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_asaas_webhook_events_payment
|
||||||
|
ON public.asaas_webhook_events (asaas_payment_id);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.4 Coluna ENCRYPTED na `payment_settings`
|
||||||
|
|
||||||
|
Tenant-level API key (Opção B). Usa pgsodium ou Supabase Vault.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- Sandbox e prod separados — terapeuta começa em sandbox, migra pra prod quando OK.
|
||||||
|
ALTER TABLE public.payment_settings
|
||||||
|
ADD COLUMN IF NOT EXISTS asaas_api_key_sandbox text, -- prefixado com "$pgsodium-encrypted$" via trigger
|
||||||
|
ADD COLUMN IF NOT EXISTS asaas_api_key_prod text,
|
||||||
|
ADD COLUMN IF NOT EXISTS asaas_environment text DEFAULT 'sandbox' CHECK (asaas_environment IN ('sandbox', 'prod')),
|
||||||
|
ADD COLUMN IF NOT EXISTS asaas_webhook_token text;
|
||||||
|
```
|
||||||
|
|
||||||
|
**⚠️ Atenção:** API keys EM TEXTO NA TABELA é vulnerabilidade séria. Em produção precisa Supabase Vault (pgsodium) ou KMS externo. Pra MVP sandbox dá pra deixar plaintext + RLS restritiva, mas tem que documentar como dívida.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Status mapping Asaas → financial_records
|
||||||
|
|
||||||
|
| Asaas | financial_records.status |
|
||||||
|
|---|---|
|
||||||
|
| PENDING | pending |
|
||||||
|
| RECEIVED / CONFIRMED | paid |
|
||||||
|
| RECEIVED_IN_CASH | paid (manual) |
|
||||||
|
| OVERDUE | overdue |
|
||||||
|
| REFUNDED / CHARGEBACK_REQUESTED | refunded |
|
||||||
|
| DELETED / CHARGEBACK_DISPUTE | cancelled |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Flow completo (happy path) — Tier 1 PIX
|
||||||
|
|
||||||
|
1. Terapeuta cria sessão na agenda → trigger gera `financial_records` row (status=pending, payment_method=null, payment_link=null)
|
||||||
|
2. Terapeuta vê record na UI e clica **"Gerar cobrança Asaas (PIX)"**
|
||||||
|
3. Cliente JS chama `asaasGatewayService.createPaymentForRecord(recordId, { method: 'PIX' })`
|
||||||
|
4. Service invoca Edge Function `asaas-create-payment-record`
|
||||||
|
5. Edge Function:
|
||||||
|
- Lê financial_record + patient + tenant_settings (API key)
|
||||||
|
- Garante asaas_customers row (chama asaas-create-customer-patient se não existe)
|
||||||
|
- POST `https://sandbox.asaas.com/api/v3/payments` com `customer`, `value`, `dueDate`, `billingType=PIX`, `externalReference=<financial_record_id>`
|
||||||
|
- Asaas retorna `id`, `invoiceUrl`, e (pra PIX) `id` de QR code
|
||||||
|
- Edge Function chama POST `/payments/:id/pixQrCode` pra pegar QR base64
|
||||||
|
- INSERT em `asaas_payments` com toda metadata
|
||||||
|
- UPDATE `financial_records.payment_link = invoiceUrl, payment_method = 'pix_asaas'`
|
||||||
|
6. Service retorna `{ paymentUrl, qrCode, copyPaste }` pro cliente
|
||||||
|
7. UI mostra QR code + link pra paciente
|
||||||
|
8. Paciente paga via PIX
|
||||||
|
9. Asaas dispara webhook PAYMENT_RECEIVED → Edge Function `asaas-webhook`:
|
||||||
|
- INSERT em `asaas_webhook_events` (idempotência via event_id)
|
||||||
|
- Busca `asaas_payment` por `asaas_payment_id`
|
||||||
|
- Se status=='paid' já: skip
|
||||||
|
- UPDATE `asaas_payments.status='RECEIVED'`, `payment_date=now()`
|
||||||
|
- UPDATE `financial_records.status='paid'`, `paid_at=now()`
|
||||||
|
- Marca event como `processed_at=now()`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Decisões de implementação
|
||||||
|
|
||||||
|
| Decisão | Confirmada |
|
||||||
|
|---|---|
|
||||||
|
| Tier 1 (paciente paga terapeuta) primeiro | ✅ |
|
||||||
|
| PIX + boleto primeiro (cartão depois) | ✅ |
|
||||||
|
| Modelo tenant-level (Opção B) | ⚠️ PROPOSTO — confirme antes de implementar |
|
||||||
|
| Sandbox first, prod depois | ⚠️ default — confirme |
|
||||||
|
| Storage de API key plaintext em `payment_settings` (com RLS) pra MVP | ⚠️ DÍVIDA conhecida — vault depois |
|
||||||
|
| `externalReference` no Asaas = financial_records.id | ⚠️ PROPOSTO — facilita reconciliação |
|
||||||
|
| Webhook compartilha mesma Edge Function (`asaas-webhook` estendida) | ⚠️ PROPOSTO — evita duplicar token validation |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Checklist do que VOCÊ precisa fornecer
|
||||||
|
|
||||||
|
Antes da Fase B (implementação real):
|
||||||
|
|
||||||
|
- [ ] Criar conta Asaas (https://asaas.com)
|
||||||
|
- [ ] Habilitar PIX (gera chave PIX automática) + Boleto na conta
|
||||||
|
- [ ] Pegar API key de SANDBOX (Configurações → Integrações)
|
||||||
|
- [ ] Configurar webhook no Asaas: `https://<seu-projeto>.supabase.co/functions/v1/asaas-webhook` + token
|
||||||
|
- [ ] Setar ENV vars no Supabase (Dashboard → Edge Functions → Secrets):
|
||||||
|
- `ASAAS_API_URL_SANDBOX=https://sandbox.asaas.com/api/v3`
|
||||||
|
- `ASAAS_API_URL_PROD=https://api.asaas.com/v3`
|
||||||
|
- `ASAAS_WEBHOOK_TOKEN=<token-aleatorio>` (já existe? checar)
|
||||||
|
- [ ] Decidir modelo de negócio (Opção A/B/C — §3) — recomendo **B** pra MVP solo
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Phasing — entrega faseada
|
||||||
|
|
||||||
|
### Fase A — Foundation (esta sessão)
|
||||||
|
- [x] Design doc (este arquivo)
|
||||||
|
- [ ] Migration de schema (asaas_customers + asaas_payments + asaas_webhook_events + colunas em payment_settings)
|
||||||
|
- [ ] Client service `asaasGatewayService.js` (skeleton)
|
||||||
|
- [ ] Edge Function stubs (3 novas + nota sobre estender webhook existente)
|
||||||
|
- [ ] README/Checklist no service file
|
||||||
|
|
||||||
|
### Fase B — Implementação real (próxima sessão, requer credenciais + decisões §7)
|
||||||
|
- [ ] Edge Functions: chamadas reais ao Asaas
|
||||||
|
- [ ] Webhook extension: handler pra `financial_records`
|
||||||
|
- [ ] UI: botão "Gerar cobrança Asaas" no card do financial_record
|
||||||
|
- [ ] UI: dialog mostrando QR code PIX + link boleto
|
||||||
|
|
||||||
|
### Fase C — Onboarding (após B testar)
|
||||||
|
- [ ] Página de config Asaas no `/configuracoes/financeiro`
|
||||||
|
- [ ] Wizard pra terapeuta inserir API key + testar conexão
|
||||||
|
- [ ] Migration de sandbox→prod com confirm
|
||||||
|
|
||||||
|
### Fase D — Avançado (futuro)
|
||||||
|
- [ ] Cartão on file (Asaas tokenizado)
|
||||||
|
- [ ] Auto-billing recorrente (sessão realizada → gera Asaas automático)
|
||||||
|
- [ ] Split payment se Opção A
|
||||||
|
- [ ] Cobrança SaaS (Tier 2)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Riscos conhecidos
|
||||||
|
|
||||||
|
1. **API key vazada** — se plaintext em `payment_settings`, qualquer breach da DB compromete. **Mitigação:** RLS restritiva + Vault em produção.
|
||||||
|
2. **Duplicate billing** — webhook dispara 2× (retry Asaas). **Mitigação:** `asaas_webhook_events.event_id` UNIQUE + check de status atual antes de mutar.
|
||||||
|
3. **Cancelamento race** — paciente paga enquanto terapeuta cancela. **Mitigação:** UPDATE `financial_records` só se `status='pending'` (CAS).
|
||||||
|
4. **Reconciliação manual** — se webhook falha 3× e dá up, paciente pagou mas record fica pending. **Mitigação:** Edge Function `asaas-sync-payments` (manual trigger) que consulta `/payments` por externalReference e força update.
|
||||||
|
5. **CPF/CNPJ obrigatório no Asaas** — paciente sem CPF não pode receber cobrança. **Mitigação:** validação client-side antes de chamar service.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Referências
|
||||||
|
|
||||||
|
- Asaas API docs: https://docs.asaas.com/
|
||||||
|
- Existing webhook pattern: `supabase/functions/asaas-webhook/index.ts`
|
||||||
|
- Migration `financial_records.payment_link`: `20260514000001_financial_records_payment_link.sql`
|
||||||
|
- Memory: `project_agenda_billing_decisoes` (decisões #1, #4, #5, #7, #8 confirmadas; #2/#3/#6 pendentes)
|
||||||
|
- ROADMAP: `development/04-roadmap/ROADMAP.md` Fase 1.1 (#1-#4 Monetização)
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Agência PSI
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Arquivo: src/features/financeiro/services/asaasGatewayService.js
|
||||||
|
|
|
||||||
|
| Cliente JS pra orquestrar cobranças Asaas via Edge Functions.
|
||||||
|
| Browser NUNCA fala direto com Asaas — API key não pode chegar aqui.
|
||||||
|
|
|
||||||
|
| Arquitetura: ver development/02-auditoria/DESIGN_ASAAS_GATEWAY.md
|
||||||
|
|
|
||||||
|
| ⚠️ FOUNDATION SKELETON. Edge Functions ainda são stubs — chamadas vão
|
||||||
|
| retornar erro até deploy real. Requer credenciais Asaas configuradas.
|
||||||
|
|
|
||||||
|
| Pré-requisitos (do user):
|
||||||
|
| 1. Migration 20260521000001_asaas_gateway_tables.sql aplicada
|
||||||
|
| 2. Migration 20260521000002_asaas_gateway_rls.sql aplicada
|
||||||
|
| 3. Edge Functions deployadas (asaas-create-payment-record, asaas-cancel-payment)
|
||||||
|
| 4. API key Asaas inserida em payment_settings (via UI futura ou SQL manual)
|
||||||
|
| 5. payment_settings.asaas_enabled = true
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
*/
|
||||||
|
import { supabase } from '@/lib/supabase/client';
|
||||||
|
import { useTenantStore } from '@/stores/tenantStore';
|
||||||
|
|
||||||
|
// ─── Status mapping Asaas → financial_records.status ────────────────────────
|
||||||
|
|
||||||
|
const ASAAS_TO_STATUS = {
|
||||||
|
PENDING: 'pending',
|
||||||
|
RECEIVED: 'paid',
|
||||||
|
CONFIRMED: 'paid',
|
||||||
|
RECEIVED_IN_CASH: 'paid',
|
||||||
|
OVERDUE: 'overdue',
|
||||||
|
REFUNDED: 'refunded',
|
||||||
|
CHARGEBACK_REQUESTED: 'refunded',
|
||||||
|
CHARGEBACK_DISPUTE: 'cancelled',
|
||||||
|
DELETED: 'cancelled'
|
||||||
|
};
|
||||||
|
|
||||||
|
export function mapAsaasStatus(asaasStatus) {
|
||||||
|
return ASAAS_TO_STATUS[asaasStatus] || 'pending';
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Validations ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function assertTenantId(tenantId) {
|
||||||
|
if (!tenantId || tenantId === 'null' || tenantId === 'undefined') {
|
||||||
|
throw new Error('Tenant ativo inválido pra operar Asaas.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveTenantId() {
|
||||||
|
const tenantStore = useTenantStore();
|
||||||
|
const tid = tenantStore.activeTenantId || tenantStore.tenantId;
|
||||||
|
assertTenantId(tid);
|
||||||
|
return tid;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Core API ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria cobrança Asaas pra um financial_record existente.
|
||||||
|
*
|
||||||
|
* Invoca Edge Function `asaas-create-payment-record` que:
|
||||||
|
* 1. Lê financial_record + patient
|
||||||
|
* 2. Garante asaas_customer existe (cascade pra create-customer-patient)
|
||||||
|
* 3. POST /payments no Asaas com externalReference=financial_record.id
|
||||||
|
* 4. INSERT asaas_payments + UPDATE financial_records.payment_link
|
||||||
|
*
|
||||||
|
* @param {string} financialRecordId
|
||||||
|
* @param {Object} opts
|
||||||
|
* @param {'PIX'|'BOLETO'|'CREDIT_CARD'} [opts.method='PIX']
|
||||||
|
* @param {string} [opts.dueDate] - YYYY-MM-DD. Default = financial_record.due_date
|
||||||
|
* @returns {Promise<{asaas_payment_id, payment_url, pix_qr_code?, pix_copy_paste?, bank_slip_url?}>}
|
||||||
|
*/
|
||||||
|
export async function createPaymentForRecord(financialRecordId, opts = {}) {
|
||||||
|
if (!financialRecordId) throw new Error('financialRecordId obrigatório.');
|
||||||
|
const tenantId = resolveTenantId();
|
||||||
|
const method = opts.method || 'PIX';
|
||||||
|
|
||||||
|
if (!['PIX', 'BOLETO', 'CREDIT_CARD'].includes(method)) {
|
||||||
|
throw new Error(`Método inválido: ${method}. Aceitos: PIX, BOLETO, CREDIT_CARD.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data, error } = await supabase.functions.invoke('asaas-create-payment-record', {
|
||||||
|
body: {
|
||||||
|
tenant_id: tenantId,
|
||||||
|
financial_record_id: financialRecordId,
|
||||||
|
billing_type: method,
|
||||||
|
due_date: opts.dueDate || null
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) throw new Error(formatEdgeError(error));
|
||||||
|
if (!data?.ok) throw new Error(data?.error || 'Falha ao criar cobrança Asaas.');
|
||||||
|
|
||||||
|
return data.payment;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancela cobrança Asaas. Não afeta o financial_record diretamente — webhook
|
||||||
|
* processará PAYMENT_DELETED e fará o sync.
|
||||||
|
*
|
||||||
|
* @param {string} asaasPaymentId
|
||||||
|
*/
|
||||||
|
export async function cancelPayment(asaasPaymentId) {
|
||||||
|
if (!asaasPaymentId) throw new Error('asaasPaymentId obrigatório.');
|
||||||
|
const tenantId = resolveTenantId();
|
||||||
|
|
||||||
|
const { data, error } = await supabase.functions.invoke('asaas-cancel-payment', {
|
||||||
|
body: { tenant_id: tenantId, asaas_payment_id: asaasPaymentId }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) throw new Error(formatEdgeError(error));
|
||||||
|
if (!data?.ok) throw new Error(data?.error || 'Falha ao cancelar cobrança.');
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Busca info de pagamento Asaas (PIX QR code, boleto URL, status atual).
|
||||||
|
* Read-only: vai na tabela asaas_payments. Não chama API Asaas.
|
||||||
|
*
|
||||||
|
* @param {string} financialRecordId
|
||||||
|
* @returns {Promise<Object|null>}
|
||||||
|
*/
|
||||||
|
export async function getPaymentForRecord(financialRecordId) {
|
||||||
|
if (!financialRecordId) return null;
|
||||||
|
const tenantId = resolveTenantId();
|
||||||
|
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('asaas_payments')
|
||||||
|
.select('id, asaas_payment_id, billing_type, status, value, due_date, payment_date, invoice_url, payment_url, bank_slip_url, pix_qr_code, pix_copy_paste, cancelled_at')
|
||||||
|
.eq('tenant_id', tenantId)
|
||||||
|
.eq('financial_record_id', financialRecordId)
|
||||||
|
.is('cancelled_at', null)
|
||||||
|
.order('created_at', { ascending: false })
|
||||||
|
.limit(1)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
return data || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sincroniza força um pagamento Asaas (consulta API Asaas + atualiza row local).
|
||||||
|
* Use quando suspeitar que webhook falhou (record fica pending mas paciente diz que pagou).
|
||||||
|
*
|
||||||
|
* @param {string} asaasPaymentId
|
||||||
|
*/
|
||||||
|
export async function syncPayment(asaasPaymentId) {
|
||||||
|
if (!asaasPaymentId) throw new Error('asaasPaymentId obrigatório.');
|
||||||
|
const tenantId = resolveTenantId();
|
||||||
|
|
||||||
|
const { data, error } = await supabase.functions.invoke('asaas-sync-payment', {
|
||||||
|
body: { tenant_id: tenantId, asaas_payment_id: asaasPaymentId }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) throw new Error(formatEdgeError(error));
|
||||||
|
if (!data?.ok) throw new Error(data?.error || 'Falha ao sincronizar.');
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifica se gateway Asaas está habilitado pro tenant ativo.
|
||||||
|
* Usado pra mostrar/esconder botões de cobrança Asaas na UI.
|
||||||
|
*/
|
||||||
|
export async function isGatewayEnabled() {
|
||||||
|
const tenantId = resolveTenantId();
|
||||||
|
const { data, error } = await supabase.from('payment_settings').select('asaas_enabled, asaas_environment').eq('tenant_id', tenantId).maybeSingle();
|
||||||
|
if (error) return false;
|
||||||
|
return !!data?.asaas_enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function formatEdgeError(err) {
|
||||||
|
if (typeof err === 'string') return err;
|
||||||
|
if (err?.message) return err.message;
|
||||||
|
if (err?.error) return String(err.error);
|
||||||
|
return 'Erro desconhecido na Edge Function.';
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Agência PSI — Edge Function: asaas-cancel-payment
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Cancela cobrança Asaas. Atualização do financial_record fica pro webhook
|
||||||
|
| (PAYMENT_DELETED) — single source of truth.
|
||||||
|
|
|
||||||
|
| ⚠️ STUB — chamada real ao Asaas marcada TODO.
|
||||||
|
|
|
||||||
|
| Input: { tenant_id, asaas_payment_id }
|
||||||
|
| Output: { ok: true } ou { ok: false, error }
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
*/
|
||||||
|
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
||||||
|
|
||||||
|
const corsHeaders = {
|
||||||
|
'Access-Control-Allow-Origin': '*',
|
||||||
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||||
|
'Access-Control-Allow-Methods': 'POST, OPTIONS'
|
||||||
|
};
|
||||||
|
|
||||||
|
function json(body: unknown, status = 200) {
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
status,
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Deno.serve(async (req: Request) => {
|
||||||
|
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
||||||
|
if (req.method !== 'POST') return json({ ok: false, error: 'method_not_allowed' }, 405);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = (await req.json().catch(() => null)) as Record<string, unknown> | null;
|
||||||
|
if (!body) return json({ ok: false, error: 'invalid_body' }, 400);
|
||||||
|
|
||||||
|
const tenantId = String(body.tenant_id || '');
|
||||||
|
const asaasPaymentId = String(body.asaas_payment_id || '');
|
||||||
|
|
||||||
|
if (!tenantId || !asaasPaymentId) return json({ ok: false, error: 'missing_fields' }, 400);
|
||||||
|
|
||||||
|
const supa = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!);
|
||||||
|
|
||||||
|
// 1. Lê config + API key
|
||||||
|
const { data: settings } = await supa.from('payment_settings').select('asaas_enabled, asaas_environment, asaas_api_key_sandbox, asaas_api_key_prod').eq('tenant_id', tenantId).maybeSingle();
|
||||||
|
|
||||||
|
if (!settings?.asaas_enabled) return json({ ok: false, error: 'gateway_not_enabled' }, 403);
|
||||||
|
|
||||||
|
const environment = settings.asaas_environment || 'sandbox';
|
||||||
|
const apiKey = environment === 'prod' ? settings.asaas_api_key_prod : settings.asaas_api_key_sandbox;
|
||||||
|
const apiUrl = environment === 'prod'
|
||||||
|
? Deno.env.get('ASAAS_API_URL_PROD') || 'https://api.asaas.com/v3'
|
||||||
|
: Deno.env.get('ASAAS_API_URL_SANDBOX') || 'https://sandbox.asaas.com/api/v3';
|
||||||
|
|
||||||
|
if (!apiKey) return json({ ok: false, error: 'api_key_missing' }, 403);
|
||||||
|
|
||||||
|
// 2. Verifica que payment pertence ao tenant
|
||||||
|
const { data: payment } = await supa.from('asaas_payments').select('id, status, cancelled_at').eq('tenant_id', tenantId).eq('asaas_payment_id', asaasPaymentId).eq('environment', environment).maybeSingle();
|
||||||
|
|
||||||
|
if (!payment) return json({ ok: false, error: 'payment_not_found' }, 404);
|
||||||
|
if (payment.cancelled_at) return json({ ok: true, already_cancelled: true });
|
||||||
|
|
||||||
|
// 3. DELETE /payments/:id no Asaas
|
||||||
|
// TODO Fase B:
|
||||||
|
// const resp = await fetch(`${apiUrl}/payments/${asaasPaymentId}`, {
|
||||||
|
// method: 'DELETE',
|
||||||
|
// headers: { 'access_token': apiKey }
|
||||||
|
// });
|
||||||
|
// const asaasResult = await resp.json();
|
||||||
|
// if (!resp.ok) throw new Error(asaasResult.errors?.[0]?.description || 'asaas_delete_failed');
|
||||||
|
|
||||||
|
// 4. UPDATE asaas_payments.cancelled_at
|
||||||
|
// (webhook PAYMENT_DELETED também vai chegar, mas update aqui é mais rápido pra UI)
|
||||||
|
|
||||||
|
return json({
|
||||||
|
ok: false,
|
||||||
|
error: 'STUB_not_implemented_TODO_fase_B',
|
||||||
|
note: 'Edge Function estruturada — implementar DELETE call quando Asaas configurado.',
|
||||||
|
api_url: apiUrl,
|
||||||
|
environment
|
||||||
|
}, 501);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[asaas-cancel-payment] fatal:', err);
|
||||||
|
return json({ ok: false, error: String(err) }, 500);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Agência PSI — Edge Function: asaas-create-payment-record
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Cria cobrança Asaas pra um financial_record existente.
|
||||||
|
|
|
||||||
|
| ⚠️ STUB FOUNDATION — chamadas reais ao Asaas API marcadas TODO.
|
||||||
|
| Fluxo completo descrito em DESIGN_ASAAS_GATEWAY.md §6.
|
||||||
|
|
|
||||||
|
| Input (body JSON):
|
||||||
|
| {
|
||||||
|
| tenant_id: uuid,
|
||||||
|
| financial_record_id: uuid,
|
||||||
|
| billing_type: 'PIX' | 'BOLETO' | 'CREDIT_CARD',
|
||||||
|
| due_date?: 'YYYY-MM-DD' // default = financial_record.due_date
|
||||||
|
| }
|
||||||
|
|
|
||||||
|
| Output (JSON):
|
||||||
|
| {
|
||||||
|
| ok: true,
|
||||||
|
| payment: {
|
||||||
|
| asaas_payment_id, payment_url, pix_qr_code?, pix_copy_paste?, bank_slip_url?
|
||||||
|
| }
|
||||||
|
| }
|
||||||
|
|
|
||||||
|
| Errors:
|
||||||
|
| 400 — input inválido
|
||||||
|
| 403 — gateway não habilitado pro tenant
|
||||||
|
| 404 — record não encontrado
|
||||||
|
| 500 — erro Asaas
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
*/
|
||||||
|
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
||||||
|
|
||||||
|
const corsHeaders = {
|
||||||
|
'Access-Control-Allow-Origin': '*',
|
||||||
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||||
|
'Access-Control-Allow-Methods': 'POST, OPTIONS'
|
||||||
|
};
|
||||||
|
|
||||||
|
function json(body: unknown, status = 200) {
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
status,
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Deno.serve(async (req: Request) => {
|
||||||
|
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
||||||
|
if (req.method !== 'POST') return json({ ok: false, error: 'method_not_allowed' }, 405);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = (await req.json().catch(() => null)) as Record<string, unknown> | null;
|
||||||
|
if (!body) return json({ ok: false, error: 'invalid_body' }, 400);
|
||||||
|
|
||||||
|
const tenantId = String(body.tenant_id || '');
|
||||||
|
const recordId = String(body.financial_record_id || '');
|
||||||
|
const billingType = String(body.billing_type || 'PIX');
|
||||||
|
const dueDateOverride = body.due_date ? String(body.due_date) : null;
|
||||||
|
|
||||||
|
if (!tenantId || !recordId) return json({ ok: false, error: 'missing_fields' }, 400);
|
||||||
|
if (!['PIX', 'BOLETO', 'CREDIT_CARD'].includes(billingType)) {
|
||||||
|
return json({ ok: false, error: 'invalid_billing_type' }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const supa = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!);
|
||||||
|
|
||||||
|
// 1. Verifica gateway habilitado + lê API key do tenant
|
||||||
|
const { data: settings } = await supa
|
||||||
|
.from('payment_settings')
|
||||||
|
.select('asaas_enabled, asaas_environment, asaas_api_key_sandbox, asaas_api_key_prod')
|
||||||
|
.eq('tenant_id', tenantId)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (!settings?.asaas_enabled) {
|
||||||
|
return json({ ok: false, error: 'gateway_not_enabled_for_tenant' }, 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
const environment = settings.asaas_environment || 'sandbox';
|
||||||
|
const apiKey = environment === 'prod' ? settings.asaas_api_key_prod : settings.asaas_api_key_sandbox;
|
||||||
|
const apiUrl = environment === 'prod'
|
||||||
|
? Deno.env.get('ASAAS_API_URL_PROD') || 'https://api.asaas.com/v3'
|
||||||
|
: Deno.env.get('ASAAS_API_URL_SANDBOX') || 'https://sandbox.asaas.com/api/v3';
|
||||||
|
|
||||||
|
if (!apiKey) {
|
||||||
|
return json({ ok: false, error: 'api_key_missing_for_environment', environment }, 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Lê financial_record + patient
|
||||||
|
const { data: record } = await supa
|
||||||
|
.from('financial_records')
|
||||||
|
.select('id, tenant_id, patient_id, amount, due_date, description, status, deleted_at, agenda_evento_id')
|
||||||
|
.eq('id', recordId)
|
||||||
|
.eq('tenant_id', tenantId)
|
||||||
|
.is('deleted_at', null)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (!record) return json({ ok: false, error: 'record_not_found' }, 404);
|
||||||
|
if (record.status !== 'pending') {
|
||||||
|
return json({ ok: false, error: `record_not_pending (status=${record.status})` }, 409);
|
||||||
|
}
|
||||||
|
if (!record.patient_id) return json({ ok: false, error: 'record_has_no_patient' }, 400);
|
||||||
|
|
||||||
|
const { data: patient } = await supa
|
||||||
|
.from('patients')
|
||||||
|
.select('id, nome_completo, email_principal, telefone, cpf')
|
||||||
|
.eq('id', record.patient_id)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (!patient) return json({ ok: false, error: 'patient_not_found' }, 404);
|
||||||
|
if (!patient.cpf) return json({ ok: false, error: 'patient_missing_cpf_required_by_asaas' }, 400);
|
||||||
|
|
||||||
|
// 3. Garante customer no Asaas (chama interna asaas-create-customer-patient OU inline)
|
||||||
|
// TODO Fase B: chamar Edge Function asaas-create-customer-patient ou inline upsert.
|
||||||
|
// Por ora, busca cache local — se não existe, retorna erro.
|
||||||
|
let { data: customer } = await supa
|
||||||
|
.from('asaas_customers')
|
||||||
|
.select('id, asaas_customer_id')
|
||||||
|
.eq('tenant_id', tenantId)
|
||||||
|
.eq('patient_id', patient.id)
|
||||||
|
.eq('environment', environment)
|
||||||
|
.is('deleted_at', null)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (!customer) {
|
||||||
|
// TODO Fase B: criar customer via POST /customers no Asaas
|
||||||
|
return json({
|
||||||
|
ok: false,
|
||||||
|
error: 'customer_not_cached_TODO_create_via_asaas_api',
|
||||||
|
hint: 'Implementar inline ou via chamada asaas-create-customer-patient'
|
||||||
|
}, 501);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. POST /payments no Asaas
|
||||||
|
// TODO Fase B: fetch real à Asaas API
|
||||||
|
const asaasPayload = {
|
||||||
|
customer: customer.asaas_customer_id,
|
||||||
|
billingType,
|
||||||
|
value: Number(record.amount),
|
||||||
|
dueDate: dueDateOverride || record.due_date,
|
||||||
|
description: record.description || `Sessão #${record.id.slice(0, 8)}`,
|
||||||
|
externalReference: record.id
|
||||||
|
};
|
||||||
|
|
||||||
|
// TODO Fase B: substituir mock por fetch real
|
||||||
|
// const asaasResp = await fetch(`${apiUrl}/payments`, {
|
||||||
|
// method: 'POST',
|
||||||
|
// headers: { 'Content-Type': 'application/json', 'access_token': apiKey },
|
||||||
|
// body: JSON.stringify(asaasPayload)
|
||||||
|
// });
|
||||||
|
// const asaasPayment = await asaasResp.json();
|
||||||
|
|
||||||
|
return json({
|
||||||
|
ok: false,
|
||||||
|
error: 'STUB_not_implemented_TODO_fase_B',
|
||||||
|
note: 'Edge Function pronta na estrutura, fetch ao Asaas marcado TODO. Ver DESIGN_ASAAS_GATEWAY.md §9 (Phasing).',
|
||||||
|
would_send_to_asaas: asaasPayload,
|
||||||
|
api_url: apiUrl,
|
||||||
|
environment
|
||||||
|
}, 501);
|
||||||
|
|
||||||
|
// 5. INSERT asaas_payments
|
||||||
|
// TODO Fase B: salvar resposta + extras (QR code pra PIX)
|
||||||
|
|
||||||
|
// 6. UPDATE financial_records.payment_link
|
||||||
|
// TODO Fase B
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[asaas-create-payment-record] fatal:', err);
|
||||||
|
return json({ ok: false, error: String(err) }, 500);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/*
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Agência PSI — Edge Function: asaas-sync-payment
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
| Consulta status atual de um pagamento Asaas e força atualização local.
|
||||||
|
| Use quando suspeitar que webhook falhou (paciente diz que pagou mas
|
||||||
|
| record fica pending no banco).
|
||||||
|
|
|
||||||
|
| ⚠️ STUB — chamada real ao Asaas marcada TODO.
|
||||||
|
|--------------------------------------------------------------------------
|
||||||
|
*/
|
||||||
|
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
||||||
|
|
||||||
|
const corsHeaders = {
|
||||||
|
'Access-Control-Allow-Origin': '*',
|
||||||
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||||
|
'Access-Control-Allow-Methods': 'POST, OPTIONS'
|
||||||
|
};
|
||||||
|
|
||||||
|
function json(body: unknown, status = 200) {
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
status,
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Deno.serve(async (req: Request) => {
|
||||||
|
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
||||||
|
if (req.method !== 'POST') return json({ ok: false, error: 'method_not_allowed' }, 405);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = (await req.json().catch(() => null)) as Record<string, unknown> | null;
|
||||||
|
if (!body) return json({ ok: false, error: 'invalid_body' }, 400);
|
||||||
|
|
||||||
|
const tenantId = String(body.tenant_id || '');
|
||||||
|
const asaasPaymentId = String(body.asaas_payment_id || '');
|
||||||
|
if (!tenantId || !asaasPaymentId) return json({ ok: false, error: 'missing_fields' }, 400);
|
||||||
|
|
||||||
|
const supa = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!);
|
||||||
|
|
||||||
|
const { data: settings } = await supa.from('payment_settings').select('asaas_enabled, asaas_environment, asaas_api_key_sandbox, asaas_api_key_prod').eq('tenant_id', tenantId).maybeSingle();
|
||||||
|
if (!settings?.asaas_enabled) return json({ ok: false, error: 'gateway_not_enabled' }, 403);
|
||||||
|
|
||||||
|
const environment = settings.asaas_environment || 'sandbox';
|
||||||
|
const apiKey = environment === 'prod' ? settings.asaas_api_key_prod : settings.asaas_api_key_sandbox;
|
||||||
|
const apiUrl = environment === 'prod'
|
||||||
|
? Deno.env.get('ASAAS_API_URL_PROD') || 'https://api.asaas.com/v3'
|
||||||
|
: Deno.env.get('ASAAS_API_URL_SANDBOX') || 'https://sandbox.asaas.com/api/v3';
|
||||||
|
if (!apiKey) return json({ ok: false, error: 'api_key_missing' }, 403);
|
||||||
|
|
||||||
|
// TODO Fase B:
|
||||||
|
// const resp = await fetch(`${apiUrl}/payments/${asaasPaymentId}`, {
|
||||||
|
// headers: { 'access_token': apiKey }
|
||||||
|
// });
|
||||||
|
// const asaasPayment = await resp.json();
|
||||||
|
// // map asaasPayment.status → financial_records.status, UPDATE asaas_payments + financial_records.
|
||||||
|
|
||||||
|
return json({
|
||||||
|
ok: false,
|
||||||
|
error: 'STUB_not_implemented_TODO_fase_B',
|
||||||
|
note: 'Edge Function estruturada — GET /payments/:id pra Asaas marcada TODO.',
|
||||||
|
api_url: apiUrl,
|
||||||
|
environment
|
||||||
|
}, 501);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[asaas-sync-payment] fatal:', err);
|
||||||
|
return json({ ok: false, error: String(err) }, 500);
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user