# Smiloo · ERP integration kit for AI assistants

This file lets an AI coding assistant (Claude Code, Cursor, Copilot, ChatGPT or similar) connect a
point-of-sale or ERP system to Smiloo. With the integration, the tablet next to the checkout
becomes the customer's second screen: it shows the items while the sale is registered, the total,
the PIX QR code, and at the end asks the customer to rate the service, linked to the sale.

- API: `https://api.smiloo.io`
- Full contract (OpenAPI 3.1): https://api.smiloo.io/v1/openapi.json
- Human guide: https://smiloo.io/parceiros/guia

**How to use:** save this file in the root of the ERP project, open the AI assistant in that folder
and say: "Read erp-integration-ai-kit.md in this folder and follow its "Instructions for the AI assistant". Ask me the questions it lists before writing any code."

---

## Instructions for the AI assistant

You are helping a developer send checkout events from their ERP to the Smiloo API. Talk to the
developer in their own language. Follow these steps in order.

### Step 1 · Ask before coding

Read the project first (look for the checkout/POS screens, the sale model, payment flow and any
existing HTTP or background-job code). Then ask the developer only what you could not find out by
reading. Ask in small groups, not all at once. The answers you need:

1. **Stack and placement.** Language, framework and runtime version. Where should the integration
   module live? Is there an existing pattern for background jobs, outbound HTTP or local queues?
2. **Checkout moments.** Which places in the code correspond to: sale opened, item added, item
   changed or removed, discount or totals changed, sale closed for payment, back to items, payment
   method chosen, PIX QR generated (and where the "copia e cola" payload comes from), payment
   approved, payment declined, sale finished, sale abandoned or turned into a quote, return without
   purchase, and sale cancelled or refunded after it was finished (credit note, cancelled invoice).
3. **Terminals and tablets.** How many checkouts (terminals, PCs) per store? How does the program
   know which terminal it is running on? Where can a "terminal → tablet deviceId" map be stored?
4. **Sale and item ids.** Which id identifies a sale, and can it change after saving (renumbering,
   offline invoice contingency)? Which id identifies an item line?
5. **People.** Is the seller set per item or per sale? Is there a cashier? Which field is the staff
   code that the store will type in the "ERP code" of each team member?
6. **Customer.** Is a short name for the greeting available (nickname or first name)? A phone
   number? Only send what the store is allowed to share.
7. **Money and quantities.** How are amounts stored (decimal, float, cents)? Units (UN, KG)?
   Returns as negative quantities?
8. **Time.** Does the program know its time zone? (`occurredAt` must carry an offset.)
9. **Offline.** Does the checkout keep working without internet? Is there a local database where
   an outbox of events can be kept?
10. **Secrets.** Where can the API key be stored outside the source code (config file, environment
    variable, encrypted settings)?
11. **Anything unusual.** Several stores in one database, several companies, kits or combos,
    weighed items, tips, split payments, anything the checkout does that the events below do not
    cover.

Then write a short plan (files to create or change, where each event is fired) and wait for the
developer's OK.

### Step 2 · Rules that must hold

- **Never slow down or block the checkout.** Events go out in the background with a short timeout
  (2 to 5 s). If the API is down, the sale goes on and the events wait in a local queue.
- **Never lose events.** Keep a persistent outbox; resend with growing waits (2 s, 4 s, 8 s... up
  to 60 s). Resending is safe: the same `eventId` is never applied twice.
- **Order per sale.** `seq` starts at 1 for each sale and goes up by 1 for every event of that
  sale. Never reuse a `seq` for a different event. After a connection drop, first send a
  `sale.snapshot` of the current sale, then the pending events.
- **Money in integer cents** (`4590` = 45.90 in the store currency). Quantities with up to 3
  decimals, never zero.
- **The API key is a password.** Never hard-code it, never log it, never commit it.
- **Personal data.** Send only what the checkout already shows to the customer. Never log phones.
- Keep the integration in its own module, with one small call per checkout moment, so it is easy
  to switch off.

### Step 3 · Test

1. In the store's Portal, under "ERP integration", the owner creates an API key and pairs a tablet
   as an integrated tablet. For a first test, the Portal also has a test store and a simulator.
2. `GET /v1/erp/devices` must list the tablet; save its `id` for the terminal.
3. Run a full sale (two items, one removed, PIX, finished) and watch the tablet follow along.
4. Check `GET /v1/erp/sales/{saleId}/rating` after the customer rates.
5. Pull the network cable in the middle of a sale, finish it, plug it back: the tablet must catch up.

---

## API summary

All calls send `Authorization: Bearer <api key>` (format `smk_live_<prefix>_<secret>`). The store
comes from the key, never from the URL.

| Call | What it does | Limit |
|---|---|---|
| `POST /v1/erp/events` | One event, or `{ "events": [ ... ] }` with up to 100 | 600/min |
| `GET /v1/erp/devices` | Paired integrated tablets: `id`, `name`, `place`, `online` | 120/min |
| `GET /v1/erp/staff` | Team with `erpCode` and `functionIds`, plus `functions` | 120/min |
| `GET /v1/erp/sales/{saleId}/rating` | The rating of a sale, or `null` | 120/min |
| `GET /v1/erp/sales/outcomes` | Finished sales waiting for the ERP to reconcile, with no deadline: `{ saleId, version, rating: { id, score, completed } or null, seller: { erpCode, name } or null }`. Save the rating id on the sale and, when `seller` differs, switch the sale to the seller the customer chose | 300/min |
| `POST /v1/erp/sales/outcomes/ack` | `{ "items": [{ saleId, version, sellerErpCode? }] }`: confirms what the ERP saved; a later change puts the sale back in the queue with a higher `version` | 300/min |
| `PUT /v1/erp/users` | `{ "users": [{ erpCode, name, login? }] }`: all ERP users; replaces the previous list | 30/min |

### Envelope

```json
{
  "eventId": "store1-pos2-000123-0005",
  "type": "sale.item_added",
  "occurredAt": "2026-11-04T14:03:21-03:00",
  "deviceId": "0193a2b4-5c6d-7e8f-9a0b-1c2d3e4f5a6b",
  "saleId": "000123",
  "seq": 5,
  "data": {}
}
```

- `eventId`: up to 100 chars, unique per store (store + terminal + sale + seq works well).
- `occurredAt`: ISO 8601 with offset.
- `deviceId`: the tablet next to this terminal (from `GET /v1/erp/devices`).
- `saleId`: the sale id in the ERP, up to 100 chars.
- Person = `{ "erpCode": "7", "name": "Ana" }`.
- Item = `{ "itemId", "name", "quantity", "unit", "unitPriceCents", "totalCents", "seller"?, "dueDate"? }` (`dueDate` YYYY-MM-DD: an installment of a store credit payment, listed instead of products);
  sending the same `itemId` again updates the line.
- `method`: `pix`, `credit`, `debit`, `cash`, `voucher`, `store_credit` (store credit plan, the tablet asks the customer to sign the contract) or `other`.

### Events (`type` → `data`)

| type | data | Tablet shows |
|---|---|---|
| `sale.started` | `seller?`, `cashier` (always; missing is an error shown in the Portal), `customer?` { `name`, `phone` (E.164), `locale` } (omit when the customer is not identified), `serviceType?` (service type code from the Portal, only if the store uses service types), `askSeller?` (false when the register works without sellers: no "who served you") | greeting, empty list |
| `sale.customer_changed` | `customer` { `name`, `phone`, `locale` } or `null` | the greeting changes; the customer at the end of the sale counts |
| `sale.item_added` | item | the item in the list |
| `sale.item_cancelled` | `itemId` | the item struck through |
| `sale.totals_updated` | `subtotalCents`, `discountCents`, `totalCents` | new totals |
| `sale.snapshot` | totals, `seller?`, `cashier?`, `serviceType?`, `items[]` (up to 500) | the whole sale at once |
| `sale.totalized` | totals, `ratingWaitSeconds?` (0–120) | payment summary; with a wait, the tablet asks for the rating again |
| `sale.back_to_items` | `{}` | back to the list |
| `sale.parked` | `{}` | the operator left this sale's screen without closing it: the tablet shows the free screen and keeps the rating; send `sale.snapshot` to bring the sale back (no second rating is asked) |
| `payment.method_selected` | `method`, `amountCents` | chosen method |
| `payment.pix_requested` | `amountCents`, `pixPayload` (up to 1000), `expiresAt` | PIX QR full screen |
| `payment.confirmed` | `method`, `amountCents` | approved, then the rating |
| `payment.failed` | `method`, `reason` | back to the summary |
| `sale.finished` | `cashier?`, `document?` { `kind`: order/nfce/nfe/other, `number` }, `sellers[]` | rating and thanks |
| `sale.cancelled` | `reason`: abandoned/quote/return | back to ads, no rating |
| `staff.ask` | `functionIds?` | "Who served you?" |
| `staff.confirm` | `seller` | "Did {name} serve you?"; "Someone else" opens the list |
| `register.opened` / `register.closed` | `{}` (no `saleId`, no `seq`; latest `occurredAt` wins) | with no sale: "Checkout closed" or the ads, as the store chooses |
| `sale.voided` | `document?` (no `deviceId`, no `seq`) | nothing; rating leaves the indicators |

A full sale: started → item_added × n → (item_cancelled) → totalized → method_selected →
(pix_requested) → confirmed → finished, with `seq` 1, 2, 3...

### Responses and errors

`POST /v1/erp/events` answers 200 with `{ "accepted": [], "duplicates": [], "rejected": [ { "eventId",
"error", "path"? } ] }`. Each event is validated on its own.

| Where | Code | What to do |
|---|---|---|
| rejected | `VALIDATION_ERROR` | Fix the field in `path`, resend with the same `eventId` |
| rejected | `DEVICE_NOT_FOUND` | Refresh the terminal → tablet map |
| rejected | `SALE_NOT_FOUND` | Only `sale.voided`: resend later |
| HTTP 400 | `VALIDATION_ERROR` / `BATCH_TOO_LARGE` | Fix the body / split the batch |
| HTTP 401 | `API_KEY_INVALID` | Stop and tell the operator |
| HTTP 422 | `PLAN_FEATURE_LOCKED` | Stop and tell the operator |
| HTTP 429 | `RATE_LIMITED` | Wait and resend |
| 5xx / timeout | | Resend later with growing waits |

---

## Reference client (TypeScript, Node 18+)

Translate it to the ERP's language. Every line marked `CUSTOMIZE` depends on the answers to
Step 1.

```ts
import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';

// CUSTOMIZE: read from the ERP's settings; never hard-code the key.
const API_URL = process.env.SMILOO_API_URL ?? 'https://api.smiloo.io';
const API_KEY = process.env.SMILOO_API_KEY ?? '';
// CUSTOMIZE: which tablet sits next to each terminal (ids from GET /v1/erp/devices).
const TABLET_BY_TERMINAL: Record<string, string> = { 'POS-1': '<tablet id>' };
// CUSTOMIZE: a stable prefix per store, so eventIds never collide between stores.
const STORE_PREFIX = 'store1';
// CUSTOMIZE: use the ERP's local database instead of a file if there is one.
const OUTBOX_FILE = './smiloo-outbox.jsonl';

type Person = { erpCode: string; name: string };
type Event = {
  eventId: string;
  type: string;
  occurredAt: string;
  deviceId?: string;
  saleId: string;
  seq?: number;
  data: Record<string, unknown>;
};

/** Next seq per sale. CUSTOMIZE: persist it with the sale if the program can restart mid-sale. */
const seqBySale = new Map<string, number>();

function nowWithOffset(): string {
  const d = new Date();
  const off = -d.getTimezoneOffset();
  const sign = off >= 0 ? '+' : '-';
  const pad = (n: number) => String(Math.abs(Math.trunc(n))).padStart(2, '0');
  const local = new Date(d.getTime() + off * 60_000).toISOString().slice(0, 19);
  return `${local}${sign}${pad(off / 60)}:${pad(off % 60)}`;
}

/** CUSTOMIZE: convert the ERP's money type to integer cents without float errors. */
export function toCents(value: number): number {
  return Math.round(value * 100);
}

/** Queues one checkout event. Returns immediately: the checkout never waits for the API. */
export function emit(terminal: string, saleId: string, type: string, data: Record<string, unknown>) {
  const seq = (seqBySale.get(saleId) ?? 0) + 1;
  seqBySale.set(saleId, seq);
  const event: Event = {
    eventId: `${STORE_PREFIX}-${terminal}-${saleId}-${String(seq).padStart(4, '0')}`,
    type,
    occurredAt: nowWithOffset(),
    deviceId: TABLET_BY_TERMINAL[terminal],
    saleId,
    seq,
    data,
  };
  appendFileSync(OUTBOX_FILE, `${JSON.stringify(event)}\n`);
  void flush();
}

let flushing = false;
let wait = 2_000;

/** Sends the outbox in batches of up to 100; keeps whatever could not be sent. */
export async function flush(): Promise<void> {
  if (flushing || !API_KEY || !existsSync(OUTBOX_FILE)) return;
  flushing = true;
  try {
    const pending: Event[] = readFileSync(OUTBOX_FILE, 'utf8')
      .split('\n')
      .filter(Boolean)
      .map((line) => JSON.parse(line));
    while (pending.length) {
      const batch = pending.slice(0, 100);
      const res = await fetch(`${API_URL}/v1/erp/events`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({ events: batch }),
        signal: AbortSignal.timeout(5_000),
      });
      if (res.status === 401 || res.status === 422) {
        // CUSTOMIZE: show this to the operator (invalid key or plan without integrated tablet).
        console.error('Integration stopped:', res.status);
        return;
      }
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const body = (await res.json()) as {
        rejected: { eventId: string; error: string; path?: string }[];
      };
      for (const r of body.rejected) {
        // CUSTOMIZE: log to the ERP's log (never the API key or phone numbers).
        console.warn('Event rejected', r.eventId, r.error, r.path ?? '');
      }
      pending.splice(0, batch.length);
      writeFileSync(OUTBOX_FILE, pending.map((e) => JSON.stringify(e)).join('\n') + (pending.length ? '\n' : ''));
    }
    wait = 2_000;
  } catch {
    setTimeout(() => void flush(), wait);
    wait = Math.min(wait * 2, 60_000);
  } finally {
    flushing = false;
  }
}

// CUSTOMIZE: call these from the ERP's checkout code (Step 1, question 2).
export const checkout = {
  started: (t: string, sale: string, seller?: Person, customerName?: string) =>
    emit(t, sale, 'sale.started', {
      ...(seller ? { seller } : {}),
      ...(customerName ? { customer: { name: customerName } } : {}),
    }),
  itemAdded: (
    t: string,
    sale: string,
    item: { id: string; name: string; qty: number; unit: string; price: number; total: number; seller?: Person },
  ) =>
    emit(t, sale, 'sale.item_added', {
      itemId: item.id,
      name: item.name,
      quantity: item.qty,
      unit: item.unit,
      unitPriceCents: toCents(item.price),
      totalCents: toCents(item.total),
      ...(item.seller ? { seller: item.seller } : {}),
    }),
  itemCancelled: (t: string, sale: string, itemId: string) =>
    emit(t, sale, 'sale.item_cancelled', { itemId }),
  totalized: (t: string, sale: string, subtotal: number, discount: number, total: number) =>
    emit(t, sale, 'sale.totalized', {
      subtotalCents: toCents(subtotal),
      discountCents: toCents(discount),
      totalCents: toCents(total),
    }),
  method: (t: string, sale: string, method: string, amount: number) =>
    emit(t, sale, 'payment.method_selected', { method, amountCents: toCents(amount) }),
  pix: (t: string, sale: string, amount: number, payload: string, expiresAt: string) =>
    emit(t, sale, 'payment.pix_requested', { amountCents: toCents(amount), pixPayload: payload, expiresAt }),
  paid: (t: string, sale: string, method: string, amount: number) =>
    emit(t, sale, 'payment.confirmed', { method, amountCents: toCents(amount) }),
  finished: (t: string, sale: string, sellers: Person[], cashier?: Person, nfce?: string) =>
    emit(t, sale, 'sale.finished', {
      sellers,
      ...(cashier ? { cashier } : {}),
      ...(nfce ? { document: { kind: 'nfce', number: nfce } } : {}),
    }),
  cancelled: (t: string, sale: string, reason: 'abandoned' | 'quote' | 'return') =>
    emit(t, sale, 'sale.cancelled', { reason }),
};
```

## Go-live checklist

- [ ] Every checkout moment from Step 1 fires its event, in order, with `seq` per sale.
- [ ] The checkout never waits for the API (tested with the network cable unplugged).
- [ ] The outbox survives a restart of the program.
- [ ] The API key lives outside the source code and never shows in logs.
- [ ] Each terminal points to its own tablet; `DEVICE_NOT_FOUND` refreshes the map.
- [ ] Team members have their ERP code filled in the Portal; sellers show up on the ratings.
- [ ] A sale cancelled after finishing sends `sale.voided`.
