# Development Guide

## Documentation (read first)

- **Index:** [00-docs-index.md](./00-docs-index.md)
- **AI agents:** [10-ai-documentation-guide.md](./10-ai-documentation-guide.md) — **mandatory** doc updates when changing features
- **Frontend UI rules:** `sdm-frontend/AI_FRONTEND_RULES.md`

---

## Prerequisites

- Node.js 18+ (ESM required — `"type": "module"` in package.json)
- Docker Desktop (required for `db:clone-dev` script)
- Python 3.13 (for `sdm-receipt` microservice only)
- Neon account access (for production DB)

---

## Initial Setup

```bash
cd sdm-backend
npm install
```

Copy environment files:
- `.env` — production (DATABASE_URL → production Neon DB)
- `.env.local` — local dev (DATABASE_URL → dev Neon DB or local postgres)

Minimum `.env.local` contents:
```dotenv
DATABASE_URL=postgresql://...
JWT_SECRET=...
FIREBASE_SERVICE_ACCOUNT_PATH=./path/to/firebase-creds.json
RAZORPAY_KEY_ID=...
RAZORPAY_KEY_SECRET=...
```

Optional performance/observability vars (see [01-project-overview.md](./01-project-overview.md)):
```dotenv
DB_APPLICATION_NAME=sdm-backend-api
PG_POOL_MAX=10
PG_IDLE_TIMEOUT_MS=30000
PG_CONNECT_TIMEOUT_MS=10000
FORM_CACHE_TTL_MS=300000
FORM_DETAIL_CACHE_TTL_MS=120000
AUTH_TOKEN_EXPIRES_IN=7d
```

---

## Running Locally

```bash
npm run dev          # Start with .env.local + nodemon hot reload
npm run prod         # Start with .env (production DB — use carefully)
```

---

## Database Operations

```bash
# Generate Prisma client
npm run build

# Push schema changes to dev DB
npm run prisma:push:local

# Open Prisma Studio against dev DB
npm run prisma:studio:local

# Clone production DB to dev
npm run db:clone-dev   # Requires Docker Desktop running
```

---

## Production Database Migrations

See [06-database-and-prisma.md](./06-database-and-prisma.md) for the full migration workflow.

**Never** use `prisma:push:prod` for enum changes — it will fail with permission errors.

---

## Seeding

```bash
npm run seed:core-data                   # Pradesh + Mandal master data
npm run seed:super-admins                # Super admin accounts
npm run seed:account-admin               # Account admin account
npm run seed:pradesh-users               # Pradesh admin accounts
npm run seed:karyakarta-table            # Karyakarta hierarchy from CSV
npm run seed:mahayag-rates               # Mahayag seva rates
```

---

## sdm-receipt Microservice

```bash
cd sdm-receipt
py -3.13 -m venv .venv
.venv\Scripts\activate
pip install -r requirements.txt
copy .env.example .env     # Fill in Firebase credentials
uvicorn app.main:app --reload
```

Service runs on `http://localhost:8000` by default.

---

## Frontend (sdm-frontend)

```bash
cd sdm-frontend
npm install
npm run dev     # Next.js dev server
npm run build   # Production build
```

### Next.js 16 Notes

- Middleware uses `src/proxy.ts` with `export function proxy(...)` convention (not the old middleware.ts convention).
- Any page using `useSearchParams()` must be wrapped in a `<Suspense>` boundary to avoid build-time prerender failures (e.g., `/login`).

### Frontend Rules

See `sdm-frontend/AI_FRONTEND_RULES.md` for mandatory conventions:
- All tables must be sortable and paginated.
- Mobile-first responsive design.
- Reuse existing SDM UI components (`Card`, `Table`, `Badge`, `Button`, `Sheet`, `Input`).
- Use theme tokens — no ad-hoc color palettes.

### Keeping docs current

When you add or change admin features (e.g. registration edit modal, new admin routes):

1. Update the relevant file under `sdm-backend/docs/` (see [10-ai-documentation-guide.md](./10-ai-documentation-guide.md)).
2. Add API paths, role gates, and frontend component paths.
3. Remove outdated descriptions of old UI (inline table edits, removed columns, etc.).

**Registration admin UI** is documented in [03-registration-system.md § Admin Registration Editing](./03-registration-system.md#admin-registration-editing-super_admin--account_admin).

---

## Debugging

### Backend 401 loops
- Check that JWT_SECRET matches between your running backend and the token the frontend holds.
- Verify `AUTH_TOKEN_EXPIRES_IN` is the same in running backend vs when the token was issued.

### Prisma runtime 500
- Check for `null` passed to enum fields in `where` clauses (e.g., `recipientRole: null`).
- Check field names against schema — `Registration.karyakartaHaridhamId` not `haridhamId`.

### DB duplicate queries
- Use `x-request-id` from backend logs to trace a single frontend action.
- Filter Neon logs by `application_name = sdm-backend-api`.

### Notifications returning 403 for DB_ADMIN/ACCOUNT_ADMIN
- Ensure the backend process was restarted after the last deploy.
- These roles should have super-admin-equivalent access; 403 means old process is still running.
