Files
agenciapsilmno/supabase/functions/asaas-sync-payment/index.ts
T
Leonardo 9b21642e15 F4 schema-per-tenant: edge functions roteiam pro schema do tenant
- _shared/tenant.ts: helper (adminClient, tenantDbForId, schemaForTenant,
  listTenantSchemas, resolveTenantByChannel, tenantSchemaName)
- _shared/whatsapp-hooks.ts: hooks de tabela tenant recebem tdb; RPCs de
  credito (deduct/add_whatsapp_credits) e tenant_members seguem em supa+p_tenant_id
- inbound (twilio/evolution): tenant_id da URL -> tdb pra conversation_messages
  e notification_channels
- crons de fila (process-notification/email/sms/whatsapp-queue): varrem
  listTenantSchemas e drenam a fila de cada schema (Q3: filas sao per-tenant);
  modo single-tenant se body.tenant_id vier
- crons reminders/checks (send-session-reminders, conversation-sla-check,
  whatsapp-heartbeat-check, convert-abandoned-intakes, sync-email-templates):
  loop por tenant
- routing por tenant_id (send-whatsapp-message, send-session-reminder-manual,
  twilio-provision, de/reactivate-channel, twilio-webhook): tenantDbForId;
  channel-actions sem tenant_id varrem schemas por channel_id
- asaas-*: tenant_id do body -> tdb; asaas-webhook fica global (whatsapp_credit_purchases)
- notification-webhook (Meta): resolve tenant via channel_routing por phone_number_id,
  fan-out por message_id quando nao resolve
- caller send-session-reminder-manual passa tenant_id (evento vive no schema)

Pendente: save-intake-progress e fluxos anon por token (decisao de roteamento)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 08:44:09 -03:00

71 lines
3.1 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 { adminClient, tenantDbForId } from '../_shared/tenant.ts';
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 admin = adminClient();
const tdb = await tenantDbForId(admin, tenantId);
const { data: settings } = await tdb.from('payment_settings').select('asaas_enabled, asaas_environment, asaas_api_key_sandbox, asaas_api_key_prod').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);
}
});