Multi-Company Tenant Architecture Every data model in ERP is strictly scoped using a company ForeignKey. Users authenticate into a specific company context, ensuring complete tenant-level data isolation across the entire application. The underlying schema physically ensures no data bleed between tenants, allowing multiple businesses to run securely on a single database instance.
16 Applications
Modular Django apps handling domains like Invoicing, Finance, Master Data, and Reporting. Each app focuses on single-responsibility, maintaining clean code architecture and reducing technical debt.
40+ Core Models
Relational PostgreSQL schema with highly optimized indexing strategies, strict referential integrity checks (CASCADE/SET_NULL), and robust unique constraints for data validity.
500+ Routes & APIs
Extensive URL dispatching handling traditional HTML template rendering, AJAX JSON response patterns for dynamic UI, and dedicated Mobile API endpoints for cross-platform integration.

High-Level Architecture Flow

The system operates on a linear, strict tier-based flow to ensure maximum security and separation of logic.

Client Tier
Browser / Mobile App
Application Tier
Django MVT (16 Apps)
Data Tier
PostgreSQL + Cache

3-Tier Architecture Model

The system is physically and logically partitioned into three discrete tiers to isolate presentation from complex business logic and persistent storage.

TierPrimary TechnologiesRole & ResponsibilitySecurity Boundaries
Client / PresentationHTML5, Tailwind CSS, Vanilla JS, React NativeRenders user interface, handles client-side form validation, and manages DOM interactions without heavy processing.CSRF Token Validation, HTTPS Encryption, Input Sanitization
Application / LogicPython 3.12, Django 4+, Gunicorn, CeleryThe core Brain. Evaluates business rules (e.g. Double-entry balancing), handles session authentication, and controls tenant-scoping dynamically.Session Auth, Multi-Company Context Isolation, Row-Level Permissions
Data / StoragePostgreSQL 15+, Redis (Cache)Ensures ACID compliance, executes complex relational joins securely, and maintains strict foreign key constraints across all 16 applications.Network Isolation (VPC), Encrypted at Rest, No Direct Public Access

Request Lifecycle Flow

A detailed view of how a typical HTTP request (e.g. Saving a new Sales Invoice) traverses through the Django MVT stack.

1. HTTP Request
OriginBrowser UI
PayloadPOST Data + CSRF
2. Middleware
AuthSession Verification
SecurityCSRF Validation
3. URL Router
urls.pyMatch Regex Path
DispatchRoute to View
4. View Logic (Controller)
ContextInject Company_ID
ActionValidate & Save Model
5. Database Commit
TransactionAtomic (All or None)
ReturnSuccess / Error

Applications Directory

ERP consists of 16 modular Django applications. This modularity ensures separation of concerns, clean routing, and explicit database schema boundaries.

MasterApp (Entity Lifecycle Hub)

The MasterApp serves as the central source of truth for all business entities. Every transactional record in the system (Invoice, Voucher, Ledger) maintains a relational link back to these master records.

Multi-Dimensional Grouping Hierarchy

The system uses recursive parent-child relationships for Customers, Suppliers, and Items, enabling infinite depth for complex organizational structures.

Group Node
TypeRecursive
ConstraintUnique/Company
Leaf Entity
RelationBelongs to Group
InheritTax/COA Settings
Transaction
ImpactBalance Update
CheckCredit Limit
CategoryCore ModelsTechnical ResponsibilityBusiness Impact
Trade PartiesCustomerModel, SupplierModelStores PAN/VAT, credit limits, and aging settings.Accounts Receivable (AR) & Accounts Payable (AP) management.
Inventory ControlItemModel, CategoryModel, UnitModelHandles multi-unit conversions (e.g. Kg to Bag), SKU mapping, and BOM.Stock valuation and procurement planning.
WarehousingGodownModelMaps physical storage locations to digital records.Multi-location stock tracking and internal transfers.
Costing & AllocationCostCenter, SubLedgerModelSecondary classification for expense/income tracking.Departmental budgeting and profit-center analysis.
Taxation & LogisticsTdsMaster, VehicleMasterManages TDS rates and transport entity records.Compliance reporting and dispatch logistics.
Product VariationSizeSetup, ColorMasterExtends items with specific attributes for retail/fashion workflows.Detailed inventory granularity (Matrix Inventory).

Master Data Validation Workflow

Before any master record is committed to the database, it undergoes a multi-step validation to ensure global system consistency.

1. Uniqueness Check
ScopeWithin Company
TargetName/Code/PAN
2. COA Mapping
AutoCheck Group Link
StatusVerified Ledger
3. Atomic Save
ActionWrite to Postgres
ResultActive for Vouchers

InvoicesApp

The comprehensive transactional engine handling the entire lifecycle of Sales, Purchases, Returns, and Orders. It operates directly on MasterApp entities and triggers financial/stock updates upon atomic saves.

Invoice Processing Lifecycle

Order Received
Draft / Pending
Inventory Allocation
Batch/Serial Check
Invoice Generation
Atomic Save
IRD Sync Trigger
VAT Compliance
Inbound (Procurement)
  • Purchase Order: Procurement planning.
  • Purchase Invoice (GRN): Goods Receipt Note. Triggers stock increment.
  • Purchase Return: Debits stock, credits supplier.
Outbound (Sales)
  • Sales Order: Order fulfillment queue.
  • Sales Invoice (GDN): Goods Dispatch Note. Triggers stock decrement and IRD sync.
  • Sales Return: Credits stock, debits customer.

FinanceApp

A rigorous double-entry bookkeeping engine that manages pure financial transactions, allocations, and cost-center distributions.

Double-Entry Principle Flow

Every transaction must result in an equal Debit and Credit sum before saving.

Entry TypeAccount LedgerDr AmountCr AmountCost Center
DebitStationery Expense15,000-Admin HQ
CreditCash In Hand-15,000-
Total15,00015,000
Journal Voucher
The core adjustment voucher. Used for non-cash/bank accounting adjustments, depreciation, and opening balance entries.
Receipt/Payment
Manages cash and bank flow. Strict validation ensures the main cash/bank ledger is always debited (receipt) or credited (payment).
Purchase Expense Journal (PEJ)
Advanced landed-cost allocator. Distributes additional purchase expenses (e.g. freight, custom duty) proportionally across specific invoice items to correctly calculate true stock value.

ReportApp

The comprehensive analytics and compliance engine. It aggregates data from Master, Invoices, and Finance apps to generate real-time financial statements and tax filings.

Real-time Aggregation Flow

Raw Tables
Sales, Journal, Items
Django QuerySet
Company/Date Filter
Aggregation
Sum, Annotate, Group
Presentation
HTML Table / Excel View
Report CategoryKey ReportsTarget Audience
Financial StatementsTrial Balance, Profit & Loss, Balance SheetManagement, Auditors
Ledger & AccountsAccount Ledger, Party-wise Summary, Day BookAccountants, Bookkeepers
Inventory ControlStock Summary, Godown Register, Item MovementStore Managers, Procurement
Tax & ComplianceVAT Register, Anusuchi Reports, IRD Sync StatusTax Authorities, Gov Auditors

ChrtofAccountApp

Manages the universal Chart of Accounts with a rigid three-pillar hierarchy: Assets, Liabilities, and P&L (Income/Expense). Every financial transaction eventually maps to a node within this module.

AccountPillar
ExamplesAssets, P&L
AccountGroup
ExamplesCurrent Assets
InheritsPillar Ref
ChartOfAccount
ExamplesCash in Hand
ActionLedger Entries

CompanyApp & SettingsApp

The operational foundation. CompanyApp handles multi-tenancy, while SettingsApp defines voucher automation formats.

Configuration SegmentManaged DataSystem Impact
Fiscal Year MgmtStart/End Dates, AD & BSLocks transactions outside period
Voucher SequencesPrefix, Suffix, PaddingAuto-generates string (e.g., INV-001-81/82)
Global PreferencesDecimal Places, Default GodownAffects global calculations and UI

Reporting Utilities (Excel, Print, Backup)

Auxiliary applications designed for data extraction, visual formatting, and security.

Extraction Pipeline

ReportApp Query
Dataset Retrieval
ExcelhubApp
openpyxl Formatting
PrintApp
WeasyPrint PDF
Utility AppCore FunctionalityTechnical Integration
ExcelhubAppGenerates styled spreadsheets with merged headers for Trial Balance, Stock Summary.Python openpyxl engine
PrintAppCompany-branded HTML/PDF invoice generation.Django Templates + WeasyPrint
BackupControlAppScheduled & manual Postgres SQL dump creation and restoration safely.pg_dump & OS Subprocess
VoucherControlAppBulk ledger and inventory rollback via mass voucher deletion.Atomic DB Transactions

AI Analytics Module

Integrates Google Gemini's advanced LLM APIs to translate complex financial and stock datasets into plain-english insights, eliminating the need for manual spreadsheet parsing.

AI CapabilityInput Context Provided to LLMBusiness Value Output
Stock PredictionHistorical Sales Data, Current Inventory Levels, Item CategoriesIdentifies fast-moving vs dead stock, predicts stockout dates.
Financial Health ScanTrial Balance Aggregates, Expense vs Income Ratio, Debtors BalanceHighlights cashflow bottlenecks and flags abnormal expense spikes automatically.
Smart Query ParsingNatural Language User Query (e.g., "Who owes us the most?")Converts text into Django ORM queries and returns direct values instantly.

Mobile API Layer

A decoupled JSON REST API architecture utilizing Token Authentication. Enables external systems and the official BeanTrack Mobile App to interface securely with the ERP without direct database access.

Handshake
Endpoint/api/token/
MethodPOST (Credentials)
Fetch Master
Endpoint/api/items/
HeadersAuth: Bearer Token
Push Orders
Endpoint/api/orders/
ActionSave SalesOrder
API NamespaceSupported MethodsPrimary ConsumerSecurity Level
/api/mob/auth/POSTMobile App Login ScreenRate-limited, Returns JWT/Token
/api/mob/stock/GETSalesmen in the fieldToken Required, Read-Only
/api/mob/ledger/GETManagement / AuditorsToken Required, Strict Tenant Scope
/api/mob/orders/GET, POSTField Agents taking ordersToken Required, Write Access

Data Layer & Master Schemas

Enterprise data definitions across the 16 applications. The representation below maps out all tables, explicitly highlighting constraints and dependencies.

Comprehensive Data Schemas

Detailed database schema tables for all models, highlighting data types and field constraints.

MasterApp Models

ModelField NameData TypeDescription & Constraints
CustomerModelcompanyFKCompany context isolation (CASCADE)
CustomerNameVarchar(255)Unique within company
ledger_accountFKMaps to Sundry Debtors in COA
is_billwise_applicableBooleanFor credit tracking
SupplierModelcompanyFKCompany context isolation
SupplierNameVarchar(255)Unique within company
ledger_accountFKMaps to Sundry Creditors in COA
pan_vat_noVarchar(50)Tax identification number
ItemModelitem_nameVarchar(255)Primary product identifier
item_group_refFKLinks to ItemGroups for tax/ledger inherit
sales_rate / purchase_rateDecimalBase pricing (max_digits=20)
ItemOpeningStockDecimalInitial inventory count
godown_refFKDefault warehouse location

InvoicesApp Models

ModelField NameData TypeDescription & Constraints
SalesInvoiceinvoice_noVarchar(100)Auto-generated, sequence tracked
voucher_configFKPoints to voucher prefix/suffix rules
bill_date / voucher_mitiDateDual calendar dates (AD/BS)
total_amountDecimalCalculated grand total
synced_with_irdBooleanCBMS compliance flag
PurchaseInvoicegrn_noVarchar(100)Goods Receipt Note number
supplier_refFKSupplier relation (RESTRICT)
subtotal / discountDecimalPre-tax financials
lc_numberVarcharLetter of Credit reference
InvoiceItemRowinvoice_refFKParent invoice (CASCADE)
item_refFKProduct relation (RESTRICT)
qty / rate / amountDecimalRow-level aggregates

Finance & Core Models

ModelField NameData TypeDescription & Constraints
JournalVouchervoucher_noVarcharUnique finance identifier
total_debit / total_creditDecimalMust balance perfectly
cost_centerFKAllocation for budgeting
narrationTextTransaction description
ChartOfAccountaccount_nameVarcharLedger identity
parent_accountFKSelf-referential recursive hierarchy
is_groupBooleanDifferentiates leaf vs node
CompanyModelcompany_nameVarcharGlobal tenant root
pan_numberVarcharLegal tax entity
fiscal_yearVarcharActive accounting period

Relational Hierarchies & Mappings

Entity-Relationship mapping showing foreign key constraints across the application ecosystem. Dependencies flow horizontally and wrap dynamically to the next line.

Core Company Context Flow

Company Context
company_idPK
company_nameChar
Master Entities
companyFK CASCADE
(Customer, Supplier, Item)
Transactional Docs
companyFK CASCADE
(Invoices, Vouchers)
User Session
active_companyFK SET_NULL
(Profile Mapping)
Configurations
companyFK CASCADE
(Voucher Configs)

Ledger & Accounts Mapping

ChartOfAccount
account_idPK
parent_accountSelf FK
Customer Model
ledger_accountFK Debtors
is_billwiseBool
Supplier Model
ledger_accountFK Creditors
pan_vat_noChar
Voucher Entry Row
ledger_accountFK CASCADE
debit / creditDecimal

Inventory Lifecycle Constraints

ItemModel
item_idPK
godown_refFK Warehouse
Sales Items
item_refFK RESTRICT
ActionDecrement
Purchase Items
item_refFK RESTRICT
ActionIncrement
Return Items
item_refFK RESTRICT
ActionReverse
BOM Components
raw_item_refFK SET_NULL
consumptionDecimal

System & DevOps

Information on Tech Stack, Routing, Security, and Deployment structure.

Tech Stack

A carefully chosen stack balancing developer productivity, enterprise-grade reliability, and the specific needs of accounting standards.

Python 3.xBackend Core Language
Django 4+Robust MVT Web Framework
PostgreSQLRelational Database
Tailwind CSSUtility-first Styling Engine
openpyxlExcel Report Generation
WeasyPrintHTML to PDF Exports
Gemini AISmart Analytics & Reporting AI
Django AuthSession-based Security

URL Routing Strategy

The routing architecture is centralized in MBILLING/urls.py, delegating routing responsibilities to app-specific configuration files via Django's include() functionality.

Prefix PatternTarget ApplicationRouting Scope & Description
/CompanyApp, MasterAppRoot endpoints handling company selection, dashboards, and core master records.
/invoice/InvoicesAppHandles all document generation: GDN, GRN, Returns, Orders, and stock lifecycle.
/finance/FinanceAppAccounting endpoints for Journal, Receipt, Payment, and Purchase Expense Journal.
/coa/ChrtofAccountAppManagement of the multi-tier Chart of Accounts (Pillar -> Group -> Ledger).
/users/UsersAppAuthentication handlers (login/logout) and user profile configuration.
/api/mob/Mobile APIRESTful JSON endpoints enabling native mobile application connectivity.
/bean/pean/admin/Django AdminSecure, obfuscated URL for the built-in superuser administration panel.

Security Architecture

A multi-layered defense mechanism ensuring that financial records remain secure, isolated, and untampered.

Defense LayerImplementation DetailThreat Mitigated
Data IsolationActive company_id injected into all ORM .filter() queries via session middleware.Cross-tenant data leakage / Unauthorized access.
Audit Trailscreated_by, updated_by, created_at triggers on all Core Models.Internal fraud, lack of accountability for edits.
Request ValidationDjango CSRF Middleware checks secure tokens on all POST/PUT requests.Cross-Site Request Forgery (CSRF).
Database IntegrityUniqueConstraint and CheckConstraint at PostgreSQL level.Corrupted data, duplicate invoice numbers, race conditions.
AuthenticationSecure, salted PBKDF2 password hashing. Sessions managed via encrypted cookies.Credential theft, session hijacking.

Deployment Architecture

The standard, highly reliable production web stack for executing the Django WSGI application asynchronously.

1. Internet Traffic
ProtocolHTTPS (Port 443)
SecuritySSL/TLS Certificate
2. Nginx Web Server
RoleReverse Proxy
AssetsServes /static/ files
3. Gunicorn WSGI
WorkersMulti-process (4-8)
AppExecutes Python Logic
4. PostgreSQL
ServiceLocal Network Only
StoragePersistent NVMe

System File Structure

The codebase follows standardized Django patterns, isolating logic inside independent application directories.

Directory / PathPurpose & ContentsDevelopment Rule
/MBILLING/Project root. Contains settings.py and global urls.py router.Only modify for global middleware or core configs.
/MasterApp/ (x16 Apps)App directories containing models.py, views.py, admin.py.Keep domains strictly separate. Do not cross-import cyclic models.
/Templates/Centralized HTML files (e.g. base.html, invoice renders).Use Django template tags and inherit from base cleanly.
/Static/Global CSS, JavaScript utilities, and Image assets (Logos).Do not place user-uploaded content here.
/Media/User-uploaded files (e.g. Company logos, signatures, backups).Served securely; must not execute scripts.