# CLAUDE.md — TechCMantix CRM (Multi-Tenant SaaS CRM)

Claude Code loads this file automatically at the start of every session. It is the **entry point**. Binding rules and current status live in [docs/context.md](docs/context.md); the **current roadmap and v2 specification** is [docs/plan.md](docs/plan.md) (v2.2, progress tracker in §11). The v1 history and the **standing rules** (§3 stack, §3.1 UI, §3.2 files, §6 workflow, §7 folders, §8 Definition of Done, §10 working rules, §11 code standards) live in [docs/plan-v1.md](docs/plan-v1.md). If any of these disagree, stop and flag it. Keep this file short.

**Stack (decided, plan-v1.md §3):** Next.js (App Router) · NestJS · TypeScript (strict) · **MySQL** · **Prisma** · **Ant Design** (components) · **Tailwind CSS** (styling and layouts) · **npm** · **no Docker** (for now).
Never use PostgreSQL, pnpm/yarn, Docker/Docker Compose, S3 or other external file storage, Redis, Kafka, microservices, a job queue, Turborepo, a second component library (shadcn/ui, MUI, Chakra) or another CSS framework (Bootstrap, styled-components, Emotion).

---

## 1. Approval gate: check before doing anything

- Read **context.md §0**. It says whether implementation is authorized and which phase is approved.
- If it says **Implementation authorized: NO**, only documentation and planning changes are allowed: no application code, migrations, `npm install`, database setup or external service connections.
- Only the owner's **explicit** instruction (e.g. "plan approved, start Phase 0") authorizes development. Silence, a new session or an unrelated request is **not** approval.
- When the owner approves, update context.md §0 (stage, authorized phase, date) **before** writing code.
- Build only the approved phase (plan.md §9 and §11, plan-v1.md §10).

## 2. Start-of-session routine

1. Read [docs/context.md](docs/context.md) in full, including the **Session log** (§12) for where the last session stopped.
2. Identify the phase and module, then read the matching sections:

| Task touches | Read |
|---|---|
| v2 decisions and pending approvals | plan.md §3 Decision register |
| v2 navigation, Customers, timeline | plan.md §2, §6 |
| Masters, lookups, stages, tax rates | plan.md §4 (rules R1–R13) |
| Schema changes, migrations | plan.md §5 Schema blueprint, §8 Migration method |
| Billing, PDFs, reminders, expenses | plan.md §7 |
| v2 phases, tasks, exit criteria, status | plan.md §9 Phases, §11 Progress tracker |
| Risks to watch | plan.md §10 |
| Stack, libraries | plan-v1.md §3 Technology decisions |
| UI screens, theme, components | plan-v1.md §3.1 UI with Ant Design and Tailwind CSS (+ context.md §6) |
| Uploads, attachments | plan-v1.md §3.2 File storage in MySQL (+ context.md §7) |
| Building any module | plan-v1.md §6 Standard workflow for every module |
| Repository layout | plan-v1.md §7 Folder structure principles |
| Any data or tenant logic | plan-v1.md §2 Architecture gate (+ context.md §4) |
| Done criteria, project rules | plan-v1.md §8 Definition of Done, §10 Working rules |
| v1 history, Phases 11–13 scope | plan-v1.md §4, §5, §9 |

3. Load the relevant skills (section 4) **before** writing code.
4. If a request conflicts with plan.md, plan-v1.md or context.md, **stop and ask**. Do not silently diverge.

## 3. Non-negotiable rules (summary; full text in context.md §3–§9)

- **Tenant isolation (multi-tenant SaaS, confirmed):** built into the **first migration**. Every customer-owned table has an indexed `tenantId`; the tenant comes **only from the signed-in session**, never from URL, body or headers; every tenant query goes through one backend helper that fails if no tenant is set; relations cannot cross tenants; cross-tenant access returns **404**. Every new tenant table and endpoint gets a cross-tenant test. Tests always create at least two tenants; `prisma/seed.ts` creates only the Platform Admin (owner decision 2026-11-19) and never resets an existing password.
- **Security:** authentication and permissions enforced in the API (frontend checks only hide controls). Backend DTO validation on every input. Hashed passwords, secure sessions, lockout, single-use reset links. No secrets in the repo. Audit important actions.
- **Architecture:** business rules only in NestJS. Next.js is the UI client and never connects to MySQL or imports Prisma. Backend organized by business module (controller, service, DTOs, tests together). Every schema change is a Prisma migration. No folders, packages or abstractions without a current use.
- **UI:** screens must look like `crm-prototype.html` (layout, colours, spacing, typography, light and dark).
  - **Ant Design** for every component, themed from the prototype tokens via one `ConfigProvider`.
  - **Tailwind CSS** for page layouts, grids, spacing, responsive behaviour and custom pieces (KPI card layout, Deal Pulse, pipeline board).
  - One shared tokens file feeds both themes; fixed CSS layer order (or preflight off) so Tailwind's reset doesn't break antd; **never restyle antd internals with Tailwind**.
  - Every screen has loading, empty, error and no-permission states.
- **Files:** stored **in MySQL only** (`files` + `file_contents` `LONGBLOB`), 10 MB default limit, uploads and downloads only through the API with permission, content-type and checksum checks.
- **Scope:** IT-company CRM (IT services, software development, IT consulting) aligned to the finalized 20-module + `Settings` `crm-prototype.html` layout (`Marketing` & `Service` removed). MVP (Phases 0–9) covers `Workspace → Dashboard`, `Sales` (`Leads`, `Contacts`, `Accounts`, `Deals`, `Pipeline`), `Productivity` (`Activities`, `Calendar`, `Files`), `Delivery` (`Projects`, `Tasks`, `Timesheets` — Phase 7), `Reports`, `Import & Export`, and basic `Settings`. Post-MVP follows the module groups cleanly: **Phase 10 (`FINANCE`):** `Products & Services`, `Quotes`, `Invoices`, payment links; **Phase 11 (`WORKSPACE & PRODUCTIVITY Ext.`):** `Approvals`, CRM `Email`; **Phase 12 (`INSIGHTS & AUTOMATION Ext. & Delivery Pro`):** `Workflows`, forecast/PDF reports, profitability, resource planning, contracts, integrations, Client Portal; **Phase 13:** SaaS commercial features (plans, billing, platform console, SSO), with commercial plans and billing deferred. **v2 upgrade track (2026-11-16, runs before Phase 11):** V2-0 … V2-8 per [docs/plan.md](docs/plan.md). It introduces Customers (Client 360, replacing Accounts + Contacts), the Masters Hub (no hardcoded choice lists), an 8-module sidebar + My Work menu, `Decimal` money, financial-year GST numbering, draft-first milestone billing, server PDFs, Expenses and reminders. Status is tracked in plan.md §11.
- **Definition of Done:** context.md §8 / plan-v1.md §8, plus the per-phase exit checks in plan.md §9.

### 3.1 Mandatory Code Quality & Engineering Standards

Every future code change, agent session, and developer commit must strictly adhere to the standards in [docs/plan-v1.md](docs/plan-v1.md) §11 and [docs/context.md](docs/context.md) §9.1:
1. **Single-line imports**: Every import in both frontend and backend must be on a single line. Multiline imports are prohibited. Zero unused/duplicate imports.
2. **Backend controller & service comments**:
   - Every controller route handler must have a concise one-line comment specifying its purpose, HTTP method, and path (e.g. `// Returns all leads. GET /api/leads`).
   - Every service method must have a concise doc comment immediately before its declaration describing its purpose.
   - Prohibit noisy, redundant, or cluttered inline comments in the middle of function bodies.
3. **Inspect before modifying**: Inspect existing patterns, types, and logic before making changes.
4. **Component reusability**: Reuse existing shared components (`RecordActivityTimeline`, `WorkspaceSubpageShell`, `Icon`, `UserAvatar`, etc.) and utilities. Avoid duplicate UI abstractions.
5. **Clean architecture**: Controllers handle HTTP; Services hold business rules; DTOs validate; Next.js is purely a UI client.
6. **Code cleanliness**: Self-describing names, clean functions, no decorative comment banners, no dead or commented-out code.
7. **Strict preservation**: Never break existing business logic, tenant isolation, permissions, or API contracts.
8. **Always verify**: Every turn must pass `npm run lint`, `npm run typecheck`, `npm run format:check`, and automated tests with 0 errors.
9. **No dummy placeholders**: Avoid `e.g. <Name>` or `e.g. <Value>` dummy placeholders across all form inputs. Use neutral directives (e.g. `Enter organization name`, `Enter contact phone`) or omit placeholder entirely if the label is already self-describing.

## 4. Skills: which to use when

| Situation | Skill |
|---|---|
| New feature or behavior change (design first) | `superpowers:brainstorming` |
| Turning an approved phase into tasks | `superpowers:writing-plans` |
| Executing a written plan | `superpowers:executing-plans` or `superpowers:subagent-driven-development` |
| Writing feature or bugfix code | `superpowers:test-driven-development` |
| Any bug or failing test | `superpowers:systematic-debugging` |
| MySQL schema, Prisma models, migrations, queries | No installed skill. Follow context.md §4 + §7 and the official MySQL / Prisma docs. (`supabase-postgres-best-practices` is PostgreSQL-only: **do not apply it**.) |
| React / Next.js components, data fetching, bundle size | `react-best-practices` |
| Reusable component APIs | `composition-patterns` |
| HTML/CSS/browser API questions (incl. Tailwind + antd layering) | `modern-web-guidance:modern-web-guidance` |
| Charts, dashboards, KPI tiles | `dataviz` |
| UI copy, empty states, errors | `design:ux-copy` |
| UI review / accessibility / prototype match | `web-design-guidelines`, `design:accessibility-review`, `ui-design-review:review` |
| Before claiming work is done | `superpowers:verification-before-completion` |
| Reviewing changes | `code-review`, `security-review` (always for auth, tenancy, permissions, files) |
| Finishing a branch | `superpowers:finishing-a-development-branch` |
| Committing | `commit-commands:commit` (only when the owner asks) |
| Keeping this file current | `claude-md-management:revise-claude-md` |

## 5. Continuity across conversations

Continuity lives **in the repo**, not in chat history:

| What | Where |
|---|---|
| Approval status, current phase | context.md §0 |
| Binding rules and decisions | context.md §1–§11 |
| Roadmap, scope and reasoning | plan.md (v2); plan-v1.md (v1 history + standing rules) |
| Phase status | plan.md §11 Progress tracker (v1 phases: plan-v1.md §9) |
| What happened, what's next | context.md §12 Session log |

**End-of-session routine (always, before the final reply):**
1. Append an entry to **context.md §12**: date, phase/module, what was done, files touched, decisions, open issues and the **next step**.
2. If a decision changed: update plan.md (decision register §3, bump its version line), plan-v1.md if a standing rule changed, then context.md, then README.md and this file. All must stay consistent.
3. Update context.md §0 if the stage or authorized phase changed; update plan.md §11 when a phase starts or completes.
4. From Phase 1 on, record pinned dependency versions in context.md §2.
5. Keep the log short; condense past ~30 entries.

**Mid-task handoff:** the log entry must say exactly which step is unfinished, any failing tests, and how to resume.

## 6. Working style

- One developer who is still learning CRM concepts: explain important CRM concepts and implementation decisions in plain language.
- Make technical decisions within the plan, but **ask when a business rule or product decision is unknown** (plan.md §3, plan-v1.md §2); do not invent one.
- Do not build every prototype screen automatically; build only what the approved phase needs. Do not add dependencies without a clear reason.
- Report outcomes faithfully: show failing test output, state skipped steps.
- The docs set is CLAUDE.md, context.md, plan.md, plan-v1.md, README.md (plus `mvp-scope.md` and `deployment.md` as references), plus the reference `crm-prototype.html`. Don't add documentation files unless asked, and don't change the prototype unless asked.
- Environment: Windows 11, PowerShell primary (Git Bash available). Forward-slash paths in docs and code.

## 7. Commands

Code lives in `frontend/` (Next.js, port 3000) and `backend/` (NestJS, port 4000), as confirmed in plan-v1.md §7.

Prerequisites: Node.js LTS with npm, **MySQL installed natively** and running locally, Git. No Docker, Redis or other services. Copy `backend/.env.example` to `.env` (crm_dev, with a 32+ character `JWT_SECRET`; the API will not start without it) and `.env.test` (crm_test). Tests delete all rows and refuse any database not ending in `_test`. On Windows run Vitest from an upper-case drive path (`D:\…`); a lower-case `d:\` cwd makes every suite fail with "Cannot read properties of undefined (reading 'config')".

| Task | `backend/` | `frontend/` |
|---|---|---|
| Install | `npm install` | `npm install` |
| Dev server | `npm run dev` | `npm run dev` |
| Build | `npm run build` | `npm run build` |
| Typecheck / lint | `npm run typecheck` · `npm run lint` | `npm run typecheck` · `npm run lint` |
| Format | `npm run format` / `npm run format:check` | `npm run format` / `npm run format:check` |
| Tests | `npm run test` (unit, needs `DATABASE_URL` → crm_test) · `npm run test:e2e` | — |
| Database | `npm run db:migrate` · `npm run db:migrate:dev -- --name <change>` · `npm run db:seed` · `npm run db:status` · `npm run db:generate` | — |

Health check: `GET http://localhost:4000/api/health`.
