Services

Web products and business system software development

When purchase approvals arrive through chat and are entered into an ERP again, inconsistent state becomes the first problem. If approved amounts, remaining budgets, and order status live in different places, requests may be processed twice or an old approval may remain attached to a changed quote. This page covers a design that keeps the flow in one transaction record.

A graphite aircraft concept illustration shown in an exploded structural view

Design scenario: purchase request and approval system for a 300-person manufacturer

Three sites submit purchase requests and the finance team enters purchase orders into the ERP. Scale and timing are design inputs and validation targets.

Organization and access
300 employees / 3 sites / 12 departments
Workload
1,800 requests per month / 60 concurrent users at month-end
Approval rules
Department head below ₩1,000,000 / additional finance review at or above that amount
Integration conditions
Existing ERP retained / a single purchase-order reference can be queried

Different approval states are more dangerous than duplicate entry

The sales team sends an equipment-parts quote through chat, a department head approves it, and procurement updates a spreadsheet. Finance reads that sheet and registers the order in the ERP. If the supplier changes the unit price meanwhile, the quote file is replaced without recording whether the existing approval still applies.

At month-end, several people process the same request. One sees that it was approved in chat; another sees no ERP record and enters it again. The first feature needed is therefore not a dashboard but a clear record of which request version was approved by whom and how far the external order has progressed.

Mismatch by workflow point and the state to make explicit
Workflow pointPossible current problemWhat the system must state
Quote revisionReuse an old approval after the amount changesApproval per request version / reapproval after edits
Concurrent approvalDuplicate processing in separate tabsConditional version update / one state change
ERP entryDuplicate order after retrying a lost responseSeparate external reference and delivery state
Budget deductionApproval and budget aggregation happen at different timesReserve the budget in the same transaction

At 1,800 requests per month, exception handling matters more than stored volume. Rather than splitting dozens of services from the start, keep requests, approvals, budgets, and audit records in one database, and separate only the ERP integration into a worker.

Do not collapse approval and ordering into one completed state

Define what ‘complete’ means on screen first. Approval complete means the company’s internal purchasing decision is finished; order complete means the ERP has confirmed that a document was created. An ERP outage must not cancel an approval, and an approved request must not appear to have succeeded in ordering.

Request states and permitted actions
StatePermitted actionsNext state / condition
DraftAuthor edits, deletes, or submitsSubmit: validate required quote and cost code
Under reviewApprover approves or rejects / author recallsApproval complete when rules are satisfied
Final approval processingConditional state change, budget reservation, event storageMove to waiting for ERP confirmation in one DB transaction
Waiting for ERP confirmationCheck status / controlled retryOrder complete when external reference is confirmed
Order completeView / request separate cancellationRelease budget after ERP cancellation is confirmed

Keep request_id, version, and status on each request. Approval records reference the approved version as well as the request ID. If an amount, supplier, account, or other payment-affecting field changes, start review on a new version instead of carrying the old approval forward.

Financial review rules belong to the business scenario. Store them as versioned policies with cost type and site rather than hard-coding an amount. Keep the policy version applied at submission so the rule used before a policy change can be reproduced.

Confirm the transaction in the database and separate external delivery with an outbox

The purchase approval API groups authorization, request-version checks, budget reservation, audit records, and delivery-event storage in one DB transaction. If the final step fails, roll everything back so partial records do not remain. PostgreSQL transactions describe atomicity inside the database; they do not include the ERP’s HTTP call.

A separate worker therefore reads the event committed to the database and sends it to the ERP. This outbox boundary prevents a state where approval was saved but the message to deliver disappeared. AWS’s transactional outbox guidance also addresses duplicate delivery and idempotent handling by the receiver.

Derive the order event key from the approved version, such as purchase:{request_id}:{approved_version}. Retry with the same key when the ERP supports idempotency. Otherwise, lock the in-flight key in an adapter and check the ERP’s external reference first. A timeout whose result cannot be confirmed goes to reconciliation; it must not automatically place another order. Do not assume exactly-once execution without an external contract.

Processing boundary from purchase approval to ERP confirmation
  1. Approval API

    Validate user, department, and request version

  2. DB transaction

    Store state, budget reservation, audit, and outbox

  3. Delivery worker

    Send committed events and retry failures

  4. ERP adapter

    Reconcile event key and external reference

  5. Apply confirmation

    Show order complete or reconciliation required

The visible button and the permission to execute are different

Hiding a button only tidies the interface. The server must check organization, department, ownership, and current state on every read, approval, and attachment-download request. An author cannot approve their own request, and a department head cannot read a department they have not been delegated. Apply OWASP’s deny-by-default and per-request authorization principles to these business objects.

Permissions and data ownership
RoleVisible scopeCan change
RequesterTheir requests, attachments, and progressDraft / recall under review
Department approverSubmitted versions for assigned departmentsApproval / rejection reason
FinanceRequests requiring financial review by policyAdditional approval / reconciliation work
Operations administratorErrors and delivery historySchedule retries / cannot change approved amount

Store purchase amounts as integer units and do not calculate external input as floating-point totals. Add both NOT NULL and UNIQUE to deduplication keys. PostgreSQL’s unique constraint prevents duplicate stored values; if the same key arrives with different content, reject it as a conflict instead of returning the previous success.

Use short-lived download routes instead of public attachment URLs, and recheck access immediately before issuing one. Logs should retain the request ID and error type, but never quote text, bank details, or access tokens.

Test timeouts, cancellation, and duplicate clicks first

The result when a user clicks again after receiving no response matters more than one clean successful run. Connect API results to browser state so a request does not disappear when the ‘saving’ screen does. If the client resends the same command, the server returns the result for that key.

Failure-injection tests and expected states
Injected situationExpected behaviorRecord to verify
20 concurrent identical approvalsOne state change / one budget reservationVersion conflicts and approval-event count
Worker stops just after DB commitOutbox delivery resumes after restartPending events and processing time
ERP succeeds but response is lostReconcile by lookup / never reorder unconditionallyExternal reference and reconciliation state
Author cancels just after approvalAlready-started order follows a separate cancellation flowCancellation intent and confirmed ERP result
Unauthorized attachment request403 / zero file-content exposureRejection reason and requesting principal

Retries need a time limit as well as a count. Retry temporary connection errors with exponential backoff, while sending invalid cost codes to an owner for correction. Separate failure causes so the same error cannot fill the queue indefinitely.

Release approval is decided by business invariants, not screen count

If ‘approval screen implemented’ is the definition of done, important checks are missed. Write validation conditions for every retry and concurrent request: the same approval must never reserve the budget twice, and a request edited after approval must never be delivered to the ERP.

Release validation targets for this scenario
AreaValidation conditionPass criterion
List query100,000 records / 60 concurrent usersServer response p95 no higher than 800 ms
Approval commandDuplicates and concurrency / ERP asynchronousInternal commit p95 no higher than 1 s / zero duplicate reservations
Delivery backlogERP unavailable for 30 minutes, then recoversZero loss / reconciliation list can be reprocessed
AuthorizationAutomated tests by role × department × stateZero unauthorized successful reads or changes
Deployment recoveryRoll back to the previous app versionSchema compatibility / zero lost approval records

Record data size, request rate, equipment, and network conditions with every measurement. Distinguish a slow database query from an API waiting on an external request so scaling the server is not the only response.

Confirm the cutover boundary with one department running in parallel

Do not switch all three sites at once. Start with a read-only migration and reconcile request records and totals, then accept only new requests from one department in the new system. Keep ERP document creation disabled behind a feature flag while reviewing intended events. Open real integration next, beginning with low-value requests.

  1. Data reconciliation: Compare request IDs, suppliers, amounts, and counts and totals by state with the existing records.
  2. Read cutover: Validate the read path first and limit writes to the existing system.
  3. Department write cutover: Mark the system of record so the same request cannot be edited in both systems.
  4. Open ERP integration: Reconcile each order reference and budget reservation.
  5. Expand scope: Add the next department only after pending, duplicate, and authorization errors meet the pass criteria.

Rollback is not just changing a page address. Do not put already-ordered requests from the new system back into the old spreadsheet as pending. Record the cutover time and last confirmed ID, clear unconfirmed events, and then switch the write path.

The deliverables leave operators with evidence for the next decision

The handoff includes more than screens and source code. Document state transitions, role permissions, the data model, API contracts, ERP event specifications, retry rules, deployment and rollback procedures, and test results. In the operations view, distinguish retryable failures, data requiring correction, and external reconciliation instead of showing one word: ‘failed’.

Operators should be able to trace a request ID from its approved version through the ERP result. When they can identify the cause and next action without direct database access, the operating boundary remains clear as features grow.

To begin the discussion, send the current purchase form, approval rules, ERP integration specification, and a path where duplication or omission occurred. Personal and vendor secrets can be removed. One request that makes the failure concrete establishes a design baseline faster than an abstract list of screens.

References