# Documents and Word files

A document is data, not a picture of a page: its blocks have ids, its fields have types, and a Word file keeps its structure one to one.


## Where a document comes from {#sources}

| Source | How |
| --- | --- |
| Word | Upload the `.docx` to `POST /v2/files`, then `POST /v2/documents` with `file`. Numbering, tables, styles, headers and footers stay as Word laid them out. |
| PDF | Upload the PDF and place fields on its pages (`placements`). The PDF is stamped, never re-rendered. |
| Markdown | `POST /v2/documents` with `markdown`. Headings, lists, tables and emphasis become Word paragraphs with real numbering. |
| Template | `POST /v2/documents` with `template` (and `template_version`). |

An agent with a terminal does not carry a file through its own context: `POST /v2/files/upload_links` gives a one-time address (15 minutes), the file goes there with `curl -X PUT --data-binary @file <url>`, and the answer is the file (MCP: `get_upload_link`). A wrong file does not spend the link.

## Photos in the text {#photos}

An inventory, a handover act, meter readings: photos belong in the contract itself. Upload each with purpose `image` (PNG or JPEG, up to 5 MB; an upload link takes `purpose: "image"` too), then place it in Markdown by its file id: `![Living room at handover](file_…)`. A photo is at most as wide as the text and 10 cm tall; a title asks for a share of the text width instead — `![Water meters](file_… "50%")`. It works in `markdown` when creating a document or template and in `replace`, `insert_after`, `insert_before` and `append` edits, and the photo stays in the preview, the DOCX, the PDF and the signed copy. Content as Markdown shows it as `![caption](file_…)`. An id that is not an uploaded picture of the account, or a web address, is refused (`image_not_found`, `image_invalid`) rather than dropped to its caption. Photos go in as taken: a sideways phone picture stays sideways.

## Blocks and revisions {#blocks}

Every paragraph and table has a stable id. Read them with `GET /v2/documents/{id}/content?format=blocks`; the same ids appear as `data-block-id` in the HTML the components show. Each change makes a new revision, and an edit names the revision it was made on, so two editors never overwrite each other silently.

Formats of `GET /v2/documents/{id}/content`:

- `markdown`: the text with field values (or markers),
- `html`: what the components render, with exact numbering,
- `blocks`: ids and plain text, for agents,
- `json`: the full model.

## Editing precisely {#editing}

`PATCH /v2/documents/{id}/content` takes the revision and a list of operations:

| Operation | Effect |
| --- | --- |
| `replace_text` | Replace exact text inside paragraphs, keeping the formatting of the run it starts in. Scope it with `block`. |
| `replace` | Replace a block with Markdown; plain text keeps the paragraph's style and numbering. |
| `insert_after`, `insert_before` | Add Markdown next to a block, taking its neighbour's formatting. |
| `append` | Add Markdown at the end. |
| `delete` | Remove a block. |

```json
{ "revision": 3, "operations": [{ "op": "replace_text", "block": "p4", "find": "12 months", "replace": "24 months" }] }
```

Prefer `replace_text` for small changes: it keeps bold, fonts and colour exactly where they were.

## Templates {#templates}

A template is read and changed like a document. `GET /v2/templates/{id}/content` gives a version's text (Markdown with field markers and conditions, or `format=html` to show it); `GET /v2/templates/{id}/versions` lists every version with who published it and why.

To change a template, open its working draft: `POST /v2/templates/{id}/draft` returns a draft document made from the current version — one per template, shared, edited with every document tool (fields, conditions, co-editing, comments). It never appears among documents and cannot be sent. `POST /v2/templates/{id}/publish` with the draft's id (and a `note`) makes it the next version and removes the draft; until then the template does not change, and documents made earlier keep their version. `DELETE /v2/templates/{id}` moves a template to the archive (`GET /v2/templates?archived=only`), `POST /v2/templates/{id}/unarchive` brings it back, `DELETE /v2/templates/{id}?forever=true` deletes it from the archive for good (a person only); documents made from it stay either way. `POST /v2/templates/{id}/duplicate` makes a draft copy, `PATCH` with `name` renames it, `POST /v2/templates/bulk` (`archive`, `unarchive`, `duplicate`, `delete`) works on many at once.

## The document list {#list}

`GET /v2/documents` pages through documents and holds large workspaces: on 100 000 documents every filter, sort and group answers in tens of milliseconds.

- **Filters:** `stage` (`draft`, `approval`, `signing`, `completed`, `declined`, `voided`, `expired`, comma-separated), `template` (`none` for documents without one), `counterparty` (case-insensitive; `none` for documents without one), `created_from`/`created_to`, `updated_from`/`updated_to`, `q` — words to [search](#search), `archived` (`only` for the archive, `include` for both).
- **Field values:** `field.<key>=Moscow,Kazan` (any of, case-insensitive), `field.<key>.contains=…`, `field.<key>.gte=100000` and `.lte=` (numbers, amounts, dates as `YYYY-MM-DD`), `field.<key>.filled=true` and `.empty=true`. Up to 10 conditions.
- **Sorting:** `sort` = `created` (the default, newest first), `updated`, `name`, `status`, `counterparty` or `field.<key>`; a leading minus sorts descending: `sort=-field.amount`. Empty values always come last.
- **Columns:** `columns=amount,city` — each row then carries `columns` with those fields' values as shown.
- **Pages:** the next page is `cursor` = the answer's `next_cursor`; the cursor stays exact under equal values.

`GET /v2/documents/groups?by=counterparty` counts documents per group — `counterparty`, `template`, `stage`, `status` or `field.<key>` — with the same filters, largest first, the empty group last. Pass a group's `value` back as the list's filter to open it. `GET /v2/documents/columns` lists the fields the workspace's documents carry, most used first: the choices for columns, sorting and groups.

## Search {#search}

`GET /v2/search?q=…` searches documents and templates at once: names, text, field values (amounts, tax ids, dates, addresses), the counterparty, recipients' names and e-mails. Every word must match the start of a word ("contract" finds "contracts"); `"quoted words"` in that order; `-word` excludes; `a | b` either. A document changed a second ago is already found. `kind=document` or `template` narrows it.

Each hit carries `matched` (where: `name`, `details` — fields, people, counterparty — or `text`), a `snippet` with the found words between «», and for a document its status, stage and counterparty. Matches in the name and fields rank first. The same search filters the list: `GET /v2/documents?q=…` with any filters and sorting.

## Counterparty {#counterparty}

Every document has a `counterparty` — who it is with, to filter and group by. It is found by itself: from the field the template names as the counterparty field (`counterparty_field` in `PATCH /v2/templates/{id}`), else from a field whose label says so ("Counterparty", "Company name", "Client name"…), else the first outside signer. `source` says where it came from. `PUT /v2/documents/{id}/counterparty` with `name` sets it by hand, with `field` points it at a field, with `name: null` lets it be found again. When the field's value changes, the counterparty follows.

In the app it is shown and changed in two places. On a template's page, on the right, «Counterparty in documents» picks the field naming the other side: in a contract with both a customer's and a supplier's name, the automatic rule would take the first. The choice applies to documents already made from the template too, except those whose counterparty was set by hand. On a document's page the line under the title says who the counterparty is and where it comes from («from the field …», «set by hand», «found by a field's label», «the first outside signer»); «Change» picks a field of this document, names it by hand or goes back to automatic. The chosen field is in the document's `counterparty_field`, also while it is still empty.

## The archive and actions on many {#archive}

`POST /v2/documents/{id}/archive` takes a document off the list into the archive, `…/unarchive` brings it back; a document out for signature must be withdrawn first. The archive is the list with `archived=only`. A draft or an archived document can be deleted for good: `DELETE /v2/documents/{id}`; `POST /v2/documents/archive/empty` empties the whole archive.

`POST /v2/documents/bulk` with an `action` (`archive`, `unarchive`, `delete`) and up to 200 `ids` does one thing to many documents; each succeeds or fails on its own, one line per document in the answer.

Agents only archive: deleting for good and emptying the archive are refused for an agent's key (`agents_archive_only`); a person does it, in the app or with their own key.

## Ready to send {#readiness}

A draft read with `GET /v2/documents/{id}` carries `readiness`: `ready`, and the `issues` that stand between it and sending (a signer missing for a role, fields to fill, a review not finished), the same ones sending would refuse with.

## Exports {#exports}

- `GET /v2/documents/{id}/docx`: the document as Word, fields filled.
- `GET /v2/documents/{id}/pdf`: the signed PDF with its certificate once completed; before that, a preview with the current values.
- `GET /v2/documents/{id}/audit_trail`: every event with its hash.
