# Wings Finance — Full QA Prompt for Grok

**How to use:** Copy everything below the line into Grok (or any coding/QA agent with repo access). Do not copy this header.

---

You are a senior QA / test engineer. Perform a FULL, end-to-end testing analysis of the Wings Finance ERP monorepo and produce a complete, executable test plan with concrete test cases, expected results, and severity.

## Product context

Wings Finance is a Finance ERP monorepo:

- Backend: Express + MySQL 8.4 + Sequelize 6 (CommonJS), Socket.IO
- Frontend: React 18 + Vite + Tailwind + TanStack Query (ESM)
- Infra: docker-compose → MySQL 8.4 (ignore outdated README Postgres notes)
- API envelope: `{ success, data }` or `{ success: false, error: { message } }`
- Auth: JWT Bearer; permissions are `module:action` strings; live reload from DB on every request
- Mutations: prefer transactions + audit logs; money/payment routes REQUIRE `Idempotency-Key` header
- Multi-company: active company switcher filters lists; “All companies” often blocks create actions
- Demo login (non-prod): `admin@wings.local` / `admin123` (or empty body if DEMO_AUTH_ENABLED)

### How to run (for environment / smoke checks)

```bash
# DB
docker compose up -d

# Backend (port typically 5000; align with Vite proxy which may point to 3000)
cd backend && cp .env.example .env && npm install && npm run migrate && npm run seed && npm run dev

# Frontend (Vite ~5173)
cd frontend && cp .env.example .env && npm install && npm run dev
```

API base: `/api/*`. Health: `/health`.

### Live modules / API mounts

`/auth`, `/users`, `/roles`, `/companies`, `/banks`, `/clients`, `/vendors`, `/settings`, `/employees`, `/employee-salaries`, `/payroll`, `/commissions`, `/projects`, `/invoices`, `/bills`, `/finance`, `/liabilities`, `/countries`, `/notices`, `/notifications`, `/credit-notes`

### Frontend routes to cover

`/login`, `/dashboard`, `/users`, `/roles`, `/roles/:roleId/permissions`, `/companies`, `/companies/new`, `/companies/:id`, `/banks?tab=banks|loan|credit_card`, `/liabilities`, `/liabilities/:id`, `/clients`, `/clients/:id`, `/vendors`, `/vendors/:id`, `/employees`, `/employees/:id`, `/projects`, `/projects/:id`, `/invoices`, `/invoices/new`, `/invoices/:id`, `/invoices/report`, `/credit-notes`, `/bills`, `/bills/new`, `/bills/:id`, `/finance`, `/finance/new?type=receipt|payment|contra|transfer|salary`, `/employee-salaries`, `/payroll`, `/commissions`, `/reports/salary`, `/notices`, `/settings/*` (profile, business, appearance, salary, tax-rates, currencies, categories, directors, backup), `/403`

Known gap: `/forgot-password` is linked on login but has NO page/API — treat as defect/regression check.

### Permissions (guard map — keep FE/BE in sync)

dashboard:read; users:read; roles:read;
company:read|write|create|delete|import|export;
bank:read|write|create|delete;
client:read|write|create|delete|export; (DB also has client:import)
vendor:read|write|create|delete|export;
employee:read|write|sync|import|export;
employee_salary:read|write;
payroll:read|write|run;
project:read|write|sync|import;
settings:read|write|create|delete;
invoice:read|write|create|delete|write_off;
bill:read|write|create|delete;
finance:read|write|create;
liability:read|write|create|delete;
notice:read|write|create|delete;

Seeded roles: admin (all), viewer (dashboard:read), staff (none).

### Idempotency-required money routes

Header: `Idempotency-Key`. Missing → 400; same key different body → 422; in-progress → 409; same key+body → replay stored response (no double ledger).

Cover: finance receipts/payments/transfers/salaries create+update; invoice write-off; bill payments; payroll run create/finalize/disburse; employee-salary payments create+update; liability entries.

---

## Your deliverables

1. **Environment & smoke checklist** (setup, migrate, seed, login, health, port/proxy mismatch risks).
2. **Master test matrix** by module (UI + API), with:
   - Test ID, title, preconditions, steps, expected result, priority (P0/P1/P2), type (functional / negative / security / regression / edge).
3. **End-to-end business journeys** (happy path + failure path).
4. **RBAC matrix** (admin / viewer / custom role / revoked mid-session + Socket.IO `permissions:changed` → UI `/403`).
5. **Data integrity / money correctness** checks (ledgers, invoice status, GST/TDS buckets, overpayment → credit note).
6. **Import/export & file upload** cases.
7. **Existing automated scripts to run and map to acceptance criteria:**
   - `backend/src/modules/finance/invoiceSettlement.test.js`
   - `npm run test:receipt-allocation` (receiptAllocation.selftest)
   - `backend/src/modules/commission/commissionCalc.selftest.js`
8. **Bug report template** for any defects found (steps, expected, actual, severity, module).
9. **Final summary**: coverage %, P0 gaps, recommended release gate.

Assume you can explore the codebase and/or run the app. Prefer concrete, reproducible cases over vague advice. Do NOT invent features outside this scope. Call out known product gaps (e.g. forgot-password) explicitly.

---

## Scenarios you MUST cover

### A. Auth & session

- Login success/fail, rate limit, demo empty credentials (non-prod)
- Logout clears token, user, active company, Query cache, socket
- `GET /auth/me` bootstrap with valid/invalid/expired JWT
- Password change via Settings (current + new); wrong current password
- Forgot-password link → expected 404 / unimplemented
- Session still authorized after role permission change (live DB reload)

### B. Users & roles

- CRUD users; assign roles; cannot break admin lockout if applicable
- Role CRUD; permission matrix load from DB catalog; update role permissions
- Realtime: change permissions for logged-in user → socket update + next API 403 + ProtectedRoute
- Viewer sees only dashboard; staff sees nothing useful / forbidden; custom role partial access (sidebar + deep links)

### C. Companies (multi-company)

- Create/update company (FY cycle apr_mar / jan_dec, currency, logo)
- Branches CRUD; link/unlink banks
- Import/export CSV; bulk delete; cascade behavior
- Active company switcher filters clients/banks/finance/dashboard
- “All companies” mode: create actions blocked where designed
- Delete company with dependent data

### D. Banks & ledgers

- Bank CRUD under selected company; ledger view
- Banks page tabs: banks / loan / credit_card (liabilities)
- Create bank without selected company → blocked
- Ledger consistency after receipts/payments/transfers

### E. Clients & vendors

- Client CRUD, contacts, documents, ledger, invoices panel
- Client import (template + file) and export
- Vendor CRUD, TDS tax rate, ledger, export (no import)
- Validation: required fields, duplicates, company scoping

### F. Employees & projects

- Employee CRUD, documents, bank/statutory (UAN/ESI), salary, revisions, ledger, commission rules/entries
- Employee import/export/sync
- Project CRUD, members + member salaries, milestones, expenses, client assign, import, PMS sync
- Project financial snapshot / alerts if present

### G. Invoices (critical money)

- Create invoice with line items, GST, TDS, proforma (proforma skips GST/TDS path)
- Edit, duplicate, void, write-off (+ history), payment history, report, bulk delete
- Status transitions: sent → partially_paid → paid; delete/edit receipt recalculates status
- ₹1 PAID tolerance
- Unpaid GST keeps partially_paid when applicable
- Write-off permission `invoice:write_off` OR `finance:write`
- Idempotent write-off double-submit

### H. Credit notes

- Manual create; apply to invoice; remove application
- Available balance per client
- Overpayment from receipt creates CN; apply CN to later invoice (excess_applied)
- UI gated by invoice:read where applicable

### I. Bills (AP)

- Manual create; CSV/XLSX import; image/PDF OCR parse → confirm (human verify vendor/GST/TDS)
- Duplicate; record payment (idempotent double-submit); stats; bulk delete
- Payment modes: cash / bank / cheque / upi — bank required for non-cash

### J. Finance (receipts / payments / transfers / salary)

- Receipt types: customer (invoice allocations), advance, director
- Allocations across multiple invoices; bank vs TDS buckets; GST/TDS at receipt
- Overpayment → credit note; commission preview on receipts
- Payments; bank transfers (contra); salary disbursement edit via finance salaries
- Delete receipt/payment/transfer recalculates invoice/ledger (deletes are NOT idempotent — verify no orphan double effects on retry)
- Idempotency matrix for all create/update money endpoints listed above
- Missing Idempotency-Key → 400; conflict cases 409/422

### K. Payroll, employee salaries, commissions

- Payroll run lifecycle: draft → approve/verify → finalize → disburse/posted
- Payslip edit/delete; paid payslips protected
- Excel import; run export; KPIs PF/ESI/PT/TDS
- Settings salary components + TDS slabs affect calc
- Employee salary payment candidates by period; create/update payments (idempotent); deep-link from finance/payroll
- Commission hub; approve; new vs existing project rates/targets; reduced rate; share %; status before payroll

### L. Liabilities

- Create loan/credit-card style liability; generate EMI schedule (reducing balance)
- Dues / overdue; statement; payment entries (idempotent)
- Banks page loan/CC tabs integration

### M. Settings

- Profile, avatar, password; business logo; appearance
- Salary components; salary TDS slabs; tax rates; currencies; categories; directors
- Backups: generate / download / delete
- Unauthorized settings:write attempts

### N. Notices & notifications

- Notices admin CRUD; active feed in header for any auth user
- Notifications list; mark read / read-all (auth only, no RBAC codes)
- Priority / visibility behavior

### O. Reports & dashboard

- Dashboard with company filter / period
- Invoice report; salary report (`payroll:read`)
- Empty states, loading, error toasts

### P. Cross-cutting non-functional

- API envelope consistency; validation errors messages
- Audit log written on mutations (spot-check company/finance/payroll/settings password)
- Unauthorized (401) vs forbidden (403)
- File upload limits / invalid types for logos, docs, bill OCR
- Countries public list for address forms
- Concurrent double-click submit on money forms
- Browser refresh mid-form; back navigation; deep links without permission → /403
- Mobile/responsive smoke on list + entry forms
- Socket disconnect/reconnect permission updates

### Q. Regression / known footguns

- README Postgres vs real MySQL
- Vite proxy port vs backend PORT mismatch
- CLIENT_IMPORT constant missing from permissions map while DB has client:import
- Forgot-password dead link
- Idempotency TTL (~24h) replay behavior

---

## Critical E2E journeys (must write step-by-step)

1. **AR settlement:** Create company → bank → client → invoice (GST+TDS) → customer receipt with partial allocation → second receipt completing payment → verify invoice paid + bank ledger + TDS bucket.
2. **Overpay + CN:** Receipt overpaying invoice → CN created → apply CN to another invoice → statuses/balances correct.
3. **AP bill pay:** Vendor → bill (manual + one OCR/CSV path) → bill payment with Idempotency-Key → replay same key → single payment only.
4. **Payroll pay-out:** Configure salary components/TDS → employee with salary → payroll run → approve → finalize → disburse → employee-salary / finance salary row consistency.
5. **Commission:** Project + commission rules → receipt triggers commission preview → approve commission → appears correctly for payroll period.
6. **Liability EMI:** Create liability → generate schedule → post EMI entry (idempotent) → statement/dues update.
7. **RBAC revoke live:** User with invoice:create → open invoice form → admin revokes permission → save fails 403 and UI updates without full logout.
8. **Multi-company isolation:** Data created under Company A not visible/editable under Company B when switcher set to B.

---

## Output format

For each module section use a table:

| ID | Scenario | Steps | Expected | Priority |

Then:

- E2E journeys (numbered steps)
- Bugs / gaps found
- Scripts run + pass/fail
- Release recommendation (Go / No-Go) with P0 open issues

Start by outlining your test strategy, then execute/analysis in depth module by module, and finish with the release gate summary.
