Closed states — keep a finished document final
Declare closedStates on an object so a paid invoice or an approved order, and its lines, can no longer be changed by any caller, and learn what that does to actions, automation, approvals and the lock read.
A paid invoice, an approved order or a posted journal entry is finished: nobody
should edit it, delete it, or change its lines. An object says when its records
reach that point with closedStates (ADR-0162). The platform then refuses
every caller's change to such a record and to its master_detail lines, at
every door, whatever grants the caller holds. The app's own elevated automation
is the way to reopen or move a closed document on.
Declare it
The showcase's invoice is closed once it is paid. Its declaration
(examples/app-showcase/src/data/objects/invoice.object.ts), with the fields
this page needs:
import { ObjectSchema, Field } from '@objectstack/spec/data';
export const Invoice = ObjectSchema.create({
name: 'showcase_invoice',
sharingModel: 'public_read_write',
label: 'Invoice',
fields: {
number: Field.text({ label: 'Number', required: true }),
status: Field.select({
label: 'Status',
required: true,
options: [
{ label: 'Draft', value: 'draft', default: true },
{ label: 'Sent', value: 'sent' },
{ label: 'Paid', value: 'paid' },
{ label: 'Void', value: 'void' },
],
}),
},
// A paid invoice and its lines are closed to every caller's change.
closedStates: {
status: ['paid'],
},
});
export const InvoiceLine = ObjectSchema.create({
name: 'showcase_invoice_line',
sharingModel: 'controlled_by_parent',
label: 'Invoice Line',
fields: {
// The line is closed because it is a master_detail line of a closed invoice.
invoice: Field.masterDetail('showcase_invoice', {
label: 'Invoice',
required: true,
deleteBehavior: 'cascade',
}),
description: Field.text({ label: 'Description' }),
},
});The key is a map from a field of the object to the list of that field's values
that close a record. A record is closed when any listed field holds one of
its listed values. Two fields are the ordinary case: an approval mirrors its
outcome into one field and the business status lives in another, as in
closedStates: { status: ['paid', 'void'], approval_status: ['approved'] }.
Nothing is stored for it. There is no closed flag, no lock row and no backfill: every judgement reads the record's state as the store holds it when the write reaches it. Whatever sets the state closes the record, whether that is an approval's status mirror, a payment service, an action, or a caller's own edit of the state field where the app leaves that field writable.
The key is optional, and an object without it behaves exactly as before. It has
no tie to a state_machine rule: the rule says which moves of the field are
legal, and closedStates says when the record stops accepting a caller's writes.
The line object declares nothing to be closed with its master. It may declare
closedStates of its own, for a line that closes on its own state.
What a field must be
Each field the key names is a stored, single-value select field of the object
that declares its options inline. Each listed value is one of those options, a
list is not empty, and it lists a value once. These are refused where the object
is authored, at defineStack, at a raw parse of the object, and at the metadata
save and publish door, each with a message located at the entry:
- a key that names no field of the object;
- a field that is not a
select, or amultiple: trueselect; - a select whose options come from a
picklist, since the listed values cannot be checked against it; - an empty list, a value that is not an option of the field, or a value listed twice.
The same rules keep a declaration honest after it is written. A field the key
names cannot be removed, renamed, retyped or made multi-value, and an option it
lists cannot be removed, while the declaration names them: take the entry out of
closedStates first. On an object a package owns, a tenant's customization may
add closed values of its own but cannot shorten the package's list, and another
package's extension that redeclares a named field so that it breaks the
declaration has that redeclaration refused (the rest of the extension still
applies).
What a closed record holds
The unit is the record itself and every row, of any object, that points at it
through a master_detail field:
- every
master_detailedge counts, so a junction row under two masters is a line of both, and is closed when either master is; - one level only: a line's own lines are not in the unit;
- not in the unit: rows that reference the record through a
lookup, and the record's satellites in objects of their own (comments, attachments, shares, history), which keep their own rules. A file field on the record is a field of the record and is closed with it.
What is refused, and for whom
| Write | On a closed record | On a line of a closed record |
|---|---|---|
| Create | not judged: there is no stored state yet | refused |
| Update | refused, whichever fields it carries, the state field included | refused |
| Delete | refused | refused |
| Move a line to another master | — | refused when either end is closed |
- An update is judged by the keys it carries. One that carries no field writes nothing and is not refused; any other is a change, even where its values equal the stored ones.
- The state field is frozen with the rest. A caller cannot reopen a closed record by editing its state.
- A write that names many rows is refused whole. A predicate update or delete, or a many-row create of lines, that reaches one closed record or one line of one is refused before any row is written.
- The write that closes a record lands whole, with whatever other fields it carries: the record was open when it began. The next write is refused. Inside one unit of work order matters, so a later write in the same transaction meets a closed record (below).
- Creating a record already in a closed state is not this lock's question.
Whether an invoice may be born
paidis the state field's own rule, such asinitialStateson itsstate_machine. - What cannot be judged is refused, never taken for open: a line write that names its master by something that is not one id, a read of the state that fails, and a predicate write on a store that cannot run the line check whose matched rows pass the engine's per-row ceiling.
Every caller is bound. The data API and its batch forms, a page or grid in
the console, an API key, an AI agent acting for a person, and automation that
acts as the caller are all refused, and so is a write that carries no context at
all. No grant opens a closed record: not a permission set, not
modifyAllRecords, not administrator access.
A system context is not bound. The platform's own services write a closed record where their job needs it (the roll-up recompute of a summary field, the approval status mirror), and so does the app's own elevated automation:
- a
type: 'script'action, both its inlinebodyand the handler registered for it withregisterAction, which runs through the same elevated context as the body (Authorization inside an action); - a flow declared
runAs: 'system'; - a hook declared
runAs: 'system'(Elevation).
That automation is how a closed document is reopened, voided or refunded (The way out).
Where it runs. The lock judges a write after the object permission and row access gates have answered and before the before-phase hooks run. A caller whom the object permission or the row's access refuses gets the answer an open record gives, so the lock tells nobody anything a refusal would not. One refusal is not the lock's: a line create or move that names a master the caller cannot read is refused by the reference check, in its own words, exactly as under an open master.
Writes that are not a caller's change follow their own context. A delete
elsewhere that clears a lookup on a closed record clears exactly that field,
and putting a deleted record back from the recycle bin restores it as it stood,
closed or not, with its lines. Restoring a line under a closed master that is not
part of the same entry is refused to a caller.
The refusal
Every refusal is 409 RECORD_LOCKED, the code the pending-approval lock already
answers with, so a client that handles one handles both. The sentence a person
reads arrives as the error's userMessage, in the caller's language. It names
the record by its object's label and by the title the caller would be served
under its own field permissions, never by an id, an API name or the state's
value. A line write names the master by its object's label alone, and a write
that matched many rows uses the label form.
The refusal carries nothing that says which lock refused. A page that wants to
word the reason before the save asks the lock read, which answers
lockReason: "closed_state" or "approval". A refusal of a write that could not
be judged carries the developer's sentence instead, addressed to whoever scoped
the write.
What an action button does on a closed document
An action button still works on a closed document. A type: 'script'
action's body, or the handler registered for it, runs as system whoever clicks
the button, so it changes a closed document as it would an open one. So does a
flow or a hook declared to run as system. The lock does not stop such a change
and adds no notice or record of its own; the audit the app already keeps is where
it is traced.
visible and disabled on an action decide what the console shows, and the
server does not read them. An action that must not run on a closed document
checks the state in its body:
if (ctx.recordLoadDenied === true) throw new Error('Record not available');
if (ctx.record.status === 'paid') throw new Error('A paid invoice cannot be re-sent.');An action that updates declaratively (operation: 'update' with a patch, no
body) writes as the caller, so on a closed document it is refused like an edit.
The built-in Edit and Delete buttons are the app's to shape. The showcase greys
Edit and hides Delete on a paid invoice with its object's userActions
predicates (edit: { disabledWhen: ... }, delete: { visibleWhen: ... }), so
the record page does not offer a write the server will refuse.
The way out
An app that lets users reopen, void or refund a closed document ships the action
for it and decides who may run it (requiredPermissions,
Permissions and visibility). The
action needs a script body or a registered handler, or a flow that runs as
system: a declarative update is the caller's own write and is refused. For the
invoice above, a reopen action could read:
import { defineAction } from '@objectstack/spec/ui';
export const ReopenInvoiceAction = defineAction({
name: 'showcase_reopen_invoice',
label: 'Reopen',
objectName: 'showcase_invoice',
type: 'script',
body: {
language: 'js',
source:
"if (ctx.recordLoadDenied === true) throw new Error('Record not available');" +
"await ctx.api.object('showcase_invoice').update({ id: ctx.record.id, status: 'sent' });" +
"return { ok: true };",
capabilities: ['api.write'],
},
visible: "has(record.status) && record.status == 'paid'",
locations: ['record'],
refreshAfter: true,
});The body runs elevated, so it bypasses row- and field-level security too: re-establish any rule about who may reopen inside it, as Authorization inside an action describes.
Automation that acts as the caller
Automation that acts as the caller is refused on a closed record. A flow
that runs as the user, which is a flow's default, and a hook whose ctx.api
runs as the user or inherits the context of the write that fired it, which is a
hook's default, write as the caller. A flow that stamps a field after the
document closed, or an after-phase hook that writes back to the record once the
closing write has landed, fails with RECORD_LOCKED. Either the stamp belongs
in the write that closes the document, where a beforeUpdate hook can add it,
or the flow or hook is declared to run as system.
The steps after an approval decision. On an object that closes on its
approval's outcome, the outcome is written when the approval is over, and until
then the document reads pending. The nodes that follow a decision in the
approval's own flow write the record through the approval's hold, as the
approval's own run, and need no elevation for it. What meets a closed document
is what comes after the outcome: a node that runs on after a pause that follows
the last step, and any other flow or hook that acts as the caller, such as a
record-change flow with runAs: 'user' that the outcome sets off. Declare such a
flow to run as system, or move the write ahead of the pause. The approvals guide
says when the outcome lands
(When the outcome lands on the record)
and what passes the hold (The document is held for the whole approval).
Every approval on an object that declares closedStates holds its document
between its steps, whichever field it mirrors onto and whatever its nodes'
lockRecord says, and opens only on a host that runs a job service. A flow
that relied on callers editing the document between two steps moves that edit
into the revise window of a send-back, ahead of the submission, or into the
flow itself (the hold).
Code that calls the engine with no context is bound like a caller. A programmatic write that passes no execution context reaches the engine with no identity, and no identity is not an elevated identity: it is refused as a caller's write is. Server code that means to write a closed document as the platform passes a system context.
A closed document keeps its owner
Change Owner is an edit, and is refused on a closed record and on a line of
one. The many-record form moves the open records and lists each closed one among
its failures with RECORD_LOCKED. The hand-over of a banned user's work
(Handing over a banned user's work)
leaves the closed records with that user and counts them among its failures. An
app that reassigns closed documents ships an action for it.
Line edits go before the closing write
Once the write that closes a document has landed, a later write in the same unit
of work meets a closed record. So when line edits and the closing write travel in
one save, the lines are written first and the header that closes the document
last. The console's master-detail form follows this order: when a save sets a
value the header object lists in closedStates, it writes every line first and
the header last, in one transaction, so a save that changes lines and closes the
document lands whole.
A create has no such order. A caller cannot create a document that is already closed together with its lines, because each line would be added under a closed master. The caller creates it open, adds the lines, and closes it last. A load of finished documents runs as system, as the showcase's seed loads its paid invoices and their lines.
What the lock read tells a reader who may not see the state field
The data layer's lock read, GET /api/v1/data/:object/:id/lock and
POST /api/v1/data/:object/locks (client.data.getRecordLock,
client.data.getRecordLocks), answers whether a record is locked and by which
lock: lockReason: "closed_state" or "approval", and lockSource: "record" or
"master" for a line of a closed record (Record locks).
A page reads it to grey an edit before the save rather than after.
The lock read tells every reader of a document that it is closed. Every
caller who can read the record is answered, whether or not it may write the
record and whether or not its field permissions let it read the state field.
A user who may read a record but not its state field is still told that it is
closed, though not by which field or which value. So an app that hides a state
field so that some readers do not learn the outcome, such as a portal user who
must not see an internal decision, does not declare closedStates on that
field: closed or not is one bit of it that every reader learns.
The approvals-family read (GET /api/v1/approvals/records/:object/:id/lock)
answers for a pending approval only and says nothing of a closed state.
Publishing a declaration closes existing records at once
Closed is read off the stored row, so the publish that adds a value to
closedStates closes every stored record already in that state, from that
moment. There is no grace period and no backfill to wait for. Removing a value
opens those records again. Before publishing, find the records the declaration
will close and the automation that still writes them as the caller.
An object that already runs approvals meets the approvals guide's conditions before, or together with, its closed values: a save or publish of an object or a flow that would leave a gap is refused, and so is the first request of an approval that reaches one at run time (Refused where the approval is authored).
A new approval of a closed document, and what an abandoned approval leaves
A new approval reopens a document that is closed on its approval field. The
approval status mirror writes in a system context, so the pending of a new
approval's first request takes a document off a closed approved. What that
field and the approval's flow owe for it is the approvals guide's
(What the mirror field owes,
What the flow owes); without it
the approval is refused when it opens. An approval none of whose steps mirrors
onto a field the object closes on moves nothing on that field, so it does not open
a closed document
(An approval that does not mirror onto the closing field).
An abandoned approval does not close it again. An approval that is recalled,
overridden by an administrator, released from a dead run, or that ends between
two steps never writes a closed value of the field. The document reads
recalled where the field declares that value and does not close on it, and
otherwise the value it held at submit, the field's default, or empty, each passed
over where it is a closed value
(What an abandoned approval leaves).
So an approval of a decided document that is then recalled costs the document
its decision, also when it was started by mistake: it is approved again before it
reads approved again, and listing recalled among the closed values closes
nothing. An author who does not want a decided document sent for approval again
gates the flow's start on the state, or closes on a business state the mirror
does not write.
A parent is not deleted while a closed document hangs below it
A delete whose cascade would remove a closed record, or a line of one, is refused whole before anything is removed, with or without a transaction. The refusal names the record the caller asked to delete and the kind of document in the way, not which document: a user who cannot see it asks someone who can. This differs from a pending approval, where deleting the record lands and cancels the request: a closed record is not deleted by a caller at all, directly or by a cascade. A system context's delete is not bound.
See also
- Decision record: ADR-0162 (closed states, the one lock read, and the approvals on a declaring object).
- Approvals on a declaring object: Approvals guide.
- The lock read: Data API, Record locks.
- What a system context changes everywhere: System context.
- Reference: Object (
closedStates).