Skip to content

Instantly share code, notes, and snippets.

@amal-babu-git
Created June 19, 2026 09:19
Show Gist options
  • Select an option

  • Save amal-babu-git/e850a773a61aec7dfee720ef698b0eb9 to your computer and use it in GitHub Desktop.

Select an option

Save amal-babu-git/e850a773a61aec7dfee720ef698b0eb9 to your computer and use it in GitHub Desktop.

Herbally — Complete System Documentation

Document purpose. This is a single, consolidated reference describing the entire Herbally platform — what it is, what each part does, how the parts work together, and the technology it runs on. It is written so that a non-technical reader can understand the system as a whole and use it as the basis for a client handover document. Deeper technical details for each module live in the per-module reference files listed in Appendix C.

Product Herbally — Integrated Hospital, Pharmacy & Distribution Management Platform
Document version 1.0
Prepared on 19 June 2026
Audience Management / client handover (non-technical, with technical appendices)
System type Web-based business application (cloud-hosted)

Table of Contents

  1. Executive Overview
  2. What Herbally Does — At a Glance
  3. System Architecture
  4. Users, Roles & Access Control
  5. Functional Modules
  6. Key End-to-End Business Flows
  7. Cross-Cutting Capabilities
  8. Technology Stack
  9. Deployment & Operations
  10. Data Integrity, Security & Compliance
  11. Appendix A — Complete Module Inventory
  12. Appendix B — Glossary
  13. Appendix C — Where the Detailed Technical Docs Live

1. Executive Overview

Herbally is an integrated, web-based management platform that runs an Ayurvedic hospital, its pharmacy, and the associated retail/distribution and back-office operations on a single system. It replaces the patchwork of separate tools a business of this kind would otherwise need — appointment book, pharmacy billing, inventory register, purchase files, customer follow-up sheets, HR/payroll registers, and the accounting books — with one connected application where every transaction flows through to inventory and the financial ledgers automatically.

The platform is organised as a set of functional modules (roughly 19) that share a common foundation for login, permissions, audit logging, and configuration. A user only sees the modules and records their role allows.

What makes the system noteworthy

  • One transaction, recorded everywhere. When a pharmacy dispenses a prescription or a sales order is invoiced, the system simultaneously reduces inventory, updates the customer's outstanding balance, and posts the correct double-entry accounting voucher — in a single, all-or-nothing operation. There is no separate "post to accounts" step that can be forgotten.
  • Two sales channels on one engine. Retail/company sales (to CRM customers) and hospital pharmacy sales (from a doctor's prescription) use the same invoicing engine, so totals, tax, and stock behave identically while each channel keeps its own workflow.
  • Full audit trail. Every create, update, and delete across the system is recorded in an append-only activity log, with the actor, timestamp, and a before/after snapshot for sensitive edits (such as corrections to posted accounting entries).
  • Multi-location aware. The business can operate multiple branches/locations; stock, sales, and visibility are scoped per location, and staff only see the locations they belong to.
  • Built for Indian compliance. GST (CGST/SGST/IGST), HSN codes, batch numbers and expiry dates, and a double-entry chart of accounts with GST input/output ledgers are first-class parts of the system.

2. What Herbally Does — At a Glance

Business area What the system handles
Patient care Patient registration, appointment bookings, token/queue management, the doctor's consultation queue, consultations, and prescriptions.
Pharmacy A pharmacy dispensing queue driven by prescriptions, dispense-to-invoice billing, partial dispensing with reasons, and pharmacy sales analytics.
Retail / distribution sales Sales orders, invoices, customer payments (instalments), sales returns, and a per-customer receivables ledger.
Customer relationships (CRM) Lead capture and pipeline, lead-to-customer conversion, follow-up tasks, after-sales calls, and a CRM dashboard.
Procurement Purchase requisitions → purchase orders → goods receipt → supplier bills, supplier payments, purchase returns, and a per-supplier payables ledger.
Inventory A single, authoritative stock ledger across locations, batch/expiry tracking, goods receipt and quality checks, inter-branch stock transfers, and manual stock adjustments with approval.
Product catalogue Products with pricing, tax, HSN, brands, categories, units, variations, warranties, attachments, and bulk Excel import/export.
Suppliers Vendor master records (individuals and businesses) with banking, tax, and credit-term details.
Finance & accounting Double-entry bookkeeping, chart of accounts, vouchers, fiscal-year close, and a full set of financial reports (Trial Balance, P&L, Balance Sheet, Cash Flow, ledgers).
Human resources & payroll Employees, departments, shifts, attendance (incl. biometric punches), leave management, holidays, teams, and monthly salary computation.
Inventory valuation A FIFO cost layer that values opening/closing stock for the "Trading" section of the Profit & Loss.
Reporting A configurable report engine that generates and exports operational and financial reports to Excel/CSV.
Administration User management, roles & permissions, locations and tax rates, support tickets, release notes, and a system-wide audit log.

3. System Architecture

3.1 The simple picture

Herbally has three main parts that talk to each other over the internet:

   ┌───────────────────┐        ┌────────────────────┐        ┌────────────────────┐
   │   Web Browser     │  ───►  │   Frontend (UI)    │  ───►  │   Backend (API)    │
   │  (staff / admin)  │  ◄───  │   Next.js app      │  ◄───  │   FastAPI service  │
   └───────────────────┘        └────────────────────┘        └─────────┬──────────┘
                                                                          │
                                          ┌───────────────────────────────┼───────────────────────┐
                                          ▼                                ▼                       ▼
                                   ┌──────────────┐               ┌──────────────┐        ┌──────────────────┐
                                   │  PostgreSQL  │               │    Redis     │        │  Object Storage  │
                                   │  (database)  │               │ (cache/queue)│        │ (files: S3-like) │
                                   └──────────────┘               └──────────────┘        └──────────────────┘
  • Frontend (the user interface) — what staff actually click on, in a web browser. It is a modern single-page application.
  • Backend (the engine) — receives every request, applies the business rules and permission checks, and reads/writes the database. All logic that matters for correctness lives here.
  • Database — the permanent system of record for all data.
  • Supporting services — a cache/queue (for speed and for background jobs like nightly attendance processing and report generation) and file storage (for attachments, documents, and photos).

3.2 The technical picture

  • The backend is a modular monolith: one deployable application internally divided into clearly separated modules (sales, purchase, accounting, hospital, etc.). Each module follows the same strict internal layering — Route → Service → CRUD → Database model — which keeps business logic, data access, and the web layer cleanly separated and easy to maintain.
  • Modules communicate through well-defined internal interfaces. For example, the Sales module asks the Stock module to deduct inventory and asks the Accounting module to post a voucher; it never reaches directly into their data.
  • A handful of foundation modules (login/RBAC, audit log, configuration) are reusable and shared by every feature module.

3.3 Core engineering principles (why the system stays reliable)

Principle What it means in practice
Transactions are all-or-nothing A pharmacy invoice that touches stock, the customer ledger, and the accounting voucher either fully succeeds or fully rolls back. The books can never be left half-updated.
Single source of truth for stock Every inventory change in the entire system flows through one component, which writes an append-only movement ledger with full attribution (who, why, source document).
Exact money arithmetic All monetary values use exact decimal arithmetic (never floating-point), so totals and tax never drift by fractions of a paisa.
Soft deletes Records are almost never physically erased — they are flagged as deleted, preserving history and audit integrity.
Everything is timestamped in UTC The database stores all times in a single standard time zone; the interface converts to local time for display.
Permission-checked at the source Access rules are enforced by the backend on every request, not just hidden in the UI.

4. Users, Roles & Access Control

Access is controlled in two independent layers, which together decide both what a user can do and which records they can see.

4.1 Layer 1 — Permissions ("what actions can I perform?")

Every sensitive action is gated by a named permission such as "create a sale", "approve a purchase", or "finalize a salary". Permissions are grouped into roles, and a user is granted one or more roles. There are roughly 150 distinct permissions across the system.

4.2 Layer 2 — Scope ("which records can I see/touch?")

On top of permissions, the system filters the actual rows a user can access:

  • A receptionist or sales agent typically sees only records for their own assigned location(s) or their own records.
  • A manager with the matching "read-all" permission sees everything across all locations.
  • A super administrator bypasses all checks.

This means two users with the same "view sales" permission can legitimately see different data — each sees only what belongs to their location or to them.

4.3 Standard roles

The system ships with 13 pre-defined roles (which administrators can extend with custom roles). The main ones:

Role Typical user Scope
Super Admin System owner Everything, everywhere; bypasses all checks
Admin Staff Office administrator Broad cross-cutting access; user management, settings, reports
Hospital Manager Clinic manager Full hospital operations + pharmacy + read-only HR/reports
Doctor Physician Own consultation queue, own patients, prescriptions (across their locations)
Receptionist Front desk Bookings, tokens, and patient registration at their location
Pharmacist Pharmacy staff Pharmacy queue, dispensing, pharmacy invoices
Sales Manager Sales head All sales + all CRM
Sales Agent Salesperson Their own orders, invoices, and payments only
CRM Agent / Manager Tele-caller / CRM lead Own leads, customers, follow-ups, and calls
Purchase Staff Procurement Suppliers, products, and purchase orders
Logistics Staff Warehouse Goods receipts, GRNs, and stock transfers
HR Manager / HR Staff Human resources Full or operational HRM access (salary finalize is manager-only)

Administrators can create new roles and re-assign permissions at any time through the Access Control screens — roles are data, not code.

4.4 Security highlights

  • Login uses industry-standard JWT access tokens with short-lived sessions and rotating refresh tokens; passwords are stored only as bcrypt hashes.
  • Password reset is a request-and-fulfil workflow (the user requests a reset; an admin resolves it). Login does not reveal whether an email exists (protection against account enumeration).
  • Self-protection rules prevent an admin from deleting their own account, and prevent the deletion of built-in system roles.
  • The frontend keeps authentication tokens in secure, browser-managed cookies that JavaScript cannot read.

5. Functional Modules

Each module below is described in business terms: what it is for, its key capabilities, and how it connects to the rest of the system.


5.1 Clinical / Hospital Group

Hospital (Patient Care)

Purpose. Manages the end-to-end patient journey inside the clinic — from booking an appointment to the doctor's consultation and prescription.

Key capabilities.

  • Patient registration and patient master records.
  • Bookings — appointment scheduling per hospital location.
  • Tokens / queue — issuing and calling patient tokens.
  • Doctor queue — each doctor's live list of patients to be seen.
  • Consultations — recording the clinical encounter.
  • Prescriptions — the medicines and quantities prescribed, with a dedicated pharmacy status (active → completed / cancelled) that drives the pharmacy workflow.
  • Doctors can work across multiple hospital locations.

Connects to. Pharmacy (a prescription becomes a dispensing task), Sales (the dispense produces an invoice), Stock (medicines are deducted), and HR (doctors/receptionists are employees linked to locations).

Pharmacy

Purpose. Turns a doctor's prescription into a dispensed, billed sale — without duplicating the sales/billing logic.

Key capabilities.

  • Pharmacy queue of prescriptions awaiting dispensing (today's active prescriptions by default).
  • Dispense → invoice in one action: the pharmacist confirms quantities and the system creates a pharmacy invoice (prefixed PHARM-), deducts stock at the hospital location, and marks the prescription as completed.
  • Partial dispensing — quantities can be reduced from what was prescribed, with an adjustment reason captured for audit.
  • Cancellation of a prescription's dispensing (with a mandatory reason) — this never touches billing.
  • Pharmacy analytics for dispensing activity.

Connects to. It is a thin, controlled wrapper around the Sales invoice engine, so a pharmacy invoice behaves exactly like a normal sale (stock deduction, totals, tax, accounting voucher) while the hospital module retains control of prescription state.


5.2 Sales & Customer Group

Sales

Purpose. The complete order-to-cash engine for both retail/company sales and hospital pharmacy sales.

Key capabilities.

  • Sales orders with a clear lifecycle: draft → confirmed → invoiced → cancelled, including stock-availability validation and reservation.
  • Create order directly from a CRM lead (atomically converting the lead to a customer in the same step).
  • Invoices generated from confirmed orders (or, for pharmacy, from a prescription). Invoice numbers are auto-generated (INV- for company sales, PHARM- for pharmacy).
  • Payments recorded as instalments, with overpayment prevention and automatic payment-status derivation (due / partial / paid).
  • Sales returns with a two-step pending → completed workflow that restores stock and adjusts the customer's balance, including correct handling of cash refunds vs. cancelled debt.
  • Accounts-receivable (AR) ledger — a running, per-customer balance of what each customer owes.
  • Attachments on invoices and payments (e.g. signed copies, proofs).

Connects to. Stock (deduction on sale, restoration on return/cancel), CRM (customer records), Accounting (each invoice, payment, and return automatically posts the matching voucher), Products, and Settings (locations & tax).

CRM (Customer Relationship Management)

Purpose. Captures and nurtures prospective and existing customers, especially for an outbound, follow-up-driven sales motion.

Key capabilities.

  • Leads with auto-generated contact IDs, duplicate detection (the lead is still created but flagged), and rich filtering/search.
  • Configurable master data — sources (Call, Instagram, WhatsApp…), pipeline life-stages, follow-up heat categories, marketing/ad codes for spend attribution, and health/disease categories.
  • Bulk operations — random round-robin assignment to agents, bulk re-assignment, bulk pipeline-stage moves, and bulk department changes.
  • Append-only notes on leads (an immutable interaction trail).
  • Lead → customer conversion, keeping the two records linked.
  • Follow-ups — task reminders attachable to a lead or a customer.
  • Sales calls — scheduled after-sales outbound calls with outcomes.
  • CRM dashboard — key counts (total/today's leads, customers, deal status, priority).

Connects to. Sales (a lead can become a customer and an order in one step; customers carry the AR ledger), and Users (agents and assignment pickers).

Suppliers

Purpose. The vendor master used by the procurement process.

Key capabilities.

  • Two contact types — individual (person) or business (company).
  • Auto-generated supplier IDs (SUP-0001…), contact details, GST/PAN, banking details, credit payment terms, and an opening balance used in payables calculations.
  • Rich filtering (type, status, city, pay-term range, balance range) and soft-delete.

Connects to. Purchase (every purchase requisition, order, record, and return references a supplier) and Logistics (goods receipts).


5.3 Procurement & Inventory Group

Purchase (Procurement)

Purpose. Manages the full procure-to-pay cycle and supplier payables.

Key capabilities.

  • Two-tier workflow: Purchase Requisition (PR) → (on approval) auto-created Purchase Order (PO) → Purchase Record (the supplier bill). A standalone purchase path also exists.
  • Approvals — PRs are approved or rejected; approval automatically generates the PO.
  • Supplier payments as instalments with overpayment guards and soft-cancel.
  • Purchase returns with a two-step pending → completed workflow that deducts the returned stock and posts the payables adjustment.
  • Accounts-payable (AP) ledger — a running, per-supplier balance of what the business owes, posted automatically on bills, payments, and returns.
  • Attachments on records and payments.

Connects to. Suppliers, Products, Stock (returns deduct stock; goods receipt — not the bill — adds stock, via Logistics), Settings (locations), and Accounting.

Important distinction: A purchase record is a financial document. Stock is added when goods are physically received and quality-checked (the GRN step in Logistics), not when the bill is entered.

Logistics (Goods Movement)

Purpose. Manages the physical movement of goods — inbound receipts and inter-branch transfers.

Key capabilities.

  • Goods Receipt (GIN) — records goods arriving against a purchase order; verified via a two-step receive-then-quality-check flow. Receiving alone does not add stock.
  • Goods Received Note (GRN) — the quality-verification step. Accepting goods here is what adds stock to inventory (with batch and expiry) and updates the PO status.
  • Stock transfers — moving stock between locations through a three-phase lifecycle: initiated → in-transit (stock deducted from source) → received (stock added to destination).
  • Sequential, gap-free document numbers (GR-, GRN-, ST-).

Connects to. Purchase (PO linking), Stock (all quantity changes go through the central stock service), Suppliers, and Settings (locations).

Stock (Inventory Ledger)

Purpose. The single, authoritative inventory system for the whole platform. Every quantity change anywhere in the system goes through it.

Key capabilities.

  • Per-location and per-batch stock tracking (with expiry dates).
  • Append-only movement ledger — every change writes one immutable row recording the signed quantity, the reason (purchase, sale, return, GRN, transfer, pharmacy dispense, adjustment, opening balance…), the source document, and who triggered it.
  • Manual stock adjustments with a draft → approved/rejected approval workflow and reason codes (damage, expiry, theft, stock-take correction, data-entry error, other).
  • Idempotency and safety — retried operations don't double-count, and negative balances are blocked unless an explicit reversal allows them.
  • Stock queries: by location, by product, batch inventory, FEFO (first-expiry-first-out) picking, typeahead pickers, and a by-location report.

Connects to. Effectively every operational module (Sales, Purchase, Logistics, Hospital pharmacy, and manual adjustments) and feeds the Inventory Valuation module.

Products (Catalogue)

Purpose. The product master that everything else references.

Key capabilities.

  • Products with SKU, barcode type, HSN code, pricing (purchase/selling/MRP), tax rate, unit, brand, category, warranty, dimensions/weight, custom fields, and a low-stock alert threshold.
  • Supporting master data — brands, categories, units, variations, warranties (each with its own management screens).
  • Bulk Excel import/export with pre-upload validation and optional on-the-fly creation of missing brands/categories/units/etc.
  • File attachments (brochures, images) and a separate alert-quantity bulk update.
  • Performance caching of dropdown lists.

Connects to. Stock (a product's total on-hand is maintained by the stock service), Settings (tax rates), and every transactional module that lists products.

Inventory Valuation

Purpose. Puts a cost value on inventory so the accounts can show a traditional "Trading" Profit & Loss with opening and closing stock.

Key capabilities.

  • A FIFO (first-in-first-out) cost sub-ledger that automatically tracks the cost of every stock layer as goods come in and are consumed.
  • Computes opening and closing stock value as of any date, with today's closing becoming tomorrow's opening (rolling stock).
  • Fed automatically from the central stock ledger, so it captures every stock source without extra data entry.

Connects to. Accounting reports — it supplies the Opening Stock, Closing Stock, and Cost-of-Goods-Sold figures into the Trial Balance, Profit & Loss, and Balance Sheet.


5.4 Finance & Accounting Group

Accounting

Purpose. A complete double-entry bookkeeping system that records the financial side of every operation and produces statutory-style financial statements.

Key capabilities.

  • Chart of Accounts — a single, configurable tree of account groups and postable ledgers (ERPNext/Tally-style), rooted in the five natures: Assets, Liabilities, Equity, Revenue, Expenses. Includes GST input/output ledgers and TDS ledgers. The structure is protected (you cannot delete a group that has children or a ledger that has postings).
  • Vouchers (journal entries) of six types — Payment, Receipt, Contra, Journal, Purchase, Sales — each enforcing the fundamental rule that debits equal credits. Vouchers save directly as posted; corrections are made as audited in-place edits (with a mandatory reason and a full before/after snapshot retained).
  • Automatic, race-free voucher numbering (e.g. SLV-2026-0001).
  • Fiscal years with a period-close workflow that locks the books for a closed year (and a controlled reopen). Writing into a closed period requires a special, fully-logged override.
  • Financial reports (all from posted entries, all in exact decimals):
    • Trial Balance (with opening/movement/closing columns and net-GST presentation),
    • Profit & Loss (with a Trading section: opening stock, direct costs, closing stock, gross profit → net profit),
    • Balance Sheet (Assets = Liabilities + Equity, with net profit folded into equity),
    • General Ledger (per-account running balance),
    • Cash Flow Statement (direct method, split into operating/investing/financing),
    • Group Summary and Grouped Ledger Summary (Tally-style collapsible trees).
  • GST presentation — reports can net GST input against output into a single "GST Payable (Net)" / "GST Receivable (Net)" line for financial-statement presentation, while keeping the gross per-ledger view available for GST return reconciliation.

The "posting bridge" — accounting that books itself. This is the heart of the integration. Operational modules don't ask accountants to re-key transactions; instead, each business event automatically drafts the correct voucher in the same database transaction:

Business event Accounting voucher created automatically
Company or pharmacy sale invoiced Sales voucher (Dr Receivable, Cr Revenue + GST)
Customer payment received Receipt voucher (Dr Bank/Cash, Cr Receivable)
Sale return completed Journal voucher reversing revenue and GST
Sale / payment cancelled The linked voucher is cancelled in the same step

Anything that can't be auto-posted cleanly (e.g. a standalone return that predates the integration) is routed to an accounting review queue for an accountant to handle, with suggested entries pre-filled. If a sale falls in a closed fiscal year, the system refuses to silently re-open the books and asks an authorised user to reopen the year first.

Connects to. Sales and Purchase (via posting bridges), Inventory Valuation (stock figures in reports), and Settings (bank accounts linked to cash/bank ledgers).


5.5 Platform & Administration Group

Human Resource Management (HRM) & Payroll

Purpose. Manages the workforce and computes monthly salaries from attendance.

Key capabilities.

  • Employees with employment type, designation, department or hospital-location assignment, shift, banking details, documents, and photo.
  • Master data — departments, designations, hospital locations, and shifts (with grace periods, required minutes, weekly-offs, break and overtime rules).
  • Attendance — clock-in/out, biometric device punches, admin overrides, and an automated nightly processing pipeline that derives status (present/late/half-day/absent/on-leave/holiday) and computes worked/deficit/overtime minutes. Times stored in UTC, evaluated against the shift in local time.
  • Leave management — leave types, applications with approval, balances, and medical document uploads; holidays with bulk Excel import.
  • Teams with leaders, enabling "team leader sees their team's records" scoping.
  • Payroll — a 3-tier deduction model (absent days, time-deficit to the minute, manual adjustments) plus overtime pay, producing a draft salary record that is then finalized (locked).
  • Weekly and monthly attendance summaries (automated background jobs).

Connects to. Users (employees link to login accounts), Settings/hospital locations, and the access-control scope system (an employee's location/department drives what they can see).

Reports (Export Engine)

Purpose. A configurable engine for generating and exporting operational and financial reports.

Key capabilities.

  • A catalogue of report types — sales (summary/detailed/by user), purchases, stock movements/valuation, CRM (leads/customers/follow-ups), HR (attendance/salary), hospital (consultations/prescriptions), suppliers, outstanding payables, product sell/return, input/output tax, and more.
  • Export to Excel or CSV, with permission-scoped access (e.g. "export" vs. "view own").
  • Background generation for large reports.

Connects to. Reads across all operational modules.

Activity Log (Audit Trail)

Purpose. A system-wide, append-only record of who did what and when.

Key capabilities.

  • Every create/update/delete across modules writes an activity entry with the actor's name/email (snapshotted), timestamp, resource type, and details.
  • Per-module feeds (e.g. an Accounting activity feed) and an organisation-wide feed.
  • Sensitive edits (such as corrections to posted accounting vouchers) store a full before/after diff that can be expanded in the UI.

Settings (Configuration)

Purpose. Global configuration shared across the application.

Key capabilities.

  • Locations — a unified list of business and hospital locations, including printable prescription letterhead details (title, GSTIN, footer) for hospital locations.
  • Tax rates — named GST/IGST rates (e.g. "GST 18%") used by products and sales/purchase lines.
  • Bank accounts — linked to the accounting cash/bank ledgers so payments post correctly.
  • Soft-delete with safety checks (e.g. a hospital location with assigned employees can't be deactivated), and cached dropdown lists.

Tickets (Internal Support)

Purpose. A lightweight internal support/issue channel.

Key capabilities.

  • Any authenticated user can raise a ticket, categorised (technical, billing, account, feature request, bug, other), and sees only their own tickets.
  • The super admin handles all tickets. Tickets support messages and attachments.

Release Notes ("What's New")

Purpose. Communicates new features and changes to users inside the application, following semantic versioning.

User Management & Access Control

Purpose. The foundational security layer (covered in detail in Section 4).

Key capabilities. User lifecycle (create, update, soft-delete, restore, permanent delete), self-service profile and password change, password-reset request handling, and full management of roles and the permissions assigned to each role.


6. Key End-to-End Business Flows

These flows show how the modules combine to handle real business events. They are the clearest demonstration that Herbally is an integrated system, not a set of disconnected tools.

6.1 Pharmacy: prescription → dispensed invoice

Doctor writes        Pharmacist opens         System, in ONE transaction:        Prescription
prescription   ──►   the pharmacy queue  ──►  • creates PHARM- invoice      ──►  marked
(Hospital)           and dispenses            • deducts stock @ location          "completed"
                                              • posts the sales voucher
                                              • (no customer ledger if walk-in)

One click bills the patient, reduces inventory, and books the revenue and GST — all together, or not at all.

6.2 Retail: lead → order → invoice → payment → books

CRM lead ──► convert to customer ──► sales order (stock checked & reserved)
        ──► confirm ──► convert to invoice ─┐
                                            ├─► stock deducted
                                            ├─► customer AR ledger debited
                                            └─► sales voucher posted (Dr Debtors, Cr Revenue+GST)
        ──► record payment ─┐
                            ├─► AR ledger credited
                            └─► receipt voucher posted (Dr Bank, Cr Debtors)

By the time the customer has paid in full, the receivable nets to zero and the bank/revenue/GST ledgers are all correct — with no manual journal entries.

6.3 Procurement: requisition → goods in stock → supplier paid

Purchase Requisition ──► approve ──► Purchase Order ──► Goods Receipt (GIN)
                                                    ──► quality check (GRN) ──► STOCK ADDED (batch+expiry)
Supplier bill (Purchase Record) ──► AP ledger credited (we owe the supplier)
Supplier payment ──► AP ledger debited (balance reduced)

Stock only increases after physical receipt and quality acceptance; the payables ledger tracks exactly what is owed to each supplier.

6.4 Inventory valuation → financial statements

Every stock movement ──► FIFO cost layers updated ──► Opening/Closing stock value
                                                  ──► fed into Trial Balance, P&L (Trading section),
                                                      and Balance Sheet

6.5 Cancellations stay consistent

When a sale, payment, or return is cancelled, the linked accounting voucher is cancelled in the same transaction and stock is reversed. A cancelled voucher keeps its row for audit but drops out of all financial reports. If the entry belongs to a closed fiscal year, the system blocks the cancellation until an authorised user reopens the year — the books cannot be quietly altered.


7. Cross-Cutting Capabilities

These features work consistently across the whole platform:

Capability Description
Multi-location operations Business and hospital locations are first-class; stock, sales, and visibility are scoped per location.
GST & Indian tax compliance CGST/SGST/IGST on line items, HSN codes, GST input/output ledgers, and net-GST financial presentation.
Batch & expiry tracking Medicines and goods carry batch numbers and expiry dates through receipt, stock, and sale; FEFO picking is supported.
Attachments everywhere Invoices, payments, purchase records, products, employee documents, and tickets support file uploads (stored in S3-compatible object storage with secure, time-limited download links).
Audit trail Append-only activity logging on every change, with before/after snapshots for sensitive edits.
Exact financial arithmetic Decimal money handling end-to-end; balanced double-entry enforced.
Document numbering Human-readable, auto-generated reference numbers for every document type (orders, invoices, vouchers, receipts, returns, adjustments).
Bulk Excel import/export Products, holidays, and reports support spreadsheet workflows.
Background processing Nightly attendance processing, weekly/monthly summaries, and large report generation run as background jobs.
Caching Frequently-read dropdown/master lists are cached for speed and refreshed automatically on change.

8. Technology Stack

This section is intended for technical reviewers; the rest of the document is deliberately non-technical.

Backend (the engine)

Area Technology
Language / framework Python with FastAPI (async)
Architecture Modular monolith; strict Route → Service → CRUD → Model layering
Database access SQLAlchemy 2.0 (async ORM)
Database PostgreSQL 16
Migrations Alembic (versioned schema changes)
Cache & message broker Redis 7
Background jobs Celery (worker + beat scheduler), monitored via Flower
File storage S3-compatible object storage (DigitalOcean Spaces)
Auth JWT access/refresh tokens; bcrypt password hashing; role-based access control
API docs Auto-generated OpenAPI/Swagger UI
Observability Structured logging, Prometheus metrics, health checks

Frontend (the user interface)

Area Technology
Framework Next.js 16 (App Router) on React 19
Language TypeScript (strict)
Server data TanStack Query
UI state Zustand
Forms & validation React Hook Form + Zod
Styling Tailwind CSS v4 with custom UI components
Auth pattern Backend-for-Frontend (BFF) with secure httpOnly cookies

9. Deployment & Operations

  • Containerised deployment. The entire backend stack runs in Docker containers (API, PostgreSQL or managed Postgres, Redis, Celery worker, Celery beat). A reusable, template-driven deployment system ("deploy-v2") brings up a new production server from a single configuration file, including automatic SSL certificate setup for the domain.
  • Database migrations run automatically on deploy, keeping the schema in sync with the code.
  • Seeding scripts create the standard roles, ~150 permissions, the chart of accounts, and an initial super-admin — and are safe to re-run (idempotent).
  • The frontend is a standard Next.js application suitable for hosting on platforms such as Vercel or alongside the backend.
  • Monitoring & health endpoints (health check, metrics, background-job dashboard) support ongoing operations.

Recommended/typical production target: managed Kubernetes with managed PostgreSQL, container images published to a registry, Redis in-cluster, and database migrations run as a job. (The deployment tooling also supports a simpler single-server Docker Compose setup.)


10. Data Integrity, Security & Compliance

Concern How the system addresses it
Financial correctness Double-entry enforced (debits = credits); exact decimal money; balanced trial balance by construction; closed-period locking.
Inventory correctness A single writer for all stock with an append-only ledger, idempotent operations, and negative-balance guards.
Auditability Every change is logged with actor and timestamp; sensitive edits keep full before/after history; records are soft-deleted, not erased.
Access security Permission checks on every backend request; per-row scope filtering; secure token-based auth; passwords hashed; tokens in httpOnly cookies.
Tax compliance (India) GST on transactions, HSN codes, GST input/output ledgers, GST return-friendly and statement-friendly report presentations.
Traceability Batch numbers and expiry dates tracked from goods receipt through to the patient/customer sale.
Resilience All-or-nothing transactions across modules ensure stock, ledgers, and accounting never go out of sync.

Appendix A — Complete Module Inventory

# Module Group One-line purpose
1 Hospital Clinical Patient care: bookings, tokens, doctor queue, consultations, prescriptions
2 Pharmacy Clinical Prescription dispensing → invoice
3 Sales Sales & Customer Orders, invoices, payments, returns, AR ledger
4 CRM Sales & Customer Leads, customers, follow-ups, sales calls
5 Suppliers Sales & Customer Vendor master records
6 Purchase Procurement & Inventory Requisitions, orders, bills, payments, returns, AP ledger
7 Logistics Procurement & Inventory Goods receipt, quality check (GRN), stock transfers
8 Stock Procurement & Inventory Authoritative inventory ledger + adjustments
9 Products Procurement & Inventory Product catalogue + master data
10 Inventory Valuation Procurement & Inventory FIFO stock costing for the P&L
11 Accounting Finance Double-entry books, vouchers, fiscal years, financial reports
12 HRM & Payroll Platform & Admin Employees, attendance, leave, salary
13 Reports Platform & Admin Configurable report generation & export
14 Activity Log Platform & Admin System-wide audit trail
15 Settings Platform & Admin Locations, tax rates, bank accounts
16 Tickets Platform & Admin Internal support tickets
17 Release Notes Platform & Admin In-app "What's New"
18 User Management Platform & Admin User lifecycle & self-service
19 Access Control Platform & Admin Roles, permissions, scoped access

Appendix B — Glossary

Term Meaning
AR / AP ledger Accounts Receivable (what customers owe us) / Accounts Payable (what we owe suppliers).
Voucher A double-entry accounting transaction (journal entry) with balanced debits and credits.
Chart of Accounts (CoA) The structured list of all accounts (groups and postable ledgers) used in bookkeeping.
Posting bridge The mechanism that automatically creates the correct accounting voucher when an operational event occurs.
GIN / GRN Goods Inward Note (goods received) / Goods Received Note (quality-verification step that adds stock).
PR / PO Purchase Requisition / Purchase Order.
FIFO / FEFO First-In-First-Out (cost flow) / First-Expiry-First-Out (picking order).
GST / CGST / SGST / IGST India's Goods & Services Tax and its central/state/inter-state components.
HSN code Harmonised System of Nomenclature code used to classify goods for tax.
RBAC Role-Based Access Control.
Scope The row-level filter deciding which records a user may see (e.g. their location only).
Soft delete Marking a record as deleted (hidden) rather than physically removing it.
Idempotent An operation that produces the same result even if accidentally run twice.
Fiscal year close Locking an accounting year so its books can no longer be changed without a controlled reopen.
Modular monolith A single deployable application that is internally divided into well-separated modules.

Appendix C — Where the Detailed Technical Docs Live

Each module maintains an authoritative, developer-facing reference. For deeper technical detail, consult these files in the source repository:

Module / topic Backend reference Frontend reference
Conventions & architecture herbally-backend/docs/PROJECT_CONVENTIONS.md herbally-frontend/FRONTEND_ARCHITECTURE_GUIDE_V2.md
Access control & scope herbally-backend/docs/RBAC_AND_SCOPE.md, app/user/permission_management/ACCESS_CONTROL_MODULE_LLM.md src/components/access-control/ACCESS_CONTROL_MODULE_INFO.md
Accounting app/accounting/ACCOUNTING_MODULE.md
Sales app/sales/SALES_MODULE_LLM.md src/components/sales/SALES_MODULE_INFO.md
Purchase app/purchase/PURCHASE_MODULE_LLM.md src/components/purchase/PURCHASE_MODULE_INFO.md
Products app/products/PRODUCTS_MODULE_LLM.md src/components/products/PRODUCTS_MODULE_INFO.md
Stock app/stock/STOCK_MODULE_LLM.md src/components/stock/STOCK_MODULE_INFO.md
Logistics app/logistics/LOGISTICS_MODULE_LLM.md src/components/logistics/LOGISTICS_MODULE_INFO.md
Inventory valuation app/inventory_valuation/INVENTORY_VALUATION_LLM.md
CRM app/crm/BUSINESS_LOGIC.md, app/crm/CRM_MODULE_MAP.md src/components/crm/CRM_MODULE_MAP.md
HRM & payroll app/hrm/HRM_MODULE_LLM.md src/components/hrm/HRM_MODULE_INFO.md
Suppliers app/supplier/SUPPLIER_MODULE_LLM.md src/components/supplier/SUPPLIER_MODULE_INFO.md
Settings app/settings/SETTINGS_MODULE_LLM.md src/components/settings/SETTINGS_MODULE_INFO.md
Users app/user/USER_MODULE_LLM.md src/components/user/USER_MODULE_INFO.md
Hospital ↔ Pharmacy flow herbally-backend/docs/PHARMACY_SALES_FLOW.md
Deployment herbally-backend/deploy-v2/README.md, deploy-v2/QUICK_START.md

End of document. Prepared as a consolidated overview of the Herbally platform for management and client-handover purposes. For the latest authoritative detail on any module, refer to the per-module references in Appendix C.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment