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.
High-Level Architecture Flow
The system operates on a linear, strict tier-based flow to ensure maximum security and separation of logic.
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.
| Tier | Primary Technologies | Role & Responsibility | Security Boundaries |
|---|---|---|---|
| Client / Presentation | HTML5, Tailwind CSS, Vanilla JS, React Native | Renders user interface, handles client-side form validation, and manages DOM interactions without heavy processing. | CSRF Token Validation, HTTPS Encryption, Input Sanitization |
| Application / Logic | Python 3.12, Django 4+, Gunicorn, Celery | The 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 / Storage | PostgreSQL 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.
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.
| Category | Core Models | Technical Responsibility | Business Impact |
|---|---|---|---|
| Trade Parties | CustomerModel, SupplierModel | Stores PAN/VAT, credit limits, and aging settings. | Accounts Receivable (AR) & Accounts Payable (AP) management. |
| Inventory Control | ItemModel, CategoryModel, UnitModel | Handles multi-unit conversions (e.g. Kg to Bag), SKU mapping, and BOM. | Stock valuation and procurement planning. |
| Warehousing | GodownModel | Maps physical storage locations to digital records. | Multi-location stock tracking and internal transfers. |
| Costing & Allocation | CostCenter, SubLedgerModel | Secondary classification for expense/income tracking. | Departmental budgeting and profit-center analysis. |
| Taxation & Logistics | TdsMaster, VehicleMaster | Manages TDS rates and transport entity records. | Compliance reporting and dispatch logistics. |
| Product Variation | SizeSetup, ColorMaster | Extends 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.
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
- Purchase Order: Procurement planning.
- Purchase Invoice (GRN): Goods Receipt Note. Triggers stock increment.
- Purchase Return: Debits stock, credits supplier.
- 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 Type | Account Ledger | Dr Amount | Cr Amount | Cost Center |
|---|---|---|---|---|
| Debit | Stationery Expense | 15,000 | - | Admin HQ |
| Credit | Cash In Hand | - | 15,000 | - |
| Total | 15,000 | 15,000 |
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
| Report Category | Key Reports | Target Audience |
|---|---|---|
| Financial Statements | Trial Balance, Profit & Loss, Balance Sheet | Management, Auditors |
| Ledger & Accounts | Account Ledger, Party-wise Summary, Day Book | Accountants, Bookkeepers |
| Inventory Control | Stock Summary, Godown Register, Item Movement | Store Managers, Procurement |
| Tax & Compliance | VAT Register, Anusuchi Reports, IRD Sync Status | Tax 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.
CompanyApp & SettingsApp
The operational foundation. CompanyApp handles multi-tenancy, while SettingsApp defines voucher automation formats.
| Configuration Segment | Managed Data | System Impact |
|---|---|---|
| Fiscal Year Mgmt | Start/End Dates, AD & BS | Locks transactions outside period |
| Voucher Sequences | Prefix, Suffix, Padding | Auto-generates string (e.g., INV-001-81/82) |
| Global Preferences | Decimal Places, Default Godown | Affects global calculations and UI |
Reporting Utilities (Excel, Print, Backup)
Auxiliary applications designed for data extraction, visual formatting, and security.
Extraction Pipeline
| Utility App | Core Functionality | Technical Integration |
|---|---|---|
| ExcelhubApp | Generates styled spreadsheets with merged headers for Trial Balance, Stock Summary. | Python openpyxl engine |
| PrintApp | Company-branded HTML/PDF invoice generation. | Django Templates + WeasyPrint |
| BackupControlApp | Scheduled & manual Postgres SQL dump creation and restoration safely. | pg_dump & OS Subprocess |
| VoucherControlApp | Bulk 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 Capability | Input Context Provided to LLM | Business Value Output |
|---|---|---|
| Stock Prediction | Historical Sales Data, Current Inventory Levels, Item Categories | Identifies fast-moving vs dead stock, predicts stockout dates. |
| Financial Health Scan | Trial Balance Aggregates, Expense vs Income Ratio, Debtors Balance | Highlights cashflow bottlenecks and flags abnormal expense spikes automatically. |
| Smart Query Parsing | Natural 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.
| API Namespace | Supported Methods | Primary Consumer | Security Level |
|---|---|---|---|
/api/mob/auth/ | POST | Mobile App Login Screen | Rate-limited, Returns JWT/Token |
/api/mob/stock/ | GET | Salesmen in the field | Token Required, Read-Only |
/api/mob/ledger/ | GET | Management / Auditors | Token Required, Strict Tenant Scope |
/api/mob/orders/ | GET, POST | Field Agents taking orders | Token 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
| Model | Field Name | Data Type | Description & Constraints |
|---|---|---|---|
| CustomerModel | company | FK | Company context isolation (CASCADE) |
| CustomerName | Varchar(255) | Unique within company | |
| ledger_account | FK | Maps to Sundry Debtors in COA | |
| is_billwise_applicable | Boolean | For credit tracking | |
| SupplierModel | company | FK | Company context isolation |
| SupplierName | Varchar(255) | Unique within company | |
| ledger_account | FK | Maps to Sundry Creditors in COA | |
| pan_vat_no | Varchar(50) | Tax identification number | |
| ItemModel | item_name | Varchar(255) | Primary product identifier |
| item_group_ref | FK | Links to ItemGroups for tax/ledger inherit | |
| sales_rate / purchase_rate | Decimal | Base pricing (max_digits=20) | |
| ItemOpeningStock | Decimal | Initial inventory count | |
| godown_ref | FK | Default warehouse location |
InvoicesApp Models
| Model | Field Name | Data Type | Description & Constraints |
|---|---|---|---|
| SalesInvoice | invoice_no | Varchar(100) | Auto-generated, sequence tracked |
| voucher_config | FK | Points to voucher prefix/suffix rules | |
| bill_date / voucher_miti | Date | Dual calendar dates (AD/BS) | |
| total_amount | Decimal | Calculated grand total | |
| synced_with_ird | Boolean | CBMS compliance flag | |
| PurchaseInvoice | grn_no | Varchar(100) | Goods Receipt Note number |
| supplier_ref | FK | Supplier relation (RESTRICT) | |
| subtotal / discount | Decimal | Pre-tax financials | |
| lc_number | Varchar | Letter of Credit reference | |
| InvoiceItemRow | invoice_ref | FK | Parent invoice (CASCADE) |
| item_ref | FK | Product relation (RESTRICT) | |
| qty / rate / amount | Decimal | Row-level aggregates |
Finance & Core Models
| Model | Field Name | Data Type | Description & Constraints |
|---|---|---|---|
| JournalVoucher | voucher_no | Varchar | Unique finance identifier |
| total_debit / total_credit | Decimal | Must balance perfectly | |
| cost_center | FK | Allocation for budgeting | |
| narration | Text | Transaction description | |
| ChartOfAccount | account_name | Varchar | Ledger identity |
| parent_account | FK | Self-referential recursive hierarchy | |
| is_group | Boolean | Differentiates leaf vs node | |
| CompanyModel | company_name | Varchar | Global tenant root |
| pan_number | Varchar | Legal tax entity | |
| fiscal_year | Varchar | Active 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
Ledger & Accounts Mapping
Inventory Lifecycle Constraints
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.
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 Pattern | Target Application | Routing Scope & Description |
|---|---|---|
| / | CompanyApp, MasterApp | Root endpoints handling company selection, dashboards, and core master records. |
| /invoice/ | InvoicesApp | Handles all document generation: GDN, GRN, Returns, Orders, and stock lifecycle. |
| /finance/ | FinanceApp | Accounting endpoints for Journal, Receipt, Payment, and Purchase Expense Journal. |
| /coa/ | ChrtofAccountApp | Management of the multi-tier Chart of Accounts (Pillar -> Group -> Ledger). |
| /users/ | UsersApp | Authentication handlers (login/logout) and user profile configuration. |
| /api/mob/ | Mobile API | RESTful JSON endpoints enabling native mobile application connectivity. |
| /bean/pean/admin/ | Django Admin | Secure, 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 Layer | Implementation Detail | Threat Mitigated |
|---|---|---|
| Data Isolation | Active company_id injected into all ORM .filter() queries via session middleware. | Cross-tenant data leakage / Unauthorized access. |
| Audit Trails | created_by, updated_by, created_at triggers on all Core Models. | Internal fraud, lack of accountability for edits. |
| Request Validation | Django CSRF Middleware checks secure tokens on all POST/PUT requests. | Cross-Site Request Forgery (CSRF). |
| Database Integrity | UniqueConstraint and CheckConstraint at PostgreSQL level. | Corrupted data, duplicate invoice numbers, race conditions. |
| Authentication | Secure, 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.
System File Structure
The codebase follows standardized Django patterns, isolating logic inside independent application directories.
| Directory / Path | Purpose & Contents | Development 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. |