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).
Overview¶
A Django 6 + Django REST Framework ERP built outward from a double-entry accounting core into a modular enterprise system: chart of accounts, journal entries, invoices/payments and async financial reports, plus business partners, products, multi-warehouse inventory with a stock ledger and moving-average costing, purchasing, sales, manufacturing (BOMs and work orders), and an MRP planning engine — the bare minimum for end-to-end order-to-cash, procure-to-pay and make-to-stock processing.
The financial core was consolidated from amrs-project (AMRS), the most mature of several overlapping accounting prototypes in the fleet. The supply-chain and planning modules re-implement proven designs from ERPNext, Odoo, Tryton, InvenTree and frePPLe — see docs/ARCHITECTURE.md for the module map, invariants, posting matrix, MRP algorithm, and exactly which pattern came from where (and why no copyleft code was copied). See AGENTS.md for the domain rules that must not be broken.
Features¶
- Double-entry accounting core: chart of accounts, journal entries, invoices and payments
- Asynchronous financial reports via Celery
- Business partners, products, multi-warehouse inventory with a stock ledger and moving-average costing
- Purchasing, sales, manufacturing (BOMs and work orders) and an MRP planning engine
- JWT-authenticated REST API with Swagger and ReDoc docs
- A workspace at
/app/: one app shell for every module — role-filtered navigation, global search, lists, document pages with their lifecycle, actions, document flow, journal entries, stock moves and audit trail, forms and financial statements — built entirely on the public API (workspace/README.md) - An agent simulation sandbox: customers, suppliers, managers, line crews, machines and a controller — heuristic or small Claude models — drive the ERP through its services over simulated time, with balanced, reconciled books as the guardrail, a live browser console at
/console/and what-if experiments (simulation/README.md)
Quick start¶
From a clone of bamr87/djangoerp, with Python 3.12+:
# 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
Migrating seeds the five AccountType codes (AS/LI/EQ/RE/EX) that reports/report_generators.py hard-codes, via coa's 0002_seed_account_types data migration — a fresh database has a working chart of accounts from the start. A createsuperuser account can open /admin/ but needs an accounts.UserRole row before the API lets it in (every permission class reads request.user.role.role).
Run the agent simulation¶
python manage.py simulate --ticks 30 # bootstrap the sandbox economy, run 30 simulated days
python manage.py simulate --what-if add_line:A # what would a second line for product line A cost?
python manage.py runserver # then open http://localhost:8000/console/ (or /app/ for every module)
Agents act only on a database flagged SIMULATION_SANDBOX (on in dev, off in production). Every tick posts through the same services as the API, and the command fails if the books stop balancing or a subledger stops reconciling. Set ANTHROPIC_API_KEY and --driver llm to let small Claude models (claude-haiku-5-5 by default) make the agents' policy decisions; without a key they fall back to seeded heuristics. See simulation/README.md.
Or run it in Docker¶
The compose stack runs the app against PostgreSQL and Redis rather than the SQLite/eager-Celery defaults, and seeds an admin account (djangoerp / djangoerp by default, from .env) with its UserRole row:
docker compose up # web + postgres + redis, autoreload on
docker compose --profile celery up # ...plus a real Celery worker
docker compose down -v # stop and drop the database volume
Published ports bind to 127.0.0.1. The port map, the in-container test loop, and attaching the VS Code debugger (F5 → Docker: Attach to Django) are in docs/DOCKER.md.
Production settings¶
DJANGO_SETTINGS_MODULE=djangoerp.settings.prod (the image's prod target) adds HSTS, an HTTPS redirect and secure cookies, and refuses to start without a real SECRET_KEY: unset, empty or django-insecure… raises ImproperlyConfigured, because the key signs sessions, password-reset links and every JWT. Generate one with python3 -c "import secrets; print(secrets.token_urlsafe(50))" (django-environ reads a value that starts with $ as the name of another variable, so avoid keys that do). With a real key, python manage.py check --deploy --fail-level WARNING reports no issues, and core/test_prod_settings.py keeps both rules under test.
See the whole ERP loop run¶
python manage.py demo_erp builds a demo company (chart of accounts, GL mappings, partners, warehouse, a make/buy product structure with a BOM), then runs the full loop through the same services the API uses: sales order → MRP run → planned orders (pegged, lead-time offset) → purchase order + work order → goods receipt → production at rolled-up cost → shipment → customer invoice → payment → supplier settlement → trial balance / balance sheet / income statement. It exits non-zero if the books don't balance. The same flow is pinned with exact numbers in core/tests.py::EndToEndERPFlowTests.
Technology stack¶
- Backend: Python 3.12+, Django 6.1, Django REST Framework
- Database: PostgreSQL in production, SQLite by default in development
- Authentication: JSON Web Tokens (JWT) via
djangorestframework-simplejwt - API docs: Swagger & ReDoc (
drf-yasg) - Task queue: Celery (Redis broker); runs synchronously in dev — reports and MRP runs both use it
- Testing:
pytest/pytest-django, plusmanage.py test
API overview¶
Every app exposes a DRF router under /api/<area>/ — auth, coa, journal, invoices, reports, partners, products, inventory, purchasing, sales, manufacturing, mrp, company, simulation, workspace — plus /admin/, the workspace at /app/, the simulation console at /console/, /swagger/, /redoc/, the landing page at / (which links each area to its section of the Swagger UI, /swagger/#/<area>), a JSON liveness probe at /health/, and /version, the build identity ({"name", "version", "commit", "built_at"}; commit and built_at are null unless the image was built with GIT_SHA/BUILT_AT, see the Dockerfile). Authenticate with POST /api/auth/login/ and send the JWT as a bearer token. Document state changes are actions on the document (/api/sales/orders/{id}/ship/, /api/invoices/invoices/{id}/post/), never direct status writes. Journal entry numbers are assigned by the server from the JE sequence (a client-sent entry_number is ignored), a posted manual entry is corrected with POST /api/journal/entries/{id}/reverse/ rather than edited, and an account that has journal lines is retired with is_active=false rather than deleted.
The full route table — method, path, view, permission classes and summary — is generated from the URLconf in docs/reference/api-routes.md (python3 tools/gen_api_routes.py --write). Reports are generated by creating a ReportTemplate with the desired report_type and then a SavedReport from it; MRP runs follow the same async pattern — create a run, poll it, then convert its planned orders.
Probes and tracing headers follow the fleet's backend standard (hub specs/BACKEND.md UPS-BE-10 and UPS-BE-04). GET /healthz is liveness: 200 {"status": "ok"} from any live process, touching no dependency. GET /readyz is readiness: 200 {"status": "ok", "checks": {"db": "ok", "broker": …}} while the database answers SELECT 1 and, unless Celery runs eagerly (broker then reads skipped), Redis answers a ping; otherwise 503 with "status": "degraded" and the failing check marked error. Both are public and uncached, and the compose healthcheck probes /readyz. /health/ stays for existing callers and reports only status, app and version. Every response, pages and API errors included, carries X-Request-Id (a well-formed inbound value is echoed, anything else replaced by a fresh id) and X-App-Version, set by core/middleware.py.
Consolidation roadmap¶
- Done — core ledger (
accounts,coa,journal,invoices,reports) ported fromamrs-project, withamrs-django's settings-split/test scaffolding adopted and real migrations committed from day one. - Done — enterprise ERP consolidation: partners, products, inventory (stock ledger + moving-average costing), purchasing, sales, manufacturing and MRP, integrated with the GL through idempotent posting services, with the audit trail wired through every document transition and the whole loop demonstrable via
manage.py demo_erp. - Planned — port
amrs-project'sedgarapp (SEC/XBRL-to-ledger integration) as a self-contained optional module. - Planned — port
amrs-django's React frontend as DjangoERP's UI, rewired from its Token auth to this project's JWT convention. - Future — manufacturing depth (routings/work centers, WIP staging, reservations), vendor-bill three-way match, UoM conversions, lot/serial tracking, HR/payroll — see the deliberate-exclusions list in docs/ARCHITECTURE.md.
amrs-project, afms, and amrs-django remain in place with pointers back to this repo; nothing has been deleted from them.
Documentation¶
- docs/README.md — the index of every document in the repo.
- docs/ARCHITECTURE.md — module map, invariants, GL posting matrix, MRP algorithm, and which open-source pattern came from where.
- docs/DOCKER.md — the Docker stack, ports and VS Code debugging.
- workspace/README.md — the common app shell, its routes, registry and document-flow read models.
- simulation/README.md — the agent simulation sandbox, its console, guardrails and what-ifs.
- docs/reference/api-routes.md — every route, generated from the URLconf.
- AGENTS.md — commands, conventions and the domain rules that must not be broken.
Project structure¶
djangoerp/ # Project settings (base/dev/prod split), root urls, celery app
core/ # TimestampMixin, DocumentSequence numbering, audit writer, API exception handler, draft-only DELETE mixin, demo company + demo_erp
company/ # Company (the entity whose books these are), the landing page, /health/ and /version
templates/ # Project-wide templates: includes/ holds the feedback widget's mount points
public/ # The feedback widget's scripts, vendored from the hub and served as static/js/
accounts/ # UserRole (admin/accountant/viewer/auditor), AuditLog, JWT login, permissions
coa/ # Chart of accounts: AccountType + self-referencing Account tree
journal/ # JournalEntry + JournalLine — the double-entry ledger — and the posting service
invoices/ # Invoice, InvoiceLineItem, Payment — AR with GL posting actions
reports/ # ReportTemplate + SavedReport, and report_generators.py (the report math)
partners/ # BusinessPartner — customers/suppliers with AR/AP control accounts
products/ # UnitOfMeasure, ProductCategory (GL mappings), Product (buy/make, MRP parameters)
inventory/ # Warehouse, StockMove ledger, StockLevel cache with moving-average costing
purchasing/ # PurchaseOrder + lines, confirm/receive flow (stock in + AP accrual)
sales/ # SalesOrder + lines, confirm/ship/invoice flow (COGS + billing)
manufacturing/ # BillOfMaterials + BOMLine, WorkOrder complete flow (backflush + rolled-up cost)
mrp/ # MRPRun + PlannedOrder, the planning engine, plan-to-order conversion
simulation/ # Agent simulation sandbox: tick engine, heuristic and Claude brains, what-ifs, the /console/ client
workspace/ # The /app/ shell: registry introspected from the API, document flow, search, statements, the SPA
docs/ # ARCHITECTURE.md, DOCKER.md, the generated reference/ and the index
docker/ # Container entrypoint, admin bootstrap, dev server/worker launchers, healthchecks
tools/ # gen_api_routes.py (route reference), docs_index.py + unwrap-prose.py (vendored from the hub)
Development¶
Build, test and lint commands are in Quick start. CI is the hub's shared standard-ci.yml gate, called from .github/workflows/ci.yml. After changing a route or a view docstring, regenerate the route reference with python3 tools/gen_api_routes.py --write — core/test_docs_reference.py fails while it is stale. Full commands, conventions and gotchas for humans and AI agents live in AGENTS.md.
Every page rendered from company/templates/company/base.html or the workspace shell (workspace/templates/workspace/shell.html, which the console extends) carries the fleet's "Improve this page" widget, which files a prefilled GitHub issue (page, environment and recent console errors) against this repo. Its scripts live in public/ and its body include in templates/includes/fleet-feedback.html, all three vendored unchanged from the hub's feedback kit (tools/fanout.sh --kit feedback --upgrade refreshes them), so change them upstream in bamr87/bamr87, never here. This repo owns the <head> include templates/includes/fleet-feedback-head.html, the mount points in base.html and shell.html, and company/context_processors.py, which supplies the repo, branch and version the widget reports.
A change to what a visitor sees is verified the fleet way (hub docs/VERIFICATION.md): verify/verify.yml tells the Verify workflow how to start the app, and node verify/runner.mjs drives verify/scenarios/ in Chromium and writes screenshots and a report to test/evidence/<scenario>/. Install its two dev packages first, as CI does: npm install --prefix verify --no-save --no-package-lock @playwright/test yaml (then verify/node_modules/.bin/playwright install chromium if no Chromium is cached).
Contributing¶
Contributions are welcome via pull request. Use Conventional Commits and keep the CI checks green. The fleet-wide workflow is described in the hub's CONTRIBUTING.md. AI agents should start with AGENTS.md.
Changelog¶
Notable changes are recorded in CHANGELOG.md; the full record is in the commit history.
License¶
Released under the MIT License.
Part of the bamr87 portfolio — browse every project on Amr's GitHub profile.