Skip to content

Latest commit

 

History

History
1715 lines (1317 loc) · 84.4 KB

implementation-plan.md

File metadata and controls

1715 lines (1317 loc) · 84.4 KB

Point of Sale System — Architecture and Implementation Plan

Document status: Phases 1–8 implemented; Phase 9 final verification in progress

Prepared: 2026-07-28

Target: A secure, maintainable POS for a small or medium retail business

Initial deployment model: One business, one base currency, and one default stock location, with location-aware inventory so that multiple locations can be added without redesigning the ledger

1. Planning scope and current checkpoint

This document began as the Phase 1 deliverable. It records the workspace assessment, proposed architecture, application boundaries, core data model, business invariants, risks, decisions, testing strategy, implementation roadmap, and verified results at each completed checkpoint.

Phases 1–8 are implemented. The repository now contains the Django foundation, product and inventory ledgers, register and POS workflows, customer and supplier accounting, purchasing, expenses, returns/refunds, employee management, dashboard/reporting, and the security-quality hardening pass. Phase 9 is completing clean-install, PostgreSQL, browser, documentation, and final release verification.

2. Workspace assessment

2.1 Physical workspace

At inspection time, the workspace at C:\Users\hp pro\Desktop\codexceo contained only the .git directory. There was no working Django project, Python package, virtual environment, database, or documentation directory.

2.2 Git state

The repository is on local branch master at commit e514dd2 (Serve metadata as static assets).

Important findings:

  • All 78 files tracked by HEAD are deleted in the working tree but are not staged.
  • The working-tree diff represents 18,810 deleted lines.
  • The index and local Git history are still intact.
  • There are six local commits.
  • No Git remote, upstream branch, or tag is configured.
  • docs/implementation-plan.md did not previously exist, so this Phase 1 document does not replace a tracked file.

These deletions are treated as user-owned work. They were not restored, staged, discarded, or otherwise modified during Phase 1.

2.3 Previously tracked technology

Read-only inspection of HEAD showed an unrelated product named ProofReply, an evidence-first security-questionnaire prototype. It used:

  • Next.js 16, React 19, and TypeScript
  • Tailwind/PostCSS
  • Vinext/Vite
  • Vitest and Playwright
  • A static export/deployment configuration

The previous README explicitly stated that the application had no user accounts, persistent database, backend API, storage, or audit log. Git history contains no Django or Python POS implementation. The old product and its domain logic are not reusable as a retail POS backend.

The previously tracked .openai/hosting.json also identified a static Sites deployment project. That file is currently deleted. A dynamic Django deployment must not silently reuse that static hosting identity or deployment design.

2.4 Repository replacement decision

Decision recorded 2026-07-28: ProofReply is retired. The Django POS will replace it at the repository root.

Consequences:

  • The 78 existing ProofReply working-tree deletions are intentional.
  • The old files will not be restored or reused.
  • The old static Sites hosting configuration will not be reused for Django.
  • Replacement files such as README.md and .gitignore may be created during their planned phases after reviewing the prior tracked versions.
  • The deletions remain unstaged and uncommitted until an intentional implementation/commit checkpoint.
  • Git history is not rewritten, so the old project remains recoverable from commit e514dd2.

Because no Git remote exists, a repository bundle or other external backup remains recommended before the first production release.

2.5 Local tool availability

Tool Observed state
Python 3.12.10 and 3.14.0 installed
Recommended project interpreter Python 3.12 for broad dependency compatibility
Django Not installed in either inspected interpreter
Python SQLite library Available; SQLite 3.50.4
SQLite CLI Not found on PATH
PostgreSQL psql Not found on PATH
Node.js/npm 22.19.0 / 10.9.3, inherited from the previous project
Git 2.51.1.windows.1

The recommended framework baseline is Django 5.2 LTS on Python 3.12, always using the latest available 5.2 security patch when dependencies are installed. The official Django supported-versions table lists 5.2 LTS extended support through April 2028. PostgreSQL will be required for production and for concurrency/integrity testing; SQLite is suitable only for the initial local bootstrap and fast non-concurrency tests.

2.6 Missing foundations

Every POS foundation is currently missing, including:

  • Django project and application packages
  • Dependency and environment management
  • Development and production settings
  • Custom user model, authentication, roles, and permissions
  • Database schema and migrations
  • Templates, static assets, media handling, and UI shell
  • Business services and transactional workflows
  • Tests, linting, formatting, and CI
  • PostgreSQL development/test environment
  • Seed data and operational documentation

This is therefore a greenfield Django build, subject to the repository decision above.

3. Architecture overview

3.1 Architectural style

Use a modular Django monolith.

This keeps sales, payments, inventory, returns, register activity, and audit events inside one relational database and one atomic transaction where required. It avoids distributed consistency problems while still separating the domain into maintainable Django apps.

The request flow should be:

URL/view
  -> form or explicit command input validation
  -> permission and object-scope policy
  -> transactional service
  -> models and database constraints
  -> audit event

URL/view
  -> selector/query service
  -> optimized queryset/projection
  -> template, JSON response, chart data, or CSV stream

Key boundaries:

  • Views coordinate HTTP concerns only.
  • Forms validate user-entered shape and simple field rules.
  • Services own state changes, permissions that protect business commands, transactions, locking, calculations, and audit creation.
  • Models and database constraints enforce invariants that remain valid outside the UI.
  • Selectors own reusable, permission-scoped, optimized reads and reporting queries.
  • Templates render server-authoritative data and never decide authorization.
  • Signals may support non-critical framework events such as login audit, but must not drive stock, totals, payments, receipts, returns, or refunds.

3.2 Technology choices

  • Python 3.12
  • Django 5.2 LTS, latest security patch
  • PostgreSQL in production and in integrity/concurrency test runs
  • SQLite only during the initial local bootstrap
  • Django templates and Bootstrap 5
  • Vanilla JavaScript, with HTMX only for interactions that materially improve the POS workflow
  • Chart.js for charts
  • Django JsonResponse for the small internal product/customer search endpoints
  • No Django REST Framework until a real external/mobile integration requires a versioned API
  • Decimal for all money, rates, and sellable quantities
  • pytest, pytest-django, and Django test utilities
  • Ruff for formatting and linting
  • Pillow for validated raster images
  • Psycopg 3 for PostgreSQL

Receipt printing will initially use authenticated HTML views and print-specific CSS for 80 mm and A4 layouts. Barcode scanners are assumed to behave as keyboard input. Direct printer, cash-drawer, payment-terminal, offline/PWA, and payment-gateway integrations are not implied.

3.3 Settings and deployment structure

Use split settings:

config/
  settings/
    __init__.py
    base.py
    local.py
    test.py
    production.py
  urls.py
  asgi.py
  wsgi.py

Environment variables will control at least:

  • DJANGO_SETTINGS_MODULE
  • SECRET_KEY
  • DEBUG
  • ALLOWED_HOSTS
  • CSRF_TRUSTED_ORIGINS
  • DATABASE_URL or discrete PostgreSQL connection values
  • secure-cookie and proxy/HTTPS behavior
  • static/media storage configuration
  • logging level

Production settings will fail closed when required variables are absent. Secrets, credentials, .env, SQLite databases, media uploads, virtual environments, caches, and generated reports must be ignored by Git.

3.4 Proposed source tree

manage.py
config/
apps/
  accounts/
  core/
  audit/
  products/
  inventory/
  customers/
  suppliers/
  registers/
  sales/
  purchases/
  expenses/
  reports/
templates/
  components/
  registration/
  errors/
static/
  css/
  js/
  vendor/
media/                 # local development only; never committed
tests/
  integration/
docs/
  implementation-plan.md

Each domain app should contain only the modules it needs, generally:

models.py or models/
services.py or services/
selectors.py
forms.py
views.py
urls.py
admin.py
permissions.py
tests/

Large apps such as sales may use packages for models, services, and tests. Small apps should stay simple rather than adopting empty boilerplate.

3.5 Dependency direction

  • core and accounts are foundational.
  • products depends on core.
  • inventory depends on core, accounts, and products.
  • customers and suppliers depend on core.
  • registers depends on core and accounts.
  • sales may orchestrate inventory, registers, and customers.
  • purchases may orchestrate inventory and suppliers.
  • expenses may reference registers only when a cash expense is explicitly represented by a register cash-out.
  • audit accepts safe event data but does not import transactional domain models.
  • reports may read all apps but no transactional app may depend on reports.

Inventory must not import sales or purchases. Originating services pass a stable source identity to the inventory service. This avoids circular dependencies.

4. Django app responsibilities

App Responsibility
accounts Custom user model, employee identity, active/default business and location, group bootstrap, permission helpers, login/logout audit
core Business, business settings, location, document sequences, shared validators, money/quantity utilities, common abstract models
audit Append-only audit events and authorized audit search
products Categories, units of measurement, product master data, price/cost changes, search/filtering
inventory Per-location balances, immutable stock ledger, adjustments, reconciliation, low-stock queries
customers Customer master data, append-only account ledger/payments, purchase history, spending, outstanding balance, and store credit
suppliers Supplier master data and supplier-facing history
registers Registers/drawers, sessions, cash-in/cash-out, close reconciliation
sales Completed sales, item snapshots, payments, POS checkout, receipts, cancellation, returns, refunds
purchases Purchase orders, goods receipts, posted supplier invoices, supplier payments/allocations, supplier returns, stock receipt orchestration
expenses Expense categories, posted/voided expenses, protected attachments
reports Dashboard metrics, report filters, optimized selectors, charts, CSV exports; normally no transactional models

5. Main models and relationships

5.1 Relationship summary

Business
  |-- BusinessSettings
  |-- Location
  |-- User -- UserLocationAccess -- Location
  |-- Category -- Product -- InventoryBalance -- Location
  |                         \- StockMovement
  |-- Customer -- CustomerAccountEntry / CustomerPayment
  |       \- Sale -- SaleItem -- Product
  |                 |  \- SalePayment
  |                 \- SaleReturn -- SaleReturnItem -- SaleItem
  |                                \- Refund
  |-- Register -- RegisterSession -- RegisterCashMovement
  |                 \- Sale
  |-- Supplier -- PurchaseOrder -- PurchaseOrderItem -- Product
  |                    \- GoodsReceipt -- GoodsReceiptItem
  |             \- SupplierInvoice -- SupplierInvoiceItem
  |             \- SupplierPayment -- SupplierPaymentAllocation
  |-- ExpenseCategory -- Expense
  \-- DocumentSequence / AuditEvent

Use BigAutoField internal primary keys and separate unique, human-readable document references. Sensitive object access must be protected by scoped querysets and permissions rather than relying on unpredictable IDs.

5.2 core

Business

  • Legal/display name
  • Address, phone, email, tax identifier
  • Active flag
  • Created and updated timestamps

V1 supports one active business, but explicit business ownership prevents accidental cross-business access and keeps future migration options open.

BusinessSettings

One-to-one with Business:

  • Logo
  • Currency code, default USD
  • Default tax rate
  • Tax configuration
  • Receipt footer
  • Invoice prefix
  • Allow negative stock
  • Require manager approval for refunds
  • Time zone
  • Register-session policy
  • Allow on-account customer sales
  • Prospective configuration version/timestamps

Currency is stored as an ISO code, not a hardcoded symbol. Changing currency or settings affects new documents only.

Location

  • Business
  • Code and name
  • Address
  • Active/default flags

One default location is seeded. Inventory is location-aware from the beginning even though multi-location transfers are deferred.

DocumentSequence

  • Business
  • Optional location
  • Document type
  • Optional fiscal period
  • Prefix
  • Next integer

A service locks the row with select_for_update() and returns a unique reference. References must also have database uniqueness constraints. Never use MAX(number) + 1. The system guarantees uniqueness, not legal gaplessness, unless a jurisdiction-specific policy is later supplied.

CommandIdempotency

  • Business
  • Operation code
  • Client-generated key
  • Canonical request fingerprint
  • Result object type and ID/reference
  • Created/completed timestamp
  • Uniqueness on (business, operation code, key)

Every irreversible browser command uses this registry or an equivalent unique key on its aggregate root. Reusing a key with the same fingerprint returns the original result; reusing it with different input is rejected. It covers checkout, goods receipt, return/refund completion, sale cancellation, customer/supplier payment, supplier return, register cash movement, expense posting/voiding, and register opening/closing.

5.3 accounts

User

Create a custom user model before the first migration, derived from AbstractUser:

  • Business
  • Employee code
  • Default location
  • Active flag and standard Django identity fields
  • Created/updated timestamps where useful

Users with financial history are deactivated, not deleted. Django Groups named Admin, Manager, and Cashier provide default capability bundles; granular Django permissions remain authoritative.

UserLocationAccess

  • User and location
  • Active flag
  • Optional location-specific capability overrides
  • Uniqueness on (user, location)

The user’s default location must be one of their active allowed locations. Admins may be granted all locations in their business explicitly; “allowed location” is never inferred from an untrusted URL/form value.

5.4 audit

AuditEvent

Append-only fields:

  • Business and optional location
  • User, nullable only for justified system events
  • Action code
  • Object type and object ID/reference
  • Safe human-readable description
  • Request/correlation ID
  • Validated IP address when available
  • Safe structured metadata
  • Timestamp

Audit rows must not contain passwords, session tokens, secret keys, full card data, receipt attachment contents, or unnecessary personal data. Sensitive command services create their audit event in the same transaction as the domain change whenever possible.

5.5 products

Category

  • Business
  • Name, description
  • Active flag
  • Timestamps

UnitOfMeasure

  • Business
  • Name and short code
  • Whether fractional quantities are allowed
  • Supported decimal scale
  • Active flag

V1 does not perform unit conversion.

Product

  • Business
  • Name
  • Normalized unique SKU
  • Optional normalized barcode, unique when present
  • Category
  • Description
  • Current cost price
  • Selling price
  • Current catalog currency code
  • Tax rate
  • Unit of measurement
  • Minimum stock level
  • Validated raster image
  • Active flag
  • Timestamps

Barcodes are text so leading zeroes are preserved. Blank barcodes normalize to NULL. SKU and barcode uniqueness are scoped to the business and enforced in the database. Inactive products retain their identifiers and cannot be sold, but remain available to returns and historical reports.

current_stock is a read-only displayed value obtained from InventoryBalance, not a freely writable Product column.

Catalog currency must match the business base currency. The base currency may be changed freely only before catalog values or financial/stock activity exist. After activity begins, a normal settings edit is blocked because it would reinterpret existing product values; changing it requires an explicit repricing/migration workflow while historical documents keep their original currency.

5.6 inventory

InventoryBalance

  • Business, location, product
  • Current quantity
  • Updated timestamp
  • Uniqueness on (location, product)

The balance is a transactionally maintained quantity projection for fast reads. It may only be changed through the inventory service. Product.cost_price is the authoritative current moving-weighted-average cost across the business; there is not a second editable per-location cost.

StockMovement

Append-only fields:

  • Business, location, product
  • Signed quantity delta
  • Movement type
  • Human reference
  • Stable source type, source ID, and source-line ID
  • Previous stock and new stock
  • Unit cost/valuation data where required
  • User
  • Timestamp
  • Required reason/notes where applicable
  • Optional reversal movement

Movement types include opening, purchase, sale, sale return, purchase return, manual adjustment, damaged, expired, and future transfer. Positive values add stock; negative values remove stock. Constraints reject zero movement and inconsistent before/after quantities.

A uniqueness rule on the originating source line and movement purpose prevents one sale, receipt, return, or adjustment from affecting inventory twice.

InventoryCostRevaluation

  • Product
  • Previous and new authoritative cost
  • Reason and reference
  • User and timestamp

When positive stock exists, a manual cost change must use this explicit audited service/record rather than an ordinary product edit. It changes current inventory valuation prospectively but never changes historical sale-item cost snapshots.

5.7 customers

Customer

  • Business
  • Full name
  • Phone, email, address
  • Optional tax identifier
  • Notes
  • Active flag
  • Created/updated timestamps

Purchase history and total spending are derived from completed sales and returns.

CustomerAccountEntry

An append-only receivable/store-credit ledger:

  • Customer, currency, entry type, and posting date
  • Signed amount: positive means the customer owes the business; negative means store credit
  • Stable source type, source ID, and source-line ID identifying the sale, return, or customer payment without requiring the customer app to import those aggregates
  • User, note, reversal link, and timestamp

Entry types include opening balance, on-account sale charge, customer payment, return credit, store-credit use, and explicit correction/reversal. A unique source rule prevents double posting. Outstanding balance is max(ledger balance, 0) and available store credit is max(-ledger balance, 0); neither is a manually editable customer column.

CustomerPayment

  • Customer and currency
  • Method: cash, card, bank transfer, or mobile payment
  • Positive amount and safe reference
  • Optional register session for cash
  • User, status, reversal data, and timestamp

Posting a customer payment and its account entry is atomic. On-account checkout is disabled by default. When enabled, it requires an attached customer and sell_on_account; a customer credit limit/policy must be validated if one is configured.

5.8 suppliers

Supplier

  • Business
  • Name and contact person
  • Phone, email, address
  • Tax identifier
  • Notes
  • Active flag
  • Timestamps

Supplier balance is derived from posted supplier invoices, allocated payments, returns, and approved credits rather than a freely editable balance field.

5.9 registers

Register

  • Business and location
  • Code/name
  • Active flag

This represents a logical or physical drawer/terminal.

RegisterSession

  • Unique session reference
  • Register and cashier
  • Currency code
  • Status
  • Opening amount and opening time
  • Closing user/time
  • Expected cash snapshot
  • Counted cash
  • Difference
  • Close-time snapshots for cash sales, non-cash sales, refunds, and cash movements

RegisterCashMovement

  • Session
  • Type: cash-in or cash-out
  • Positive amount
  • Required reason
  • Reference
  • User and timestamp
  • Optional reversal

Only one session may be open per register. When multiple sessions per cashier are disabled, the service serializes openings by locking the cashier’s persistent User row and then checking active sessions; a mutable setting cannot safely be represented by one static database uniqueness constraint.

Expected cash is:

opening cash
+ cash payment amounts applied to completed sales
- cash refunds
+ cash additions
- cash removals

Card, bank, and mobile payments are reported but do not affect physical expected cash. An expense affects the drawer only when it is explicitly linked to a register cash-out.

5.10 sales

Sale

  • Business, location, register session
  • Unique receipt/invoice number
  • Unique checkout idempotency key and request fingerprint
  • Cashier and optional customer
  • Status
  • Payment status and balance due
  • Currency code
  • Subtotal, item discount, allocated sale discount, tax, total, paid, and change snapshots
  • Total cost snapshot
  • Business/receipt identity snapshots needed for faithful reprinting
  • Note
  • Completion/cancellation metadata
  • Timestamps

The checkout service creates a completed sale atomically. An abandoned browser cart is not a sale. A completed sale is not edited in place.

SaleItem

  • Sale and protected product reference
  • Product name, SKU, barcode, and unit snapshots
  • Quantity
  • Unit/list price snapshot
  • Unit cost snapshot
  • Tax rate snapshot
  • Item discount
  • Allocated sale-level discount
  • Net, tax, total, and cost snapshots

The immutable unit cost is the source for historical gross-profit reports.

SalePayment

  • Sale
  • Method: cash, card, bank transfer, or mobile payment
  • Amount applied to the sale
  • Cash amount tendered and change given, where applicable
  • Safe external reference
  • User and timestamp

“Mixed” is a UI/payment composition, not a stored tender method. A mixed payment creates two or more ordinary payment rows. No PAN, CVV, bank credentials, or equivalent sensitive payment data is stored.

Normally payment amounts applied equal the sale total. When on-account sales are enabled and authorized, payment amounts + customer account charge = sale total; the unpaid portion is not mislabeled as a tender method.

SaleReturn and SaleReturnItem

  • Unique return reference
  • Original sale
  • Requested/approved/completed state and timestamps
  • Reason
  • Requester and approver
  • Snapshot of whether approval was required
  • Immutable request revision and canonical approval fingerprint
  • Totals and currency
  • Each return item references an original SaleItem
  • Returned quantity and original-price/tax/discount/cost-derived refund snapshots
  • Restock location/disposition

The original sale and item rows remain unchanged.

Submission freezes the requested item IDs, quantities, calculated values, refund method, register context, and stock disposition into a revision. Approval verifies the fingerprint of that exact revision, and completion recomputes and verifies it under lock. Only an operational cash-drawer rebind may revise an approved request; item and financial values remain immutable.

Refund

  • Return
  • Refund method
  • Amount
  • Safe reference
  • User and timestamp
  • Register session when cash is refunded

Refunds remain separate from returns so approval, inventory, and money movement are auditable.

SaleCancellation

A manager-only specialized full reversal for an erroneous completed sale. The cancellation service creates a SaleReturn of kind CANCELLATION, return items for every remaining quantity, and corresponding Refund records, then restores inventory and register effects through the same audited ledgers. It preserves the original sale/items/payments, cannot run after an incompatible partial return, and is included as a reversal in every sales, tax, COGS, inventory, tender, and register report. Abandoning an uncompleted cart is not cancellation.

5.11 purchases

PurchaseOrder and PurchaseOrderItem

Purchase order:

  • Business, destination location, and supplier
  • Unique order reference
  • Currency, order date, expected date, state, notes, and user/timestamps
  • Estimated subtotal, discount, tax, and total

Purchase order item:

  • Product and product-name/SKU/unit snapshots
  • Ordered quantity, quoted unit cost, tax/discount, and estimated line totals

A purchase order is a commitment/workflow document, not an accounts-payable liability. Creating or ordering it does not change stock or supplier balance.

GoodsReceipt and GoodsReceiptItem

  • Unique receipt reference and idempotency key
  • Purchase order, location, receiving user/time, notes
  • Each receipt item references its purchase-order item and product snapshots
  • Quantity received and cost snapshot

Inventory changes only when a goods receipt completes. A separate receipt aggregate supports partial receipts and prevents a repeated “receive” action from applying stock twice, even if the first UI offers only “receive all.”

SupplierInvoice and SupplierInvoiceItem

Supplier invoice:

  • Business, supplier, and location
  • Unique internal reference and supplier-provided invoice number
  • Optional purchase order and matched goods receipts
  • Currency, invoice date, due date, posting state, and payment status
  • Subtotal, discount, tax, total, paid, credited, outstanding, and supplier refund-receivable snapshots
  • Supplier identity snapshots, notes, user, and timestamps

Invoice item:

  • Product when applicable, description, and product/unit snapshots
  • Quantity, unit cost, tax/discount, and line totals
  • Optional links to purchase-order and goods-receipt lines for matching

Only a posted supplier invoice creates accounts payable. Receipt and invoice may occur in either order; the service exposes mismatched ordered/received/invoiced quantities rather than silently changing them.

SupplierPayment and SupplierPaymentAllocation

  • Business, supplier, and currency
  • Payment method
  • Positive amount
  • Safe reference
  • User/date and an optional separate linked reversal
  • One or more immutable allocations to posted supplier invoices

Invoice payment status and supplier balance reconcile payments, explicit supplier credits, AP outstanding, and any supplier refund receivable. A payment cannot exceed the selected invoice balances.

PurchaseReturn and PurchaseReturnItem

Separate supplier-return records reference original goods-receipt items, support the required purchase-return stock movement, and cannot return more than net received quantity. A posted return credit or linked supplier credit note reduces accounts payable; returning physical stock alone does not silently edit an invoice.

5.12 expenses

ExpenseCategory

  • Business
  • Name, description, active flag

Expense

  • Business and location
  • Category
  • Description
  • Amount and currency
  • Expense date
  • Payment method
  • Reference
  • Protected receipt attachment
  • Recording user
  • Posted/voided state and reversal metadata
  • Timestamps

Posted expenses are not deleted or silently edited. Corrections use void/reversal records.

5.13 reports

No report tables are planned initially. Reports use shared selectors and annotated querysets over immutable source data. A materialized summary may be considered only after profiling proves it necessary.

5.14 Explicit document state machines

Only the listed services may perform these transitions. Models validate allowed state changes, and admin forms cannot mutate state directly.

Aggregate Allowed states and transitions Actor/side effects
Browser cart Ephemeral -> abandoned or checkout command It is not a financial record and has no stock effect
Sale Created directly as COMPLETED; COMPLETED -> CANCELLED only after the specialized full cancellation return/refund commits Authorized cashier completes; manager cancels; item/payment values stay immutable
Sale payment Created as POSTED; never edited; money back is a separate refund/reversal record Checkout service only
Sale return Created as REQUESTED when approval is required; REQUESTED -> APPROVED -> COMPLETED or REQUESTED -> REJECTED. Approval-disabled requests complete atomically during submission Required approval records the approving manager and a frozen fingerprint; only COMPLETED changes stock/money. An approved cash return may bind a replacement open drawer without changing its financial values
Refund Created directly inside completed return processing and never edited or deleted Never silently edits the original payment; each refund remains linked to its return and processing actor
Purchase order DRAFT -> ORDERED -> PARTIALLY_RECEIVED -> RECEIVED; DRAFT/ORDERED -> CANCELLED; progress changes only through posted receipts Buyer orders; authorized receiver posts receipts; cancellation cannot undo a receipt
Goods receipt Created directly as POSTED; physical correction uses a supplier return, never edit/delete Posting changes stock and cost once
Supplier invoice DRAFT -> POSTED or DRAFT -> CANCELLED; POSTED -> VOIDED only with no payment-allocation or supplier-credit history Posting creates liability; cancellation/void creates an immutable correction record
Supplier/customer payment Original payment records stay immutable; reversal is a separate linked record Posting changes the applicable account once. Supplier reversals restore AP allocations; customer reversals negate the customer ledger entry
Purchase return Created directly as an immutable posted return together with its supplier credit One atomic service validates received-quantity caps, removes stock, and applies the explicit supplier-approved credit to AP
Expense Created directly as POSTED; POSTED -> VOIDED through an explicit reversal Creation/void may create a linked current-session cash movement
Register session Created as OPEN; OPEN -> CLOSED once Open/close service only; closed snapshots never change
Register cash movement Immutable once created; a correction is another linked compensating movement Requires reason, actor, current open session, and idempotency key; later corrections never rewrite a closed session

“Partially returned” and “fully returned” are derived sale facts, not editable sale states. Payment status and purchase-receipt progress are derived or synchronized only inside their owning services and must reconcile to immutable child records.

State values use TextChoices plus database check constraints. Transition services lock the root row, verify the expected prior state, apply all side effects, and create the audit event in one transaction. Direct QuerySet.update() state changes are forbidden outside reviewed migrations/services.

Submitting a sale return snapshots the current approval setting and freezes a fingerprint over its financial details. When approval is required, an authorized manager moves REQUESTED -> APPROVED; the requester then completes the approved return. When approval is disabled, submission approves and completes the return in the same transaction. A cash return whose original drawer closed may be rebound to another open drawer at the same location; that operational rebind increments the revision and fingerprint but does not change items, amount, method, or approval.

6. Transactional service contracts

6.1 Inventory mutation

All inventory-changing workflows call one service that:

  1. Starts or joins transaction.atomic().
  2. Locks the product and balance row with select_for_update().
  3. Creates the missing balance safely under a uniqueness constraint.
  4. Reads the latest business setting and current balance.
  5. Validates quantity precision, movement sign, source idempotency, and negative-stock policy.
  6. Updates the balance.
  7. Inserts the immutable movement with previous/new values.
  8. Inserts an audit event in the same transaction.

No view, form, admin action, fixture, or ordinary model save may update stock directly.

6.2 Complete sale

complete_sale(actor, command) will:

  1. Check the cashier permission, allowed business/location, and open register session.
  2. Validate only identifiers, quantities, discount requests, customer, note, and tender details from the browser.
  3. Reject an idempotency key reused with a different request fingerprint.
  4. Aggregate duplicate product lines.
  5. Lock the register session and product/balance rows in stable primary-key order.
  6. Re-read active state, prices, taxes, costs, units, stock, and settings from the database.
  7. Recalculate all discounts, taxes, totals, payments, and change using Decimal.
  8. Enforce stock, discount, and on-account sale permissions.
  9. Allocate the receipt number using a locked sequence.
  10. Create the sale, immutable items, and payment rows.
  11. If an authorized balance remains, create the customer account charge; otherwise require full tender settlement.
  12. Reduce each inventory balance and create sale movements.
  13. Create the sale-completion audit event.
  14. Commit once.

If two requests race with the same idempotency key, one sale wins and the other request returns that completed sale after the uniqueness conflict is resolved outside the rolled-back transaction.

6.3 Complete return/refund

complete_return(actor, command) will:

  1. Check refund request/approval permissions and actor separation if configured.
  2. Verify that the approved frozen revision fingerprint matches the submitted items, quantities, amounts, method/allocation, and disposition.
  3. Lock the original sale items and relevant register/balance rows.
  4. Sum already completed return quantities.
  5. Reject quantities or values beyond the remaining refundable amount.
  6. Calculate from original snapshots, never current product data.
  7. Reduce any still-outstanding customer receivable before issuing cash/non-cash money back; never refund more tender than the customer actually settled.
  8. Mark the already-existing frozen return/items completed and create the customer account credit where applicable, refund records, stock restoration, register effect, and audit event atomically.

Inactive products remain returnable. The default interpretation of the brief is to restock returned goods; damaged returns can then be moved out through a separate damaged-item adjustment. A disposition policy must be confirmed before Phase 6.

6.4 Purchasing commands

receive_purchase(actor, command) will lock purchase-order items, products, and balances, validate remaining quantities, create a unique goods receipt, apply the costing algorithm in section 7.2, add inventory and stock movements, and audit the receipt in one transaction. Posting a SupplierInvoice is a separate accounts-payable transition and does not apply stock a second time.

post_supplier_invoice validates invoice uniqueness, totals, currency, supplier, and any order/receipt matching before creating liability. post_supplier_payment locks the supplier invoices, validates allocations against outstanding amounts, records optional drawer cash-out exactly once, posts allocations, and audits atomically.

6.5 Open/close register

Opening locks the cashier User row first and the Register row second, then checks all active sessions under the current policy. Every register-opening path uses that order, so a mutable “multiple sessions per cashier” setting is enforced safely without a nonexistent dynamic database constraint. Closing locks the session so checkout cannot attach a sale after closing begins, recalculates all authoritative totals, stores close-time snapshots, and records the audit event atomically.

Closed-session snapshots are immutable. A later refund, cancellation, customer payment, supplier payment, or expense never rewrites the old session: if physical drawer cash is involved, it is posted to a currently open authorized session.

6.6 Sensitive administration

Price changes, stock adjustments, settings changes, sale cancellation, expense voids, purchase returns, refund approval, and user-role changes use explicit services. The Django admin is a support interface, not a bypass around those services; protected financial/ledger fields will be read-only or unavailable there.

6.7 Idempotent command handling

The CommandIdempotency service canonicalizes the validated command, hashes its material input, and reserves (business, operation, key) inside the transaction. It is used for every irreversible retryable command listed in section 5.2. A uniqueness race is handled outside the failed atomic block, after which the winning result is returned only when its fingerprint matches.

6.8 Cash source and drawer effects

For customer payments, supplier payments, refunds/cancellations, and expenses, “cash” must specify either:

  • REGISTER_DRAWER: requires a currently open authorized register session and creates exactly one linked cash-in/cash-out effect; or
  • EXTERNAL_CASH_ACCOUNT: records cash outside the POS drawer and does not affect expected drawer cash.

Direct cash sale/refund components are counted from their payment/refund records. Ancillary cash flows use a linked RegisterCashMovement. A database uniqueness rule on the source prevents both the domain payment and a duplicate manual cash movement from being counted.

6.9 Customer account commands

post_customer_payment locks the customer/account scope, validates currency and positive tender, creates the payment and one ledger credit, records any current-drawer cash-in, and audits atomically. Corrections create linked reversals. Services may cache a balance for performance only if every post locks and updates it with the immutable entry; reconciliation always treats the ledger sum as authoritative.

7. Calculation specification

7.1 Numeric representation

  • Money: Decimal, with storage precision sufficient for prices and calculations; never float.
  • Quantities: Decimal; the product unit defines allowed scale.
  • Rates: Decimal percentage values.
  • Currency code: snapshot on every financial document.
  • Calculation helpers construct Decimal from strings/integers only.
  • Every rounding point uses an explicit rounding mode and currency minor unit.

USD begins with two minor-unit decimal places. Supporting a different configured currency means looking up its exponent and display format; no template or service hardcodes $.

7.2 Authoritative inventory costing policy

V1 uses a business-wide moving weighted-average cost per product:

  • Product.cost_price is the one authoritative current average cost.
  • InventoryBalance stores quantity only; it does not contain a competing editable cost.
  • Every quantity mutation locks the Product row before its location balance, so all locations serialize cost/quantity effects for that product.
  • Checkout snapshots the locked Product.cost_price into SaleItem.unit_cost.
  • Inventory valuation is the sum of each location quantity multiplied by that product’s authoritative cost.

For a purchase receipt or other costed inbound movement while total business stock is non-negative:

new_cost =
  ((old_total_quantity * old_cost) + (inbound_quantity * inbound_unit_cost))
  / (old_total_quantity + inbound_quantity)

The result is retained at internal cost precision; currency rounding occurs only where a posted money amount requires it. Inbound unit cost is net of line discount and excludes recoverable tax. Landed-cost allocation is out of v1 unless a concrete allocation rule is added.

Cost effects by movement:

  • Opening stock or a positive adjustment requires an authorized unit cost and uses the weighted-average formula.
  • A purchase receipt uses its received net unit cost.
  • A sale, damaged/expired movement, negative adjustment, or supplier return reduces quantity without changing the current average; its movement snapshots the current cost.
  • A sale return blends the original SaleItem.unit_cost back into current stock.
  • A future transfer moves quantity between location balances, snapshots the product cost on both ledger legs, and does not change the business-wide product cost.
  • When stock reaches zero, the last average remains as the default cost.
  • If negative stock is explicitly enabled, outbound stock is costed at the last known average. When an inbound movement arrives while pre-inbound total stock is zero or negative, the authoritative cost resets to that inbound cost rather than applying a mathematically invalid negative weighted average.

Before stock exists, an authorized manager may set the product’s initial cost. With positive stock, manual cost changes require InventoryCostRevaluation, a reason, permission, and audit event.

This policy is fixed before Phase 3, not deferred until purchases, because opening stock and Phase 4 sale COGS already depend on it.

7.3 Recommended initial tax and discount policy

Unless changed before Phase 4:

  • Catalog prices are tax-exclusive.
  • Discounts reduce the taxable base.
  • Item discounts are applied before the sale-level discount.
  • Percentage inputs are converted by the server to stored money amounts.
  • Discounts cannot make a line negative.
  • Sale-level discounts are allocated proportionally across eligible lines.
  • Rounding residuals are distributed deterministically in stable line order.
  • Tax is rounded per line to the currency minor unit.

For a line:

gross = quantity * unit_price
discounted_base = gross - item_discount - allocated_sale_discount
tax = round_currency(discounted_base * tax_rate / 100)
line_total = discounted_base + tax
line_cost = quantity * unit_cost_snapshot

Sale totals are sums of stored line results, not an independently rounded browser total.

7.4 Payments, receivables, and change

  • By default, sum of payment amounts applied must equal the completed sale total.
  • For an authorized on-account sale, applied payments + new customer receivable = completed sale total.
  • Cash tendered may exceed the amount applied; the excess is change.
  • Non-cash overpayment is rejected.
  • Every mixed-payment component is positive and uses a real tender method.
  • The browser cannot submit an authoritative paid total or change value.

7.5 Recommended reporting definitions

Use consistent shared definitions:

  • Gross sales: completed line value before discounts and tax, less full cancellation-reversal line value.
  • Net sales: completed line value after discounts and before tax, less completed return line value; cancellation return items are included.
  • Tax collected: sale tax less returned/cancellation-reversed tax.
  • Net tender collected: posted sale/customer payments less completed refunds, cancellation reversals, and payment reversals; on-account charges are not tender.
  • Transactions: count of completed sales that do not have a completed full cancellation; partial returns remain transactions.
  • Average order value: net sales divided by qualifying transaction count, with the displayed definition stated.
  • COGS: completed sold quantity multiplied by sale-item cost snapshots, less returned and cancellation-reversed cost snapshots.
  • Gross profit: net sales excluding tax minus COGS.
  • Expenses: posted, non-voided expense amounts in the report period.
  • Top-selling products: net quantity/value after completed returns and cancellation reversals.
  • Payment-method totals: applied payments less completed refunds/cancellation reversals by method.
  • Customer outstanding/store credit: positive/negative sides of the posted customer account-ledger balance.
  • Inventory valuation: each location’s current quantity multiplied by the product’s authoritative current moving-average cost.
  • Supplier balance: posted supplier-invoice liability less valid payment allocations and posted supplier-return credits.

“Gross profit” is not net profit; operating expenses remain a separate metric unless a clearly labelled derived metric is added.

7.6 Dashboard and report catalog

The dashboard will expose, with business-time-zone date boundaries:

  • Net sales today, this week, and this month
  • Gross profit
  • Qualifying transaction count and average order value
  • Posted expenses
  • Low-stock products
  • Top-selling products
  • Recent sales
  • Net sales by payment method
  • Net-sales trend and gross-profit trend charts

The report selectors will cover:

  • Daily sales and arbitrary sales date ranges
  • Sales by product, category, cashier, customer, and payment method
  • Gross profit
  • Inventory valuation, current stock, low stock, and stock movement history
  • Purchase orders, goods receipts, supplier invoices/payments, and supplier balances
  • Expenses
  • Returns, refunds, and cancellation reversals
  • Register sessions

Important tabular reports support permission-checked CSV export using the same validated filter object as the on-screen results.

8. Permissions and object scope

Groups seed baseline permissions; views and services check permissions on the server. Every queryset is scoped to the user’s business and allowed location before an object is retrieved.

Capability Admin Manager Cashier
Users, roles, critical settings Full No by default No
Products/categories Full Manage View/search
Product cost/profit Full View/manage Hidden and denied
Stock adjustment Full Manage No
Purchases/suppliers Full Manage No
Customers Full Manage Search/create minimum fields
Open/close own register Full Manage/override Own only
Complete sale Full Yes Own open session
Sell on customer account / post customer payment Full Policy-limited Only explicit permission
View sales All All permitted locations Own unless granted view_all_sales
Discounts/price override Full Policy-limited Only explicit permission/limit
Request refund Full Yes Optional explicit permission
Approve refund/cancel sale Full Yes No
Expenses Full Manage Optional create-only permission
Reports/CSV export Full Permitted reports Own summary only if granted
Audit log Full Read if granted No

Custom permissions should include at least:

  • change_product_price
  • view_product_cost
  • adjust_stock
  • view_all_sales
  • apply_discount
  • override_price
  • sell_on_account
  • post_customer_payment
  • cancel_sale
  • request_refund
  • approve_refund
  • receive_purchase
  • manage_registers
  • view_profit_reports
  • export_reports
  • change_critical_settings

Hiding a link or button is only interface behavior and never substitutes for these checks.

9. Critical business invariants

9.1 Products and inventory

  • SKU normalization is consistent and uniqueness is database-enforced.
  • Barcode is optional, stored as text, and unique when present.
  • Identifier reuse is not allowed merely because a product is inactive.
  • Transaction quantities are positive; adjustment deltas are non-zero.
  • Fractional quantities are rejected for units that do not allow them.
  • Every balance change has exactly one immutable stock movement.
  • A movement uses one sign convention and records correct previous/new values.
  • Negative stock is rejected while the locked balance is current unless the setting permits it.
  • Disabling negative stock does not rewrite existing negative balances; it blocks further outbound movement and permits inbound recovery.
  • A reconciliation command must prove balance equals opening plus ledger deltas.

9.2 Sales

  • Server calculations are authoritative.
  • Inactive/missing products cannot be newly sold.
  • Checkout validates the current price, tax, cost, unit, and stock under lock.
  • Completed sale items and payments are immutable.
  • A sale, items, payments, stock changes, reference, register link, and audit event succeed or fail together.
  • A unique idempotency key prevents duplicate completion.
  • Historical receipts and reports use stored snapshots.
  • Sale-level discount allocation is deterministic and preserved per line.
  • Mixed payments reconcile exactly.
  • An on-account balance is permitted only for an attached customer when the business setting and actor permission allow it; the unpaid portion creates exactly one account-ledger entry.
  • Applied tenders plus the authorized account charge reconcile exactly to the total.
  • Abandoning a cart, cancelling a sale, and returning goods are distinct actions.

9.3 Purchases

  • Draft/ordered purchase orders do not change inventory or accounts payable.
  • Only a completed goods receipt adds inventory.
  • Only a posted supplier invoice creates accounts payable; receipt and invoice matching cannot apply stock twice.
  • Receiving is atomic and idempotent.
  • Cumulative receipts cannot exceed ordered quantity without an approved over-receipt policy.
  • Supplier payments are positive and cannot be allocated beyond posted outstanding invoices until supplier credit exists.
  • Cancelling/closing a purchase order cannot remove received stock; use a purchase return.

9.4 Returns and refunds

  • Original sale data remains unchanged.
  • Every returned line references an original sale item.
  • Cumulative completed returns cannot exceed the sold quantity.
  • Refund value cannot exceed the remaining refundable value.
  • Return math uses original price, discount, tax, and cost snapshots.
  • Approval requirements are snapshotted when the request is made.
  • Inventory, refund, register effect, and audit commit together at completion.

9.5 Registers

  • Opening and counted balances are non-negative.
  • A cashier cannot sell without an open session when the role requires it.
  • Only one open session exists per register.
  • Cash-in/cash-out is append-only and always has a reason.
  • A closed session cannot be reopened or edited.
  • Checkout and close lock the same session row.

9.6 Records and settings

  • Financial and ledger records are never hard-deleted.
  • Master/reference data is deactivated instead of deleted when history exists.
  • Foreign keys to historical data use PROTECT/RESTRICT, not destructive cascade.
  • Corrections use explicit reversal/cancellation/return records.
  • Currency, tax, cost, names, and receipt identity are snapshotted.
  • Settings changes are prospective.
  • Audit events are append-only.
  • All stored times are timezone-aware UTC; business dates use the snapshotted/configured zoneinfo time zone.
  • Every relationship is same-business and, where relevant, same/allowed-location: category/product, product/balance/location, sale/customer/register, purchase order/supplier/receipt, expense/location, and actor/location.
  • Cross-table business/location consistency is enforced in command services and model validation, with negative tests; redundant business IDs are never trusted merely because each foreign key is individually valid.
  • A user’s default/current location must be an active UserLocationAccess row in that user’s business.

9.7 Audit event acceptance matrix

Every row below requires a workflow test asserting event code, actor, object identity, timestamp, safe description/metadata, request correlation ID, and IP when a validated HTTP request is available.

Required action Event code(s) Minimum safe metadata
Successful/failed login and logout auth.login_succeeded, auth.login_failed, auth.logout Username/user ID as appropriate; never password
Product creation/update product.created, product.updated Product ID/SKU and changed field names
Selling-price or cost change/revaluation product.price_changed, inventory.cost_revalued Old/new Decimal values, reason, product
Stock adjustment/damaged/expired movement inventory.adjusted Movement/reference, quantity delta, previous/new stock, reason
Sale completion sale.completed Receipt, totals, location/register; no private tender data
Sale cancellation sale.cancelled Sale/cancellation/return references and reason
Refund lifecycle refund.requested, refund.approved, refund.rejected, refund.completed, refund.reversed Frozen revision/fingerprint, amount, method, requester/approver IDs
Goods receipt purchase.received Order/receipt references, location, quantities
Supplier invoice/payment/return supplier_invoice.posted, supplier_payment.posted, purchase_return.completed References and aggregate amounts
Expense creation/void expense.created, expense.voided Expense reference, category, amount, reason
Register open/close and cash movement register.opened, register.closed, register.cash_moved Session, expected/counted/difference or movement amount/reason
Settings change settings.changed Changed field names and safe old/new values; never secret values
User/group/location access change account.access_changed Target user and role/location deltas

10. Risks and mitigations

Risk Mitigation and required proof
Existing work is accidentally lost Resolve the 78-file deletion state; create a backup reference; never bulk restore/stage without review
Two checkouts oversell the last unit PostgreSQL row locks, deterministic lock order, negative-stock validation, two-transaction test
A failed checkout leaves partial data One outer atomic transaction and injected-failure rollback tests
Retry/double-click duplicates an irreversible command Shared idempotency registry, request fingerprint, uniqueness constraint, concurrency tests for every listed command
Two returns exceed the sold quantity Lock original sale items and test concurrent returns
Stock balance diverges from ledger One mutation service, no admin edits, unique source movements, reconciliation command/test
Register closes during checkout Both workflows lock the session and recheck open state
Tax/discount rounding drifts Written formula, fixed rounding points, deterministic allocation, golden-value tests
Settings rewrite history Snapshot currency, tax, item values, and receipt identity
Base-currency edit reinterprets live catalog prices Snapshot catalog currency and block ordinary base-currency changes after activity; require explicit repricing migration
Profit changes after cost edits Snapshot unit cost on every sale item
Two competing cost sources drift Product.cost_price is the sole locked business-wide moving-average source; balances hold quantity only
SQLite hides production races Run all locking, constraint, and concurrency tests on PostgreSQL
Cashier accesses another user’s data Business/location/owner-scoped selectors plus negative object-ID tests
Admin bypasses services Read-only/limited admin for financial and stock models
Upload contains active/malicious content Size and signature validation, raster re-encoding, reject SVG/HTML, randomized names, authorized downloads
CSV export triggers spreadsheet formula execution Escape values starting with =, +, -, @, tab, or carriage return
Report queries become slow or inconsistent Shared metric selectors, proper indexes, query-count tests, bounded filters and pagination
Time-zone day boundaries are wrong UTC storage, configured zone conversion, DST/midnight tests
Payment data leaks Store only method, amount, and safe external reference; redact logs
Cash is counted twice or mutates a closed drawer Explicit drawer/external cash source, unique linked cash movement, current-session-only posting
Purchase order incorrectly creates supplier debt Separate PO, goods receipt, posted supplier invoice, and allocated payment aggregates
Approved refund input changes before completion Frozen revision fingerprint; any change clears approval
Audit can be bypassed or tampered with Transactional audit creation, append-only permissions, workflow audit assertions
Negative stock corrupts average costing Disable by default; define cost behavior before enabling it
Reference generation collides Locked DocumentSequence plus unique constraints and concurrency tests

11. Security baseline

Phase 2 and later must include:

  • Environment-only secrets and production DEBUG=False
  • Explicit allowed hosts and trusted CSRF origins
  • HTTPS redirect, secure cookies, staged HSTS, and appropriate security headers
  • Correct trusted-proxy configuration before trusting forwarded IP/protocol headers
  • Django password validators, generic login errors, session expiry, and login audit
  • Brute-force/rate-limit protection selected and tested before production
  • CSRF on every unsafe browser request; no state-changing GET endpoints
  • Whitelisted form fields and server-side validation
  • Permission checks both at the HTTP boundary and inside sensitive services
  • Business/location/owner scoping before object retrieval
  • Protected private media rather than public predictable expense-receipt URLs
  • Upload size/type/signature checks and safe generated filenames
  • Redacted application logs and error reporting
  • Locally vendored frontend assets or pinned CDN assets with integrity/CSP controls
  • Bounded searches, pagination, report ranges, and export sizes
  • Least-privilege PostgreSQL application user
  • Encrypted backups with documented, tested restoration
  • manage.py check --deploy, dependency auditing, secret scanning, and static analysis before release

12. Important decisions, defaults, and remaining confirmations

These are not blockers for writing Phase 1, but each must be confirmed before its affected phase. The recommended default is recorded so work can proceed deliberately.

Decision Recommended default
Repository replacement strategy Decided 2026-07-28: retire ProofReply and build the POS at the repository root
Tenancy One business per deployment; no SaaS multi-tenancy in v1
Locations One default location in UI; location-aware inventory schema from day one
Tax mode and rounding Tax-exclusive, after discounts, rounded per line
Discount policy Fixed/percentage requests converted to money; deterministic line allocation; role-based limits
Inventory costing Decided: business-wide moving weighted average in section 7.2; negative stock disabled by default
Partial purchase receiving Schema supports it; initial UI may offer receive-all plus partial quantities
Customer credit/outstanding balance Account ledger and customer payments are required; on-account checkout is disabled by default until enabled with explicit permission/policy
Returned item condition Restock by default; damaged goods require a separate damaged movement
Refund approval Effects occur only on approved completion; requester cannot self-approve when approval is required
Completed-sale cancellation Manager-only explicit reversal, never in-place deletion/edit
Register meaning Logical/physical drawer per location; one open session per register
Multiple cashier sessions Disabled by default; add the requested setting and serialize openings by locking the cashier row
Invoice numbering Unique prefix + locked counter; reset policy configurable; no gapless promise
Currency changes Snapshot all documents; block ordinary base-currency changes after activity and require an explicit repricing migration; no exchange rates/multi-currency in v1
Payment integration Record externally completed tenders only; no gateway/device integration
Daily report cutoff Business calendar day in configured time zone
Expiry/batch tracking Movement reason only in v1; lot/batch/expiry inventory is separate future scope
Refund window/method Requires business policy before Phase 6
Legal/fiscal rules Owner must provide jurisdiction-specific tax, numbering, retention, and receipt requirements

13. Test strategy

Prioritize service and database-integrity tests over superficial template tests.

13.1 Unit and service tests

  • Decimal tax, item discount, sale discount allocation, rounding residuals, weighted quantities, mixed payments, and change
  • Moving-average cost for receipts, returns, zero stock, and explicitly allowed negative stock
  • Customer receivable/store-credit signs, on-account reconciliation, payments, and return allocation
  • State transitions and invalid transitions
  • SKU/barcode normalization and uniqueness
  • Quantity precision by unit
  • Reference formatting and currency formatting
  • Expected cash and report metric helpers

13.2 Transaction and integration tests

  • Atomic stock adjustment
  • Atomic sale completion with failure injected after each major step
  • Prevent overselling
  • Duplicate idempotency key
  • Same/different-fingerprint retries for return/refund, cancellation, customer/supplier payment, supplier return, cash movement, expense post/void, and register open/close
  • Receipt-number collision protection
  • Mixed payments and non-cash overpayment rejection
  • Purchase receipt idempotency and over-receipt rejection
  • Return/refund rollback and excessive-return rejection
  • Register open/close and checkout-versus-close
  • Drawer versus external cash behavior and post-close correction posting
  • Ledger/balance, sale/payment/account, supplier-invoice/payment allocation, return/refund, and register reconciliation

13.3 PostgreSQL concurrency tests

  • Two checkouts for the last unit
  • Two requests with one checkout idempotency key
  • Two returns against the same sold item
  • Two register openings
  • Checkout racing register close
  • Two goods receipts for the same remaining quantity
  • Concurrent document-number allocation

SQLite cannot prove these behaviors.

13.4 Permission and security tests

  • Role matrix across GET, POST, HTMX/JSON, receipt, attachment, report, and CSV endpoints
  • Cashier-owned versus guessed sale IDs
  • Cross-location and cross-business access
  • CSRF and unsafe-method enforcement
  • Refund approval bypass/self-approval
  • Protected attachment downloads
  • Oversized, malformed, renamed executable, SVG/HTML, and traversal upload cases
  • CSV formula injection
  • Logs/audit entries do not expose sensitive values

13.5 Historical and reporting tests

  • Product price/cost/name/tax changes do not alter old receipts or profit
  • Currency/settings changes do not relabel old records
  • Voids, cancellations, partial returns, mixed payments, and expenses are classified correctly
  • Time-zone midnight/DST boundaries
  • Inactive products/users remain reportable
  • Empty ranges and zero denominators
  • Dashboard/report query-count budgets

13.6 Manual acceptance checks

  • Barcode scanner keyboard flow and focus behavior
  • Keyboard-only POS operation
  • Mobile/tablet responsiveness
  • 80 mm and A4 print preview with long names and mixed payments
  • Accessible labels, focus states, errors, and color contrast
  • Custom 403, 404, and 500 pages

14. Indexing and query strategy

Plan indexes for:

  • Normalized SKU, barcode, product name, category, and active state
  • Inventory balance by location/product
  • Stock movements by product/location/time, type, reference, and source
  • Sales by completion time, cashier, customer, location, status, and receipt number
  • Sale items by product and sale
  • Payments by method/time
  • Returns by original sale, state, and completion time
  • Purchase orders and supplier invoices by supplier/location/date/state/reference
  • Goods receipts by order/time/idempotency key
  • Expenses by date/category/location/state
  • Register sessions by cashier/register/state/time
  • Audit events by user/action/object/time

Selectors use select_related, prefetch_related, annotations, conditional aggregates, and pagination. Dashboard cards should share bounded date filters and avoid one query per row. Query-count tests will guard the highest-traffic pages.

15. Phase-by-phase implementation roadmap

Every phase follows this loop:

  1. Announce the coherent scope.
  2. Inspect relevant files and current Git state.
  3. Implement the smallest complete slice.
  4. Create/review migrations when models change.
  5. Run focused tests and Django checks.
  6. Fix failures before continuing.
  7. Record files, commands, results, and remaining work here.
  8. Stop at the phase checkpoint.

Phase 1 — Analysis and architecture

Status: Complete.

Delivered:

  • Workspace and Git assessment
  • Architecture and dependency direction
  • Django app structure
  • Core models and relationships
  • Transaction/service boundaries
  • Permission matrix
  • Calculation and reporting definitions
  • Critical invariants
  • Risk and security baseline
  • Test strategy and implementation roadmap

Exit criteria:

  • This document exists.
  • Phase 2 code has not begun.
  • The existing 78 deletions remain untouched.

Phase 2 — Project foundation

Status: Complete.

Entry gate:

  • Repository replacement decision in section 2.4 is resolved.

Steps:

  1. Safeguard the old Git history.
  2. Create a Python 3.12 virtual environment.
  3. Pin Django 5.2 LTS at the latest security patch and add only justified dependencies.
  4. Create config and domain app packages.
  5. Add split settings and environment validation.
  6. Add PostgreSQL-ready and initial SQLite configuration.
  7. Define the custom user model before the first migration.
  8. Add Business, BusinessSettings, Location, sequence, and audit foundations.
  9. Seed groups and granular permissions through an idempotent data migration/command.
  10. Add login/logout, base Bootstrap templates, sidebar/topbar, messages, and error pages.
  11. Configure static/media, logging, uploads, and production security.
  12. Add .env.example, Python-aware .gitignore, test configuration, and initial README sections.
  13. Create and apply migrations.
  14. Run system checks, focused tests, production setting checks, and a server smoke test.

Delivered:

  • Python 3.12 virtual environment and exact dependency pins for Django 5.2, PostgreSQL, image validation, Argon2 password hashing, pytest, and Ruff
  • Split base, local, test, and fail-closed production settings
  • SQLite local/test support and PostgreSQL URL/environment configuration
  • Custom accounts.User model with durable business/default-location invariants, protected security-field writes, and explicit per-location access
  • Idempotent Admin, Manager, and Cashier group synchronization through bootstrap_roles and post_migrate, limited to POS-domain permissions
  • Global support administration restricted to superusers; business roles cannot enumerate or mutate cross-business records through Django admin
  • Business, BusinessSettings, Location, DocumentSequence, and CommandIdempotency models with validation and database constraints
  • Separately permission-checked business-profile and critical-settings editing, with redacted old/new audit context
  • Append-only AuditEvent model, authoritative request IDs, safe client-IP handling, metadata redaction, and authentication/settings/access audit hooks
  • Transactional database-backed login throttling with independent HMAC-only identity and IP buckets, including the global support login
  • Login/logout, protected home page, responsive Bootstrap shell, messages, form states, and custom 400/403/404/500 pages
  • Static/media, upload validation, CSP and other security headers, logging, .env.example, .gitignore, pytest/Ruff configuration, and README
  • Initial core, accounts, and audit migrations plus the regular-user business constraint and login-throttle state migrations
  • SQLite and disposable PostgreSQL 17 migration/test verification

Exit criteria:

  • Clean SQLite and PostgreSQL migrations succeed.
  • Login/logout, roles, CSRF, unauthorized access, and custom error tests pass.
  • manage.py check passes.
  • manage.py check --deploy passes under a representative secure production environment.
  • The development server starts.
  • No secret or generated data is tracked.

All Phase 2 exit criteria were met on 2026-07-28. Detailed commands and results are recorded in section 17.

Phase 3 — Products and inventory

Steps:

  1. Implement category, unit, product, location balance, and movement models.
  2. Add SKU/barcode normalization and database constraints.
  3. Implement the authoritative moving-average cost algorithm, opening-cost rules, and audited cost revaluation.
  4. Implement the single stock mutation service and opening/adjustment commands.
  5. Lock down admin and ordinary saves from direct balance changes.
  6. Add product CRUD, image validation, search, filters, pagination, stock views, and low-stock warnings.
  7. Add inventory ledger/history and reconciliation command.
  8. Test cost calculations, all movement types required at this stage, precision, negative stock, rollback, and permissions.
  9. Run PostgreSQL last-unit concurrency tests.

Exit criteria:

  • Every stock change has a matching movement.
  • No reachable UI/admin path writes stock directly.
  • Balance reconciliation passes.
  • SKU/barcode, negative-stock, atomicity, and concurrency tests pass.
  • Search/filter queries are indexed and query-count checked.

Phase 4 — Sales, POS, receipts, and registers

Steps:

  1. Implement registers, sessions, cash movements, sales, item snapshots, and payments.
  2. Implement the minimal Customer model, search, and quick-create path required by the Sale foreign key; broader customer management/accounting remains in Phase 6.
  3. Implement the Decimal calculation/allocation module with golden-value tests.
  4. Implement open/close register services and reconciliation.
  5. Implement atomic, idempotent checkout with row locks and document sequencing.
  6. Build a fast responsive POS interface with product/barcode search and keyboard workflow.
  7. Add customer selection, discounts, notes, mixed payments, loading/duplicate-submit UX, and server error recovery.
  8. Add authenticated 80 mm and A4 receipt views and print CSS.
  9. Add permission, ownership, rollback, idempotency, oversell, mixed-payment, register-race, and snapshot tests.

Exit criteria:

  • Sale, payments, inventory, register, reference, and audit reconcile.
  • Injected failures leave no partial checkout.
  • Double submission creates one sale.
  • Concurrent last-unit checkout yields only valid outcomes.
  • Cashier ownership restrictions pass.
  • 80 mm/A4 printing is manually verified.

Phase 5 — Suppliers and purchases

Steps:

  1. Implement suppliers, purchase orders/items, and their state transitions.
  2. Implement goods receipts and partial-receipt-capable lines independently from liabilities.
  3. Implement posted supplier invoices/items, receipt/order matching, payment status, and supplier balance.
  4. Apply the already-defined moving weighted-average costing policy to purchase receipts and supplier returns.
  5. Implement atomic/idempotent receiving and purchase stock movements.
  6. Implement supplier payments and invoice allocations.
  7. Implement supplier returns for purchase-return movements.
  8. Add views, filters, permissions, audit, and tests.

Exit criteria:

  • Draft/order creation never changes stock.
  • A receipt changes stock exactly once.
  • Partial/full receipt, over-receipt, overpayment, return, rollback, and permission tests pass.
  • Stock ledger and supplier balance reconcile.

Phase 6 — Customers, expenses, returns, and refunds

Entry decisions:

  • Confirm whether on-account checkout is enabled, any credit limit/terms, return disposition, refund window/method, and approval policy.

Steps:

  1. Complete customer CRUD, search, history, spending, and the existing quick POS path.
  2. Implement the required customer account ledger/payments and outstanding/store-credit calculations; enable on-account checkout only under the confirmed policy.
  3. Implement expense categories, posted expenses, private attachments, filters, and void workflow.
  4. Implement sale-return requests, approval, item quantity caps, and snapshot calculations.
  5. Implement atomic refunds, stock restoration, register cash effects, and audit.
  6. Implement completed-sale cancellation/reversal.
  7. Add customer-ledger reconciliation, on-account permission, return allocation, concurrency, approval, history, attachment, and malicious-upload tests.

Exit criteria:

  • Original completed sales remain immutable.
  • Concurrent returns cannot exceed sold quantity.
  • Refund, stock, register, and audit effects are atomic.
  • Approval and object-access bypass tests pass.
  • Customer outstanding/store-credit values reconcile exactly to the real account ledger; on-account sales remain disabled unless their policy is enabled.

Phase 7 — Dashboard and reports

Steps:

  1. Implement shared metric/query selectors using section 7.5 definitions.
  2. Add dashboard cards, recent sales, low stock, top products, payment mix, and Chart.js trends.
  3. Add all requested date/filter forms and paginated reports.
  4. Add safe CSV exports for important reports.
  5. Add indexes and optimize N+1/query-count issues.
  6. Add realistic-volume seed fixtures and metric reconciliation tests.

Exit criteria:

  • Metrics reconcile across sales, returns, discounts, tax, payments, expenses, and time zones.
  • Historical profit remains unchanged after cost edits.
  • Exports match filters and resist formula injection.
  • Recorded query-count and response-time budgets are met.

Phase 8 — Security and quality review

Steps:

  1. Inventory every endpoint, unsafe method, permission, object scope, and export.
  2. Review service-only mutations, validation, atomicity, lock order, idempotency, and race tests.
  3. Review production settings, proxy/HTTPS, sessions, CSRF, uploads, private media, logging, and secrets.
  4. Review query plans, pagination, export limits, and dashboard performance.
  5. Review accessibility, keyboard workflow, validation messages, and error states.
  6. Run the full PostgreSQL suite, security checks, lint/format, dependency audit, secret scan, and accessibility/browser smoke checks.

Exit criteria:

  • No known critical/high authorization, integrity, secret, or upload issue remains.
  • Every sensitive mutation has permission, scope, validation, transaction, audit, and failure-path coverage as applicable.
  • Full PostgreSQL and security/quality gates pass.
  • Accepted lower risks have an owner and documented mitigation.

Phase 9 — Documentation and final verification

Steps:

  1. Complete README, architecture, business rules, Windows setup, PostgreSQL setup, environment, migrations, tests, and troubleshooting.
  2. Create a development-only, repeat-safe demo-data command for Admin, Manager, Cashier, products, parties, purchases, sales, and expenses.
  3. Document demo credentials prominently and require changing them outside development.
  4. Document deployment, HTTPS, static/media, least privilege, backup/restore, monitoring, rollback, and incident steps.
  5. Verify a clean installation using only the documentation.
  6. Run migration drift, migrations, tests, checks, static collection, lint/format, dependency/security checks, and final secret/tracked-file review.

Exit criteria:

  • A clean clone can be installed, migrated, seeded, tested, and started from the documentation.
  • All final commands and their actual results are recorded.
  • Implemented, deferred, and known-limitation lists are accurate.
  • No placeholders or apparently functional but unimplemented controls remain.

16. Phase 1 verification record

Read-only inspection commands included:

  • Get-ChildItem -Force
  • rg --files with generated/dependency exclusions
  • git status --short --branch
  • git status --porcelain=v2 --untracked-files=all
  • git diff --stat
  • git log --oneline --decorate -10
  • git ls-tree -r --name-only HEAD
  • git show HEAD:<path> for prior instructions, README, package metadata, ignore rules, and hosting metadata
  • git remote -v
  • Python, Django, SQLite, PostgreSQL, Node, npm, and Git version probes

Results:

  • Workspace/Git assessment completed.
  • No files were restored, staged, deleted, or overwritten.
  • No code tests were applicable because no working application exists.
  • Django import/version probes confirmed Django is not installed; this is an environment finding, not a failed application test.
  • No migration or server command was run because Phase 2 has not started.
  • This implementation plan is the only Phase 1 file created.

17. Phase 2 verification record

Implementation and review commands included:

  • python -m pip check
  • python manage.py migrate --noinput
  • python manage.py bootstrap_roles
  • python manage.py check
  • python manage.py check --deploy under representative fail-closed production environment variables
  • python manage.py makemigrations --check --dry-run
  • python manage.py showmigrations core accounts audit
  • python -m pytest
  • python -m ruff format --check .
  • python -m ruff check .
  • python -m compileall -q apps config manage.py
  • python manage.py collectstatic --noinput
  • python manage.py runserver 127.0.0.1:8765 --noreload
  • HTTP probes of /accounts/login/ and /
  • A disposable postgres:17-alpine container for production migrations and the full test suite

Results:

  • All Phase 2 migrations applied successfully on SQLite and PostgreSQL 17.
  • Migration drift check reported No changes detected.
  • SQLite completed 67 tests with the PostgreSQL-only row-lock concurrency test skipped; all 68 tests passed on PostgreSQL 17.
  • The test suite covers user/business/location invariants, protected ORM mutation paths, global-support isolation, role synchronization, split permissions, CSRF, login throttling, settings/access auditing, audit immutability and redaction, request IDs, trusted-proxy IP handling, document sequencing, command idempotency, Decimal safety, upload validation, authentication events, custom error handlers, and protected settings views.
  • The PostgreSQL suite includes a two-connection login-throttle row-lock test; no failure increment was lost.
  • Django system checks and hardened production deployment checks reported no issues.
  • The real development server started; /accounts/login/ returned HTTP 200 with request-ID and CSP headers, while protected / returned HTTP 302 to login.
  • Ruff formatting and lint checks passed across 80 files.
  • Dependency consistency and Python byte-compilation checks passed.
  • Static collection copied 129 assets successfully.
  • The disposable PostgreSQL container was stopped and automatically removed after verification.
  • Two independent adversarial reviews were resolved; the final spot check found no remaining blocker/high issue in the Phase 2 scope.
  • Generated databases, collected static files, virtual environments, uploads, caches, and secrets remain ignored.
  • The retired ProofReply deletions and all Phase 2 work remain unstaged; Git history was not rewritten.

18. Phases 3–8 implementation record

Phase 3 — products and inventory

Delivered category, unit, and product management; normalized tenant-scoped SKU and optional barcode uniqueness; validated product images; search, category, active, and stock filters; per-location balances; an immutable movement ledger; opening stock, adjustment, damage/expiry, purchase, sale, and return movement orchestration; negative-stock enforcement; weighted-average cost; explicit cost revaluation; low-stock views; inventory reconciliation; database constraints; permission and concurrency tests.

All balance changes flow through the inventory service under an atomic row lock. The projected balance and average cost are recorded on every movement so the ledger can be reconciled independently.

Phase 4 — sales, POS, receipts, and registers

Delivered atomic/idempotent checkout, historical line snapshots, deterministic discount allocation, inclusive/exclusive tax calculations, cash/card/bank/mobile and mixed tenders, cash change, on-account sales, product/customer search, responsive cart UI, duplicate-submit protection, receipt references, cashier ownership scope, oversell protection, 80 mm receipts, A4 invoices, authenticated downloads, register/drawer setup, opening/closing, cash in/out, and expected-versus-counted reconciliation.

The server recalculates every total from stored product and settings data. Sales, items, payments, stock movements, customer ledger entries, register effects, references, and audit events commit or roll back together.

Phase 5 — suppliers and purchases

Delivered supplier management, purchase orders and line snapshots, placed and cancelled order states, partial goods receipts, over-receipt prevention, weighted-cost inventory updates, posted supplier invoices, unpaid/partial/paid status, supplier payments and allocations, list/detail/create/receive/payment screens, supplier returns tied to exact received quantities, explicit supplier credits, AP refund receivables, draft cancellation, posted-invoice voids, supplier-payment reversals, closed-drawer correction tracking, filters, server-side permissions, audit events, and rollback-focused tests.

Draft and placed orders do not affect stock. Inventory increases only from an idempotent goods receipt. Supplier-return stock and the corresponding approved supplier credit post atomically; the AP ledger never infers an approved credit from inventory cost alone.

Phase 6 — customers, expenses, returns, and refunds

Delivered customer CRUD/search/history, spending, outstanding balance, store credit and append-only customer account payments; expense categories, posted and voided expenses, date filters, private validated attachments and register cash effects; full/partial sale-return requests, manager approval/rejection, quantity caps, snapshot-based refund calculations, restocking, refund/customer ledger/register effects, and completed-sale cancellation.

Original completed sales remain unchanged. Returns and cancellations of on-account value credit the customer account instead of paying out uncollected cash. Cash corrections discovered after a register closes preserve the immutable closing snapshot and are surfaced as outstanding drawer reconciliation work.

Phase 7 — dashboard and reports

Delivered business/location/date scoped dashboard cards, sales/profit trends, payment mix, top products, low stock, recent sales, and the requested sales, profit, inventory, purchase, supplier, expense, return/refund, and register reports. Report selectors use bounded querysets and grouped aggregates; profit uses the cost captured on each sale line. Important reports support formula-safe CSV export and profit visibility is separately permissioned.

Phase 8 — security and quality review

The implementation review covered server-side permission and tenant/location scope, protected object access, service-level authorization, malformed/non-finite decimal input, approval binding, idempotency fingerprints, lock order, return/refund overrun races, financial immutability, private uploads, audit metadata, report CSV injection, query counts, CSP/security settings, accessibility labels, destructive confirmations, and error handling.

Automated coverage includes authentication and roles, custom-user scope, products, inventory adjustments and reconciliation, register lifecycle, checkout and mixed tenders, overselling and idempotency, customers/suppliers, purchasing, expenses, returns and excessive quantities, report calculations, exports, dashboard query budgets, seed idempotency, and PostgreSQL-only concurrency cases.

19. Phase 9 final verification record

Status: complete.

  • SQLite: 239 tests passed, 4 PostgreSQL-only tests skipped as expected, and 43 subtests passed.
  • PostgreSQL 17: fresh migrations applied and 243 tests plus 43 subtests passed with no failures or skips. The disposable verification containers were removed afterward.
  • Configuration: manage.py check, migration-drift detection, and a hardened production manage.py check --deploy all passed.
  • Code quality: Ruff lint and format checks passed across 191 files; all local JavaScript passed node --check; pip check, bytecode compilation, collectstatic, and whitespace validation passed.
  • Demo data: roles were bootstrapped, the idempotent demo seed was run twice, and the inventory reconciliation command passed.
  • Live acceptance: the development server returned successful authenticated responses for the dashboard, POS, sales, customers, suppliers, products, inventory, purchases, expenses, registers, reports, employees, and settings. Dashboard metrics and chart payloads, exact-SKU POS search, static assets, role boundaries, and self-contained receipt/invoice downloads were also checked against the running application.

The local dashboard is served at http://127.0.0.1:8000/reports/dashboard/.