de3898878a
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>
70 lines
3.2 KiB
TypeScript
70 lines
3.2 KiB
TypeScript
/*
|
|
|--------------------------------------------------------------------------
|
|
| 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);
|
|
}
|
|
});
|