Skip to content

Constanza (CFDI)

CFDI 4.0 stamping, cancellation, and fiscal events for the RBS ecosystem. Partners send invoice data; Constanza returns a stamped XML, UUID, PDF, and QR.

URL: constanza.redbroomsoftware.comStatus: LIVE Tier: T1 SDK: @r-bsoftware/ecosystem-sdkcreateWebhookHandler, createWebhookSender, getEntityTypeFromRegime, getISRTypeFromRegime, Constanza fiscal types (ISRType, FiscalLimits, DeclarationStatus, DeclarationFiledEvent)

What you can integrate

  • Stamp CFDI 4.0 for any ecosystem app using the central issuer endpoint
  • Cancel CFDI via SAT with authorization key
  • Geo-aware invoicing — CFDI for Mexican receivers, PDF invoice for international
  • Register a B2C service provider and stamp on their behalf
  • Sync journal entries (polizas) from your app into a partner firm's books
  • Consume fiscal intelligence events — deadline reminders, RESICO utilization, health scores

Authentication

  • Per-app API key via env vars (e.g., CARACOL_API_KEY, LA_HOJA_API_KEY) — sent as Authorization: Bearer <key> or app-specific header per config
  • Ecosystem admin: HMAC-SHA256 for privileged admin endpoints
  • User flows: Camino OAuth2 PKCE — see Auth

All stamping calls are rate-limited via a sliding window.

Endpoints

MethodPath
GET, POST/api/ai/classify
GET/api/ai/usage
GET, POST/api/analytics/anomalies
POST/api/assistant/chat
GET, POST/api/audit
GET/api/audit/accounting
GET, POST/api/bank/reconciliation
GET, POST/api/billing/sw-user
GET, POST, DELETE/api/certificates
POST/api/cfdi/cancel

182 total — 27 admin/cron/internal (hidden) — +145 more primary endpoints not shown. Source: src/routes/api/**/+server.{ts,js} in the Constanza repo.

PAC routing

Constanza uses SW SmartWeb as its PAC.

EnvHost
Testservices.test.sw.com.mx
Prodservices.sw.com.mx

Flow: build payload → XML → sign with CSD → stamp via PAC → return UUID / XML / PDF / QR. Transient 5xx errors retry with exponential backoff. Errors are categorized as transient, config (credentials), or data (fields).

Ecosystem apps may also run in ecosystem stamp mode: call /api/ecosystem/stamp with a receptor block, Constanza handles CSD + PAC, you get the stamped response. No PAC contract required on your end.

Events emitted

EventReceiversDescription
cfdi.cancelledagente, hoja, madriguera, mancha, plenuraA CFDI invoice has been cancelled
cfdi.failedcomalA CFDI invoice stamping has failed
cfdi.stampedagente, agora, camino, comal, continua, cosmos-pet, garita, goodbay, hoja, madriguera, mancha, patadas, plenuraA CFDI invoice has been stamped by the SAT via Constanza — receiver apps attach the UUID to their local invoice record and update status.
constanza.partner_billing_periodcolectiva[auto-derived] constanza.partner_billing_period event
constanza.poliza.reclassifiedcaracolAn accountant reclassified partidas in a póliza (journal entry) — Caracol mirrors the updated category metadata on the referenced sale so future margin and ROI metrics reflect the corrected classification. No inventory mutation downstream.
creditnote.issuedcaracolA credit note (nota de crédito) was issued in Constanza — Caracol records the adjustment against the original invoice for reconciliation
customer.updatedagente, colectiva, constanza, cosmos-pet, garita, hoja, madrigueraA customer/contact record was updated in Camino — receiver apps sync the changed fields to their local customer records for display and invoicing accuracy.
employee.missing_datacaracol, colectiva, cosmos-pet, hoja, madriguera, mancha, plenuraConstanza detected an employee with missing fiscal data (RFC/CURP/etc.) — routed back to the source app that created the employee so the missing fields can be completed.
fiscal.anomaly_detectedcamino, colectivaConstanza AI detected an unusual pattern in an organization's financial data (z-score outlier, Benford violation, duplicate transaction, timing anomaly, etc.). Routed to Camino for CRM health alerts and to Colectiva so the Brain can factor fiscal anomalies into business intelligence.
fiscal.compliance_riskcaminoConstanza identified a SAT compliance risk for an organization: missing declarations, RFC issues, expired CSD certificate, or overdue obligations. Routed to Camino so the CRM can surface the alert and prompt the tenant to take corrective action.
fiscal.deadline_remindercolectivaConstanza detected an upcoming tax deadline (3/7/30 days out) — notifies Colectiva so the Brain can surface the deadline as a priority.
fiscal.health_score_updatedcamino, colectiva[auto-derived] fiscal.health_score_updated event
fiscal.resico_warningcaracol, colectiva, cosmos-pet, hojaConstanza detected an organization whose RESICO income utilization crossed the warning threshold (>=90%). Routed to accounting-sensitive apps so they can surface limit warnings in POS/invoice flows.
invoice.compliance_issuecaracol, comal, cosmos-pet, hoja, madriguera, mancha, plenuraConstanza detected an invoice compliance issue (missing/invalid RFC, duplicate, format error) — routed back to the source app for review.
invoice.issuedcolectivaConstanza issued and stamped an invoice — Colectiva syncs the CFDI to the workspace invoices collection for the business owner's records.
invoice.queuedcolectivaConstanza accepted a deal-billing póliza and queued the invoice for CFDI stamping — notifies Colectiva so the deal-billing pipeline can track the pending invoice.
labor_costs.updatedcamino, hoja[auto-derived] labor_costs.updated event
payment.receivedagente, continua, cosmos-pet, garita, goodbay, hoja, madriguera, patadasA payment has been processed via Colectiva
payment.reconciledagente, cosmos-pet, hoja, madrigueraConstanza completed bank reconciliation for a payment — receiver apps update their local payment records to mark the payment as reconciled against the bank statement.
payroll.processedconstanza[auto-derived] payroll.processed event
poliza.generatedritoConstanza generated a journal entry (póliza) for a Rito deal event — Rito records the poliza reference on the deal for fiscal-accounting traceability.
spv.createdritoConstanza created a fiscal SPV entity for a Rito deal and is sending back the constanza_org_id so Rito can store it on the deal record.
upsell.constanza_onboardingcaminoConstanza detected an org has no active CSD certificate configured — prompts Camino to surface a CSD setup upsell.
upsell.declaration_servicecaminoConstanza detected an org with overdue declarations (>30 days) — prompts Camino to surface a managed-declarations upsell.
upsell.stamp_upgradecaminoConstanza detected an org whose stamp usage has exceeded 80% of its plan allocation — prompts Camino to surface a plan-upgrade upsell.

Events consumed

EventSendersDescription
ai_cost.recordedcolectivaMonthly AI cost aggregate recorded by Colectiva for an org — carries provider, token totals, and MXN spend for the period. Sent to Constanza for bookkeeping.
bank_package.generatedritoRito generated a bank financing package — Constanza pre-prepares fiscal structure for the loan; Camino logs the activity.
baul.creditnote.issuedbaulBaúl credit note stamped — Constanza posts contra-revenue/contra-COGS pólizas (S458)
caja.closedcaracolCash register (caja) close summary from Caracol POS — end-of-day totals for fiscal reconciliation in Constanza
caracol.creditnote.cancelledcaracolCaracol cancelled a previously-stamped credit note — Constanza reverses both pólizas posted at issuance (revenue reversal + COGS reclass), restoring the books to their state before the credit note was issued.
caracol.creditnote.issuedcaracolCaracol stamped a credit note (nota de crédito) for a customer — Constanza generates reversal pólizas: revenue side (Dr 4102 Devoluciones sobre Ventas / Cr payment) and COGS reclass (Dr 1151 Inventario or Dr 5005 Merma / Cr 5001) per item returnsTo flag.
caracol.intercompany_movement_completedcaracolInter-tenant movement reaches ownership-transfer state (FOB-Destination = at receive; FOB-Origin = at dispatch). Triggers Constanza intercompany CFDI emission with partes-relacionadas detection (per OL-2).
caracol.invoice.stampedcaracolA CFDI was stamped through Caracol's own PAC flow (not routed through Constanza). Distinct from cfdi.stamped which Constanza emits after stamping. Used for unified fiscal record + subscription metering.
cfdi_global.stampedcaracolMonthly factura global (CFDI Público en General) successfully stamped by the monthly-cfdi-publico cron. Distinct from caracol.invoice.stamped (per-sale) — carries batch context (period, salesIds) for downstream fiscal reconciliation and subscription metering.
cfdi.distribution_requestedritoRito requests Constanza to generate a CFDI for a distribution. Deal must already have a constanza_org_id. Constanza responds asynchronously with the stamped CFDI.
cost.calculatedagente[auto-derived] cost.calculated event
cpi.purchasedcolectivaA CPI (Colectiva Participation Instrument) was purchased — Camino creates/updates contact with cpi_holder tag + logs purchase timeline; Constanza records sale for accounting.
customer.createdcamino, caracol, comal, servilletaA new customer/contact/third-party record was created — used for CRM sync, fiscal pre-registration, and cross-app contact linking.
customer.updatedcamino, constanza, caracolA customer/contact record was updated in Camino — receiver apps sync the changed fields to their local customer records for display and invoicing accuracy.
deal.billedcamino, colectiva[auto-derived] deal.billed event
deal.createdritoA new real estate deal was created in Rito — Camino CRM logs the activity; Constanza pre-registers fiscal structure for the deal.
decision.expense.approve(none declared)Colectiva's decision hub approved an expense request — Constanza books the approved expense as a poliza and records the approval for audit trail.
decision.hiring.approve(none declared)Colectiva's decision hub approved a hiring request — Constanza registers the new employee for fiscal purposes (RFC, IMSS, payroll onboarding).
decision.salary_change.approve(none declared)Colectiva's decision hub approved a salary change — Constanza updates the employee's payroll record and books the new salary.
decision.termination.approve(none declared)Colectiva's decision hub approved an employee termination — Constanza processes the finiquito calculation and IMSS baja for the employee.
deposit.completedbaulCash deposit completed at bank with proof (photo of slip, GPS). Baul physical layer event. Triggers expense creation in Constanza and agreement reconciliation in Colectiva.
escrow.releasedcolectivaAn escrow hold was released in Colectiva — Constanza books the escrow release as a poliza entry for fiscal reconciliation.
garita.cfdi.stamp.requestedgaritaA Garita boutique-hotel stay requires a CFDI — Constanza queues the stamp request in garita_cfdi_requests. Actual stamping completes when a Constanza org is linked to the Garita property (post-firma operations). Introduced S203 Park Nilo Wave 4.
handoff.completedbaulGeneric physical handoff completed with proof. Covers document delivery, product returns, sample collection, key handoff, equipment transfer. Baul physical layer event.
inventory.cogscaracol, hojaCost of goods sold event emitted by POS on sale completion. Triggers Constanza to post a COGS poliza (Dr 5001 / Cr 1151).
inventory.transit_losscaracolPérdida en tránsito recorded at receive time when the user picks the 'register as transit loss' resolution for a short-receive (received < shipped). Constanza posts a merma póliza Dr 5005 / Cr 1151 when totalCost is present, and persists an audit row in caracol_inventory_transit_losses keyed on (movementId, productId, branchId) for idempotency. Sender clears source.reserved by the full shipped quantity but does NOT restore source.quantity — the diff is written off as merma. Restore-to-source resolution does NOT emit this event (no loss occurred).
k1.deliveredritoA K-1 LP tax report was delivered to an investor in Rito — Constanza records the delivery for tax-compliance audit trail.
order.completedcomal, manchaAn e-commerce order has been completed (paid + fulfilled)
order.refundedcomalAn e-commerce order has been refunded
payment.chargeback_resolvedcolectivaA MercadoPago chargeback reached a terminal state. Colectiva emits this when verdict.terminal && outcome ∈ {lost, won, coverage}. Constanza uses it to post a counter-póliza and (on lost + originalCfdiUuid present) cancel the original CFDI. Canonical contract is whatever colectiva/src/lib/services/ecosystem-webhook.service.js notifyPaymentChargebackResolved emits.
payment.completedcolectivaA payment transaction was fully completed in Colectiva — source apps confirm the payment for delivery orders, subscriptions, or escrow. Used by baul to confirm delivery payment, mancha for reservation payment, constanza for accounting, and cosmos-pet for vet clinic subscription payments.
payment.refundedcolectiva, comalA payment was refunded by Colectiva — voluntary refund initiated by a tenant app or by Colectiva ops, OR an involuntary MP-platform-side refund. Receivers branch on paymentReferenceType. For voluntary refunds with proration, isPartial=true and proration block carries period bounds. paymentLayer is the primary routing discriminator; receivers MUST check it before paymentReferenceType.
payroll.calculatedcolectiva[auto-derived] payroll.calculated event
payroll.processedcolectiva, constanza[auto-derived] payroll.processed event
sale.completedcaracol, hoja, cosmos-petA POS sale has been completed
spv.creation_requestedritoRito requests Constanza to create a fiscal SPV entity for a deal. Constanza responds asynchronously with the constanza_org_id via spv.created.
subscription.activatedcamino, colectivaA subscription plan has been activated for a tenant — all apps that gate features behind the subscription tier update their local tier state.
subscription.cancelledcamino, colectivaA subscription has been cancelled — all apps that gate features behind the subscription tier update their local tier state to free/cancelled.
subscription.payment_receivedcamino[auto-derived] subscription.payment_received event
subscription.renewedcamino, colectivaA subscription was successfully renewed for a new billing period — receiver apps update the subscription period end date and resume any paused features.
team_member.createdcaminoA new team member was added to a workspace in Camino — Constanza pre-registers the employee for fiscal/payroll onboarding.
team_member.deactivatedcaminoA team member was deactivated in Camino — Constanza marks the employee as inactive and may trigger an IMSS baja process.
team_member.updatedcaminoA team member's record was updated in Camino — Constanza syncs the changed fields on the employee record.
trust.deposit(none declared)A trust account deposit instruction was sent to Constanza — Constanza books the deposit in the trust wallet ledger for the IOLTA-style escrow account.
trust.disburse(none declared)A trust account disbursement was sent to Constanza — Constanza books the outflow from the trust wallet and generates the corresponding poliza.
trust.hold(none declared)A trust account hold was placed — Constanza books the hold in the trust ledger pending instruction to release or disburse.
vendor.createdcaracol, hojaA vendor (supplier) was created in a source app. Constanza accumulates these for monthly SAT DIOT submission (Declaración Informativa de Operaciones con Terceros). PD-074 (S313) — replaces the broken Constanza→{caracol,hoja,cosmos-pet,colectiva} POST /api/ecosystem/diot/vendors pull (S271 BROKEN #7).
vendor.updatedcaracol, hojaA vendor's fields changed in a source app. Constanza merges non-undefined fields into the accumulated DIOT vendor record (matched by vendorId). PD-074 (S313).
workflow.actioncolectivaColectiva dispatches a workflow action to a target app — instructs the receiver to perform a specific operation (create employee, generate poliza, update record). Payload includes the action type and data needed by the receiver.

Four-entity support

Constanza is multi-tenant and multi-entity — a single account can manage several RFCs (e.g., a parent company and its subsidiaries). All Firestore queries are scoped to orgId and all fiscal queries to the active rfc. Partners only see their own entity.

Alegra export

Constanza exposes an export endpoint for accounting-firm clients who keep a parallel book in Alegra. Contact support for the current schema.

Webhook signature

Standard ecosystem HMAC-SHA256 — see Webhooks.

Gotchas

  • CFDI receivers must have a valid RFC, regime code, and postal code. Send via /api/ecosystem/fiscal-data before the first stamp to avoid invoice.compliance_issue storms.
  • Polizas must balance: sum(debe) === sum(haber). Validation is server-side; unbalanced journal entries are rejected.
  • Audit logs are create-only — you cannot delete or mutate historical entries. Plan your integration to avoid needing to.
  • Use getFiscalLimits(year) from the SDK for year-specific rates. Never hardcode tax rates — they change annually.

Red Broom Software Ecosystem