Skip to main content

Open, Edit, and Submit a Protected Order Document

Let a customer edit quantities on an order. Product names and SKUs are visible but read-only. The customer can explicitly remove an order line. Another user's copy, an older edit, or a retry must not silently overwrite the saved order.

Here, a document is an editable business-data view with a protected snapshot. It is not a PDF or Word file. This guide uses the optional SecureDocumentReferenceModule in the Java source preview, without the Blob module.

Evidence status: The downloadable Java/SQLite terminal example was compiled and executed on 2026-11-01. It includes an application-owned order service and nine checked outcomes. It uses JDBC and explicit SQL, not generated Q/E APIs. Versions and execution receipt remain separate from published-package availability.

Run the complete example​

You need Java 21, Maven, and a source checkout containing the preview APIs. SQLite runs in the process; you do not need a database server or a web framework.

git clone https://github.com/teaql/teaql-java.git
cd teaql-java
git checkout af59bf4ee6f003f509ce8cc42a5d96bb5dcdb8c3
mvn -pl examples/round-trip-reference-runtime -am install -DskipTests
export TEAQL_JAVA_SOURCE="$PWD"
cd ..

Download these three files into one directory, then enter it:

bash run.sh

Keep Java 21 java and javac on PATH. If your source build uses a custom Maven cache or executable, set TEAQL_MAVEN_REPO or MAVEN_BIN consistently. The demo creates its own temporary SQLite database and removes it on exit.

The application prints these receipts, without printing document tokens:

PASS open: business ID, editable body and protected token; no raw row IDs
PASS projection: read-only field changes and implicit row removal rejected
PASS actor: another user cannot submit Alice's document
PASS rollback: failed child write leaves order, quantity and receipt unchanged
PASS accept: quantity 2 to 5; revision 1 to 2; one durable receipt
PASS retry: identical command returns first result; changed payload conflicts
PASS stale: a new command against the old document cannot overwrite the saved edit
PASS remove: refreshed document and explicit removedRefs delete only the selected row
PASS revocation: current permission denies both new open and committed-command replay

Separate module setup from order rules​

The two endpoint calls below are small because a domain service implements the order's editing contract. Installing the module does not automatically create that service.

Once for the applicationFor this order-editing feature
Install SecureDocumentReferenceModule with a governed reference provider, server-held keys, service/environment identity, and current authorization.Implement/register a ContextBoundDocumentService that loads the permitted order and its complete editable item relation.
Derive the trusted principal from authenticated server context.Declare visible fields, writable quantity, row references and explicit-removal rules in the protected snapshot.
Define token lifetime and persistent key configuration.Recheck permission and versions, validate the submitted body, and save order/line changes plus the command receipt in one SQL transaction.
Map sanitized errors into your transport and keep credentials out of logs.Expose open and submit operations and return the next editable document.

The example's context(subject) creates the module and a trusted context. Its registration ends with actual runtime APIs:

return new DefaultUserContext(runtime)
.withTrustedReferencePrincipal(
new TrustedReferencePrincipal("demo-auth", subject, "Customer", 7))
.withContextBoundDocumentService(new SqliteOrderDocumentService(url));

subject and customer 7 come from the demo fixture. In an HTTP application, resolve them from authentication and your ownership model, not from client JSON. The demo generates a random server key for one execution. A deployed service needs a persistent key provider; restarting with a new random key would invalidate outstanding documents. The complete assembly code is in the download.

Open the edit page by business ID​

The open endpoint chooses the aggregate type, editing purpose and lifetime. ctx is the trusted current UserContext; it already has the domain service:

ContextualDocument opened = ctx.openDocument(new OpenRequest(
"Order", "ORDER-1001", "edit-order-items", Duration.ofMinutes(15)));

The service checks current permission and order ownership, loads the order and items, and issues the protected snapshot. Return the document's three public parts: businessId(), documentToken(), and body(). Their JSON shape is:

{
"businessId": "ORDER-1001",
"documentToken": "<opaque server-issued token>",
"body": {
"orderNumber": "ORDER-1001",
"items": [
{"ref": "item:0", "productName": "Blue cup", "sku": "CUP-1", "quantity": 2},
{"ref": "item:1", "productName": "Red cup", "sku": "CUP-2", "quantity": 3}
]
}
}

This is a schematic serialization; the executable does not log its token. The client keeps the token unchanged while editing the body. item:0 is a row alias inside this particular document, not a global database ID or an independent permission grant. The protected snapshot connects it to the real row, its version, and the allowed edit surface.

Edit the body and submit it​

For the first edit, change the Blue cup quantity to 5. Keep the Red cup and all displayed read-only fields unchanged. The submitted body is:

{
"orderNumber": "ORDER-1001",
"items": [
{"ref": "item:0", "productName": "Blue cup", "sku": "CUP-1", "quantity": 5},
{"ref": "item:1", "productName": "Red cup", "sku": "CUP-2", "quantity": 3}
],
"removedRefs": []
}

The client sends that body, the original business ID and token, and a new commandId, such as edit-1. The submit endpoint constructs:

AcceptedDocument accepted = ctx.acceptDocument(new AcceptRequest(
"Order", "edit-order-items",
new SubmittedDocument(businessId, documentToken, commandId, editedBody)));

The four variables in SubmittedDocument are decoded request data; editedBody is a Map<String, Object>. Aggregate type and purpose are fixed by the server endpoint. The runnable example's edit and request helpers build this exact DTO shape without needing HTTP.

For this service, submission is a full issued item projection, not a dirty-field patch. Unknown fields, forged row aliases, read-only field changes, and missing rows without explicit removal are rejected. The service rechecks current permission and versions before writing.

The successful edit moves the order from revision 1 to 2 and quantity 2 to 5, with one durable command receipt. Use accepted.document() as the next editable document; return its business ID, new token and body. The acceptance metadata includes internal changed-entity identities, so do not blindly serialize the entire AcceptedDocument as the public editing response.

Retry the same submission, or start a new edit​

These are different operations:

SituationClient actionExample result
The response was lost; you do not know whether the save succeeded.Retry the exact original request, including the token, body and commandId.While its token is valid and current permission permits, the service returns the first result without another write.
The user changes the quantity again after a successful save.Use the returned document and a new command ID.A new edit is validated against the new snapshot.
An old document is submitted with a new command ID after another save.Reload the current document and reconcile the intended change.DOCUMENT_REVISION_CONFLICT; no overwrite.
The same command ID is reused with different request content.Correct the client's request identity handling.DOCUMENT_COMMAND_CONFLICT; no new write.

A token does not preserve old permissions. In the demo, revoking Alice's SQL permission prevents both opening a new document and replaying a committed command. Token expiry also remains an authentication boundary; the replay result above is not an unlimited recovery promise after expiry.

Remove a line explicitly​

Use the latest returned document. Remove the selected row from items and add that row's currently issued ref to removedRefs:

{
"orderNumber": "ORDER-1001",
"items": [
{"ref": "item:0", "productName": "Blue cup", "sku": "CUP-1", "quantity": 5}
],
"removedRefs": ["item:1"]
}

Submit with a new command ID, such as remove-1. This example permits removal because it issued a complete relation with that mutation enabled. Simply leaving a row out is an error. Do not infer removal permission or relation completeness from arbitrary client JSON. This fixture's row aliases are shown for clarity; read the aliases returned in the current document in a real client.

Know which failure can be retried​

The example installs a temporary SQLite trigger that aborts a child update after the root update has begun. The order version stays 1, the original quantity stays 2, and no command receipt is inserted. After removing the trigger, the same request succeeds. The domain service owns that transaction; token cryptography alone cannot make independent SQL writes atomic.

ErrorMeaning in this exampleNext step
DOCUMENT_PROJECTION_VIOLATIONThe returned structure or a read-only value violated the issued surface.Correct the client request against the current document.
DOCUMENT_REVISION_CONFLICTThe issued order/line version is stale.Reload and reconcile.
DOCUMENT_COMMAND_CONFLICTA command ID was reused for a different request.Fix command identity handling.
SCOPE_MISMATCHThe document does not belong to this actor/context.Reject that submission.
AUTHORIZATION_REQUIREDCurrent permission no longer allows the operation.Refresh authorization/UI; do not repeatedly resubmit.

The injected write failure is reported as DOCUMENT_VALIDATION_FAILED by this sample service; its SQL assertions prove rollback for that failure. Do not interpret every database or network error as proof of rollback. If the transport loses a result, use the exact command retry or a service recovery policy rather than inventing a different mutation.

Adapt the example to your application​

Use the companion service as a complete reference for projection, snapshot creation, validation, version-checked SQL and receipt persistence. Define those rules for your own aggregate. A generated application can implement its domain loader and mutations with its discovered APIs; this JDBC example does not establish generated API names or generation results.

The terminal program calls openDocument and acceptDocument directly. It does not implement an HTTP server or exercise governed ViewPreparationService integration. If your application uses that final presentation pipeline, use its supported document-adoption path rather than issuing a second token from a client-supplied map.

For file attachments, start with the separate Blob guide. Combining protected edits with file selection adds another contract; this order-quantity example makes no Blob selection or file-encryption claim.