# AiEngage CRM — Modules Public API Documentation

OpenAPI 3.1 documentation for the CRM's **public Modules API** — the 16
endpoints that create, read, update, archive, search, batch-process and link
records, plus the field metadata that describes what each module contains.

| File | What it is |
|---|---|
| `module-public-api.yaml` | **The master document.** The guide *and* the reference: 16 operations, 13 module field schemas, 275 field definitions, and the whole Quick Start / walkthrough written into `info.description`. Source of truth. |
| `index.html` | One page that renders it. |
| `logo.svg` | Copy of `frontend/public/aiengage-white-logo.svg`, kept here so the folder is self-contained. |
| `README.md` | This file (for maintainers — readers want `index.html`). |

### Branding

Colours are the product's own, read from `frontend/src/app/globals.css` rather
than invented:

| Token | Value | Used for |
|---|---|---|
| `--primary` | `#F3724C` / `#EE5D3D` | Links, active sidebar item, primary button, token-field highlight |
| `--foreground` | `#424C60` | Body text |
| `--accent` | `#F1F4F8` | Table headers, hover surfaces |
| `--accent-foreground` | `#1B2333` | Headings |

The logo's mark is `#FF5F38`, which is why the header is dark — it is the
white logo variant.

Scalar is themed by overriding its own `--scalar-*` CSS variables. **Those
names were read off the rendered DOM, not guessed**, so they are the ones
Scalar actually consumes. If you restyle, do the same rather than assuming a
name.

> ℹ️ `documentation_url` in every error example points at **aitrillion.com**,
> not aiengagecrm.com. That is not a mistake: `ApiResponse::publicError()`
> hardcodes that host, so the doc reproduces what callers actually receive.
> AiTrillion is the parent company — the logo reads "AiEngage by AiTrillion".

**It is one page.** The Quick Start, the guides and the endpoint reference are
all at the same URL, in one sidebar, with one search box. There is nothing to
navigate between.

---

## Scope

This covers the public **Modules** API only — the endpoints under
`/api/public/v1/objects` and `/api/public/v1/properties` **implemented by
Atul**.

| # | Method | Endpoint | Tag |
|---|---|---|---|
| 1 | GET | `/objects/{module}` | Records |
| 2 | POST | `/objects/{module}` | Records |
| 3 | PUT | `/objects/{module}` | Records |
| 4 | GET | `/objects/{module}/{id}` | Records |
| 5 | PATCH | `/objects/{module}/{id}` | Records |
| 6 | DELETE | `/objects/{module}/{id}` | Records |
| 7 | POST | `/objects/{module}/search` | Search Records |
| 8 | POST | `/objects/{module}/batch/create` | Batch Operations |
| 9 | POST | `/objects/{module}/batch/read` | Batch Operations |
| 10 | POST | `/objects/{module}/batch/update` | Batch Operations |
| 11 | POST | `/objects/{module}/batch/archive` | Batch Operations |
| 12 | PUT | `/objects/{module}/{id}/associations/{toModule}/{toId}` | Associations |
| 13 | GET | `/objects/{module}/{id}/associations/{toModule}` | Associations |
| 14 | DELETE | `/objects/{module}/{id}/associations/{toModule}/{toId}` | Associations |
| 15 | GET | `/properties/{module}` | Fields Metadata |
| 16 | GET | `/properties/{module}/{property}` | Fields Metadata |

### Deliberately excluded

Two endpoints live in the same route file and are **not** Atul's, so they are
out of scope here:

| Endpoint | Author |
|---|---|
| `GET /objects` — module catalogue | Prayas Jain |
| `GET /objects/{module}/{id}/timeline` | Prayas Jain |

Everything outside Modules — reports, analytics, dashboards, campaigns,
support, WhatsApp, the OAuth server, public forms, booking, documents,
portfolio and the widget — is also out of scope.

### How the scope was established

Not by reading commit messages. Every route line in
`backend/routes/api/public-v1.php` was attributed with:

```bash
git blame -w -M -C backend/routes/api/public-v1.php
```

`-M -C` make the blame movement- and copy-aware, so a line that was merely
reformatted or relocated still credits whoever wrote it. Controller
authorship was checked independently and agrees: `ObjectsController`,
`SearchController`, `BatchController`, `PropertiesController` and
`AssociationsController` were all created by Atul (`df739f9e3`, with
associations added in `77fdc4215`), while `ObjectTypesController` and
`TimelineController` are 100% Prayas Jain's.

A check script asserts the doc contains **exactly** Atul's 16 — no missing
route, no extra operation, no documented path that is not a real route.

---

## Documentation style

The structure follows two references:

- **[Zoho CRM v8 API](https://www.zoho.com/crm/developer/docs/api/v8/get-records.html)**
  — each endpoint reads *Purpose → Endpoint → Scope → Header → Parameters →
  Sample Request → Sample Input → Sample Response → Possible Errors*, and the
  error list gives a **Resolution** for every code rather than only a message.
- **[Shopify Admin API](https://shopify.dev/docs/api/admin-rest/latest/resources/product)**
  — fields are typed blocks carrying their flags (required, unique,
  read-only), with picklist values enumerated, and each resource shows a full
  example object.

---

## Opening it

Deployed:

```
https://crm-dev1.aiengagecrm.com/docs/modules
```

That short URL comes from a **rewrite in `frontend/next.config.js`** —
`/docs/modules` → `/module-api/index.html`. It is a rewrite, not a redirect,
so the address bar keeps the readable path.

`/module-api/index.html` keeps working too; nothing was moved.

### Running it locally

```bash
cd frontend/public && python -m http.server 8080
# then: http://localhost:8080/module-api/index.html
```

⚠️ Serve **`frontend/public`**, not this folder on its own. The page addresses
its spec, logo and README from the site root (`/module-api/…`), so served from
inside the folder those paths will not resolve.

### Why absolute paths

The page answers at two URLs. From `/docs/modules`, a *relative*
`module-public-api.yaml` would resolve against `/docs/` and 404. Absolute
paths work from both addresses. **Do not convert them to relative** — there is
a note at the top of `index.html` saying the same thing.

### Deep links

Section hashes (`#tag/records`, `#description/guide-searching`) are real and
shareable — send a colleague a link to the exact section. They work on both
URLs.

### What a reader gets

- **Ctrl+K search** across the whole document — endpoints, field names, error
  categories and the guide text.
- A sidebar that lists the Quick Start steps and each guide section
  individually, then the five endpoint groups, then the module field schemas.
- **Code samples in 20+ languages** per endpoint — curl, Python, Node, PHP,
  Java, Go and more. curl is the default, because that is what the guides use.
- An **Authorize** box: paste a token once and it is remembered in that
  browser's localStorage (`persistAuth`).

### Renderer

[Scalar](https://github.com/scalar/scalar) (`@scalar/api-reference`), **pinned
to 1.69.2** via the ESM CDN build. Chosen over Swagger UI for the search, the
multi-language code samples and the readability — Swagger UI's filter box only
matches tag names, which is not enough for a document this size.

The version is pinned deliberately: this page persists a token to
localStorage, so an unpinned CDN tag would let the bundle change underneath
it. If you bump it, re-check the page renders before deploying.

### ⚠️ "Test Request" and the missing proxy

Scalar ships a built-in request sender, and it is **deliberately left without
a proxy**, so it will be blocked by browser CORS.

The reason: a browser page cannot call the CRM API cross-origin, and Scalar's
documented fix is its own hosted proxy at `proxy.scalar.com` — which would
route a real `cak_live_` CRM token through a third party. That is not an
acceptable default for a production key.

So the supported ways to actually call the API are the **copyable curl
samples** and **Postman**. If you later stand up a proxy that follows the
Scalar Proxy API, set `proxyUrl` in `index.html` and Test Request starts
working.

---

## Importing into Postman

1. **Import → File** → `module-public-api.yaml`
2. Postman reads OpenAPI 3.1 YAML natively and builds a collection grouped by
   tag.
3. Set the collection variable `host` to your CRM host.
4. Add your token as collection-level **Bearer Token** auth — every request
   inherits it.

Every operation carries request and response examples, so the generated
requests run rather than being empty shells.

---

## Module field reference

The API is module-agnostic: one set of routes serves every module. That keeps
it small, but means the endpoints alone cannot tell you what a contact
contains. So the spec carries a typed field schema per standard module, under
**Schemas** at the foot of the Swagger page.

| Module | `{module}` | Fields | Module | `{module}` | Fields |
|---|---|---|---|---|---|
| Contacts | `contacts` | 24 | Payments | `payments` | 22 |
| Deals | `deals` | 12 | Leads | `leads` | 25 |
| Companies | `companies` | 20 | Tasks | `tasks` | 15 |
| Products | `products` | 15 | Tickets | `tickets` | 22 |
| Quotes | `quotes` | 34 | Meetings | `meetings` | 20 |
| Invoices | `invoices` | 34 | Calls | `calls` | 18 |
| | | | Notes | `notes` | 14 |

**275 field definitions**, each with its type, required/unique flags, max
length, picklist values and labels, and layout section.

⚠️ These are the **seeded defaults** — what a fresh organization starts with,
read from `Module::createDefault*Fields()`. An admin can add, rename, hide or
remove fields, and custom modules have no seeded set at all.
**`GET /properties/{module}` is the live source of truth** for any given
tenant; these tables are the map you read before calling it.

### How the fields were extracted

By parsing `backend/app/Models/Module.php`, not by hand. Each module's field
count was asserted against the number of `'field_slug' =>` declarations in the
source, and all 14 groups matched exactly.

Two expressions could not be resolved statically and were **left out rather
than guessed**: `TransactionalModuleConfig::lineItemsFieldOptions()` and
`DEFAULT_TRANSACTIONAL_TERMS`, both on Quotes and Invoices. Their fields are
documented; only those option details are missing.

---

## Things worth knowing before you integrate

**Call `GET /properties/{module}` first.** It is the only way to know a
tenant's real field names.

**Batches of more than one record are a mass operation.** `batch/update` and
`batch/archive` with two or more inputs are checked against the acting user's
profile **before anything is written**, and refused whole with 403 if Mass
Update / Mass Delete is off. A single-item batch behaves like an ordinary
`PATCH` or `DELETE`.

**Batch calls always return 207.** Read `status` and `errors`; the status code
alone tells you nothing.

**Upsert reports its action in a header.** `PUT /objects/{module}` returns 200
whether it created or updated — read `X-Upsert-Action`.

**Associations check both modules.** You need the scope for the near side and
the far side.

**Paging is cursor-based — with one exception.** The association list is the
only offset-paged endpoint on this API.

**404 does not always mean "does not exist".** A record outside the acting
user's visibility returns the same 404, deliberately, so existence never
leaks.

**One category is a 404 where it is a 400 elsewhere.**
`GET /properties/{module}/{property}` returns `INVALID_PROPERTY` with status
404; every other endpoint returns that category as 400. Documented as the
backend actually behaves.

---

## Maintaining this

The YAML is hand-maintained. When a module endpoint changes:

1. **Change the route or controller first.** This folder is documentation only
   and must never be the reason behaviour changes.
2. Edit `module-public-api.yaml`. One operation per route; reuse the existing
   `components` rather than inlining a new schema.
3. Re-validate: YAML parses, `openapi: 3.1.0`, every operation has a unique
   `operationId`, a summary, tags and responses; every `$ref` resolves; every
   tag is declared and used; every `{param}` in a path is declared.
4. Re-check against the real route table **in both directions** — a missing
   endpoint matters as much as a wrong one.
5. Reload the Swagger UI and confirm it renders.

When a module's seeded fields change in `Module.php`, re-extract rather than
hand-editing 275 entries, and assert the per-module counts against the source
again.

**Do not invent schemas.** Anything that cannot be established from the code
is marked `x-unverified` with a note. An honest "not verified" is more useful
than a plausible guess.

### The MCP chapter

The MCP chapter lives in `info.description`, between *Using the spec
elsewhere* and *Reference*. It adds **no paths, no servers and no tags** — the
OpenAPI file stays exactly the 16 Modules operations, so anything generated
from the spec is unaffected by it.

Its tool table is **generated, not typed.** The source is
`backend/resources/public-api/crm-tool-catalog.json`, which mirrors AI-Lab's
`CRM_TOOLS` registry. To refresh it after the registry changes:

```bash
cd backend && php artisan mcp:sync-tool-catalog    # pull the snapshot
cd ../frontend
node scripts/gen-mcp-tool-table.js    # paste under "What the connector can read"
```

The registry has grown twice already (22 → 25 tools when Advertising landed,
47 → 48 when *My agenda* did). A hand-kept table would have been silently
wrong both times, which is why the generator exists. Note the help-centre
article still says 47 tools in 15 groups; the code is the authority, and the
consent screen renders the live catalogue from AI-Lab rather than this
snapshot.

Everything else in the chapter was read out of the code, not the help centre:

| Claim | Source |
|---|---|
| issuer, resource, scopes, token lifetimes | `backend/config/mcp-oauth.php` |
| the five `/oauth/*` endpoints, three discovery paths | `backend/routes/mcp-oauth.php` |
| PKCE S256 only, CIMD, grant types | `McpOAuth/MetadataController.php` |
| consent choices ARE scope grants | `Services/PublicApi/McpToolScopeResolver.php` |
| `cak_oauth_*` shares the REST auth path | `Http/Middleware/PublicApiAuthenticate.php` (MODE 4) |
| which host serves what | `ait-serverless/crm-mcp/README.md` |

Two UI pieces exist only for this chapter, both in `index.html`: `mcpRange()`
decides where the chapter starts and stops (used by the document *and* the
sidebar, so the two cannot disagree), and `wireGuideTabs()` merges code blocks
that begin with `# tab: Label` into one tabbed card.

---

## Verification performed

| Check | Result |
|---|---|
| YAML parses | ✅ |
| Valid OpenAPI 3.1, 0 structural problems | ✅ |
| All 44 `$ref`s resolve | ✅ |
| 5 tags, all declared and used | ✅ |
| 16 documented operations | ✅ |
| Doc matches Atul's routes **exactly** (git blame) | ✅ 0 missing, 0 extra, 0 phantom |
| Field counts match `Module.php` source | ✅ 14/14 groups |
| Swagger UI renders the spec | ✅ |

Every schema was derived by **reading code** — routes, middleware,
controllers, form requests, resources and services. No request was made
against any environment.

No route, controller, middleware, service, business logic or database
behaviour was changed to produce this documentation.
