Plank help · updated 2026-11-20
Working with 1C over OData
The working rules for reading and writing a 1C database over its standard OData interface — what the integration user can and cannot do, how to recognise a document that already exists, how to create one safely, and the server limits that shape every script you write.
Agents: fetch the raw markdown of this page at /en/help/1c-odata-working-rules.md
Working with 1C over OData
Before any operation in 1C, read the rules. Read your section in
scripts/1c/universal-rules.md(rules for every Plank accountant) and inknowledge/1c-rules.md(this space's rules): «Общее» and the section of the operation — «ЭСФ входящие», «Выписки», «Реализация и исходящие ЭСФ», «Зарплата и кадры», «Контрагенты и договоры», «Склад» or «Налоги». A rule from there outranks the kit's default, but not the kit's §0 and not a write prohibition. When the two files disagree, the space's rule wins. No file or no section means no rules: work by the kit. Every write-capable kit script also prints these sections to stderr before its plan; that is a check, not a replacement for reading them before the first request to 1C.
This page is the mechanics of talking to a 1C database over its standard OData interface. It holds for any 1C database and any configuration.
- To get OData switched on and the credentials stored, read Connecting 1C first.
- For the Kazakhstan bank-statement and payroll workflow built on top of these rules, read Importing a bank statement into 1C.
- For sales documents and ЭАВР, read Sales realizations from customer invoices; for the monthly payroll chain, Monthly payroll accrual.
The scripts already exist. Every mechanic on this page ships as working, adaptable Python in the 1C starter kit — the access check, the catalog matching, the duplicate signature, the create-unposted-then-re-read discipline. Check for
scripts/1c/before you write any of it, and install the kit if it isn't there. Each section below names the file that implements it.Start from the kit; write your own script when the kit has no tool for the job. You may write any script you need — a kit command that is missing is not a reason to stop or to hand the work back. What a hand-written script must not do is skip the checks: the duplication incidents all came from writers that started without the dry-run gate, without the duplicate guard, and without the checks that make a re-run safe, and it is used against a live accounting base within the hour. Every bank-statement duplication incident so far has come from a hand-written writer, never from the kit. If the kit is wrong for your database, change
mapping.json, then change the kit's payload builders; if it has no command for what the person asked, write one — dry run first,_guard.pyagainst duplicates, one document at a time, re-read after. The same goes for catalog items (nomenclature, counterparties, contracts, price types): create and edit them with_odata.py'screate/update, after checking by identifier that the item does not already exist. Changing, posting, unposting, marking or deleting an existing document is different: it goes through the kit's verbs (correct-document.py,post-documents.py,mark-for-deletion.py), never through a script of your own around a raw PATCH or DELETE. Never answer the person with «the kit does not support this», never ask whether you may write a script, and never reach for the 1C web client because a command is missing — what you show in the chat is the change itself («было → станет»), not the script.When no kit covers the document at all — a hire, a dismissal, an accrual the accountant names, a document type nobody has scripted — do not stop: reason it out and write it — through the guarded path where it fits,
scripts/1c/odata/create-document.py(§7, «A document no kit covers»). In order of preference: a specialised kit; a posted precedent in THIS base, written by the accountant (--precedent); the Kazakhstan accounting rules in /help/1c-kz-accounting-rules.md (--without-precedent); and where the rules leave a choice, a question to the accountant. You decide every field; the script refuses what you did not decide.If you genuinely must write something new for documents in bulk, use
_guard.py— it is three lines and it is the whole difference between a safe script and the ones that have caused every duplication incident so far:
from _guard import Guard
guard = Guard(client, catalogs, run_key=make_run_key(account, period, declared_total))
guard.create("outgoing_payment_order", payload,
number=op.number, date=op.operation_date, amount=op.amount)
Guard.create stamps the anchor and verifies it survived, returns the existing document instead of creating a second one when that operation is already there, refuses if the index could not be read completely, and never posts. run_key must come from the source file's own values — account, period, declared totals, operation count — never from the clock, or every run looks unique and the guard protects nothing.
It also does two things you get without asking:
- A write log. Every document it creates, and every duplicate it prevents, is appended as one JSON line to
scripts/1c/write-log.jsonl. It never fails your import if it cannot be written, and it is the only record of what this workspace wrote to 1C that does not require reading the chat back. It is write-only: nothing consults it to decide whether to create, because a document the accountant deleted in 1C is still in the log and refusing to recreate it would be wrong. - A report.
guard.report(source="kaspi-06-2026.csv")returns the end-of-run markdown — counts, the run key, the created documents with theirRef_Keys, and the duplicates it prevented — derived from what the guard actually did. Pair it withwrite_reportto save it undersynced_data/1c/. Use this instead of writing your own summary: a narrated total is the thing that has been wrong, and this one cannot disagree with what was written.
The single most important thing on this page: find out what your integration user is actually allowed to do, before you design anything around it. A restricted user — read and create, but no edit, no delete, no posting — is what providers hand out by default, and it changes the whole shape of the work. If that's what you've got, say so early and get it widened (§3). If it can't be widened, assemble each document completely, verify it locally, and only then POST: you will not get a second attempt.
1. Addresses
The web-client address and the OData address are different addresses.
web client https://<host>/<database>/ru_RU/
OData https://<host>/<database>/odata/standard.odata
metadata https://<host>/<database>/odata/standard.odata/$metadata
A healthy endpoint returns XML or JSON, or challenges for a password. An HTML page means OData is not published — see the troubleshooting section of Connecting 1C, which covers the two independent switches and the "friendly error page" trap. That holds for the first answer only: if the same base already returned data earlier in the run and then answers with a page, the session was dropped or the host is under maintenance — the kit opens a fresh session and retries a read once, and otherwise reports odata-session-lost («хостинг ответил страницей вместо данных … повторите позже»). Do not go and check the publication in that case, and never resend a write: re-read to see whether it landed. And if the page comes back for one request while the same base answers everything else (the kit checks this with a one-row control read), the error is odata-request-page and names that request: read the document narrowly ($select) and find the field with python3 scripts/1c/odata/probe-document.py <entity-set> <Ref_Key> --mapping … --credentials … (read-only).
Credentials live in scripts/1c/credentials.json, or — once moved — the passwords live in the workspace's Доступы (the vault) and the file keeps the address, the user name and a reference: "vault": "<item>". Never copy the password into documentation, logs, reports, or source.
To move them: python3 scripts/1c/odata/move-login-to-vault.py (a dry run; add --apply, and --credentials <file> for any file other than credentials.json). It saves one item, reads it back, keeps the original as <file>.bak-<time> (mode 0600 — it still holds the password; delete it after a run works) and rewrites the file with "vault" in place of "password". A hand-written script that reads ["password"] from the file itself stops working, so the dry run lists those and --apply refuses until --accept-direct-readers. The kit reads the vault only by that reference — an item names no base, so it never picks «the one 1C item there is». A missing or withdrawn item is a refusal, never a quiet fall back to a password left in the file; PLANK_1C_USERNAME / PLANK_1C_PASSWORD still win, and PLANK_1C_VAULT_ITEM names the item for one run.
What things are called
Entity-set names are built from the object kind and the 1C name, and the shape is predictable:
Catalog_<Имя> справочник
Document_<Имя> документ
AccumulationRegister_<Имя> регистр накопления
AccumulationRegister_<Имя>_RecordType its movement records — the rows you read
InformationRegister_<Имя> регистр сведений
InformationRegister_<Имя>_RecordType its records
InformationRegister_<Имя>_SliceLast срез последних
Predefined fields are English; configuration attributes stay Russian. Half of a document's fields are in one language and half in the other, which catches people out constantly:
| OData field | 1C |
|---|---|
Ref_Key | ссылка — the GUID identity |
Description | Наименование |
Code | Код |
Parent_Key | Родитель |
IsFolder | ЭтоГруппа |
DeletionMark | ПометкаУдаления |
Recorder | Регистратор |
Period | Период |
Everything the configuration itself defines — НазначениеПлатежа, СуммаДокумента, Организация_Key — keeps its Russian name, spelled exactly as 1C spells it.
A reference is two fields, not one. A link to another object appears as <Имя>_Key holding the GUID, and as a navigation property <Имя> you can pull in with $expand. Filter on and write <Имя>_Key; use $expand=<Имя> when you want the referenced record's own fields in the same read.
The name of that reference field differs per object, and guessing it is the single most expensive mistake on this page — see §4.
2. Check access before you do anything else
Implemented by scripts/1c/odata/check-access.py (starter kit).
Run the access check before reading a single business record:
python3 scripts/1c/odata/check-access.py
A healthy result is HTTP 200, application/xml for $metadata, and hundreds of entity sets — a typical accounting configuration publishes several hundred. A handful of sets means the OData composition (Администрирование → Состав стандартного интерфейса OData) exposes almost nothing and needs widening before you go further.
Zero sets with a 200 is a failure, and the check says so. A base can answer $metadata with a well-formed, empty container: OData is published and the composition inside 1C lists nothing. That is fixed in 1C by an administrator, not on the web server.
The check also tells you whether this base filters on the server — «Server-side filtering: works», «REFUSED» or «UNRELIABLE» — after three read-only requests against the counterparty catalog. On a base that refuses, the kit reads catalogs whole once per run and matches locally, so runs are slower. Tell the accountant that is a property of her base, and do not retry $filter queries hoping for a different answer (§4).
2.5 Establish which company before anything else
An accounting practice does not have "a 1C base". It has one per client — one surveyed practice has 17 — and a single credentials.json plus a single mapping.json describe exactly one of them.
Nothing about a wrong pairing looks wrong. The connection succeeds. The catalogs read. The arithmetic balances. The reconciliation comes back clean. And the documents are in another company's books.
Three things have to agree before any write, and none of them implies the others:
- the base the credentials reach;
- the organisation
mapping.jsonpins; - the source document — this statement, this ЭСФ, this request.
_identity.py checks 1 against 2 (verify_target) and gives you assert_source_account for 3. Both entrypoints call them before planning anything, and both failures are errors, not warnings.
A base reached through a hosting portal
Some databases have no address of their own: the host publishes them behind a portal that logs you in and then redirects to a per-tenant OData root. Configure that as a portal block in credentials.json — instead of base_url, never alongside it. Two written-down answers to «which database» means only one of them gets checked.
publication is what the check compares the landing address against, and it is the whole safety of the arrangement: a portal that logs you in successfully and drops you in a different tenant answers every subsequent request with HTTP 200.
Do not write a bespoke connector for such a base. On 2026-08-28 one lived in a single workspace as a private script, and a search for six documents across "all OData connections" silently skipped that base, reported «they are nowhere», and came one guard away from marking six posted documents in an unrelated company's base for deletion because the numbers matched. A transport nothing can enumerate turns a negative result into a lie.
One base can hold two organisations with almost the same name
A base can hold two organisations whose names differ only by punctuation or word order — the same trading name registered twice, or a migration that left both. Picking by eye is a coin flip, so the pinned ref_key decides and the name is the assertion: if the reference resolves to a different name than mapping.json claims, one of the two is stale and the run stops. Do not assume the reference wins because it is more precise — a stale reference is exactly how a run lands in last quarter's client.
When a base holds more than one organisation, say so in the report even on success. The accountant's journal may be scoped to the other one, and "I don't see anything" is then about their filter, not your write.
The source document has to be this company's
verify_arithmetic proves a statement file is internally consistent. It proves that just as well when the file belongs to somebody else — so it is not a company check. The statement's own РасчСчет must equal mapping.organization_account.iban or the run refuses.
The same rule generalises: for an incoming ЭСФ, the organisation named in the ЭСФ picks the base — never the address that happens to be in a shared credentials file. See Importing incoming ЭСФ into 1C.
Working across several companies
Give each company its own workspace, with its own scripts/1c/credentials.json and scripts/1c/mapping.json. If one workspace must reach several bases, keep a register of them — company, БИН/ИИН, base URL, organisation Ref_Key, settlement accounts — and resolve the target from the source document against that register. What you must never do is carry a Ref_Key from one base into another (§11), or reuse a mapping "because the companies are similar".
Each base gets its own mapping file (mapping.json, client-b-mapping.json, …) and every run names one with --mapping. When the workspace's 1C credentials live on the platform rather than in credentials.json, that file is also what says which connection to use: add "connection_label": "<name>" at the top level, matching the label the connection is registered under. Omit it and the run uses the connection named default — right for a workspace with one base. While credentials.json still exists it may carry "label" too, and if the two disagree the run refuses and names both files: guessing which one is current is exactly how documents land in the wrong company's books.
Write down which connection, and which credentials, each base belongs with — a run now refuses without. Both keys go in the mapping file, because credentials.json is deleted when a workspace moves its credentials to the platform, and a pairing recorded there would vanish exactly when it starts to matter.
| In the mapping | What it decides | What happens without it |
|---|---|---|
"connection_label": "<name>" | Which registered connection the platform resolves — on a migrated workspace this is the only thing that picks the base | On a workspace with several bases, the run refuses. Without it every mapping resolves to the one default connection, so --mapping chooses what to write and nothing about where |
"credentials_file": "<name>.json" | Which credentials file this base is reached with, checked before anything connects | With several credentials files present, a run with no --credentials refuses rather than taking credentials.json because of what it is called |
Two mappings naming the same connection_label are refused too: they would share one connection and one duplicate index, and no run could tell which base was meant.
"Several bases" counts credentials files as well as mapping files. A practice keeping one mapping.json beside six credentials files is a multi-base workspace, and it used to read as a single-base one — which is how a run could take credentials.json by its name and write one company's documents into another company's base with every check passing. Two byte-identical credentials files are one credential and are not a choice.
Never repoint credentials.json at a different base to switch clients. Hand-written scripts in a workspace read that path directly and usually carry one client's identifiers, so a single edit moves all of them at once, silently. Keep one credentials file per base, and name it — in the mapping, or with --credentials.
python3 scripts/1c/odata/bases.py # every base, its connection, its credentials, its profile. Connects to nothing.
That listing marks ОТКАЗ on exactly the lines a run will stop on — never on a condition this workspace does not meet. A workspace with one base and one credentials file meets none of them and is unchanged.
3. Establish what the integration user is allowed to do
Do this at setup time, not when a write fails. Rights vary per user, and the restricted shape below is what a provider grants unless someone asks for more:
| Operation | Restricted user | Full role |
|---|---|---|
Read (GET) | Yes | Yes |
Create documents (POST) | Yes | Yes |
Modify a document (PATCH / PUT) | No | Yes |
Delete / mark for deletion (DELETE) | No — answers Нарушение прав доступа | Yes |
Post a document (the Post() action) | No | Yes |
| Create tabular-section rows via their own entity set | No | No — a configuration limit, not a rights one |
Ask for the full role. When a user is connecting 1C, tell them to request read, create, edit, delete / mark for deletion, and posting (проведение) from whoever administers the database — in the same message as the OData publication request, since it's the same person and the same wait. A read-and-create user looks adequate right up to the first wrong draft, at which point nothing can be corrected, removed, or finished without a human opening 1C. Widening the role later means going back to the provider; narrowing it is trivial. The exact wording to send is in Connecting 1C.
A refused write does not look like a refusal
This is the trap, and it has cost a real import three hours. When the user cannot modify an object, 1C does not answer 403. It answers:
HTTP 500
Не удалось записать "Платежное поручение (исходящее) 00000000672 от 22.06.2026"!
That reads like a complaint about your payload, and it is routinely read that way — as "1C's OData cannot modify documents", reported to the user as a platform limitation. It is not one. The identical PATCH succeeds unchanged under a user who has modify rights.
So when a write is refused: the payload and the rights matrix are equally likely, and you cannot tell them apart from the response. Check rights first, because it is the cheaper test — ask who administers the base, or try the same request as a user who has «Изменение». Never conclude anything about 1C or about OData in general from one 500.
And whatever the cause: do not respond by creating a replacement document and leaving the original in place. See §10.
The kit checks this itself on the first document of each type. Right after creating it, create_and_verify writes a few of that document's own values back unchanged. If 1C refuses with a rights error, that one document stays (it is reported as written), no further document of that type is created in the run, and the refusal carries the sentence to send the accountant: «В этой базе я могу создавать документы, но не могу их исправлять…». Only after she agrees, re-run with PLANK_1C_ACCEPT_CREATE_ONLY=1. A write-back refused without the word «прав» does not stop the run — on some document types every flag refuses a rewrite on a document that edits fine — it only prints a warning.
If the role can't be widened, the restricted column is your working reality, and two things follow:
- Preflight is everything. A wrong document cannot be repaired by the script that made it. Build the complete payload, validate it locally, then write once. Never create a nearly-right document intending to patch it.
- Correction becomes a human protocol — see §10.
Posting is yours to do — after the dry run, not instead of it (ADR 0024, PB788). Create documents unposted, show the draft, then post it yourself: posting, unposting, marking, unmarking and deleting are done on your own initiative, without waiting for a person. The order of every write is the same: a dry run showing «было → станет» for each field, then --apply --confirm <code>. The agent shows «было/станет» in the chat and writes itself, without waiting for a person. The code only guards against the document changing between the dry run and the write; it does not check who passes it.
When you post, use the kit's entrypoint rather than calling the action yourself — it posts and then proves the posting, which is the part that keeps going wrong:
python3 scripts/1c/odata/post-documents.py Document_<Name> --number 58 --number 59
python3 scripts/1c/odata/post-documents.py Document_<Name> --number 58 --apply --confirm <code>
It reads each document, posts it, looks for a register movement recorded against it, and calls it posted only if it finds one. A document that posted nothing gets its flag cleared, so it stops claiming an accounting effect it never had. One document's failure does not stop the others: a document 1C refused, or one that moved nothing and has been unposted again, is named in the report and left unposted, and the next document is still posted and proven — the exit code is non-zero if any failed. The batch stops only when a document's state is unknown (the base answered something unreadable) or when a false «posted» flag could not be cleared, because then the base no longer says what is true. A document that depends on a failed one is answered by 1C itself; the script does not guess an order. Measured 2026-10-14: one contribution basis list that moved nothing used to strand 36 independent documents behind it.
Give it every document in ONE call, of every type — one --ref Document_<Name>:<Ref_Key> per document, after the documents an import just created:
python3 scripts/1c/odata/post-documents.py --ref Document_<A>:<Ref_Key> --ref Document_<B>:<Ref_Key> --apply --confirm <code>
One call asks the registers once for the whole batch whether anything is already posted, and after each Post() stops at the first register that holds a movement for it; a call per type repeats all of that. Measured shape, 18 documents of three types on a base of 92 registers: about 4 200 requests before 2026-10-13, about 1 400 split per type now, about 600 in one call. diagnose-posting.py is not a pre-check — run it only on a document post-documents.py reported not posted.
On a base that refuses $filter on its registers, add --sweep. There, verifying one document means reading every register whole — measured at over ten minutes each, which for 256 documents is a control nobody can run, and the thing people reach for instead is a hand-written Post() loop with no verification at all. With --sweep documents are posted and verified on their own until one passes — that one proves posting works here — and a document that fails before it is named and left unposted rather than stopping the batch; the rest are posted and then every register's Recorder column is read once. Same question asked about every document, two passes instead of two hundred. What it gives up is proving each document before the next is posted, so it names each one that moved nothing and clears its flag. An incomplete sweep answers nothing and says so: a register that refused leaves GUIDs out, and a missing GUID cannot be told from «never posted».
The underlying action is Post() on the document, and note that no PostingModeOperational is passed:
POST <base>/Document_<Name>(guid'<Ref_Key>')/Post()
Writing Posted=true as a field is not posting. It does not run the posting algorithm and produces no register movements, so the document ends up looking posted while the accounting behind it never moved. Unpost() is the matching reversal.
And neither the HTTP status nor the Posted flag proves that Post() worked. Post() answers HTTP 200 with an empty body whether or not it posted anything, and Post?PostingModeOperational=true has been measured answering 200 while leaving Posted false — a no-op reported as success. Worse, a document can come back Posted=true and still have produced no register movements at all: in one production base three receipts sat like that for nine days while a fourth, posted by the accountant in the 1C client, had four movements — same base, same user, same document type, identical field-fill profiles.
When a document posts nothing, it is almost always the document, not the channel. OData Post() on a valid document produces exactly the same register movements as posting in the 1C client — measured A/B on one document: UI post → 4 movements, OData Unpost() → 0, OData Post() → the same 4. What OData will not tell you is why it refused. 1C validates on posting and the client prints the reason in full («Не совпадают сумма документа и ее расшифровка», «The "Договор" is required on line 1 of "Расшифровка платежа"», «Укажите основной банковский счет в реквизитах организации»); over OData that entire refusal arrives as HTTP 200 with an empty body and Posted left true.
So when the check below reports not-posted, open that document in the 1C client and press «Провести». The messages it prints are the fix list. Common causes: a tabular row that exists but is empty (СуммаПлатежа = 0, an all-zero reference GUID), a header total that does not equal the sum of its rows, and organisation-level settings the document depends on.
So the only evidence that a document posted is a register movement recorded against it. After posting, check for one:
python3 scripts/1c/odata/verify-posting.py Document_<Name> <Ref_Key>
python3 scripts/1c/odata/verify-posting.py Document_<Name> --number 58
On a workspace with more than one base, add --mapping <file> --credentials <file> — the same pair import-*.py and post-documents.py take; every script that reaches a base accepts both, and without them the kit refuses to guess which base you meant.
It reads every published register carrying Recorder and reports posted, not-posted or inconclusive — the last when a register refused the question, which is not the same as answering zero. To ask the same question about every document at once — which is what you want the first time, because the flag was the success criterion for a long time and nobody knows how many documents are affected:
python3 scripts/1c/odata/audit-posting.py Document_<Name> --since 2026-07-01
That reads each register once rather than once per document, and names every Posted=true document that moved nothing. If any register could not be read completely it names nobody and says so: a document missing from a partial index is indistinguishable from one that never posted, and sending an accountant to repost documents that are fine is worse than saying nothing. A document that is Posted=true with no movements cannot be fixed over OData: it needs a repost in the 1C client, one document at a time, with this check re-run after each.
4. Reading data
Implemented by scripts/1c/odata/_odata.py — iter_all() is the portable pattern below.
$filter on dates works. This page used to say it was unreliable, and the cause was ours. Until 2026-09-22 the kit built its query string with urlencode, which encodes a space as +; 1C's $filter parser will not read that and answers HTTP 500 Операция не разрешена в предложении "ГДЕ" — the same sentence a base that genuinely refuses to filter gives. So every filtered request the kit sent looked like a base limitation, and the limitation was written down here. Measured on one live base, the same filter in the same minute:
$filter=Date%20ge%20datetime'2026-01-01T00:00:00' → HTTP 200
$filter=Date+ge+datetime'2026-01-01T00:00:00' → HTTP 500
If you build a URL by hand, percent-encode the spaces. Before concluding that a publication cannot filter, look at your own query string for a +.
What one live base (four legal entities, 2.6 million documents) accepted and refused, measured: accepted — Date, ДатаОборота, DeletionMark, Организация_Key, Контрагент_Key, Ref_Key eq guid'…', and $filter together with $select. Refused — an or chain of twenty Ref_Key values (HTTP 500, AUTOORDER; two values pass, so issue one request per value rather than hunting for the limit), and Комментарий ne '' («нельзя сравнивать поля неограниченной длины»). Lies — substringof('x', Комментарий) answers HTTP 200 with zero rows for documents that demonstrably exist. A 200 is not evidence there; never build a duplicate guard on it.
A COMPOSITE reference needs its type. A field that can hold a row of several different tables — a register's Recorder, a catalog's Owner, ДокументОснование, a subconto column — cannot be compared to a loose guid, because the guid does not say which table it came from. 1C answers HTTP 500 «Неверные параметры в операции сравнения. Нельзя сравнивать…». Name the type and it answers at once:
Recorder eq guid'02e3c4fa-…' → HTTP 500
Recorder eq cast(guid'02e3c4fa-…', 'Document_СчетФактураПолученный') → HTTP 200 in 0.50s
Owner eq cast(guid'…', 'Catalog_Организации') → HTTP 200
Do not read that 500 as "this base will not filter". It is a fixable query, and reading it as a refusal is how a run falls back to scanning a register whole — measured at eighteen minutes where the cast answers in half a second. The kit builds it with ref_equals() and reports it as its own error class. Build it that way EVERYWHERE — a calibration or existence probe that sends a bare guid fails the same way and quietly falls back to a full read.
Ask an accounting register by its record table. 1C publishes AccountingRegister_X_RecordType (the rows) and AccountingRegister_X (a virtual view it computes on demand). The second does not refuse — it goes silent: measured HTTP 524 after 125.05s for $top=5, against 0.64s for the record table. Read the name from $metadata; never try both and see which answers.
A refusal is still not an empty result — reading it as "no matching rows" makes every existing document look absent, which is how a duplicate gets created (§6). The kit's client recognises the refusal and answers with guidance instead of a bare HTTP 500, and it never degrades a refused filter into [] or silently re-reads the set unfiltered.
$orderby may be silently ignored. Never assume returned order.
When a filter really is refused, the portable pattern is: page with $top / $skip, then filter locally.
GET <base>/Document_<Name>?$top=1000&$skip=0&$format=json
read_all() / iter_all() take a filter= and page under it, and read_all also returns whether the read was COMPLETE — check that before deciding anything exists or does not.
To narrow a read by FIELD, ask the base which fields there are. client.scalar_properties(entity_set) lists every <Property> the object publishes; its tabular sections are <NavigationProperty> and come back from client.tabular_sections(entity_set). Two rules go with it, and both have cost a run:
- Never hand-write a
$select. One name this configuration does not publish and the base answersHTTP 400 Сегмент пути X не найден— for the whole request, not for that field. - Pass the complete list, not the fields you think you need. Code that treats an absent field as "this base does not publish it" cannot tell that apart from "we did not ask for it". Taken from
$metadata, published means asked-for means present, and the absence keeps meaning what it meant.
$metadata is big — 5.7 MB on one live base — so the client reads it once and keeps it for the life of the run.
The query options this interface supports
1C implements OData v3.0, and the standard interface has existed since platform 8.3.5. These all work:
$filter $select $orderby $top $skip $expand $count $format=json
A GUID comparison has its own literal syntax — a bare GUID will not do:
$filter=Ref_Key eq guid'<guid>'
$filter=Номенклатура_Key eq guid'<guid>'
$count with a filter is the cheap existence check, and it is the one to reach for. It answers with a number instead of rows, so "is this item used anywhere in this register" costs one small request rather than a full read:
GET <base>/<EntitySet>/$count?$filter=<Field>_Key eq guid'<guid>'
The difference is not academic. One register on a real base held 31.8 million rows — per-item $count answers in one request each, and reading it whole is simply not something you can do. So: filter and count per item; never scan a register to answer a question about one item.
When you genuinely do need a whole catalog, read it once, with a stable ordering, into a local file, and do every subsequent question locally — not one read per question.
Page with a stable sort, or pages overlap
Because $orderby may be ignored, paging a large set with $top/$skip and no ordering at all can return overlapping pages: the same Ref_Key arrives on two pages, and anything you total comes out inflated. This has happened on a real base, and the numbers were irreconcilable until the duplicates were found.
Do both, because neither alone is enough:
- ask for a stable sort —
$orderby=Ref_Key— so a server that honours it pages correctly; - dedupe by
Ref_Keyanyway, because a server that ignores it will not say so.
And treat a first unsorted pass as unreliable: redo it rather than patching the totals. This is the same discipline as read_all() returning whether the read was complete — a total derived from a read you cannot vouch for is worse than no total, because it gets quoted.
«Сегмент пути X не найден» is a wrong field NAME, not a forbidden capability
The standard OData interface does support $filter, including by Ref_Key and by a dimension's <Dim>_Key guid. Catalog_Номенклатура?$filter=Ref_Key eq guid'…' returns 200; so does AccumulationRegister_РеализацияТМЗ_RecordType?$filter=Номенклатура_Key eq guid'…'; and …/$count?$filter=… is the cheap per-item usage check. What varies is the name of the reference/dimension field, per object — a stock register may call its nomenclature dimension Товар_Key where another object uses Номенклатура_Key.
So when a filter comes back HTTP 400 {"odata.error":{"code":"6","message":{"value":"Сегмент пути Номенклатура_Key не найден!"}}}, that means this object has no field with that name — the OData path parser could not resolve one segment — not that filtering is banned. Read the exact field name from that object's own $metadata (the kit's client.reference_fields(entity_set) lists the *_Key fields it actually has) and re-issue the filter with it. The kit does this for you: a $filter that names a missing field is turned into an error that names the object's real reference fields, never into a "filtering is unavailable" fallback.
Never conclude that a platform capability is unavailable or forbidden from a single error. On a live pilot base this exact 400 was generalised into «1С запрещает фильтрацию по Ref_Key» and the run fell back to reading a multi-million-row register whole. A negative capability claim needs a positive control test: reproduce it on a known-good case first — filtering the catalog by Ref_Key works on the very same base — and read the error text. A wrong field name and a genuine server limit are different problems with different fixes.
An object that isn't in $metadata may simply not be published
1C exposes objects to its OData interface one checkbox at a time, in «Публикация OData». An object nobody published is absent from $metadata entirely: no error, no empty collection, nothing that distinguishes it from an object this configuration does not have.
So "the base does not use X" is a conclusion you cannot reach from $metadata alone. On 2026-08-04 a base reported 687 entity sets and no ЭАВР object, which read as "this configuration does not do ЭАВР". Someone ticked the box; the count became 692 and 1,106 ЭАВР became readable that had been there all along — after most of a morning spent building an explanation for their absence.
When a document type you have concrete evidence for — a screenshot, an accountant's description, a field referencing it — is missing from $metadata:
- Count the entity sets and record the number.
- Say plainly that the object is not published, rather than that it does not exist.
- Ask for it to be published, then re-read
$metadataand compare the count.
Not published and not used need different answers, and only one of them is yours to give.
Memory: stream a big read, and write the result as you go
A sandbox has 1.5-3.5 GB for everything in it — the gateway, the agent and every script of every chat running in that space at once. A script that holds 240 000 documents in memory holds about 2.4 GB: on its own it can stop every other chat in the space. On one workspace in October 2026 this happened four times in twelve days, and the biggest file of the last one was 97 MB of JSON written by a hand-made script that read a whole register and saved it as one value.
Keep a script you write under about 400 MB. In practice:
- Read big sets page by page —
client.iter_pages(entity_set, select=…, filter=…)yields one page at a time, sends exactly the requestsread_allsends, and its.completeafterwards means whatread_all's second value means (None if you stopped early). Reduce each page — a count, a sum, a set ofRef_Key— and let it go. - Ask for the columns you use (
select=) and narrow on the server (filter=) when the answer allows it. A whole document is ~4.5 KB of JSON; three fields are a few dozen bytes. - Write results as JSON Lines while you read — one object per line, appended page by page — never one
json.dumpof a list at the end. A file you write a line at a time is never one string in memory, and a reader can stream it back the same way. - Never save a register or a whole document set to one JSON file "to look at later". Save the totals and the rows that matter; re-read 1C for the rest.
- A dict per document costs ~10 KB in Python. Before a read, multiply: 50 000 documents ≈ 500 MB. If the product is over the budget, the script must stream.
The kit's own readers already work this way (the posting proof, the history cache): a 240 000-document history read now peaks at about 0.8 GB instead of 2.4 GB.
5. Matching records in catalogs
Implemented by scripts/1c/odata/_catalogs.py, which returns a resolution rather than a record — so "nothing found" and "two found" stay distinguishable instead of collapsing into a guess.
Match on an identifier, never on a name that merely looks similar.
| Looking for | Match on |
|---|---|
| Counterparty | Catalog_Контрагенты.ИдентификационныйКодЛичности — the BIN/IIN |
| Bank account | Catalog_БанковскиеСчета.НомерСчета — the exact IBAN |
| Individual | Catalog_ФизическиеЛица.ИдентификационныйКодЛичности — the IIN |
Names are for confirming a match, not making one.
A catalog code (Code) is not an identifier either: measured on a live base, 27 codes in one nomenclature folder each belonged to two unrelated cards. Key anything you keep by Ref_Key, and when a person has to find a card in 1C, give them the code and the name.
Two rules that prevent the most common wrong-record bugs:
- Check the owner. Having found a bank account by IBAN, assert
БанковскийСчет.Owner == Контрагент.Ref_Key. An IBAN that belongs to a different counterparty is a red flag, not a match. - A stored "main account" does not outrank the account named in the source document. If the counterparty card says one IBAN and the document you're importing says another, the document wins. Silently substituting the main account produces a document that looks right and is wrong.
When an identifier resolves to two records — the same IIN on two individuals, say — do not pick one at random. Use the reference that earlier, verified documents already used.
When an identifier resolves to nothing, stop and ask. Do not auto-create a counterparty, a bank account, or a contract to make a script complete: catalogs are shared, permanent, and expensive to clean up.
A group is not a record
1C catalogs are trees, and a folder carries the same Description field as the elements inside it. «Физические лица» is routinely both — a group and an element — in the same Catalog_Контрагенты. Tell them apart by IsFolder.
A folder in a Контрагент field writes cleanly through OData and then will not post, because a group is not a counterparty. Printing both rows and noticing the difference is not enough — the exclusion has to be in the lookup, or the folder gets used anyway.
_catalogs.py now excludes IsFolder and DeletionMark from every match, and says which it excluded: "matched a group, not a record" and "not found" need different fixes, and the misleading one wastes the user's time.
6. Recognising a document that already exists
Implemented by scripts/1c/odata/_signature.py.
Getting this wrong creates duplicates in live accounting, so it earns its own section.
A document number alone is not an identity. External numbers repeat across dates and years — the same bank document number will legitimately appear in several periods. Matching on the number alone will make you skip an operation that was never imported.
The internal 1C Number is not an identity either. It can repeat across periods and numbering sequences.
Use a composite signature:
1C document type + external document number + operation date + amount
and corroborate with direction, counterparty identifier, IBAN, purpose text, and payment code where available. Ref_Key is the technical identity once you have the record; the signature is how you decide whether to create one at all.
Idempotency is the requirement. Running an import twice must not create a second document. Every run should be able to report existing versus to create before it writes anything.
The signature alone is not enough
The composite signature reads fields the configuration owns. A document type that does not carry НомерВходящегоДокумента, or a database that stores it empty, produces documents the index cannot see — and an index that silently skips what it cannot identify is worse than no index, because it reports a large signature count and inspires confidence it has not earned.
This is not hypothetical. A guard built this way has already produced a full set of duplicate documents in a live accounting base: it reported thousands of loaded signatures while recognising none of the documents it had just written, so every re-run saw every operation as absent and created it again.
So anchor identity in a field you write yourself. The kit puts [plank:doc=…;run=…] in every document's Комментарий — doc keyed on the signature, run keyed on the source file's account, period, declared totals and operation count. Комментарий is set on every document type this kit writes and re-read after every write, which is exactly what makes it usable as an identity when the numbering fields are not.
And prove the guard, don't assume it:
- Count what the index could not sign, not just what it could. A non-zero count inside the period being imported is a blind spot, and the only honest response is to refuse to write. (Outside the period it does not matter — a 2019 document cannot duplicate a June 2026 line, and failing closed over it would make the control useless.)
- A failure to read the index is an error, never a warning. Routine per-line questions train an operator to accept warnings wholesale; a warning meaning "the guard is blind" then goes through with them.
- Refuse to write a document type the index does not cover. Extending a classifier without extending the index silently removes protection for the new type.
- Scope all of that to the document types the run actually creates. A gap in a type the statement never mentions cannot produce a duplicate, and plenty of databases publish no acquiring documents at all — refusing an ordinary statement over one of those is a lockout, not a control. Report the gap, then continue. This matters more than it sounds: a guard that blocks legitimate work is a guard people route around by hand-writing a script with no guard at all.
- After the first document is written, re-read it and test the guard against it. Nothing you can read beforehand tells you whether the guard recognises your own output. If it does not, stop with one document created rather than discovering it on the next run.
Signable is not matchable
Counting what the index could not sign catches the document that has no identity. It does not catch the more common case: a document that has a perfectly good identity under a key nothing you are importing will ever produce.
A row a person typed into 1C by hand carries neither the bank's document number nor your anchor. НомерВходящегоДокумента is empty, or holds the internal 1C number, or holds whatever the accountant considered the "number" that day. The index signs it happily and counts it as covered — and then no statement line can ever collide with it, because the statement's key is built from the bank's number. The guard reports full coverage over the exact documents it is blind to, and the import creates a second copy of each.
This has happened in a live base: a run reported "16 884 indexed, 0 unsignable inside the statement period" and still duplicated a hand-entered transfer, because the hand-entered one had no bank number on it. "0 unsignable" was true and meant nothing.
So report matchable coverage, not indexed count:
- Over the account and period being imported, list every document that carries no anchor of yours and whose signature matches no row in the source. Those are the candidate twins, and they are few enough to print: number, date, amount, counterparty.
- Cross-check that list against the source by
(account, date, amount, direction)— the fields both sides always have, whatever the numbering does. A hit there is a probable existing document, and it is a question for the accountant, not a decision: the alternative to asking is creating the duplicate. - Say the number out loud in the dry run. "N documents on this account in this period that this import cannot recognise" is the honest headline; "0 unsignable" is the one that got trusted.
Never iterate on a write script against a live base. Editing a script and re-running --apply to see if the fix worked is how one mistake becomes a duplicate of every line. Dry-run between every edit.
7. Creating a document
Implemented by scripts/1c/odata/_documents.py (the payload discipline) and _runner.py (the dry-run gate).
Always dry-run first, then apply:
python3 scripts/1c/odata/<import-script>.py # dry run — writes nothing
python3 scripts/1c/odata/<import-script>.py --apply # writes
If you built the payload by reading an existing document as a template, strip the server-owned fields before POST:
odata.metadataRef_KeyDataVersionNumber- any navigation URLs
1C assigns a fresh Ref_Key and its own internal number. Leaving these in is a common source of confusing failures.
Create documents unposted:
Posted = false
DeletionMark = false
and leave a comment saying the document was created by an import and needs review. A reviewer should never have to guess where a draft came from.
Enum values must come from $metadata, not from intuition. A configuration exposes a fixed set of EnumType values and a plausible-sounding name that isn't in the list fails the write. Read the enum from $metadata and use exactly what's there.
Two things are refused at create, because 1C only refuses them at post
A document 1C accepts and then cannot post is worse than a rejected one: the create looks like success, the damage surfaces later, and the document sits in a live base looking like work that got done. Both of these are now refused before anything is written, whether you go through Guard.create or create_and_verify directly:
- «Расшифровка платежа» missing or empty against a non-zero header amount. On a payment order that document can never post. A zero header needs no breakdown and is not refused.
- A breakdown row carrying no «Статья движения денежных средств». This one does post, and is then wrong in the cash-flow report — which no arithmetic check downstream catches. An all-zeroes GUID counts as absent, because that is what 1C returns for an unset reference rather than null.
If this base renames the cash-flow section, pass the names the writer uses — otherwise the check reads a field nobody wrote:
from _documents import cash_flow_config
guard = Guard(client, catalogs, run_key=..., organisation_ref=...,
cash_flow=cash_flow_config(mapping))
Those three names live in mapping.json under cash_flow_articles and differ per 1C configuration. Omit the argument and the defaults apply; on a base that renames them the refusal says so explicitly and lists the sections it did find.
create-document.py applies the same check with the same names (core 1.94.0): its dry run refuses an empty article with cash-flow-breakdown, and so does the write. Some configurations keep the article in the document header instead of the rows (УНФ card payments: «ПоложениеСтатьи» = «ВШапке», article in «Статья_Key»). Declare that shape in cash_flow_articles: article_position (the «in the header» value) and header_article_field (the header field). Set both or neither. Only a document stating that position is then checked on its header. Without the keys, such a document with empty rows is refused, and the message names the two keys.
The message names the field and what to resolve. Do not work around either one by dropping the breakdown, zeroing the header, or inventing an article Ref_Key: resolve the article against Catalog_СтатьиДвиженияДенежныхСредств, reading what this base's own earlier documents of the same kind used, and do not create a new article — the catalog is shared. If you genuinely cannot resolve it, that is a stop-and-ask, exactly like an unresolved counterparty (§5).
Never write an amount in words yourself
scripts/1c/odata/_words.py does it, and it is unit-tested:
from _words import amount_in_words, format_amount
amount_in_words("2341502.75") # 'Два миллиона триста сорок одна тысяча пятьсот два тенге 75 тиын'
format_amount("2341502.75") # '2 341 502,75'
Russian numeral declension has exactly one correct rendering and it is the most reliable thing on a payment order to get wrong. «тысяча» is feminine, so it is одна тысяча and две тысячи, never «один тысяча». «миллион» is masculine and takes the genitive singular after 2-4: два миллиона, never «два миллион». And 11-14 take the plural however the last digit reads: 111 000 is «сто одиннадцать тысяч», because 111 % 100 == 11. Both currency words are invariant — «тенге» and «тиын» never decline.
If a function produces the exact answer, do not produce it in a sentence instead.
A document no kit covers
scripts/1c/odata/create-document.py writes ONE unposted draft of any document type, through the same gate as the kits. Two modes:
- By precedent (
--precedent <Ref_Key>) — a POSTED, not deletion-marked document of this base written by the accountant (a document any Plank kit wrote is refused as a precedent: copying our own output is how a wrong guess becomes «the base's habit»). The script copies it and applies your decisions. - By the rules (
--without-precedent) — when the base holds no such document. The payload is only what you decided, checked against$metadata: field names and types, required fields, enum members, every*_Keyresolving to a live element, and an account of the chart of accounts being neither a folder nor closed to postings. Decide each field from /help/1c-kz-accounting-rules.md; the report is marked «по правилам, без образца в базе — проверьте перед проведением».
--fields decisions.json holds your decisions: header (field → value), sections (section → rows), same_as_precedent (fields you looked at and chose to keep). Every identity-like field — date, number, any amount, counterparty, person/employee, contract, basis document, period, comment — must be set or listed in same_as_precedent, or the run refuses: a precedent's counterparty copied silently onto a new document is the defect this exists to stop. --identity Date,Контрагент_Key (at least two fields, one a date) is the duplicate question, asked over --window-days; a match refuses and names the document.
python3 scripts/1c/odata/create-document.py --entity-set Document_X --precedent <Ref_Key> \
--fields decisions.json --identity Date,Контрагент_Key # dry run: diff + confirmation code
python3 scripts/1c/odata/create-document.py ... --apply --confirm <code> # one unposted draft, re-read
Exit codes: 0 written (or a clean dry run), 1 refused, 3 written but 1C stored something other than what was sent — show the accountant, never patch around it and never write a second one — 4 held by warnings. It never posts: posting is a separate step after the draft is shown — post-documents.py, which you run yourself and which also proves the movements. Then compare the проводки with the rule you decided by; a by-rules document has no precedent to have been checked against, so that comparison is the check. A posted document is the normal state of an accepted one, not an anomaly.
A wrong unposted draft this script wrote is corrected in place with correct-document.py (§10; anchor and Ref_Key from find-runs.py) — not by marking it for deletion and creating another. The exception is a wrong document TYPE (an outgoing payment order that should be a payment ордер, say): that cannot be fixed in place, so you mark the original yourself (§10) and create the right document through the importer. When --identity finds a twin, it is corrected in place with correct-document.py — ours or hand-entered, posted or not (§10). Either way nothing is created a second time.
One base, one writer at a time
Two chats of one space writing to the same 1C base at once is what makes 1C:Fresh refuse writes for memory (odata-memory-limit) and crash the accountant's open web client — measured on a live base on 2026-11-20. So the kit's core queues writes per base: every write takes the base's lock, and a whole --apply of the core's verbs holds it from its first write to its end. Reads and dry runs never wait.
- Big batches — one per base at a time. Mass corrections are better run in the evening, when nobody works in the base.
base-busymeans another chat's write held the base past the ceiling (10 minutes;write_wait_secondsinmapping.json). That write was not sent. Tell the accountant the base is busy with another write and run it again later — do not work around the queue with a script of your own that writes past it.- While it waits, a script says «база занята другой записью агента, жду» — that is the queue, not a hang.
odata-memory-limiton a write is now a growing pause and a bounded resend of a PATCH or a posting; a create is never resent. The pause is kept with the base's lock, so the next chat that takes the base waits it out too («пауза после отказа 1С:Fresh по памяти») — even when the chat that met the refusal was stopped during its pause. After the last refusal the report names the document and the rest of the batch, as before.write-lock-unavailable(the lock file could not be opened) andwrite-wait-invalid(PLANK_1C_WRITE_WAIT/write_wait_secondsis not a number of seconds 0–3600) refuse the write with nothing sent; reads and dry runs still work. Fix the setting rather than writing around the queue.
8. Tabular sections
You cannot create tabular-section rows through a separate entity set — 1C answers Создание строк табличной части напрямую не поддерживается.
Rows must be included inside the parent document in the same POST. So a document with rows has to be fully assembled — every reference resolved, every amount final — before you write anything. If the rows reference other documents, those have to exist first, which forces the ordering: create the referenced documents, verify them, then create the parent with the row references filled in.
9. After writing, re-read
Implemented by create_and_verify() in scripts/1c/odata/_documents.py, and by scripts/1c/bank-statement/reconcile.py for the independent index.
Never treat a 2xx as proof of a correct document. Re-read what 1C actually stored and reconcile it against your source:
- every source line found, exactly once;
- zero missing lines, zero unexpected duplicates;
- totals agree;
- every new document unposted and not marked for deletion;
- references (accounts, counterparties, rows) are the ones you intended.
Build the verification index independently from the import — re-reading from 1C and comparing against the original file catches errors that re-using the import's own in-memory state cannot.
10. Fixing a wrong document
Fix it in place. Never fork it.
A correction that cannot be made in place is not automatically a new document. This is the single most expensive rule on this page. An assistant that cannot PATCH (§3) and answers each correction by creating a corrected copy — leaving the wrong one alive — turns one document needing a fix into two needing a decision, and does it once per correction. The user is then asked to clean up by hand, and that cleanup is its own hazard (§12).
Run scripts/1c/odata/correct-document.py — dry-run by default, one --set Field=value per change:
# 1. Dry run. It prints the anchor the document carries.
python3 scripts/1c/odata/correct-document.py --entity-set Document_ПлатежноеПоручениеИсходящее \
--ref <guid> --set НазначениеПлатежа="Оплата по счету 42"
# 2. Apply, naming that anchor back.
python3 scripts/1c/odata/correct-document.py --entity-set Document_ПлатежноеПоручениеИсходящее \
--ref <guid> --set НазначениеПлатежа="Оплата по счету 42" \
--anchor doc=<12hex>,run=<12hex> --apply
Values are sent as text, with one exception: exactly true or false is sent as a JSON boolean, because a Boolean property such as СуммаВключаетНДС refuses the string "true". True, 1 or да stay text — nothing else is guessed (core 1.71.0).
--apply requires --anchor, and that is the point. Taking the anchor out of the document you are about to change makes the ownership test compare a value to itself, which reduces it to "carries some anchor" — and a «Копировать» copy of one of our drafts carries one. Naming it is how you state which document you believe you are editing.
It calls _documents.correct(). Any document and any field can be corrected (ADR 0024, PB788) — including one this kit did not write, a posted one and one marked for deletion. What used to refuse is a warning in the dry run, to read and decide on: no import anchor (the accountant's record or a hand-written script's), a posted document (it is unposted, patched and posted again, then the register movements are checked), a document marked for deletion, another organisation, and a change to a field the anchor is derived from. What still refuses before sending anything:
- the anchor is not the one you named. An anchor is not proof of ownership:
parse_anchoraccepts any well-formed token anywhere in a free-text comment, and 1C's «Копировать» duplicates «Комментарий» verbatim — so an accountant's own copy of an imported document carries a valid one. The caller has to say which document it believes it is editing.
Posting, unposting, marking, unmarking and deleting are done on your initiative too — the agent shows «было/станет» in the chat and writes itself, without waiting for a person. Do it with the kit's commands, never a script of your own: re-read each document first and check it is the one meant (organisation, number, date, amount), change one document at a time, re-read it after, and report the «old → new» table. Do not send a person into 1C to click through a list you could have done. (PB191 was an agent doing this with no dry run and no checks; the dry run, the read-back and the journal are what make it right.)
- a tabular section would lose rows. A section replaces the stored one, so changing one row means sending every row you want kept; sending one row deletes the rest. Refused unless you pass
--allow-row-removal. - the document changed between the check and the write (
DataVersionmoved). Somebody is editing it in 1C right now and their change wins.
Only Ref_Key and DataVersion cannot be named — 1C owns them. Posting and the deletion mark go through post-documents.py and mark-for-deletion.py, not --set. Changing Date, СуммаДокумента or the incoming-document number is a warning: the anchor is derived from those, so the corrected document's identity no longer describes it and the next import of the same source can duplicate it — say so in the report.
After the PATCH it re-reads and checks that the fields it named actually changed — 1C accepts a PATCH naming a field its own logic then overwrites, and reporting that as corrected is how «статья ДДС заполнена» gets said about an empty field. If some fields landed and others did not, it says so: "nothing was corrected" about a half-changed document sends you looking in the wrong place.
ODataClient.update() is the raw PATCH underneath and is not guarded — no dry run, no journal, no organisation check, no read-back. Never call it directly.
When you genuinely cannot edit
Preferred. The wrong document is marked for deletion — by you, with mark-for-deletion.py (below) → you confirm it is marked and no longer counts in the reconciliation → you create the correct document → you reconcile again.
If the user explicitly accepts a temporary duplicate, and only then — this is a decision they make per document, not a mode you switch into: create the replacement with a comment marking it as a corrected replacement, leave the old document unposted, report both internal numbers, and state plainly that the reconciliation will show an expected duplicate until the user removes the old one. Only the replacement may be posted.
Never: create a replacement because a write failed, without asking; post a replacement without confirming the original is unposted; delete without showing the dry run's reference warnings in the chat; hide the fact that a duplicate was created; or call the correction finished without an explicit "old → new" table.
Deleting is a mark, and merging duplicates is not an OData operation
POST and PATCH work; a hard DELETE was refused. Measured on a pilot base: creating and editing both went through — including setting DeletionMark by PATCH — and DELETE came back 500 Нарушение прав доступа!. Treat that as the normal state and never build an import or a correction that depends on DELETE; deleting is its own explicit step, below.
That is not only a rights matter. Deleting in 1C is normally two steps: set DeletionMark = true, after which the platform's own «Удаление помеченных объектов» checks what still references the record and refuses to break those links. DELETE over OData skips that check, so the kit does it for you and shows what it found.
You mark, unmark and delete on your own initiative (ADR 0024, PB788) — the agent shows «было/станет» in the chat and writes itself, without waiting for a person. Use the kit's commands for this, not a script of your own. They take a list — written by find-runs.py --run <key> --manifest list.json for an import run, or by you from what you read — re-read every document against it (organisation, number, date, amount), dry-run by default, and write nothing without --apply --confirm <code>, the code the dry run printed:
python3 scripts/1c/odata/post-documents.py --unpost-manifest list.json # unpost; proven by the registers
python3 scripts/1c/odata/mark-for-deletion.py --manifest list.json # mark (a posted one is unposted first)
python3 scripts/1c/odata/mark-for-deletion.py --manifest list.json --delete # mark, then DELETE
python3 scripts/1c/odata/mark-for-deletion.py --manifest list.json --unmark # clear the deletion mark
python3 scripts/1c/odata/mark-for-deletion.py --rollback <journal> # undo a run
Each goes one document at a time with a read-back and keeps a journal beside the list. What used to refuse is a warning in the dry run: a posted document (it is unposted with Unpost() and read back, then marked), another organisation, a list anchor the document no longer carries, and — with --delete — everything that references the document: other documents by type, number, date and field, and register movements. After a DELETE those references point at nothing, so read them before you confirm. What still refuses: a list for another organisation than this mapping's, a document whose number, date or amount is no longer the list's, and a --confirm that is not the dry run's code for exactly this list and flags.
Before each DELETE the journal (<manifest>.mark-and-delete-<run>-journal.json) gets the whole document as read — header and tabular sections — and what references it. --rollback <journal> (dry run, then --apply --confirm <code>) undoes a run: a mark is removed, an unmark re-marked, and a deleted document is created again from the journal — unposted, with a new Ref_Key and number; the report prints old → new and «ссылки на старый остаются битыми: …». A rollback does not re-post; post-documents.py does that.
If a DELETE answers Нарушение прав доступа, this user has no delete right — the common case on hosted bases. The run stops, the documents stay marked, and the output names them for «Удаление помеченных объектов» (Администрирование → Удаление помеченных объектов), which a user with that right runs. Do not look for another route.
Merging duplicates is not an OData operation at all. A duplicate counterparty is referenced from documents and from register records all over the base, so a merge means rewriting every one of those references — which is exactly what 1C's own «Поиск и удаление дублей» and «Замена ссылок» do, atomically and with the reference check. OData can prepare the decision — find the candidates, show what each one is used by and how often, propose which survives — and a person performs the merge in 1C. Do not attempt it by patching references one at a time: a half-finished merge is worse than the duplicate, because the two records are then both live and both wrong. The procedure, how to build the list the customer approves, and whether a merged duplicate is marked or deleted outright are in Working in the 1C web client.
12. Cleaning up an import run
When documents have to be removed — by you with the commands in §10, or by the accountant in 1C — what is selected decides whether the right ones go.
Never give them a filter on the comment prose. mapping.json's comment is the same string on every run — «Создано из банковской выписки…» — so a filter on it selects every import that base has ever received, including the corrected one you just wrote. An instruction like that deletes a month of good work along with the duplicates it replaced, and nobody notices until the numbers are missing.
Filter on the run anchor instead. Every document this kit writes carries [plank:doc=…;run=…] in its comment, and the run= key identifies one import of one source file:
python3 scripts/1c/odata/find-runs.py # every run in this base
python3 scripts/1c/odata/find-runs.py --run 3f9c1a4b77de # one run, document by document
It is read-only. It prints the exact string to paste into the 1C journal's search box and the Ref_Key of every document in that run, so the selection can be checked before and after. Documents written by a hand-written script carry no anchor, cannot be listed, and cannot be cleaned up selectively — which is one more reason to adapt the kit rather than write your own writer.
To unpost, mark, unmark or delete a run, add --manifest list.json to the --run call: it writes that run's documents as the list the commands in §10 «Deleting is a mark» act on, and nothing else.
11. What does not travel between databases
This is why the kit keeps every deployment-specific value in scripts/1c/mapping.json — adapting to a new database should be a config edit, not a code edit.
Be explicit in your scripts about what is portable and what isn't.
- Hard-coded
Ref_Keyvalues — template documents, tax items, VAT rates, accounting policy references. These are meaningless in another database and worth re-checking periodically even in their own. Prefer resolving them at runtime: find the template by operation type and the most recent verified document, the tax by name/code, the VAT rate by its value. If you must pin them, keep them in a config JSON, not scattered through the code. - Local accounting policy — how a particular business classifies own-funds transfers, which counterparty stands in for a payment aggregator, how personal amounts are separated. These are decisions of one organisation, confirmed by that user. Record them in the workspace's own notes and never carry them into another database automatically.
- Case-specific scripts. A script written for one period, with that period's dates and references baked in, is a record of what was done — not a reusable importer. Name it so that's obvious, and never run it against a new period without adapting it and re-running the dry run.
Decoding an error
The same status code means different things here, and several of these have been read wrong on a live base at real cost. Look the answer up before concluding anything from it:
| What comes back | What it actually means | What to do |
|---|---|---|
400 «Сегмент пути X не найден» | This object has no field named X. A wrong field NAME — not a forbidden capability, and $filter is fine | Read the real name from that object's $metadata, re-issue (§4) |
401 | The 1C user lacks rights on that object. Per-object, not global | Ask for that object to be opened; do not conclude the connection or the user is dead |
403 + «Ошибка разделения доступа» | A file base is held exclusively right now. Not a rights problem, and nothing is misconfigured | Wait, or ask whoever has it open to close 1C |
500 «Нарушение прав доступа!» on DELETE | No delete right | Use DeletionMark instead (§10); the documents stay marked, and a user with that right removes them through «Удаление помеченных объектов» |
500 «Не удалось записать …» | 1C ran the write and refused it — rights or payload, indistinguishable from the response | §3. Never read it as "OData cannot modify documents" |
500 «…запрещена в предложении ГДЕ» | This server refuses that filter | Page and filter locally (§4). It is not an empty result |
500 «Тип не определен …» | One unservable row at a fixed offset in that set | Skip the page, mark the read incomplete, carry on |
base-busy | Another chat's write held this base past the ceiling. Nothing was sent | Tell the accountant the base is busy; run again later (§7, «One base, one writer at a time») |
write-lock-unavailable / write-wait-invalid | The base's write lock could not be opened / the wait ceiling is not a number. Nothing was sent | Fix /tmp access or the setting; never write past the queue (§7) |
500 «Ошибка датаакселератора. Недостаточно памяти» on a write (odata-memory-limit) | 1C:Fresh's server is out of memory — usually two writes at once | Already paused and resent where safe; run the rest later, one batch per base |
| HTML page, any status | OData is not published here — or, if the base already answered with data this run, the session dropped | §1 |
401 is per-object, and it is the one that produces confident wrong reports. On the pilot base InformationRegister_ЦеныНоменклатуры answered 200 while two other price registers answered 401 — same user, same run, same base. One 401 says nothing about the next object, and "there is no access to this base" is not a conclusion it supports.
The rule behind the whole table: a single error on one object never proves a capability is missing. Before writing down that something "is not supported", "is forbidden" or "is unavailable", reproduce it on a known-good control — filtering the catalog by Ref_Key works — and read the error text. A negative capability claim needs a positive control test. Skipping that is how one register's wrong field name became «1С запрещает фильтрацию» and a multi-million-row scan.
Official references
1C's own documentation for the standard OData interface, plus the filter-syntax reference worth keeping open. Note that 1C implements OData v3.0, and the standard interface has existed since platform 8.3.5 — documentation written against OData v4 does not apply.
- Стандартный интерфейс OData — ITS
- Доступ к данным через OData — 1cfresh
- Правила формирования условия отбора — filter syntax