# Complete POS Software — SRS, Architecture & Cursor AI Blueprint

**Version:** 1.0  
**Date:** 2026-05-12  
**Stack:** HTML, CSS, JavaScript, jQuery, Bootstrap 5, PHP (procedural), MySQL  
**Audience:** Developers building with Cursor AI; maintainers and QA.

---

## 1. Executive Summary

This document defines a **multi-branch, role-based POS and inventory system** with hidden **System Admin** capabilities, shop-type modules (electronics, books, clothing, cosmetics, generic retail), **Bangla/English** UI, modern responsive design, **barcode** on invoices and labels, **payment methods** with account-wise reporting, **customer groups/membership discounts**, **reward points**, **SMS** (System Admin), and **data-heavy list pages** (filters, server-side pagination, exports).

---

## 2. Goals & Non-Goals

### 2.1 Goals

- Fast POS checkout, purchase, returns, quotations, stock transfer, adjustments.
- Clear financial picture: sales, purchase, dues, expenses, profit/loss.
- Strong security: sessions, CSRF, prepared statements, least-privilege roles.
- Scalable lists: 100k+ rows with smooth UX via server-side pagination and indexes.
- Shop-type aware forms (IMEI/warranty, author/publisher, size/color emphasis, batch/expiry where relevant).

### 2.2 Non-Goals (initial phase — optional later)

- Full accounting double-entry ledger (can add simplified cash/bank ledgers per payment method).
- Native mobile apps (PWA optional later).
- Multi-tenant SaaS billing (single deployment per business assumed).

---

## 3. User Roles & Visibility Matrix

| Capability | System Admin | Admin | Manager | Cashier | Salesman | …custom |
|------------|:------------:|:-----:|:-------:|:-------:|:--------:|:-------:|
| Visible in user list to other admins | **No** (hidden) | Yes | Yes | Yes | Yes | Yes |
| Branch add/delete | Yes | No | No | No | No | No |
| All branches data | Yes | Yes | Per RBAC | Per RBAC | Per RBAC | Per RBAC |
| Membership / reward / SMS toggles & keys | Yes | No* | No | No | No | No |
| Max product limit enforcement | Yes | No | No | No | No | No |
| Copyright / branding text (footer) | Yes | View only or hidden | … | … | … | … |

\*Unless you explicitly grant Admin a subset — default: **System Admin only** for sensitive platform controls.

**Rules:**

1. **System Admin** is a special flag (`is_system_admin = 1`), not only a role name. User list queries **must exclude** this user from non–system-admin viewers.
2. **Admin** sees all branches and can edit/delete where policy allows, **except** system-only settings and system admin user records.
3. **Branch-scoped users** see only assigned branch(es); joins on `user_branch` or `branch_id` on transactions.

---

## 4. Functional Requirements (Expanded)

### 4.1 Dashboard

- KPI cards: Total Purchase, Total Sales, Purchase Due, Sales Due, Purchase Return, Sales Return, Total Expense (and optional: Net Cash Flow, Gross Profit snapshot).
- Charts: Sales vs Purchase (line/bar), expense trend, top products (optional phase 2).
- **Date filter:** Today, Yesterday, This Month, All, **Custom range** (from–to).
- **Branch filter:** All / per branch (respect user scope).
- **Welcome text** (configurable greeting + user name).
- Quick links: New Sale, New Purchase, POS.

### 4.2 Authentication & User Management

- Login, logout, session timeout, password reset (email optional; admin reset as minimum).
- User CRUD with: name, phone, email, username, password (hash: `password_hash` PASSWORD_DEFAULT), photo optional.
- **Branch assignment:** multi-select branches; enforced on every list/API.
- **Role-based permissions:** granular flags (e.g. `sales.view`, `sales.create`, `purchase.approve`) stored in DB; middleware checks on each action.
- **Audit log** (who changed what, when) — recommended for inventory and price changes.

### 4.3 Supplier

- Supplier CRUD, balance opening, ledger-style due tracking.
- Dashboard/list: **total purchase due**, **total purchase return due** (if returns credit supplier).

### 4.4 Customer

- Customer CRUD, credit limit optional, opening balance.
- **Sales due** per customer, aging (optional phase 2).
- **Customer Group / Membership:** flat or **percentage** discount on **invoice total** (or subtotal — define once in SRS: recommend **subtotal before tax**). Auto-apply when customer selected on Sale/POS/Quotation.
- **Reward points:** enable in settings; rules e.g. “৳X spent = Y points” or “Z% of sale = points”; accrue on completed sale; redeem rules (max % of bill, min redemption) in settings; show balance in customer search panel.
- Customer search panel shows: **due**, **group/membership**, **points**, last visit (optional).

### 4.5 Products

- Product list, add/edit, deactivate (soft delete preferred).
- **Units:** kg, pcs, box, etc. (master table).
- **Categories**, **Brands**.
- **Variations:** size, color, etc. (variant SKUs, separate stock per variant if needed).
- **Multi-branch stock:** product linked to many branches with per-branch quantity, reorder level, rack/bin (optional).
- **Label print** with **high-quality barcode** (Code128 or EAN-13 if GTIN available); test with real scanners.
- Shop-type **extra fields** (see §6).

### 4.6 Purchase

- Purchase list/add/edit (draft → submitted → paid partials).
- Purchase return with reference to original purchase.
- **Payment allocation** to suppliers; due balance updates.
- Electronics: **IMEI lines** per unit at purchase; validate uniqueness per branch/stock state.

### 4.7 Sales

- Sales list, add, return, **POS screen** (fast search, barcode, hold bill, discount, tax, customer attach).
- **Quotation** list/add; convert to sale.
- Attach **payment methods** (split payment supported).
- Link to **customer** for membership + points.

### 4.8 Stock Transfer & Adjustment

- Transfer between branches: draft → in-transit → received (or one-step per simplicity).
- Adjustment: reason codes (damage, theft, found, recount); approval optional for managers.

### 4.9 Branch Management

- Only **System Admin**: add/delete branch (soft delete with archive). Others: view assigned only.

### 4.10 Expense

- Categories, list, add; branch and user attribution; attachment upload optional.

### 4.11 Reports

- Profit & Loss (date range, branch).
- Product purchase / sales reports.
- Purchase payment / sales payment reports.
- Expense report.
- Stock adjustment report.
- Combined purchase & sales report.
- Product stock report (by branch, variant, batch if used).
- **Payment method summary:** amount per method, per account, per user, per branch (filters same as lists).

### 4.12 Settings

- Business info (name, logo, address, tax ID, phone).
- **Invoice profile:** A4 vs **POS thermal** (80mm/58mm); template selection per type.
- **System admin block** (visible only to system admin): SMS enable, API URL, API key, sender ID, message templates; membership master switch; reward rules; max products; copyright text; **software/shop type** selector.
- **Shop type** drives UI fields and validations (§6).
- **Language:** বাংলা / English — all UI strings from JSON/DB language tables; RTL not required.

### 4.13 Payment Methods (Accounts)

- CRUD payment methods: Cash, Card, bKash, Bank, etc.
- Each method optional **ledger account** for reporting (“which account received how much”).
- Sales/Purchase/POS: select one or **split** multiple methods; store in `payment_lines` table.

### 4.14 UX: Feedback

- **SweetAlert2** for success, error, confirm delete, session warnings.
- **Sounds:** short distinct tones for success, error, warning (user toggle in profile/settings); respect `prefers-reduced-motion` / mute where applicable.

### 4.15 Additional Recommended Features

- **Backup/restore** hint for admin (export SQL or scheduled cron doc).
- **Print queue** status for POS receipts.
- **Low stock alerts** on dashboard.
- **Tax/VAT** profiles (inclusive/exclusive).
- **Price tiers** (wholesale/retail) optional.
- **Serial/IMEI** stock trace for warranty claims.
- **Activity log** and **login IP** (fraud awareness).
- **Keyboard shortcuts** on POS (F2 pay, F4 customer, etc.).
- **Offline-first** not required; optional “unstable network” banner only.

---

## 5. Shop Type → Module Mapping (System Admin Controlled)

| Shop type | Extra product fields | Purchase/Sales behavior |
|-----------|------------------------|-------------------------|
| **Electronics / Mobile** | IMEI (unique), Serial, Warranty months, Supplier warranty | Purchase: N units = N IMEI rows; Sale: scan/select IMEI from available pool; warranty card print |
| **Books** | Writer, Publisher, ISBN, Edition, Language | Optional ISBN barcode; search by writer/publisher |
| **Clothing / Fashion** | Size chart link, Season, Fabric, Color/Size variants | Emphasis on variation matrix |
| **Cosmetics / Pharmacy** | Batch, Expiry, MRP, composition optional | FEFO warning on sale; block expired (config) |
| **Generic retail** | Minimal extra | Standard SKU |

Implementation: `settings.shop_type` + `product_attributes` JSON or normalized `product_extra_fields` table.

---

## 6. Non-Functional Requirements

### 6.1 Performance

- Server-side pagination: `LIMIT/OFFSET` or keyset (`WHERE id > ?`) for very large tables.
- DB indexes on: `(branch_id, sale_date)`, `(branch_id, created_at)`, foreign keys, search columns (phone, invoice_no).
- Avoid `SELECT *` in heavy lists; use column lists.

### 6.2 Security (Procedural PHP)

- **Prepared statements** everywhere (`mysqli_stmt` or PDO).
- **Password hashing**; no plaintext.
- **Session:** `session_regenerate_id` on login; strict cookie params; idle timeout.
- **CSRF tokens** on all POST forms and AJAX mutations.
- **Output escaping** (`htmlspecialchars`) for HTML; JSON headers for API endpoints.
- **File uploads:** whitelist MIME, store outside webroot or deny PHP execution in upload dir.
- **Authorization:** central `require_permission('sales.create')` helper; never trust client-side flags.
- **Rate limit** login attempts (IP + username).
- **HTTPS** recommended in production.

### 6.3 Responsive Design (2026-ready)

- Bootstrap 5 grid; mobile-first sidebar → offcanvas on small screens.
- Touch-friendly POS buttons (min 44px height).
- Consistent spacing scale, CSS variables for colors, one accent + neutral surfaces.
- Icons: Bootstrap Icons or Phosphor (lightweight); use meaningfully, not decorative clutter.
- Dark mode optional phase 2.

---

## 7. Standard List Page Contract (Every Data Table)

Each listing page **must** implement:

1. **Date filter:** Today | Yesterday | This Month | All | Custom (date range picker).
2. **Branch filter:** All | specific branch (scoped to user).
3. **User filter:** creator / cashier / responsible user (as relevant).
4. **Typing filter:** context-specific (name, phone, invoice no, SKU, IMEI, etc.) with debounced AJAX (300ms).
5. **Pagination:** page size 25, 50, 100, 200, 500, **All** (use “All” only with warning if row count high).
6. **Footer text:** `Showing 1 to 15 of 200` (accurate after filter).
7. **Export:** Excel (CSV or PhpSpreadsheet), PDF (TCPDF/mPDF/Dompdf), **Print** — exports respect **current filters**.
8. **Sort** by column where useful (server-side).

---

## 8. Barcode & Printing

- **Symbology:** Code128 for internal SKU; EAN-13 if valid barcode exists.
- DPI-aware label templates; quiet zone compliance for scanners.
- Invoice: order barcode + line item barcodes optional.
- Test with 2–3 common USB scanners (keyboard wedge).

---

## 9. Database Design (High-Level Entities)

**Core:** `branches`, `users`, `user_branches`, `roles`, `permissions`, `role_permissions`, `sessions_audit`  
**Catalog:** `units`, `categories`, `brands`, `products`, `product_variants`, `product_branch_stock`, `product_extra`  
**Parties:** `suppliers`, `customers`, `customer_groups`  
**Purchasing:** `purchases`, `purchase_items`, `purchase_payments`, `purchase_returns`, …  
**Sales:** `sales`, `sale_items`, `sale_payments`, `sale_returns`, `quotations`, `pos_sessions`  
**Inventory:** `stock_transfers`, `stock_transfer_items`, `stock_adjustments`, `stock_adjustment_items`, `imei_units` (status: in_stock, sold, returned)  
**Finance:** `expenses`, `expense_categories`, `payment_methods`, `payment_method_accounts`  
**Settings:** `business_settings`, `invoice_templates`, `localization_strings`, `feature_flags`  
**Rewards:** `reward_rules`, `customer_reward_ledger`  
**i18n:** `lang_keys`, `lang_strings` (en, bn)

Normalize money as **DECIMAL(18,4)** in DB; display 2 decimals in UI unless config says otherwise.

---

## 10. Folder & File Structure (Recommended)

```
POS26/
├── assets/
│   ├── css/
│   │   ├── app.css              # variables, layout, components
│   │   └── themes/              # optional theme overrides
│   ├── js/
│   │   ├── app.js               # sidebar, theme, debounce helpers
│   │   ├── datatable.js         # shared filter + pagination AJAX
│   │   ├── pos.js               # POS-only logic
│   │   └── sounds/              # success.mp3, error.mp3 (tiny)
│   └── img/
├── includes/
│   ├── config.php               # env, base URL, error reporting (dev vs prod)
│   ├── db.php                   # mysqli connection, charset utf8mb4
│   ├── session.php              # secure session bootstrap
│   ├── auth.php                 # current_user(), require_login(), is_system_admin()
│   ├── rbac.php                 # can($permission), require_permission()
│   ├── csrf.php                 # token issue/verify
│   ├── i18n.php                 # __t('key'), load active language
│   ├── functions.php            # money, date, redirect helpers
│   └── header.php / footer.php  # layout partials
├── modules/
│   ├── dashboard/
│   ├── users/
│   ├── suppliers/
│   ├── customers/
│   ├── products/
│   ├── purchases/
│   ├── sales/
│   ├── pos/
│   ├── quotations/
│   ├── stock_transfer/
│   ├── stock_adjustment/
│   ├── branches/
│   ├── expenses/
│   ├── reports/
│   ├── settings/
│   └── payment_methods/
├── actions/                     # POST-only small scripts OR module/action/*.php
│   └── ...                      # e.g. actions/sales/save_sale.php
├── api/
│   └── v1/                      # JSON endpoints for datatables, search, barcode
├── lang/
│   ├── en.php
│   └── bn.php                   # PHP arrays or JSON mirrors
├── uploads/                     # outside execution; .htaccess deny php
├── vendor/                      # if Composer used for PDF/XLS (optional)
├── install/                     # schema.sql, seed data (roles, system admin)
├── docs/
│   └── SRS-POS-Complete.md      # this file
├── index.php                    # router or redirect to dashboard
└── login.php
```

**Routing pattern (procedural):** `modules/sales/list.php` includes `../../includes/header.php`; forms POST to `actions/sales/save.php` then PRG redirect.

---

## 11. API / AJAX Conventions

- JSON responses: `{ ok: true, data: ..., meta: { page, per_page, total } }` or `{ ok: false, message_key: "...", message: "localized" }`.
- HTTP 401/403 for auth failures; never leak stack traces in production.
- List endpoints accept: `date_from`, `date_to`, `branch_id`, `user_id`, `q`, `page`, `per_page`, `sort`, `order`.

---

## 12. Cursor AI — Master Build Prompt (Copy Below)

```
You are building a multi-branch POS in PHP (procedural) + MySQL + Bootstrap 5 + jQuery.

Non-negotiables:
- includes/config.php, db.php, session.php, auth.php, rbac.php, csrf.php, i18n.php
- Every DB write: prepared statements + CSRF check
- Roles: system admin (hidden from others in user list), admin, manager, cashier, salesman — permissions in DB
- System admin only: branch add/delete, SMS keys, membership/reward toggles, max products, copyright, shop type
- Every list page: date (today/yesterday/month/all/custom), branch, user, search, pagination (25..500,all), showing X–Y of Z, export excel/pdf/print with filters applied
- Dashboard KPIs + charts + welcome + date/branch filters
- Customer groups: flat/% discount on bill; reward points from settings; show in customer panel
- Payment methods CRUD + split payments + reporting by account/method
- Shop type from settings adds fields: electronics+IMEI+warranty; books+writer+publisher+ISBN; clothing emphasis variants; cosmetics+batch+expiry
- SweetAlert2 + optional success/error sounds (toggle)
- Bangla/English from settings — no hardcoded user-visible strings in pages (use __t)
- Barcode: scannable on labels and invoice
- POS: fast search, barcode, hold, discount, tax, customer, payments
- Use recommended folder structure under /includes, /modules, /actions, /api, /assets

Implement incrementally: schema → auth → branches/users → products → purchase → sales → POS → reports → settings → polish.
```

---

## 13. Testing Checklist (Abbreviated)

- RBAC: each role denied on direct URL tampering.
- System admin invisible to admin in user list.
- Branch isolation: user A cannot read branch B data via API params.
- IMEI: duplicate blocked; sale only from in-stock IMEI.
- Large list: 50k sales — response under target with pagination.
- i18n: switch language — all menus and SweetAlerts translated.

---

## 14. Glossary

- **PRG:** Post-Redirect-Get to prevent duplicate submits.  
- **RBAC:** Role-Based Access Control.  
- **SKU / IMEI / FEFO:** Stock keeping unit; mobile identifier; first-expiry-first-out.

---

*End of document — extend with wireframes and exact table DDL during implementation.*
