# Salgbar: customers, categories and Business Central

Salgbar is Snakkbar's CRM module, beside the chat and Mailbar. This part covers customers, the
category tree, lookups in Brønnøysund's Enhetsregisteret and the connection to Microsoft Dynamics
365 Business Central. Deals and quotes come later (`docs/internal/plan-salgbar.md`).

Salgbar is switched on per tenant by Snakkbar (`TenantSettings.salgbar`). Until then every endpoint
below answers `403 forbidden` and the panel has no «Salg» in the menu.

| Thing | What it is |
| --- | --- |
| **Customer** | A company (`kind: "business"`) or a person (`kind: "private"`). It is the same record as a contact's [company](contacts.md), so a customer's contacts are the contacts with its `companyId`. Only `name` is required. |
| **Owner** | The seller responsible for the customer: an active operator of the tenant. |
| **Category** | A node in the tenant's tree (`parentId`). A customer can be in several. «Private» is the customer's `kind`, not a category. |
| **Timeline** | Every activity of the customer's contacts (mails, chats, visits, what your systems log), newest first. |
| **Enrichment** | What Enhetsregisteret said when the customer was saved with a new org. number: organisation form, NACE code, employees, founded, bankruptcy, with `source` and `fetchedAt`. |

An org. number can be on more than one customer. Business Central has such duplicates from the past
(it blocks new ones now), so Salgbar warns instead of refusing: creating or editing a customer with
an org. number another customer of the tenant has is allowed, and the answer lists the others in
`duplicates`. `bcCustomerNo` is unique per tenant; it is filled by the Business Central connection,
which owns it.

## Panel

**Salg** in the menu: the customer list (search, category with the ones under it, «Mine» or all,
business or private), the customer card (details, owner, categories, Brønnøysund facts, contacts,
timeline, and three figures from Business Central with a link to the customer there, or «Opprett i
Business Central»), «Ny kunde» (type
a name or org. number, pick Brønnøysund's suggestion, check and save; «Privatkunde» skips the
lookup; an org. number the tenant has already says «Finnes allerede: …» with links to those
customers, and «Opprett likevel» is a deliberate second step) and «Kategorier» (the tree: add, rename, move, delete). A customer can be linked to:
`/panel?tenant=…&view=sales&customer=<id>`.

## API

The same endpoints exist for your backend under `/server/crm/…` (a secret key with `crm:read` to
read, `crm:write` to change; write includes read) and for the panel under `/operator/crm/…`. In the
SDK they are `operatorClient.crm.*`. Bodies and answers use the **Customer**, **Category**,
**CustomerActivity** and **BrregCompany** types in `packages/sdk/src/types.ts`.

| Method and path | What it does |
| --- | --- |
| `GET /crm/customers` | By name, paged: `limit` (1–200, default 50) and `cursor` (`nextCursor` from the last page). `q`: words that must each be in the name, org. number, BC number or city, or in the e-mail of one of the customer's contacts. `category`: a category id, including those under it. `owner`: an operator id (`me` in the panel). `kind`: `business` or `private`. `orgNumber`: exactly this org. number (nine digits), to warn about a duplicate before saving. → `{ customers, nextCursor }` |
| `POST /crm/customers` | **CustomerInput** with `name`, optionally `categoryIds`. → `201 { customer, duplicates }` |
| `GET /crm/customers/:id` | → `{ customer, contacts }` (up to 200 contacts, as in [contacts.md](contacts.md)) |
| `PATCH /crm/customers/:id` | **CustomerInput**: a field left out is kept, `null` clears it. → `{ customer, duplicates }` |
| `PUT /crm/customers/:id/categories` | `{ categoryIds }` replaces the customer's categories. → `{ customer }` |
| `GET /crm/customers/:id/timeline` | Newest first, paged with `limit` and `cursor`. → `{ activities, nextCursor }`; each activity has its `contactId`. |
| `GET /crm/categories` | The tree. → `{ categories }` |
| `POST /crm/categories` | `{ name, parentId? }`. Names are unique under one parent (ignoring case); up to 500 per tenant. → `201 { category }` |
| `PATCH /crm/categories/:id` | `{ name?, parentId?, sort? }`: rename, re-sort, or move with everything under it (`parentId: null` for the top). Moving a category under itself or one of its own descendants is `400`. → `{ categories }` (the whole tree) |
| `DELETE /crm/categories/:id` | Deletes it and every category under it; customers only lose the link. Idempotent. → `204` |
| `GET /crm/brreg/search?q=` | A name (up to 8 main units) or an org. number (that unit, or a sub-unit). Each result has `customerId` when the tenant already has a customer with its org. number. → `{ results }` |
| `GET /crm/brreg/:orgNumber` | One unit, or `404`. → `{ company }` |
| `GET /crm/customers/:id/bc` | The customer's figures from Business Central, read live. → **CustomerBcFigures** (see below) |
| `POST /crm/customers/:id/bc` | Creates the customer in Business Central and keeps its number. → `201` (created) or `200` (BC already had it) `{ customer, bc: { customerNo, created, matchedBy } }` |

`CustomerInput` fields: `name`, `kind`, `externalId`, `orgNumber` (nine digits; spaces are fine),
`bcCustomerNo`, `domain`, `address`, `postalCode`, `city`, `country` (ISO 3166 alpha-2, default
`NO`), `phone`, `email`, `website`, `ownerId`. A new customer without `domain` gets its website's.

`duplicates` is a warning, never an error: the tenant's other customers with the saved customer's
org. number (up to 10, the oldest first), each `{ id, name, bcCustomerNo }` (**CustomerDuplicate**),
and `[]` when there are none or the customer has no org. number. The Brønnøysund suggestions carry
the same list in `customers` (and the oldest one's id in `customerId`).

Changing `kind` on a customer that is in Business Central is `409` once the sync reads the kind
from BC (below): it is changed in BC.

The Brønnøysund lookups are proxied to `data.brreg.no/enhetsregisteret/api` (a 4 second timeout,
120 lookups per minute per tenant). A business address is used where there is one, else a
sub-unit's location, else the postal address. When the register does not answer, the lookup is
`503 unavailable` and saving a customer goes ahead without enrichment.

Example: find the customers in a category and everything under it that belong to one seller.

```http
GET /api/v1/server/crm/customers?category=3f0c…&owner=9a41…&limit=100
Authorization: Bearer sk_snakkbar_…
```

## Business Central

Salgbar reads a tenant's customers from Business Central (BC) and writes to BC only to create a
customer (later also orders). **BC owns the customer's master data**: there is no two-way field
sync. A field has one owner and is edited only there.

| Owned by BC (overwritten by every sync) | Owned by Salgbar (never touched by the sync) |
| --- | --- |
| `name`, `address` (address lines joined), `postalCode`, `city`, `country`, `phone`, `email` (the first valid one), `website` (only when BC has one), `orgNumber`, `bcCustomerNo`, `bcSalespersonCode`, `kind` (with the extension 1.1 or later, below) | `owner` (except when empty, below), categories, `enrichment`, contact persons' names, `kind` with an older extension |

### Connecting

Snakkbar reaches every tenant's BC with one multi-tenant Entra app, «Snakkbar Business Central»,
owned by Sevenfold. Its credentials are deployment settings, not per tenant:

| Environment variable | What |
| --- | --- |
| `SNAKKBAR_BC_CLIENT_ID` | The Entra app's client id |
| `SNAKKBAR_BC_CLIENT_SECRET` | Its client secret |

Without them Salgbar works as before and Business Central shows as not configured. Per tenant
Snakkbar stores only the BC tenant (Entra tenant id or domain), the environment and the company
(`bc_connections`, from `20261106120000_bc_connections.sql`).

A tenant's administrator connects under **Innstillinger → Salgbar → Business Central**, which shows
these steps beside the fields:

1. An Entra administrator in the customer's tenant gives admin consent:
   `https://login.microsoftonline.com/<tenant>/adminconsent?client_id=<client id>`.
2. In BC, on the page «Microsoft Entra-applikasjoner» (Microsoft Entra Applications), add the client
   id, set the state to Enabled, give it the permission set `SNAKKBAR` from the «Snakkbar BC
   Integration» extension (`nitech/snakkbar-bc`) and click «Gi samtykke» (Grant Consent).
3. Enter the tenant id and environment, «Test tilkobling» lists the environment's companies, pick
   one and save. «Synkroniser nå» runs a sync at once; otherwise it runs within 15 minutes.

Errors are shown in plain Norwegian: a `401` from BC means the app is not added on «Microsoft
Entra-applikasjoner», a `403` that it lacks permissions, and a failed sign-in that the admin consent
is missing or the tenant id is wrong.

### The sync

A cron (`GET /api/v1/internal/bc-sync`, every 15 minutes, with `CRON_SECRET`) reads from BC,
read-only, for every enabled connection. Each run writes its counts and any error to the
connection, shown in the settings.

**Where customers are read.** From the extension's own customers page
(`…/api/sevenfold/snakkbar/v1.0/companies(…)/customers`, «Snakkbar BC Integration» 1.1 or later):
the same fields as API v2.0's `customers`, plus `kind` (`private` or `business`). BC decides the kind
in **Snakkbar-integrasjon oppsett**: Customer Posting Groups mapped to Private or Company (at Amatec
`PRIVATKUNDE` → Private, `BEDRIFTSKUNDE` → Company), else contact type Person is private, else the
setup's default (snakkbar-bc README, «Privat eller bedrift»). When the page is missing (an older
extension: `404`), the sync reads API v2.0 as before, logs that once per server instance, and the
kind stays Salgbar's. The settings show which it was (`lastStatus.customers.source`: `extension` or
`standard`). The first pass after the extension appears reads every customer, not only the changes.

**Customers** (`customers`) come by delta on `lastModifiedDateTime`. The first run reads everything
in pages of 500; a pass that does not fit in one invocation keeps BC's next-page link and the next
run continues from there. After a pass, the watermark is the time the pass started, less two minutes,
so rows BC committed late are read again (the update is idempotent). Each BC customer is matched to a
Salgbar customer:

1. by BC customer number;
2. else by Norwegian org. number (`taxRegistrationNumber`, with `NO`, `MVA`, spaces and dots
   removed), to a Salgbar customer not yet linked to BC (the oldest, if several);
3. else a new customer is created.

**Kind.** With the extension, BC is the master for `kind` once a customer has a `bcCustomerNo`: new
customers get BC's kind, and linked ones are overwritten when it differs. Changing the mapping in BC
does not change the customers' `lastModifiedDateTime`, so the delta does not see it: run
**«Synkroniser alt på nytt»** in the settings afterwards (it forgets the watermark and reads every
customer). Without the extension, a new customer is `private` only when BC's contact type is
`Person` and it has no Norwegian org. number, otherwise `business`, and Salgbar owns the kind after
that.

When two BC customers share an org. number, the first takes the Salgbar customer and the second
becomes a customer of its own (BC is the master).

**Owner**: a customer without an owner gets the operator behind BC's salesperson code, matched by the
salesperson's e-mail (`salespeoplePurchasers`) to an active operator's e-mail. An owner set in
Salgbar is never changed. The code itself is kept (`bcSalespersonCode`) for orders.

**Contact persons** (`customerContacts`: the persons under a customer's company contact) have no
change date in API v2.0, so they are read in full at most once a day, after the customers. Snakkbar's
contacts are keyed by e-mail, so a person without one is skipped. A new address becomes a contact on
the customer; a known contact without a company is linked to it; a contact that already belongs to a
company is left alone. Nothing is subscribed to any list.

### On the customer card

`GET /crm/customers/:id/bc` reads three figures from BC live (kept for a minute per server
instance) and answers with one of:

| `status` | Meaning |
| --- | --- |
| `ok` | `salesLast12Months` (posted invoices minus credit memos, excl. VAT, over the last 12 months: `customerSales` filtered on posting date), `salesTotal` (the same since the start, up to yesterday: `customerFinancialDetail.totalSalesExcludingTax`, BC's «Sales (LCY)» with the date filter up to yesterday), `balance` («Åpne poster»: `Balance (LCY)`), `overdue` («Forfalt»: `Balance Due (LCY)`, due before today), `currency` (the company's local currency) and `url` (the customer card in BC's web client) |
| `not_in_bc` | No BC number yet: the customer can be created there |
| `missing` | The BC number is no longer in BC |
| `not_configured` | No BC app in the deployment, or the tenant has not connected |

### Creating a customer in BC

`POST /crm/customers/:id/bc` (panel: «Opprett i Business Central») calls the extension's
`CreateCustomer` with `externalId` = the Salgbar customer id, `kind`, name, org. number (businesses
only), address, e-mail, phone and the salesperson code (the customer's own, or its owner's found by
e-mail in `salespeoplePurchasers`). BC picks the customer template for the kind. The action is
idempotent on the Salgbar id, and BC returns an existing customer with the same org. number instead
of creating a duplicate (`created: false`, `matchedBy`). The number BC answers with is stored on
the customer. When BC refuses (a missing posting group, say), its own message is returned as it is
(`400`). A customer that already has a BC number is `409`.

### Settings endpoints (panel, administrators)

| Method and path | What it does |
| --- | --- |
| `GET /operator/crm/bc` | → `{ configured, clientId, connection }` (**BcConnectionStatus**) |
| `POST /operator/crm/bc/test` | `{ bcTenantId, environment }` → `{ companies }`, or BC's reason as a clear message |
| `PUT /operator/crm/bc` | `{ bcTenantId, environment, companyId, enabled? }`. A new tenant, environment or company starts the sync from the beginning. |
| `POST /operator/crm/bc/sync` | Starts a sync; `202`, and `connection.running` is true until it is done. `409` while one runs. |
| `POST /operator/crm/bc/resync` | «Synkroniser alt på nytt»: the same, after clearing the customers' watermark (and any pass under way), so every BC customer is read again. For a changed kind mapping in BC. |
| `DELETE /operator/crm/bc` | Disconnects. Customers keep their BC numbers. |

To see what a first sync would do without writing anything, run `scripts/bc-dry-run.mjs` (it reads
BC with the app's credentials and the tenant's companies with read-only queries, and prints counts
and sample mappings).
