Server-Delete (Local Draft Deletion via Service Principal)
Server-Delete lets an authorised CRM or backend service remove one local DEM draft and its related local document/access records. It uses the existing storage delete lifecycle for attachment blobs and the current overflow payload. It does not update or delete CRM records, CRM documents, target child records, published forms, or other drafts.
Deletion uses the normal hard-delete model. It adds no permanent ID reservation, writer counter, lease or deletion-intent record. This API provides no undo. Recovery of accidentally deleted content depends on your independently configured backup and restoration procedures; verify those before enabling deletion.
Endpoint and authentication
POST https://{function-app}/api/dem/demdata/serverdelete/{customerid}/{environmentid}?code={function-key}
Authorization: Bearer {service-principal-jwt}
Content-Type: application/json
x-master-correlation-id: {optional-journey-id}
Pf-Master-Correlation-Id is also accepted through the existing correlation-header handling. The route's customer and environment scope every lookup and cleanup operation.
In the NPO portal, open Execution Settings → Security → Authentication and set Server Delete Allowed Application ID (ServerDeleteAllowedAppId). An empty value disables deletion. Submit permission alone does not grant deletion permission; the configured delete application may be different from the submit application.
JWT signature, issuer, audience, lifetime and caller-claim validation use the existing Server Submit Auth settings, including their authority, static PEM, metadata or JWKS source and algorithm. The resolved caller claim must match the separate delete application ID. Changing those shared JWT settings affects both APIs. See custom JWT signing keys and Server-Submit.
No form-level AllowServerSubmit permission or existing CRM skeleton is required. Deletion is an environment-authorised cleanup operation and can remove a draft that has never been written to the CRM. Treat the delete application credential and function key accordingly.
Shared lookup contract
Submit and delete use the same selector model, validation and resolver. Supply exactly one complete strategy. Empty/whitespace-only fields are absent; supplying only half of the form/reference pair or mixing strategies is invalid. Values are not trimmed or GUID-normalised.
| Strategy | JSON fields | Meaning |
|---|---|---|
| 1 | demdataId |
Exact immutable DEMData record ID. Recommended for deletion and retries. |
| 2 | formId and referenceNumber |
Case-insensitive match against DEMRenderId and ReferenceNumber. The form ID is the render identifier, not its display name, versioned artifact key or target record ID. |
| 3 | rootRecordPrimaryKey |
Case-insensitive string match against TargetRecordId["PRIMARY"]. Only usable when the draft already has that association. |
Each request deletes at most one draft. Multiple matches return a conflict; there is no first-match or bulk-delete behaviour. Indirect searches page through the scoped partition rather than stopping at 1,000 records. They have a 20-second application budget and a five-second Mongo query limit per page. A query failure or exhausted budget is an error, never a successful partial match or a not-found result. Use the direct ID for large partitions. The scan does not require backfilling new indexed selector fields.
Strategy 1: draft ID
Strategy 2: form and reference
Strategy 3: primary CRM association
requestedByUserId is optional, unverified audit information supplied by the caller. It does not select a record or grant permission. The endpoint uses the same default JSON deserialization as Server-Submit: unknown properties are ignored. Submit controls such as attemptId, crmCheckSucceeded, deferFinalization and confirmationWindowSeconds have no effect on deletion.
Responses and retry handling
Successful responses use the standard AZResponse envelope, whose content contains:
Errors use the usual errors list, for example:
| HTTP status | Meaning | Caller action |
|---|---|---|
| 200 | Deleted: the normal local deletion operations completed |
Record the returned draft ID. |
| 400 | Invalid JSON, incomplete/mixed selector, or an error mapped by the standard context handler | Inspect the errors; this status can also describe an underlying storage/cleanup failure, as with Server-Submit. |
| 401 | Missing or invalid JWT | Correct credentials or shared JWT configuration. |
| 403 | Delete disabled or caller application not allowed | Check the delete allow-list. |
| 404 | NotFound: no matching draft, including a completed deletion |
A retry by the same immutable ID can treat this as already absent. |
| 409 | Multiple matches, protected state or changed identifiers | Prefer the direct ID and investigate the record state. |
Expected result responses can include demDataId when it has been resolved. Exceptions use the same ContextBase.HandleException / context handler as Server-Submit, including its standard status mapping, sanitization and correlation handling. These exception responses do not promise a resolved draft ID in content; retain the original ID for retries and use the correlation ID when inspecting logs. There is no separate server-delete mapping of all unexpected exceptions to HTTP 500.
Related document and access records are deleted through their existing processors before the draft itself. If those operations throw, the draft remains available for an ordinary retry. There is no durable recovery queue or automatic reconciliation. If the draft is already absent, a 404 does not prove that every earlier blob cleanup succeeded; investigate the normal storage logs and recovery procedures if needed.
Indirect selectors are not safe retry identifiers. After completion, a different draft may reuse a form/reference or primary CRM association. A repeated indirect request could then delete that new draft. Prefer demdataId; this API does not promise exactly-once deletion. A stale client can also recreate an ID through existing save behaviour because no permanent marker is introduced.
Protected states and concurrent work
Ordinary drafts and failed promotions without active acknowledgement/retry protection are eligible. Skeletons, Submitted, Promoted, pending initialisation or acknowledgement, other non-empty submit states, and future/unknown states are rejected. Expiry of a pending state does not automatically make it an ordinary deletable draft.
The current selector and state are read again before cleanup. This is an eligibility check, not an atomic claim. The API does not add concurrency protection or change normal save, submit, upload, access-grant or generic delete behaviour.
As with existing normal deletion, an overlapping save/upload/submit can change or recreate data, and storage operations across Mongo and blobs are not one transaction. Avoid overlapping CRM deletion with active form editing or submission. Existing failed cleanup of older, no-longer-referenced overflow blobs is not reconciled by this endpoint. Attachment blob cleanup follows normal storage behaviour, including warnings where the storage layer treats a cleanup failure as best effort.
Audit, retention and operational recovery
Server-delete events use the separate ServerDeleteAudit Azure Table, with operation name, customer/environment, immutable draft ID, authenticated application, caller-supplied actor, request time, correlation ID and Deleted, Rejected or Failed outcome. Payloads, document contents and bearer tokens are excluded. Failures before a draft has been resolved are handled by request logs rather than per-draft events.
Days To Keep Server Delete Audit (DaysToKeepServerDeleteAudit) defaults to 90 days. Daily retention removes old audit events within the relevant environment and does not alter draft/document retention.
Audit initialization and writes are best effort. The audit processor is created lazily inside the caught audit callback, so an unavailable audit table cannot turn a completed deletion into a failed API response. Failures are logged. There is no durable audit-repair marker, and repeating deletion of an absent draft returns 404 without recreating its earlier audit.
For a persistent cleanup failure, use the customer/environment, resolved draft ID and correlation ID to inspect the normal API/storage logs. Restore the failed dependency and retry by demdataId if the draft still exists. Do not include user payloads or credentials in support tickets. If the row has already disappeared, use the deployment's ordinary storage recovery procedure; the API has no force-unlock or recovery-marker management operation.
Deploy the backend and its additive settings patch before configuring portal deletion permissions. There is no new writer protocol or lock migration to deploy.