Services Internships Case studies Pricing Blog Free consultancy Contact
README.md
Download

Gujranwala Sanitary Collection — Store Management System

One place for the shop counter, the factory floor and the owner's books.

industryRetail & manufacturing built withFlask +5 read time12 min diagrams11
Gujranwala Sanitary Collection — Shop, Factory and Admin in one system
Gujranwala Sanitary Collection — Shop, Factory and Admin in one system

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

The Shop, Factory and Admin sections, and who can open what
The Shop, Factory and Admin sections, and who can open what

#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
Three roles with strict boundaries
Three roles with strict boundaries

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
Life of a shop sale, from order to follow-up
Life of a shop sale, from order to follow-up

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)
Factory workflow: raw material to ready stock to a paid party
Factory workflow: raw material to ready stock to a paid party

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)
Admin business overview (illustrative layout)
Admin business overview (illustrative layout)

#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.

How the browser, Flask app, services and database fit together
How the browser, Flask app, services and database fit together

#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

text
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):

Conceptual data model
Conceptual data model

#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:

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.
How the Profit & Loss statement is built
How the Profit & Loss statement is built

#7. Operations add-ons

FeatureWhere
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 accountCustomer 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 orderShop → 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 lineNew Sales Order
Bulk import from Excel/CSV (products, customers, parties) with all-or-nothing optionAdmin → 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 countsAdmin sets PIN in Security & 2FA
Stock audit (count sheet, variance, apply) + damage/loss entries and loss valueShop → 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 & categoryAdmin → Profit by Product
Reorder suggestions from recent sales / material usageShop → Reorder, Factory → Reorder
Worker attendance + advances (Payment type = Advance)Factory → Attendance
Installable app (PWA) - "Add to Home Screen" on phonesautomatic

Receivables are grouped into ageing buckets so overdue udhaar is easy to chase:

Udhaar ageing buckets (illustrative)
Udhaar ageing buckets (illustrative)

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)

Built-in security protections
Built-in security protections
AreaProtection
Passwordsscrypt hashes; min 10 chars, 3 of 4 character classes, common-password + name checks
LoginGeneric error messages, equal timing for unknown users, 5-strike account lockout (15 min), per-IP throttle (12 failures / 15 min), fresh session on login
2FATOTP authenticator app (Google/Microsoft Authenticator, Authy), one-time recovery codes, replay protection, mandatory for admins, secrets encrypted at rest
SessionsHttpOnly + Secure + SameSite cookies (__Host- prefix on HTTPS), 30-min idle timeout, changing a password or "Sign out everywhere" kills all other sessions instantly
CSRFToken on every POST form; logout is POST-only
HeadersStrict CSP (nonce-based, no inline handlers, no third-party scripts), HSTS, X-Frame-Options DENY, nosniff, no-store caching, Referrer/Permissions policies
Data exportCSV/Excel formula-injection neutralised
BackupsConsistent 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 throttlePassword 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)
AuditActivity 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

VariablePurpose
APP_ENV=productionTurns on secure cookies, requires SECRET_KEY (auto-on on Vercel)
SECRET_KEY32+ random chars: python -c "import secrets; print(secrets.token_hex(32))"
DATA_ENCRYPTION_KEYOptional separate key for 2FA secrets (so rotating SECRET_KEY doesn't break 2FA)
ADMIN_USERNAME / ADMIN_PASSWORDFirst-run admin
REQUIRE_2FA_FOR_ADMINS1 (default) / 0
IDLE_TIMEOUT_MINUTES, MAX_FAILED_LOGINS, LOCKOUT_MINUTES, IP_MAX_FAILURES, PASSWORD_MIN_LENGTHTunables
TRUST_PROXY=1Use 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

#Want a system like this?

Tell us a little about your business. We reply with ideas and a rough scope — free, no obligation.

Phone or email — either one is enough.

Need something similar?

Book a free consultation — we'll scope it with you, no obligation.

Book a free consultation

More READMEs