Gujranwala Sanitary Collection — Store Management System
One place for the shop counter, the factory floor and the owner's books.
A complete Flask-based management system for a sanitary/plumbing fittings business with two operating sections — Shop and Factory — plus an Admin area for combined reports and Profit & Loss.
#At a glance
#Features
Login & Access Control
- Session-based login (Flask-Login) with 2FA, CSRF protection and a Security Center (see §8)
- Three roles:
admin(full access),shop_staff(Shop only),factory_staff(Factory only) - Admin can create/disable users from Users & Access
- Login lockout: 5 failed attempts locks an account for 15 minutes; admins can unlock early
Shop section (its own books, separate from the Factory)
- Sales orders (create / edit / delete / cancel / returns), PDF invoice and receipt
- Inventory (products) and Purchasing from suppliers (adds stock; unpaid part becomes "credit taken")
- Expenses, Capital / Investment (investment & withdrawal) and Credits (given & taken, with repayments)
- Customers with balance due; sales-order balances also show in Credits
Factory section (its own books)
- Sales to Parties & Shops (works just like Shop sales orders): pick a party/shop (or add a new one on the spot), add products with rate and quantity, discount, amount received and balance due. Each sale has Edit, Delete, Cancel, Returns, Record Payment, a printable Receipt and an Invoice PDF under the factory's name. Ready stock goes down automatically on a sale and comes back on cancel, delete or return. Parties & Shops has each one's total purchases, balance due and sale history. Unpaid balances also show in Factory Credits, and factory sales are included in Profit & Loss and the Factory Report.
- Ready Stock & Dispatch: finished goods ready to go, and every dispatch with the shop it went to (quantity, rate, vehicle/details). Monthly record download (summary + stock in + dispatches)
- Inventory (raw materials) with stock-in purchases and usage
- Workers with CNIC, paid per piece: Piece Work log (pieces x rate, optionally adds to ready stock), Worker Payments, and a per-worker monthly statement
- Expenses, Capital / Investment, Credits (given & taken)
Everywhere: every list has Edit, Delete and a month filter with Excel/CSV download of what is on screen.
Accounts: every user can change their own password (sidebar); admins can edit users (name, username, role, password reset) and delete them.
Admin / Reports
- Business overview dashboard with 6-month revenue vs. cost trend
- Profit & Loss statement for any date range: Revenue → COGS → Gross Profit → Expenses (Shop/Factory/General) → Net Profit, downloadable as Excel, PDF, or CSV
- Sales report, Production report, Inventory report (with Excel export)
- Customer Insights — top customers by revenue, outstanding balances
- Slow-Moving Stock — products with little/no sales in the last 30/60/90 days, and how much capital is tied up in them
- Worker Productivity — hours, batches, and wages per worker for any date range
- Company-wide expense ledger
- Activity log (audit trail of who did what)
- Database backups — one-click backup + download from the Admin panel, plus a CLI command for scheduled/automated backups
- WhatsApp alerts — order confirmations, payment receipts, and a manual low-stock alert button (needs a Twilio account to actually send — see below)
#Tech stack
Flask 3, Flask-SQLAlchemy, Flask-Login, SQLite (default) or any SQL database via DATABASE_URL, openpyxl (Excel export), ReportLab (PDF export), Chart.js (dashboard graphics), Twilio REST API (WhatsApp/SMS, optional). Custom dark theme — no Bootstrap.
#1. Run it locally
# from inside the project folder
python3 -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt
python3 app.py # or: flask runThat's it — the database and the login account below are created automatically the first time the app starts. No separate init-db or seed command needed.
Open http://127.0.0.1:5000 in your browser.
#First login (created automatically on first run)
There is no hard-coded password any more. On first start one admin (ADMIN_USERNAME) is created:
- if you set
ADMIN_PASSWORD(must pass the password policy) it is used; - otherwise a strong random password is generated and printed once in the server console / logs.
Either way the admin is forced to choose a new password and enrol 2FA at first sign-in. More users (shop / factory staff, more admins) are created from Admin → Users & Access; they must change their temporary password at first login.
The system starts completely empty otherwise — no products, customers, materials, orders, or batches. Everything you see is data you add yourself.
#2. Project structure
sanitary_store/
├── app.py # app factory + entrypoint + CLI commands
├── config.py # env-based configuration
├── extensions.py # db, login_manager singletons
├── models.py # all database models
├── seed.py # creates the initial admin account (no demo data)
├── reports.py # Profit & Loss calc + Excel/PDF/CSV/invoice builders
├── backup.py # database backup/restore helpers
├── notifications.py # WhatsApp/SMS via Twilio (optional, safe no-op if unset)
├── utils.py
├── auth/ # login, logout, user management, lockout
├── main/ # post-login landing page (Shop/Factory chooser)
├── shop/ # products, customers, sales orders, returns, receipts
├── factory/ # ready stock, sales to parties/shops, raw materials, workers
├── admin/ # overview, reports, P&L, expenses, backups, activity log
├── templates/ # Jinja2 templates (dark theme)
├── static/css/style.css # design system
└── requirements.txt#Data model at a glance
The main records the system keeps, and how they relate (simplified):
#3. WhatsApp / SMS alerts (optional)
Order confirmations, payment receipts, and low-stock alerts are wired up to send via WhatsApp, but this needs your own free Twilio account to actually send anything — without it configured, the app just logs what it would have sent and carries on normally (nothing breaks).
To enable it:
- Create a Twilio account at https://www.twilio.com (has a free trial with a WhatsApp sandbox number to test with).
- Set these environment variables: ``
TWILIO_ACCOUNT_SID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx TWILIO_AUTH_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx TWILIO_WHATSAPP_FROM=whatsapp:+14155238886 ADMIN_ALERT_PHONE=+923001234567`` - Restart the app. Order confirmations and payment receipts will now go out automatically to the customer's phone number on file, and the "Send Low Stock Alert" button on the Admin overview page will actually deliver.
#4. Automated database backups
From Admin → Backups the owner can:
- Download Excel – one file with all data, one sheet per topic (customers, sales, stock, payments, expenses, workers ...), with real names instead of ID numbers. Works on SQLite and hosted Postgres.
- Create Backup Now – a restorable snapshot of the database (SQLite). Each snapshot can be opened with View (read-only, searchable, right inside the app), downloaded as Excel, or downloaded as the technical .db file used to restore.
- Excel/viewer never contain password hashes, 2FA secrets, session tokens or PINs. Every download needs the admin's password again (5 wrong tries = 15-minute block) and is written to the Activity Log.
For a truly automated schedule, add a cron job (Linux/Mac) that runs the built-in CLI command:
# Example: back up every day at 2 AM
0 2 * * * cd /path/to/sanitary_store && /path/to/venv/bin/flask backup-dbThe last 30 backups are kept automatically; older ones are pruned. This only applies to a local SQLite database — if you're using a hosted Postgres/MySQL provider (see the Vercel section below), that provider already handles backups on its own.
#5. Deploying to Vercel
Vercel runs Flask as a serverless function. Two things to know before you deploy:
#⚠️ SQLite will NOT work on Vercel
Vercel's filesystem is read-only and ephemeral at runtime — every request can hit a different, freshly-reset instance, so a local SQLite file will not persist data and will likely fail to write at all. You need a **hosted database**. Good free/cheap options that work well with Flask + SQLAlchemy:
- Neon (Postgres, generous free tier)
- Supabase (Postgres)
- PlanetScale (MySQL)
Once you have a connection string, set it as the DATABASE_URL environment variable in your Vercel project settings — the app already handles both postgres:// and postgresql:// prefixes. No code changes needed.
#Steps
- Create the Postgres database (e.g. on Neon) and copy its connection string.
- Add a
vercel.jsonin the project root (already included in this project). - In the Vercel dashboard, set environment variables:
DATABASE_URL= your Postgres connection stringSECRET_KEY= a long random stringCOMPANY_NAME,CURRENCY(optional)TWILIO_*,ADMIN_ALERT_PHONE(optional, for WhatsApp alerts)
- Deploy:
vercel --prod(or connect the GitHub repo in the Vercel dashboard). - That's it — the app creates its tables and the admin account automatically the first time it runs against that
DATABASE_URL.
#Alternative: a VPS/shared host instead of Vercel
If you'd rather avoid the serverless/SQLite issue entirely, this app runs as a normal Flask app on any VPS (DigitalOcean, a Pakistani hosting provider, PythonAnywhere, etc.) with SQLite working fine out of the box — just run it behind gunicorn (included in requirements.txt):
gunicorn -w 4 -b 0.0.0.0:8000 app:app#6. Notes on the business logic
- Costing: raw materials use weighted-average costing — every purchase updates the material's average unit cost. Finished products get their
cost_priceupdated the same way whenever a production batch completes. - Multi-product batch cost allocation: when a batch produces more than one product, the shared material/labor/overhead cost is split between the outputs using the relative sales value method — each product's share is proportional to (quantity produced × its selling price). This is a standard joint-cost accounting approach; see
complete_batch()infactory/routes.pyif you'd rather allocate a different way (e.g. equally, or by weight/volume). - Sales returns: a return restocks the returned quantity and reduces the order's net total (and therefore revenue in the Profit & Loss report) — it does not delete or alter the original sale record, so you always have a full history of what was sold vs. what came back.
- Profit & Loss = Revenue (sales, net of discounts and returns) − COGS (cost of goods actually kept by the customer) − Operating Expenses (Shop + Factory + General, logged separately).
reports.py→compute_profit_loss()is the single place to adjust this formula. - Stock integrity: selling deducts Shop stock immediately; cancelling an order or processing a return restores it. Using a raw material in a batch deducts Factory stock; cancelling an in-progress batch restores it. Completing a batch adds the produced quantities to Shop stock.
#7. Operations add-ons
| Feature | Where |
|---|---|
| Udhaar ageing (0-30 / 31-60 / 61-90 / 90+ days, Excel export) | Shop → Udhaar / Receivables, Factory → Receivables |
| Customer / party statement (print, PDF) + receive payment on account | Customer or Party page → Statement |
| Opening balances (what customers owed before the system) | Bulk Import, column opening_balance |
| Cheque tracking (in hand → deposited → cleared / bounced; balance drops only when cleared) | Shop / Factory → Cheques |
| Quotations → one-click convert to a sales order | Shop → Quotations |
| Party-wise special rates (auto-filled on orders & quotations) | Customer page → Special rates |
| Quick billing: scan a barcode/SKU and press Enter = adds 1 and opens the next line | New Sales Order |
| Bulk import from Excel/CSV (products, customers, parties) with all-or-nothing option | Admin → Bulk Import |
Receipts: 58 mm / 80 mm thermal, English or Urdu (?lang=ur&w=58) | Order → Receipt |
Manager PIN approvals: staff need an admin's PIN for discounts above DISCOUNT_APPROVAL_PERCENT (10), deleting/cancelling sales, deleting payments/cheques, applying stock counts | Admin sets PIN in Security & 2FA |
| Stock audit (count sheet, variance, apply) + damage/loss entries and loss value | Shop → Stock Audit |
| Supplier ledger (purchases, what you owe) | Shop / Factory → Supplier Ledger |
| Day-end cash closing (expected vs counted, difference history) | Shop / Factory → Day-end Cash |
| Profit by product & category | Admin → Profit by Product |
| Reorder suggestions from recent sales / material usage | Shop → Reorder, Factory → Reorder |
| Worker attendance + advances (Payment type = Advance) | Factory → Attendance |
| Installable app (PWA) - "Add to Home Screen" on phones | automatic |
Receivables are grouped into ageing buckets so overdue udhaar is easy to chase:
Notes
- The cash book only knows about payments recorded after this version was installed.
- Cash-closing expected cash counts cash receipts; cheques and bank transfers are excluded.
- Until an admin sets the manager PIN, staff are blocked from the PIN-protected actions (by design).
#Tests
python tests/test_security.py # login, 2FA, CSRF, backups, throttling ...
python tests/test_ops.py # all add-on features end to end#8. Security (what's built in)
| Area | Protection |
|---|---|
| Passwords | scrypt hashes; min 10 chars, 3 of 4 character classes, common-password + name checks |
| Login | Generic error messages, equal timing for unknown users, 5-strike account lockout (15 min), per-IP throttle (12 failures / 15 min), fresh session on login |
| 2FA | TOTP authenticator app (Google/Microsoft Authenticator, Authy), one-time recovery codes, replay protection, mandatory for admins, secrets encrypted at rest |
| Sessions | HttpOnly + Secure + SameSite cookies (__Host- prefix on HTTPS), 30-min idle timeout, changing a password or "Sign out everywhere" kills all other sessions instantly |
| CSRF | Token on every POST form; logout is POST-only |
| Headers | Strict CSP (nonce-based, no inline handlers, no third-party scripts), HSTS, X-Frame-Options DENY, nosniff, no-store caching, Referrer/Permissions policies |
| Data export | CSV/Excel formula-injection neutralised |
| Backups | Consistent SQLite snapshot, integrity-checked, SHA-256 shown, read-only viewer + Excel export without secrets, every download needs password re-entry (throttled, logged), strict filename allow-list |
| Re-auth throttle | Password prompts for backups, 2FA reset and manager PIN allow 5 wrong tries per 15 min |
| Admin sessions | "Keep me signed in" is ignored for admins (idle timeout always applies) |
| Audit | Activity log with IP, searchable + paged; every sign-in attempt recorded; Admin → Security Center shows a live checklist, failed-login stats and session controls |
#Environment variables
| Variable | Purpose |
|---|---|
APP_ENV=production | Turns on secure cookies, requires SECRET_KEY (auto-on on Vercel) |
SECRET_KEY | 32+ random chars: python -c "import secrets; print(secrets.token_hex(32))" |
DATA_ENCRYPTION_KEY | Optional separate key for 2FA secrets (so rotating SECRET_KEY doesn't break 2FA) |
ADMIN_USERNAME / ADMIN_PASSWORD | First-run admin |
REQUIRE_2FA_FOR_ADMINS | 1 (default) / 0 |
IDLE_TIMEOUT_MINUTES, MAX_FAILED_LOGINS, LOCKOUT_MINUTES, IP_MAX_FAILURES, PASSWORD_MIN_LENGTH | Tunables |
TRUST_PROXY=1 | Use real client IP behind a proxy (auto-on on Vercel) |
#Emergency commands
flask reset-2fa "<username>" # lost phone AND recovery codes
flask unlock-user "<username>" # clear a lockout#Checklist before going live
APP_ENV=productionand a strongSECRET_KEYset- HTTPS only (Vercel does this automatically)
- Every admin has 2FA on and has saved their recovery codes
- Never set
FLASK_DEBUG=1on a server (debug mode = remote code execution) - Scheduled
flask backup-db(local SQLite) and copy backups off the server - Review who has the
adminrole; open Admin → Security Center and clear all ⚠️ items
#Want a system like this?
Tell us a little about your business. We reply with ideas and a rough scope — free, no obligation.
Need something similar?
Book a free consultation — we'll scope it with you, no obligation.
# Gujranwala Sanitary Collection — Store Management System
> One place for the shop counter, the factory floor and the owner's books.

A complete Flask-based management system for a sanitary/plumbing fittings
business with two operating sections — **Shop** and **Factory** — plus an
**Admin** area for combined reports and Profit & Loss.
## At a glance

## Features
**Login & Access Control**
- Session-based login (Flask-Login) with 2FA, CSRF protection and a Security Center (see §8)
- Three roles: `admin` (full access), `shop_staff` (Shop only), `factory_staff` (Factory only)
- Admin can create/disable users from **Users & Access**
- **Login lockout**: 5 failed attempts locks an account for 15 minutes; admins can unlock early

**Shop section** (its own books, separate from the Factory)
- Sales orders (create / edit / delete / cancel / returns), PDF invoice and receipt
- Inventory (products) and **Purchasing** from suppliers (adds stock; unpaid part becomes "credit taken")
- **Expenses**, **Capital / Investment** (investment & withdrawal) and **Credits** (given & taken, with repayments)
- Customers with balance due; sales-order balances also show in Credits

**Factory section** (its own books)
- **Sales to Parties & Shops** (works just like Shop sales orders): pick a party/shop (or add a new one on the spot),
add products with rate and quantity, discount, amount received and balance due. Each sale has Edit, Delete,
Cancel, **Returns**, **Record Payment**, a printable **Receipt** and an **Invoice PDF** under the factory's name.
Ready stock goes down automatically on a sale and comes back on cancel, delete or return.
**Parties & Shops** has each one's total purchases, balance due and sale history. Unpaid balances also show in
Factory Credits, and factory sales are included in Profit & Loss and the Factory Report.
- **Ready Stock & Dispatch**: finished goods ready to go, and every dispatch with the shop it went to
(quantity, rate, vehicle/details). Monthly record download (summary + stock in + dispatches)
- **Inventory** (raw materials) with stock-in purchases and usage
- **Workers** with CNIC, paid **per piece**: Piece Work log (pieces x rate, optionally adds to ready stock),
Worker Payments, and a per-worker monthly statement
- **Expenses**, **Capital / Investment**, **Credits** (given & taken)

**Everywhere**: every list has Edit, Delete and a month filter with Excel/CSV download of what is on screen.
**Accounts**: every user can change their own password (sidebar); admins can edit users
(name, username, role, password reset) and delete them.
**Admin / Reports**
- Business overview dashboard with 6-month revenue vs. cost trend
- **Profit & Loss statement** for any date range: Revenue → COGS → Gross
Profit → Expenses (Shop/Factory/General) → Net Profit, downloadable as
**Excel, PDF, or CSV**
- Sales report, Production report, Inventory report (with Excel export)
- **Customer Insights** — top customers by revenue, outstanding balances
- **Slow-Moving Stock** — products with little/no sales in the last 30/60/90
days, and how much capital is tied up in them
- **Worker Productivity** — hours, batches, and wages per worker for any date range
- Company-wide expense ledger
- Activity log (audit trail of who did what)
- **Database backups** — one-click backup + download from the Admin panel, plus
a CLI command for scheduled/automated backups
- **WhatsApp alerts** — order confirmations, payment receipts, and a manual
low-stock alert button (needs a Twilio account to actually send — see below)

## Tech stack
Flask 3, Flask-SQLAlchemy, Flask-Login, SQLite (default) or any SQL database
via `DATABASE_URL`, openpyxl (Excel export), ReportLab (PDF export),
Chart.js (dashboard graphics), Twilio REST API (WhatsApp/SMS, optional).
Custom dark theme — no Bootstrap.

---
## 1. Run it locally
```bash
# from inside the project folder
python3 -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt
python3 app.py # or: flask run
```
That's it — the database and the login account below are created
automatically the first time the app starts. No separate `init-db` or
`seed` command needed.
Open **http://127.0.0.1:5000** in your browser.
### First login (created automatically on first run)
There is **no hard-coded password** any more. On first start one admin
(`ADMIN_USERNAME`) is created:
- if you set `ADMIN_PASSWORD` (must pass the password policy) it is used;
- otherwise a strong random password is generated and **printed once in the
server console / logs**.
Either way the admin is forced to **choose a new password and enrol 2FA** at
first sign-in. More users (shop / factory staff, more admins) are created from
Admin → Users & Access; they must change their temporary password at first login.
The system starts completely empty otherwise — no products, customers,
materials, orders, or batches. Everything you see is data you add yourself.
---
## 2. Project structure
```
sanitary_store/
├── app.py # app factory + entrypoint + CLI commands
├── config.py # env-based configuration
├── extensions.py # db, login_manager singletons
├── models.py # all database models
├── seed.py # creates the initial admin account (no demo data)
├── reports.py # Profit & Loss calc + Excel/PDF/CSV/invoice builders
├── backup.py # database backup/restore helpers
├── notifications.py # WhatsApp/SMS via Twilio (optional, safe no-op if unset)
├── utils.py
├── auth/ # login, logout, user management, lockout
├── main/ # post-login landing page (Shop/Factory chooser)
├── shop/ # products, customers, sales orders, returns, receipts
├── factory/ # ready stock, sales to parties/shops, raw materials, workers
├── admin/ # overview, reports, P&L, expenses, backups, activity log
├── templates/ # Jinja2 templates (dark theme)
├── static/css/style.css # design system
└── requirements.txt
```
### Data model at a glance
The main records the system keeps, and how they relate (simplified):

---
## 3. WhatsApp / SMS alerts (optional)
Order confirmations, payment receipts, and low-stock alerts are wired up to
send via WhatsApp, but this **needs your own free Twilio account** to
actually send anything — without it configured, the app just logs what it
would have sent and carries on normally (nothing breaks).
To enable it:
1. Create a Twilio account at https://www.twilio.com (has a free trial with a
WhatsApp sandbox number to test with).
2. Set these environment variables:
```
TWILIO_ACCOUNT_SID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_WHATSAPP_FROM=whatsapp:+14155238886
ADMIN_ALERT_PHONE=+923001234567
```
3. Restart the app. Order confirmations and payment receipts will now go out
automatically to the customer's phone number on file, and the "Send Low
Stock Alert" button on the Admin overview page will actually deliver.
---
## 4. Automated database backups
From **Admin → Backups** the owner can:
- **Download Excel** – one file with all data, one sheet per topic (customers, sales, stock, payments,
expenses, workers ...), with real names instead of ID numbers. Works on SQLite *and* hosted Postgres.
- **Create Backup Now** – a restorable snapshot of the database (SQLite). Each snapshot can be opened
with **View** (read-only, searchable, right inside the app), downloaded as **Excel**, or downloaded as
the technical **.db** file used to restore.
- Excel/viewer never contain password hashes, 2FA secrets, session tokens or PINs. Every download needs
the admin's password again (5 wrong tries = 15-minute block) and is written to the Activity Log.
For a truly automated schedule, add a cron job (Linux/Mac) that runs the
built-in CLI command:
```bash
# Example: back up every day at 2 AM
0 2 * * * cd /path/to/sanitary_store && /path/to/venv/bin/flask backup-db
```
The last 30 backups are kept automatically; older ones are pruned. This only
applies to a local SQLite database — if you're using a hosted Postgres/MySQL
provider (see the Vercel section below), that provider already handles
backups on its own.
---
## 5. Deploying to Vercel
Vercel runs Flask as a serverless function. Two things to know before you deploy:
### ⚠️ SQLite will NOT work on Vercel
Vercel's filesystem is **read-only and ephemeral** at runtime — every request
can hit a different, freshly-reset instance, so a local SQLite file will not
persist data and will likely fail to write at all. You need a **hosted
database**. Good free/cheap options that work well with Flask + SQLAlchemy:
- [Neon](https://neon.tech) (Postgres, generous free tier)
- [Supabase](https://supabase.com) (Postgres)
- [PlanetScale](https://planetscale.com) (MySQL)
Once you have a connection string, set it as the `DATABASE_URL` environment
variable in your Vercel project settings — the app already handles both
`postgres://` and `postgresql://` prefixes. No code changes needed.
### Steps
1. Create the Postgres database (e.g. on Neon) and copy its connection string.
2. Add a `vercel.json` in the project root (already included in this project).
3. In the Vercel dashboard, set environment variables:
- `DATABASE_URL` = your Postgres connection string
- `SECRET_KEY` = a long random string
- `COMPANY_NAME`, `CURRENCY` (optional)
- `TWILIO_*`, `ADMIN_ALERT_PHONE` (optional, for WhatsApp alerts)
4. Deploy: `vercel --prod` (or connect the GitHub repo in the Vercel dashboard).
5. That's it — the app creates its tables and the admin account
automatically the first time it runs against that `DATABASE_URL`.
### Alternative: a VPS/shared host instead of Vercel
If you'd rather avoid the serverless/SQLite issue entirely, this app runs
as a normal Flask app on any VPS (DigitalOcean, a Pakistani hosting
provider, PythonAnywhere, etc.) with SQLite working fine out of the box —
just run it behind `gunicorn` (included in requirements.txt):
```bash
gunicorn -w 4 -b 0.0.0.0:8000 app:app
```
---
## 6. Notes on the business logic
- **Costing**: raw materials use weighted-average costing — every purchase
updates the material's average unit cost. Finished products get their
`cost_price` updated the same way whenever a production batch completes.
- **Multi-product batch cost allocation**: when a batch produces more than
one product, the shared material/labor/overhead cost is split between the
outputs using the *relative sales value* method — each product's share is
proportional to (quantity produced × its selling price). This is a
standard joint-cost accounting approach; see `complete_batch()` in
`factory/routes.py` if you'd rather allocate a different way (e.g. equally,
or by weight/volume).
- **Sales returns**: a return restocks the returned quantity and reduces the
order's net total (and therefore revenue in the Profit & Loss report) —
it does not delete or alter the original sale record, so you always have
a full history of what was sold vs. what came back.
- **Profit & Loss** = Revenue (sales, net of discounts and returns) − COGS
(cost of goods actually kept by the customer) − Operating Expenses
(Shop + Factory + General, logged separately). `reports.py` →
`compute_profit_loss()` is the single place to adjust this formula.
- **Stock integrity**: selling deducts Shop stock immediately; cancelling an
order or processing a return restores it. Using a raw material in a batch
deducts Factory stock; cancelling an in-progress batch restores it.
Completing a batch adds the produced quantities to Shop stock.

## 7. Operations add-ons
| Feature | Where |
|---------|-------|
| **Udhaar ageing** (0-30 / 31-60 / 61-90 / 90+ days, Excel export) | Shop → Udhaar / Receivables, Factory → Receivables |
| **Customer / party statement** (print, PDF) + **receive payment on account** | Customer or Party page → Statement |
| **Opening balances** (what customers owed before the system) | Bulk Import, column `opening_balance` |
| **Cheque tracking** (in hand → deposited → cleared / bounced; balance drops only when cleared) | Shop / Factory → Cheques |
| **Quotations** → one-click convert to a sales order | Shop → Quotations |
| **Party-wise special rates** (auto-filled on orders & quotations) | Customer page → Special rates |
| **Quick billing**: scan a barcode/SKU and press Enter = adds 1 and opens the next line | New Sales Order |
| **Bulk import** from Excel/CSV (products, customers, parties) with all-or-nothing option | Admin → Bulk Import |
| **Receipts**: 58 mm / 80 mm thermal, English or Urdu (`?lang=ur&w=58`) | Order → Receipt |
| **Manager PIN approvals**: staff need an admin's PIN for discounts above `DISCOUNT_APPROVAL_PERCENT` (10), deleting/cancelling sales, deleting payments/cheques, applying stock counts | Admin sets PIN in *Security & 2FA* |
| **Stock audit** (count sheet, variance, apply) + damage/loss entries and loss value | Shop → Stock Audit |
| **Supplier ledger** (purchases, what you owe) | Shop / Factory → Supplier Ledger |
| **Day-end cash closing** (expected vs counted, difference history) | Shop / Factory → Day-end Cash |
| **Profit by product & category** | Admin → Profit by Product |
| **Reorder suggestions** from recent sales / material usage | Shop → Reorder, Factory → Reorder |
| **Worker attendance** + **advances** (Payment type = Advance) | Factory → Attendance |
| **Installable app (PWA)** - "Add to Home Screen" on phones | automatic |
Receivables are grouped into ageing buckets so overdue udhaar is easy to chase:

Notes
- The cash book only knows about payments recorded **after** this version was installed.
- Cash-closing expected cash counts *cash* receipts; cheques and bank transfers are excluded.
- Until an admin sets the manager PIN, staff are blocked from the PIN-protected actions (by design).
### Tests
```bash
python tests/test_security.py # login, 2FA, CSRF, backups, throttling ...
python tests/test_ops.py # all add-on features end to end
```
## 8. Security (what's built in)

| Area | Protection |
|------|-----------|
| Passwords | scrypt hashes; min 10 chars, 3 of 4 character classes, common-password + name checks |
| Login | Generic error messages, equal timing for unknown users, 5-strike account lockout (15 min), per-IP throttle (12 failures / 15 min), fresh session on login |
| 2FA | TOTP authenticator app (Google/Microsoft Authenticator, Authy), one-time recovery codes, replay protection, **mandatory for admins**, secrets encrypted at rest |
| Sessions | HttpOnly + Secure + SameSite cookies (`__Host-` prefix on HTTPS), 30-min idle timeout, changing a password or "Sign out everywhere" kills all other sessions instantly |
| CSRF | Token on every POST form; logout is POST-only |
| Headers | Strict CSP (nonce-based, no inline handlers, no third-party scripts), HSTS, X-Frame-Options DENY, nosniff, no-store caching, Referrer/Permissions policies |
| Data export | CSV/Excel formula-injection neutralised |
| Backups | Consistent SQLite snapshot, integrity-checked, SHA-256 shown, read-only viewer + Excel export without secrets, every download needs password re-entry (throttled, logged), strict filename allow-list |
| Re-auth throttle | Password prompts for backups, 2FA reset and manager PIN allow 5 wrong tries per 15 min |
| Admin sessions | "Keep me signed in" is ignored for admins (idle timeout always applies) |
| Audit | Activity log with IP, searchable + paged; every sign-in attempt recorded; **Admin → Security Center** shows a live checklist, failed-login stats and session controls |
### Environment variables
| Variable | Purpose |
|----------|---------|
| `APP_ENV=production` | Turns on secure cookies, requires `SECRET_KEY` (auto-on on Vercel) |
| `SECRET_KEY` | 32+ random chars: `python -c "import secrets; print(secrets.token_hex(32))"` |
| `DATA_ENCRYPTION_KEY` | Optional separate key for 2FA secrets (so rotating `SECRET_KEY` doesn't break 2FA) |
| `ADMIN_USERNAME` / `ADMIN_PASSWORD` | First-run admin |
| `REQUIRE_2FA_FOR_ADMINS` | `1` (default) / `0` |
| `IDLE_TIMEOUT_MINUTES`, `MAX_FAILED_LOGINS`, `LOCKOUT_MINUTES`, `IP_MAX_FAILURES`, `PASSWORD_MIN_LENGTH` | Tunables |
| `TRUST_PROXY=1` | Use real client IP behind a proxy (auto-on on Vercel) |
### Emergency commands
```bash
flask reset-2fa "<username>" # lost phone AND recovery codes
flask unlock-user "<username>" # clear a lockout
```
### Checklist before going live
- [ ] `APP_ENV=production` and a strong `SECRET_KEY` set
- [ ] HTTPS only (Vercel does this automatically)
- [ ] Every admin has 2FA on and has saved their recovery codes
- [ ] Never set `FLASK_DEBUG=1` on a server (debug mode = remote code execution)
- [ ] Scheduled `flask backup-db` (local SQLite) and copy backups **off** the server
- [ ] Review who has the `admin` role; open **Admin → Security Center** and clear all ⚠️ items