djangoerp¶
Django ERP's direction is to become the ultimate open home for all things enterprise resource planning: data, tools, resources and transparency, with a double-entry core, modular order-to-cash, procure-to-pay and make-to-stock flows, and an inspectable API for everyone (constitution §1).
What this repo is¶
DjangoERP is a Django 6 + DRF ERP built outward from a double-entry accounting core into order-to-cash, procure-to-pay and make-to-stock processing plus an MRP planning engine. The financial core was consolidated from amrs-project (AMRS), the most mature of the fleet's three accounting prototypes (amrs-project, afms, amrs-django); the supply-chain and planning modules re-implement designs from ERPNext, Odoo, Tryton, InvenTree and frePPLe, with no copyleft code (docs/ARCHITECTURE.md). A change is done when python manage.py check is clean, makemigrations --check reports no drift, python manage.py test and python -m pytest both pass, python manage.py demo_erp still ends balanced, the generated route reference is current, and the nearest README.md reflects the change.
Stack & commands¶
Python 3.12+ (Django 6 dropped 3.11; the hub's shared CI runs 3.12), Django 6.1, DRF, SimpleJWT, drf-yasg (Swagger/ReDoc), django-filter, Celery + Redis, PostgreSQL in production and SQLite by default in dev. Dependencies are pinned exact in requirements.txt; when bumping them, the whole loop below plus demo_erp is the acceptance gate.
# install
python3.12 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt
cp .env.example .env
# run on http://localhost:8000/ (migrations are committed)
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
# test
python manage.py test
python -m pytest
# lint and verify
flake8 --max-line-length=120 --exclude=.venv,migrations .
python manage.py check
python manage.py makemigrations --check --dry-run
python manage.py demo_erp
More, as needed:
python manage.py simulate --ticks 30 # the agent sandbox: bootstrap if needed, run 30 ticks, fail if the books break
python manage.py simulate --what-if add_line:A --horizon 30 # a rolled-back what-if; the live books are untouched
isort . # configured in pyproject.toml (line_length=120, first-party apps)
black <files you touched> # installed but unconfigured: never reformat whole files
python3 tools/gen_api_routes.py --write # regenerate docs/reference/api-routes.md (--check to verify)
python3 tools/docs_index.py --write # regenerate the docs/README.md index
python3 tools/unwrap-prose.py --check # markdown: one paragraph per line (--write to fix)
# Docker: the app on PostgreSQL + Redis instead of SQLite + eager Celery; the entrypoint migrates on every start
docker compose up # web + postgres + redis, autoreload, no debugger
docker compose --profile celery up # ...plus a real Celery worker
DEBUGPY_ENABLE=1 docker compose up -d --wait web # what VS Code's preLaunchTask runs
docker compose run --rm -e RUN_MIGRATIONS=0 web python manage.py test # the loop in a container: docs/DOCKER.md
docker compose down -v # stop and drop the database volume
Docker gotchas (details in docs/DOCKER.md):
- The entrypoint seeds the admin from
.env(DJANGO_SUPERUSER_*, defaultdjangoerp/djangoerp) viadocker/bootstrap-admin.py: superuser plusUserRolerow, idempotent, never resetting an existing password. - Ports bind to
127.0.0.1because an open debugpy port is remote code execution and the stack ships a known password;BIND_HOSTopts out. - Debugging attaches (F5, Docker: Attach to Django; the
preLaunchTaskblocks on the healthcheck). Debug mode runsrunserver --noreloadon purpose — the autoreloader's child serves requests, so breakpoints would never hit. - Editing
docker/*.shneedsdocker compose build; the source tree is bind-mounted, those scripts are baked in.
Layout¶
| Path | Role |
|---|---|
djangoerp/ |
Project package: settings/ (base/dev/prod), root urls.py, celery.py, WSGI/ASGI |
core/ |
TimestampMixin, DocumentSequence (claim numbers only via DocumentSequence.next_number(prefix)), audit.py (log_event), exceptions.py (the DRF exception handler: 409 for a delete a PROTECT key refuses), viewsets.py (ProtectedHistoryDestroyMixin: DELETE removes drafts only), demo.py + demo_erp, and tests.py (the end-to-end suite) |
company/ |
Company (the legal entity whose books these are), the landing page, /health/ and /version — kept out of core/, which stays infrastructure-only |
accounts/ |
UserRole (admin/accountant/viewer/auditor), AuditLog, JWT login, the shared permission classes |
coa/, journal/ |
Chart of accounts (AccountType, self-referencing Account); the double-entry ledger, services.post_entry and services.reverse_entry |
invoices/, reports/ |
AR (Invoice, Payment, GL posting services); ReportTemplate/SavedReport and report_generators.py (all report math) |
partners/, products/ |
BusinessPartner with AR/AP control accounts; UnitOfMeasure, ProductCategory (GL mappings), Product (buy/make, MRP parameters) |
inventory/ |
Warehouse, StockMove (append-only stock ledger), StockLevel (cached on-hand + moving-average cost) |
purchasing/, sales/, manufacturing/ |
Document flows: receipts post Dr Inventory / Cr payable; shipments post Dr COGS / Cr Inventory; work-order completion backflushes at rolled-up cost |
mrp/ |
MRPRun/PlannedOrder, engine.py (the planner, a Celery task), services.convert_run (planned orders → draft POs/WOs) |
simulation/ |
The agent sandbox (README): engine.py (one transaction per tick, agents call services only), brains.py (heuristic or Claude, clamped, with fallback), experiments.py (rolled-back what-ifs), finance.py (guardrails and reconciliations), the simulate command and the /console/ client |
workspace/ |
The /app/ shell every module shares (README, ADR 0004): registry.py (layout plus introspection of every viewset and serializer, and the per-role access matrix from the permission classes; a new viewset fails workspace/tests.py until it has an entry), services.py (read-only document flow, search, overview, statements, each section gated by the owning viewset's permissions), shell.html (which the console extends) and the no-build ES modules in static/workspace/js/ |
docs/ |
ARCHITECTURE.md (module map, invariants, posting matrix, MRP algorithm, adopted patterns), DOCKER.md, the generated reference/ and the index |
tools/ |
gen_api_routes.py; docs_index.py and unwrap-prose.py are vendored from the hub — do not edit |
public/, templates/includes/ |
The feedback widget company/templates/company/base.html mounts, vendored from the hub — do not edit (fleet-feedback-head.html is ours) |
Dockerfile, docker-compose.yml, docker/, .vscode/ |
The image (dev with debugpy, prod with gunicorn), the web/db/redis/worker stack, its scripts, and the attach configurations |
Each app owns models.py, migrations/, tests.py and usually serializers.py, views.py, urls.py, admin.py; document apps also own a services.py holding their state transitions. Each app's DefaultRouter is mounted under /api/<area>/; every route is listed in the generated docs/reference/api-routes.md.
Conventions¶
- Backlog of record: GitHub Issues with the fleet labels. Pick up issues labelled
agent:ready; never touchagent:holdorhuman-review. - Definition of Done: the fleet default pull request template (inherited; none here) plus the done-criteria above.
- Decisions: ADRs in
docs/adr/NNNN-slug.md, indexed indocs/adr/README.md(0002 absorption costing, 0003 the agent sandbox, 0004 the workspace shell). Add one for anything hard to reverse. - Commits: Conventional Commits (
feat fix docs style refactor test chore perf ci build). The PR title is the squash subject. - Branches:
feature/,fix/,docs/,refactor/,test/orchore/offmain; open a PR. - Changelog:
CHANGELOG.md(Keep a Changelog) records notable changes. - Never: push to
maindirectly, commit lockfiles or secrets, suppress type errors (as any,@ts-ignore,# type: ignore), leave empty exception handlers, or edit generated files by hand (docs/reference/api-routes.md, thedocs/README.mdindex span). - README-First, README-Last: read the nearest
README.mdbefore changing a directory; update it after. - Markdown: one paragraph per line (
markdown-oneline.yml; fix withpython3 tools/unwrap-prose.py --write). - Python: 4-space indent, 120-column limit (
.editorconfig);black's default 88 disagrees, so scope it to files you touched. - API surface: one
ModelViewSetper model; read-only surfaces (JournalLine,AuditLog,StockLevel,PlannedOrder) useReadOnlyModelViewSet. Transitions are@actionendpoints delegating toservices.py, never named after an HTTP verb (post_to_ledger+url_path='post', notdef post). A viewset over posted history (journal entries, invoices, payments, stock moves, orders) listscore.viewsets.ProtectedHistoryDestroyMixinbeforeModelViewSet, overridingcheck_deletablewhen "draft" is not its rule. After changing a route or view docstring, runpython3 tools/gen_api_routes.py --write(core/test_docs_reference.pyfails while it is stale). - Permissions: master data (partners, products, warehouses, BOMs, COA) is writable by any authenticated user, like
coa; transactional documents (journal, stock moves, orders, MRP, posting actions) requireIsAccountant, likejournal. - Validation: business rules in serializer
validate(), not views or models; flow preconditions (state, stock, account configuration) inservices.py, raising DRFValidationError. Nested writes (journal, invoice, order and BOM lines) delete and recreate children inupdate(), only in draft. - Decimal precision for new models: quantities
12,3, unit costs/prices12,4, monetary totals 2 dp (ledger lines stay20,2). Quantize GL amounts withDecimal('0.01')before posting. - Ownership is server-side: set
created_byinperform_createor fromself.context['request'].user, and keep it read-only. Models withcreated_at+updated_atsubclasscore.models.TimestampMixin. - Migrations are committed (a real
0001_initial.pyper app, pluscoa's0002_seed_account_typesdata migration). Runmakemigrations --check --dry-runbefore committing a model change; treat drift as a CI failure. .github/workflows/ci.ymlis a thin caller of the hub'sstandard-ci.yml— the gate logic is not here, so don't edit it.
Domain rules that must not be broken¶
Hard-won in amrs-project; never regress them (amrs-django's reports/generators/balance_sheet.py shows what happens when you do).
- Double entry.
journal.services.validate_linesholds the line rules: amounts are non-negative and quantized to the cent, a line carries a debit or a credit (never both), the entry has a non-zero debit and a non-zero credit, and the totals are equal.JournalEntrySerializer.validate(which rejects all-zero lines) andpost_entry(which drops them) both call it,JournalLine's check constraints back it in the database, and every new write path intoJournalEntrymust call it too. Lines are created and replaced wholesale through the nestedlinesserializer, inside one transaction. - Only posted entries count. Every report generator filters
entry__status='posted'; use theJournalEntry.statuschoices (draft/posted/voided), never new magic strings. - Account type codes are load-bearing.
report_generators.pyhard-codesAccountType.codeAS,LI,EQ,RE,EXfor normal balance and report sections, andcoa's0002_seed_account_typesseeds exactly these. Don't rename or remove one without updating every generator; the API refuses to delete or recode them (AccountType.SEEDED_CODES). - Normal balances. Assets and expenses are debit-normal; liabilities, equity and revenue credit-normal.
calculate_account_balancesapplies that signing; the balance sheet and income statement build on it.generate_trial_balancedeliberately does not — it lists raw debit-minus-credit so the columns agree; "fixing" it makesbalancedpermanently false. - The balance sheet folds open P&L into equity. P&L accounts stay open until a closing entry, so
generate_balance_sheetaddscurrent_period_earnings(revenue minus expenses at the report date) tototal_equityand reports it as its own field;reports/tests.py::ReportGeneratorTestspins it. - Roles come from
accounts/permissions.py:IsAdmin,IsAdminOrSelf,IsAccountantandIsAuditor(both admin-implied). They readrequest.user.role.roleinsidetry/except AttributeError, so a user with noUserRolerow is denied, not crashed. Never re-implement role checks inline. - A superuser is not an API user. No signal creates
UserRole, so acreatesuperuseraccount opens/admin/but every role check denies it. Create theUserRolerow with the user (asdocker/bootstrap-admin.pyanddemo_erpdo). - Money is
DecimalField, neverFloatField. Ledger amounts (JournalLine.debit/credit) are20,2— wider than the12,2elsewhere, leaving headroom for a future EDGAR/XBRL import. - The COA is a tree.
AccountSerializer.validatewalks ancestors to reject cycles;Account.parent_accountandAccount.account_typearePROTECT. - Ledger lines outlive their accounts.
JournalLine.accountisPROTECT, so deleting an account can never take posted lines with it. The API refuses to delete an account that has journal lines (400) and points to retirement instead: setis_active=false.generate_trial_balanceandgenerate_general_ledgerkeep listing a retired account that still carries posted lines (reportable_accounts), or the trial balance would stop footing. Any other delete aPROTECTforeign key refuses answers 409 throughcore.exceptions.exception_handler, never a 500. - Posted history is immutable. A posted journal entry can only be voided; a done stock move, posted invoice or posted payment rejects edits. Correct with reversing entries and opposing moves:
POST /api/journal/entries/{id}/reverse/(journal.services.reverse_entry) posts a posted manual entry's mirror, linked byreverses/reversed_by, idempotent perreversal:<id>and audit-logged asjournal.reverse; an entry a business document posted is corrected through that document, and neither half of a reversal pair can be voided. DELETE is refused past draft too: the API answers 400 for a posted or voided entry, a posted invoice or payment, a done stock move and a confirmed (or later) purchase, sales or work order, andpre_deleteguards injournal/,inventory/andinvoices/signals.pyrefuse the same ledger deletes through the ORM or the admin (ProtectedError). - System postings go through
journal.services.post_entry: it enforces the line rules, quantizes to the cent, numbers from theJEsequence and is idempotent per uniquesource_reference(one business event, one entry). Never post with raw ORM calls. - Entry numbers are server-assigned. Manual (API) and system entries share the one
JEseries throughjournal.services.next_entry_number, which skips numbers an older entry already holds;entry_numberis read-only on the serializer, so a client value is ignored. - Only done stock moves count.
StockLevelcaches the sum of'done'moves, maintained under row locks byinventory.services.complete_moveand rebuildable withrebuild_stock_levels(). Never writeStockLeveldirectly. - Moving-average costing, no negative stock. Receipts re-weight
StockLevel.average_cost; issues leave at the current average and raiseInsufficientStockErrorrather than go negative. GL postings use exactly the completed move's snapshottedtotal_value, so stock ledger and GL cannot drift. - State transitions live in
services.py.confirm/receive/ship/complete/post/convert/cancelare the only status writers, each transactional and audit-logged viacore.audit.log_event; serializers reject edits on non-draft documents. - Account mappings are explicit. Postings resolve accounts from
ProductCategory,BusinessPartnerandPayment.deposit_accountand raise a clear configuration error when one is missing — never guess or hard-code account codes. - BOMs cannot loop; one is active per product.
BillOfMaterialsSerializerrejects cycles (MRP's low-level-code pass would never terminate) and a partial unique constraint allows one active BOM per product. - MRP plans only confirmed reality. Demand: confirmed sales orders, open work-order components, safety stock. Supply: on-hand plus confirmed purchase/work orders. Drafts, including freshly converted ones, are invisible until confirmed;
OPEN_STATUSESon the document models stays authoritative.
Architecture notes¶
- Auth is JWT only (chosen over
amrs-django's Token auth): SimpleJWT authentication and anIsAuthenticateddefault, so every endpoint needs a bearer token unless a viewset overrides it.CustomTokenObtainPairSerializeradds the profile and role to the login response. - Settings are split into
djangoerp/settings/{base,dev,prod}.py, picked by whetherDJANGO_SETTINGS_MODULEends in.prod.devruns Celery eagerly and defaults to SQLite;prodaddsSECURE_HSTS_*/secure-cookie hardening and refuses an unset, empty ordjango-insecureSECRET_KEY. New configuration goes inbase.pyasenv(...)with a safe default, documented in.env.example. - Filtering and paging are global:
DjangoFilterBackend,SearchFilter,OrderingFilterandPageNumberPagination(PAGE_SIZE=20) are project-wide, so viewsets declarefilterset_fields/search_fieldswithout repeatingfilter_backends. - Reports and MRP are async.
SavedReportstartsgenerating;generate_report.delay()dispatches ontemplate.report_type, writesresult_dataand endscompletedorfailed(error_message). A new report type is aReportTemplate.REPORT_TYPESchoice plus a branch and generator inreport_generators.py.mrp.engine.run_mrpdoes the same forMRPRun(results inlog). Dev'sCELERY_TASK_ALWAYS_EAGER=Trueruns both without a worker. - Audit logging is wired through services.
core.audit.log_eventwritesaccounts.AuditLogrows (action='update', event name indetails['event']) for every document transition. There is no generic model-change middleware: master-data CRUD is not audited, only document flows. New transitions must calllog_event. - The demo is executable documentation.
demo_erpruns plan → buy → make → ship → bill → collect through the real services and fails if the books don't balance;core/tests.py::EndToEndERPFlowTestspins the same flow with exact numbers. If a change breaks either, the change is wrong (or the docs are). - The simulation sandbox only posts through services, only on a sandbox.
simulationagents never write ledger models directly; every action is a service call under the agent's own user, the controller checks the books after every tick (an unbalanced tick rolls back and halts), and every write path callssimulation.world.require_sandbox()(SIMULATION_SANDBOX, off in prod). New agent behavior goes through the same services, and a new Claude-reviewed knob is a bounded field in abrainsspec, never free text the engine executes. - EDGAR is not ported yet. The
edgar_statement/edgar_reconciliationreport types and EDGAR account-scoping helpers were stripped withamrs-project'sedgarapp; restore them together with that app, not piecemeal.
Fleet context¶
One of ~40 repos managed by the bamr87/bamr87 dash (registry: _data/projects.yml; standards: specs/). It is vendored there as a git submodule: commit and push here first; the hub only bumps its pointer afterwards. Shared CI, release, schema and agent kits are seeded from the hub's templates/; prefer adopting them over hand-rolling equivalents. amrs-project, afms and amrs-django are the repos the financial core came from; see each one's own agent file for what still lives there.
Standard deviations¶
none
Governance¶
Read docs/constitution.md before changing anything: it is the highest-precedence rule set here and wins over this file when they disagree. It changes only through a numbered record in docs/amendments/, ratified by the maintainer merging the PR; agents propose, never merge. Every user-facing feature has a stable id in features/features.yml with status, location and the PRD requirement ids it serves; the PRD's "Feature catalog" block is generated from it (python3 <bamr87/bamr87>/tools/governance_lint.py prd-sync . --write; check with … check .). Never hand-edit that block or CHANGELOG.md.