Skip to content

Provisioning tenants

All calls below use the partner credential (x-partner-key: ecp_…) and the typed @emitecr/sdk/partner client — not on npm yet; partner integrations receive it directly from Futura Byte (see TypeScript SDK). They run in your backend only.

import { EmitecrPartnerClient } from '@emitecr/sdk/partner';
const partner = new EmitecrPartnerClient({
partnerKey: process.env.EMITECR_PARTNER_KEY,
baseUrl: process.env.EMITECR_BASE_URL, // optional; defaults to production
});
Section titled “0. Prefill from Hacienda’s registry (recommended)”

Don’t make your user type registry data — look it up from just the cédula, before the tenant exists:

const record = await partner.lookup(cedula);
// → { identification, identificationType, name, regimen, status, economicActivities[] }

Prefill name (razón social) and let the user pick a default among economicActivities. Typos in registry fields surface later as CERT_IDENTIFICATION_MISMATCH (certificate upload) or emission rejections (wrong activity) — prefer the registry’s version. Returns 404 when the cédula isn’t registered. Cached server-side.

const { tenantId, created } = await partner.tenants.create({
identificationType: '02',
identificationNumber: cedula,
name: razonSocial,
commercialName,
email,
// Dotted code as the padrón returns it: four digits, a dot and one digit.
// The API refuses any other shape, because Hacienda would reject the document
// (the old 6-digit '561011' comes back -408 at emission).
economicActivityCode: '5610.0',
// Fiscal address — REQUIRED for emission (the XSD's Emisor <Ubicacion>).
// Hacienda's location codes: provincia 1 digit, cantón/distrito 2 digits.
location: { provincia: '1', canton: '01', distrito: '01', otrasSenas: '…' },
});

Idempotent per (partner, cédula) — safe to retry (created: false if it already existed). A cédula you released comes back as the same tenant (created: false, revived: true), numbering intact. A cédula owned by a different tenant → 409 PARTNER_TENANT_CEDULA_CONFLICT. The cédula is normalized to uppercase, so casing never splits one restaurant into two tenants.

The .p12 passes in transit only — forward it, never persist or log it. EmiteCR validates the certificate against the cédula and the ATV credentials against Hacienda’s IdP.

await partner.tenants.credentials(tenantId, 'production', {
p12, pin, atvUsername, atvPassword, atvClientId,
});

Useful errors: CERT_IDENTIFICATION_MISMATCH, ATV_CREDENTIALS_REJECTED, ATV_USER_IDENTIFICATION_MISMATCH, PARTNER_PRODUCTION_NOT_ENABLED.

Map each physical register to a terminal so consecutivos never contend across devices. Upsert by code.

await partner.tenants.config(tenantId, {
terminals: [{ branchCode: '1', code: '2', name: 'Caja 2' }],
});
await partner.tenants.logo(tenantId, logoBytes, 'image/png'); // appears on PDFs

When the tenant invoices a customer who left an email, EmiteCR can send that customer the document as soon as Hacienda accepts it: the PDF, the signed XML and Hacienda’s response. It goes out in the tenant’s name: its trade name as the sender, replies to its email and your product’s name in the footer, never EmiteCR’s brand. It starts off, so a product that sends its own does not mail the customer twice; turn it on if yours doesn’t:

await partner.tenants.config(tenantId, { customerEmail: { enabled: true } });

The config response says whether it is on (customerEmail.enabled) and how it will present itself: the sender’s name (customerEmail.senderName) and where replies go (customerEmail.replyTo, null when the tenant’s email is not a valid address). Show those in your settings instead of deriving them from your own copy of the tenant’s data: they are what the email will say. To send a document again, for example to a corrected address, use POST /v1/invoices/{id}/resend-email with the tenant’s API key: it works with the automatic send off too.

4. (Optional) Seed sequences for a migration

Section titled “4. (Optional) Seed sequences for a migration”

Continuing numbering from another provider? Hacienda rejects a repeated consecutivo on the same branch + terminal + document type, so a business that already issued on, say, branch 001 / terminal 00001 must continue from the number after its last one instead of restarting at 1.

Both calls operate on production counters, whatever environment the tenant issues in today — set the numbering up before go-live, while still testing in sandbox. Counters only go up: a nextConsecutive below the number the counter would assign next is rejected with SEQUENCE_CANNOT_DECREASE (a live terminal may have issued meanwhile — re-read and retry), and that same number changes nothing. A batch is all or nothing.

// Where every terminal stands (ids included) — one cell per terminal × type.
const cells = await partner.tenants.getSequences(tenantId);
const tiquete = cells.find((c) => c.terminalCode === '00001' && c.docType === '04')!;
await partner.tenants.seedSequences(tenantId, [
{
branchId: tiquete.branchId,
terminalId: tiquete.terminalId,
docType: tiquete.docType,
nextConsecutive: 1501, // the previous system's last one was 1500
},
]);

With @emitecr/ui-react, <InitialNumbering> renders this as a ready-made panel (implement listSequences / seedSequences in your adapter).

The rawKey is shown once — store it encrypted in your vault, one key per customer × environment.

const key = await partner.tenants.mintKey(tenantId, {
environment: 'production',
name: 'pos-cloud',
});
// key.rawKey → vault

Minted keys are capped to a partner scope ceiling; revoking the partner cascades to all of them.

To rotate, mint again with the same name and revokeExisting: true: your other live keys for that tenant and environment are revoked in the same transaction, and keep verifying for a 5-minute grace so requests already holding the old key still land. If the mint fails, nothing is revoked.

const rotated = await partner.tenants.mintKey(tenantId, {
environment: 'production',
name: 'pos-cloud',
revokeExisting: true,
});

partner.tenants.get(tenantId) returns a readiness checklist (credentials + certExpiresAt, branch/terminal, economic activity, sequences) and the monthly cap usage — everything you need to render a “ready to invoice: 3/4” panel and alert at ~80% of the cap or ~30 days before the certificate expires.

Credentials Hacienda refuses count as missing. When Hacienda’s identity provider rejects the tenant’s ATV user and password, readiness.credentials (and with it readyToEmit) turns false and credentials.production.atvRejectedAt / atvRejectionDetail say since when and what Hacienda answered. Nothing is lost meanwhile: every document keeps its number and waits signed (no error, no 24-hour timeout), EmiteCR stops presenting those credentials to Hacienda, and the backlog goes out on its own once you upload working credentials — or once the daily probe finds them working again. This is the pull version of the credentials.rejected / credentials.restored webhooks: a managed tenant has no members to email, so one of the two is the only way the business learns it has to act.

A mistyped cédula, the owner’s personal cédula instead of the company’s, a setup started over: release undoes the provisioning. It revokes every key you minted for the tenant, deletes its ATV credentials in both environments and deletes the tenant, which frees the cédula for whoever it really belongs to.

const { revokedKeys, credentialsRemoved } = await partner.tenants.release(tenantId);

It is refused with 409 PARTNER_TENANT_HAS_FISCAL_HISTORY (params.documents) once any production document got a number: that document is Hacienda’s record for five years, and a tenant with history is offboarded with detach instead. Sandbox documents don’t count.

Provisioning the same cédula again later revives this tenant (revived: true) — never a new one, whose consecutivos would restart at 1 where Hacienda already holds numbers. It needs its credentials and a key again, like any new tenant.

A managed tenant is not sandbox or production: it has both sides, and the same partner credential sets up each one — a key and ATV credentials per environment. Opening production is a separate, deliberate act: until production_enabled is turned on for the partner app, it can only mint ec_test_… keys and upload sandbox credentials (403 PARTNER_PRODUCTION_NOT_ENABLED for production); after that, it can mint ec_live_… keys and upload production ATV credentials.