# bdMedicine — backend guide for Claude Code

Read this whole file before every task. It is the source of truth for the **backend** (REST API +
MySQL + image uploads). Put it in the backend folder as `CLAUDE.md` (or keep it as `BACKEND.md` and
tell Claude Code to read it). If anything is unclear or conflicts with the existing front end or
admin UI code, **stop and ask** instead of guessing.

---

## 0. Context and goal

- **bdMedicine** is a medicine **information** website for Bangladesh (human medicines, vet medicines,
  agro products). We **do not sell** anything.
- The **public front end** (React + Vite + Tailwind) and the **admin UI** are **already built** and
  currently use fake JSON data.
- **This phase:** build the backend so both the front end and the admin UI use real data:
  1. a **public read API** for the website,
  2. an **admin API** (login + full CRUD) for the admin UI,
  3. a **MySQL** database with migrations and seed data,
  4. **image uploads to Cloudflare R2**,
  5. ready to **deploy on cPanel** (Node.js app via "Setup Node.js App" / Passenger).
- **ONE backend for both UIs (mandatory):** the public website and the admin panel are served by a
  **single** Node/Express application, **one** MySQL database and **one** cPanel deployment.
  Do **not** create a separate backend, server, repo or database for the admin.
  - Same app, two route groups: **`/api/v1/...`** (public, read-only) and **`/api/v1/admin/...`**
    (admin, login required).
  - Both route groups share the same database, Knex repositories, services, validation and types, so
    data edited in the admin appears on the website immediately (after cache expiry).
  - Both front ends use the **same API base URL** (`VITE_API_URL`, e.g. `https://api.bdmedicine.com/api/v1`).
  - CORS allows both origins (website + admin); the admin cookie is only accepted on `/admin` routes.
- **Not in this phase:** bulk data imports (DGDA CSV, openFDA JSON), user accounts for the public,
  multiple admin roles, hospitals/doctors.

### First task before writing any code
1. Read the front-end repo: `src/lib/api.ts`, all TypeScript types, and every page that loads data.
2. Read the admin UI repo: every screen, form and the calls it makes (or its fake data layer).
3. Write `docs/api-contract.md`: every endpoint the front end and admin UI need, with request params
   and the **exact response shape they already expect**. Show it to me and wait for approval.
   **The API must fit the existing UIs; do not change UI code unless I approve.**

---

## 1. Tech stack (fixed)

| Area | Choice |
|---|---|
| Runtime | Node.js **20 LTS** (match the version available in cPanel "Setup Node.js App") |
| Language | **TypeScript** (strict), compiled to JS with `tsc` into `dist/` |
| Framework | **Express** |
| Database | **MySQL 8** (or MariaDB 10.6+ if that is what cPanel has; check and tell me) |
| DB access | **Knex + mysql2**: migrations, seeds, query builder. No raw string-built SQL. |
| Validation | **zod** for every request body, params and query |
| Auth | Admin only: **JWT in an httpOnly, Secure, SameSite=Lax cookie**; passwords with **bcryptjs** |
| Images | **Cloudflare R2** through `@aws-sdk/client-s3` + `@aws-sdk/s3-request-presigner` |
| Security | `helmet`, `cors` (allowlist), `express-rate-limit`, `compression`, `cookie-parser` |
| Logging | `pino` (+ `pino-http`); pretty logs only in development |
| Email (optional) | `nodemailer` with cPanel SMTP, for contact form notifications |
| Tests | `vitest` + `supertest` against a separate test database |
| Tooling | ESLint, Prettier, `tsx` for dev (`tsx watch`), `dotenv` |

**cPanel rule:** avoid native/compiled dependencies (no `bcrypt`, no `sharp`, no `prisma`). Keep
dependencies small; shared hosting has limited memory. Ask before adding any library.

---

## 2. Project structure

```
backend/
  src/
    server.ts            starts the app on process.env.PORT (Passenger sets it)
    app.ts               builds the Express app (used by server and tests)
    config/env.ts        loads + validates env vars with zod (fail fast if missing)
    db/knex.ts           Knex instance (pool min 0, max 5)
    db/migrations/       numbered migrations
    db/seeds/            seed files (admin user, lookup tables, fake data from the front end)
    modules/
      public/            search, medicines, generics, companies, drug-classes, dosage-forms,
                         conditions, catalogues (vet/agro), new-medicines, sitemap, redirects, forms
      admin/             auth, dashboard, brands, generics, companies, drug-classes, dosage-forms,
                         conditions, catalogue-products, images, messages, settings, audit-log
        each module: routes.ts, controller.ts, service.ts, schema.ts (zod), repo.ts (Knex)
    middleware/          auth, validate, errorHandler, notFound, rateLimits, cache
    lib/                 r2.ts, slug.ts, pagination.ts, http-errors.ts, mailer.ts
    types/               shared response types (mirror the front-end types)
  tests/
  scripts/               create-admin.ts, check-db.ts
  knexfile.ts  tsconfig.json  package.json  .env.example
```

---

## 3. Database (MySQL)

- Charset **`utf8mb4`**, collation **`utf8mb4_unicode_ci`** for every table (Bangla text must work).
- Every table: `id` (BIGINT UNSIGNED auto increment), `created_at`, `updated_at`.
- Public-facing rows have a unique **`slug`** and a **`status`**: `draft | published | archived`.
- Use foreign keys with sensible `ON DELETE` rules; index every foreign key and every slug.
- Prices are stored as `DECIMAL(10,2)`; unknown values are `NULL` (the UI shows `৳ [price]`).

### Tables (adjust names/fields to match the API contract)

| Table | Key fields |
|---|---|
| `admins` | name, email (unique), password_hash, last_login_at, is_active |
| `companies` | slug, name, catalogues (SET 'human','vet','agro'), website, status |
| `drug_class_groups` | slug, name, sort_order |
| `drug_classes` | slug, name, group_id, description, status |
| `dosage_forms` | slug, name, icon (tablet, capsule, syrup, suspension, drops, injection, iv, suppository, cream, powder), description, sort_order |
| `conditions` | slug, name, guidance, status |
| `condition_related` | condition_id, related_condition_id |
| `generics` | slug, name, catalogue, drug_class_id, status, review_status (`pending|approved`), reviewer_name, reviewed_at, sources (JSON array) |
| `generic_info` | generic_id, section (`indications, dosage, side_effects, precautions, pregnancy, contraindications, interactions, pharmacology, overdose, storage`), body_en (TEXT), body_bn (TEXT NULL). Unique (generic_id, section) |
| `generic_conditions` | generic_id, condition_id |
| `generic_components` | combination_generic_id, component_generic_id (e.g. "Paracetamol + Caffeine" → paracetamol, caffeine) |
| `brands` | slug, name, generic_id, company_id, catalogue, dosage_form_id, form_label ("Tablet (Extended Release)"), strength ("500 mg"), family_key (groups same brand's other strengths/sizes for the strength selector), pack_label ("Box: 10 × 10 tablets"), unit_price, pack_price, price_updated_at, price_source ("DGDA"), dar_number (DGDA registration, nullable), status, added_at |
| `brand_form_info` | brand_id, section, body_en, body_bn — form-specific overrides (e.g. suppository dose/storage) |
| `images` | r2_key, url, mime, size_bytes, width, height, credit ("Beximco Pharmaceuticals"), photo_date, permission_note, status |
| `brand_images` | brand_id, image_id, side (`front|back`), sort_order |
| `catalogue_tags` | slug, name, kind (`animal|crop|product_type`) — e.g. Cattle, Poultry, Rice, Insecticides |
| `brand_tags` | brand_id, tag_id (vet/agro brands → animals/crops/types) |
| `slug_redirects` | entity (`brand|generic|company|…`), old_slug, new_slug — written automatically when a slug changes |
| `contact_messages` | name, contact, topic (`mistake|missing|pack_photo|other`), message, page_ref, status (`new|read|done`), ip_hash |
| `audit_log` | admin_id, action, entity, entity_id, diff (JSON), created_at |
| `settings` | key, value (JSON) |

Search: add **FULLTEXT** indexes on `brands.name`, `generics.name`, `companies.name`,
`conditions.name`, plus normal indexes for prefix search (`LIKE 'nap%'`). Live search must answer in
**< 100 ms** on 50,000 brands.

---

## 4. Public API (`/api/v1`, read-only, no auth)

Responses must match the front-end types exactly (from `docs/api-contract.md`). Typical endpoints:

| Method + path | Purpose |
|---|---|
| `GET /search/suggest?q=&scope=` | live search: `{ brands: max 4, generics: max 2 }`, min 2 chars |
| `GET /search?q=&scope=&type=&page=` | full results with counts per tab |
| `GET /medicines?letter=&page=` | Medicine names A–Z |
| `GET /medicines/:slug` | brand detail: brand + generic + company + class + **merged medical info** (brand_form_info overrides generic_info, en + bn) + strength siblings + alternate brands preview + images + review + sources + **price** |
| `GET /generics?letter=&page=` · `GET /generics/:slug` | generics list · generic detail (info, brands grouped by form+strength, quick facts, combinations) |
| `GET /generics/:slug/brands?form=&strength=&company=&sort=&page=` | alternate brands + **facet counts** for filters |
| `GET /companies` · `GET /companies/:slug?form=&q=&page=` | companies · company detail |
| `GET /drug-classes` · `GET /drug-classes/:slug` | groups with classes · class detail with generics |
| `GET /dosage-forms` · `GET /dosage-forms/:slug?sort=&page=` | forms · form detail |
| `GET /conditions?letter=` · `GET /conditions/:slug` | conditions · condition detail |
| `GET /catalogues/:vet|agro` · `GET /catalogues/:cat/brands?tag=&page=` | vet/agro pages |
| `GET /new-medicines?period=month|3months|year&page=` | new medicines |
| `GET /redirects?entity=&slug=` | old slug → new slug (front end issues the redirect) |
| `GET /sitemap-data?type=&page=` | slugs + updated_at for building sitemaps |
| `POST /contact` | contact form (topic, page_ref); honeypot field + rate limit |

Rules
- Return only `status = 'published'` rows.
- **Prices appear only in `GET /medicines/:slug`**; never in lists or search (product rule).
- Medical text with `review_status = 'pending'` is returned with `review: { status: 'pending' }` so the
  UI shows "Verification pending" (and the page can be noindex).
- Pagination: `?page=` (1-based), page size 10 by default (max 50); respond with `{ items, page, pageSize, total }`.
- Sorting whitelist only (`name`, `popularity`, `company`, `newest`); unknown values → 400.
- Public GETs send `Cache-Control: public, max-age=300` and an ETag; add a small in-memory cache
  (LRU, ~5 min) for hot endpoints (search suggest, home data, detail pages).
- Errors: `{ error: { code, message, details? } }` with proper HTTP status; never leak stack traces.

---

## 5. Admin API (`/api/v1/admin`, auth required)

**One role: admin.** Keep the `admins` table so more admins can be added later.

- `POST /auth/login` (rate limit 5/min/IP) · `POST /auth/logout` · `GET /auth/me`
- JWT (15–60 min) in an httpOnly cookie + refresh on activity; check `Origin` on state-changing requests.
- First admin is created with `npm run create-admin -- --email=… --name=…` (prompts for password).

CRUD (list with search/filter/sort/pagination, get, create, update, delete or archive):
`brands`, `generics` (+ info sections en/bn), `companies`, `drug-classes` (+ groups), `dosage-forms`,
`conditions`, catalogue tags (animals, crops, product types), `messages` (contact inbox),
`settings`, plus `GET /dashboard` (counts: brands, generics, pending review, new messages) and
`GET /audit-log`.

Admin rules
- Validate everything with zod; return field-level errors the admin UI can show.
- Slugs auto-generated from name (+ strength + form for brands), editable; on change, write `slug_redirects`.
- Publishing: `status` draft → published. Medical text: admin sets `review_status = approved` with
  `reviewer_name` and `reviewed_at` (the website shows "Checked by …").
- Every create/update/delete writes `audit_log`.
- Deleting something that is referenced (e.g. a company with brands) → 409 with a clear message;
  prefer archiving.

---

## 6. Image uploads (Cloudflare R2)

Flow (the file never passes through our server, which keeps cPanel memory low):
1. `POST /admin/images/presign` `{ filename, mime, size }` → validate (jpeg/png/webp, ≤ 5 MB) →
   return `{ uploadUrl, key, publicUrl }` (presigned **PUT**, expires in 5 min).
   Key pattern: `brands/{yyyy}/{mm}/{uuid}.{ext}`.
2. Admin UI uploads the file directly to `uploadUrl`.
3. `POST /admin/images/confirm` `{ key, credit, photoDate, permissionNote, brandId?, side? }` →
   `HeadObject` to verify it exists and matches type/size → save `images` (+ `brand_images`).
4. `DELETE /admin/images/:id` → delete the object from R2 and the rows.

- Public images are served from the R2 **custom domain** (`R2_PUBLIC_URL`, e.g. `https://img.bdmedicine.com`).
- R2 endpoint: `https://<R2_ACCOUNT_ID>.r2.cloudflarestorage.com`, region `auto`.
- Document the **R2 bucket CORS** needed for direct uploads from the admin origin (PUT, Content-Type).
- Store `credit` and `permission_note` for every pack image (we only use images we own or have written
  permission for). No image resizing on the server for now.

---

## 7. Environment variables (`.env.example`)

```
NODE_ENV=production
PORT=3000                       # Passenger provides PORT on cPanel
APP_URL=https://www.bdmedicine.com
ADMIN_URL=https://admin.bdmedicine.com
CORS_ORIGINS=https://www.bdmedicine.com,https://admin.bdmedicine.com
DB_HOST=localhost
DB_PORT=3306
DB_NAME=
DB_USER=
DB_PASSWORD=
JWT_SECRET=                     # long random string
COOKIE_DOMAIN=.bdmedicine.com
R2_ACCOUNT_ID=
R2_ACCESS_KEY_ID=
R2_SECRET_ACCESS_KEY=
R2_BUCKET=
R2_PUBLIC_URL=https://img.bdmedicine.com
SMTP_HOST=  SMTP_PORT=465  SMTP_USER=  SMTP_PASS=  CONTACT_NOTIFY_EMAIL=
```
Never commit `.env`. Validate all variables at startup with zod.

---

## 8. cPanel deployment (write `docs/deploy-cpanel.md` with exact steps)

- **Database:** cPanel → MySQL Databases: create DB + user, grant all privileges. Use utf8mb4.
- **App:** cPanel → Setup Node.js App: Node 20, application mode Production, app root `backend`,
  application URL `api.bdmedicine.com` (or `/api`), startup file **`dist/server.js`**.
- **Build** locally (`npm run build`), upload `dist/`, `package.json`, `package-lock.json`,
  `knexfile.js`/migrations (compiled); then "Run NPM Install" (production deps only).
- Set env vars in the Node.js App screen. Run `npm run migrate` and `npm run seed` from the cPanel
  terminal (or "Run JS script"). Restart with the Restart button (or `touch tmp/restart.txt`).
- `server.ts` must listen on `process.env.PORT` and handle `SIGTERM` gracefully.
- Front end + admin are static builds in `public_html` / subdomain, with an `.htaccess` SPA fallback;
  document it, and set `VITE_API_URL` in both front ends.
- Add `GET /api/v1/health` (DB ping) for monitoring.
- Logs go to stdout (visible in cPanel logs); no file logging that fills the disk.

---

## 9. Security checklist

helmet · CORS allowlist from env · rate limits (login 5/min, contact 3/min, public 120/min/IP) ·
zod on every input · Knex parameter binding only · bcryptjs (cost 12) · httpOnly Secure cookies ·
Origin check on admin writes · no stack traces in production · upload type/size checks · secrets only
in env · `trust proxy` set for cPanel/Cloudflare · audit log for admin actions.

---

## 10. Seed data

- `npm run seed` loads: lookup tables (dosage forms, drug-class groups/classes, catalogue tags),
  and **the front end's fake JSON data** converted to DB rows, so the website and admin work end to end.
- Never invent real prices or doses: keep `NULL` / placeholders as in the fake data.
- No DGDA/openFDA imports in this phase (later we will add import scripts).

---

## 11. Build order (one step per prompt; finish and report before the next)

1. **API contract:** read front end + admin UI, write `docs/api-contract.md`, wait for approval.
2. **Setup:** TS, Express app, env validation, Knex config, health check, error handling, logging, lint, tests.
3. **Migrations** for all tables + `create-admin` script + seeds from the fake data.
4. **Public API:** search suggest + search, medicines (A–Z + detail), generics (+ brands with facets).
5. **Public API:** companies, drug classes, dosage forms, conditions, vet/agro, new medicines,
   redirects, sitemap data, contact.
6. **Admin auth** + dashboard + audit log.
7. **Admin CRUD** for every entity (incl. generic info en/bn and brand form info).
8. **R2 image uploads** (presign, confirm, delete) + bucket CORS doc.
9. **Connect the front end and admin UI:** replace fake data layers with API calls (only after I approve
   the diff); keep the same types.
10. **Hardening:** caching, rate limits, security checklist, tests for every endpoint.
11. **Deployment docs** for cPanel + a dry run checklist.

For every step: run `npm run lint`, `npm run typecheck` and `npm test`; then report what you built,
how you tested it, and anything you could not do.

---

## 12. Definition of done

- **One** backend app, **one** database, **one** deployment serves both the website and the admin panel.
- Every screen of the front end and the admin UI works with real data from MySQL.
- API responses match `docs/api-contract.md`; no UI changes needed beyond the data layer.
- Live search < 100 ms; detail endpoints < 200 ms on seeded data.
- Prices only in the brand detail endpoint; only published data is public.
- Admin login, CRUD, publishing, review fields, audit log and R2 uploads all work.
- Runs on cPanel with Node 20 using `dist/server.js`; deploy doc tested step by step.
- Lint, typecheck and tests pass; no secrets in the repo.

## 13. Working rules

- Ask before adding libraries, changing the schema after migrations are applied, or touching UI code.
- Small, focused commits after each step. Never run destructive migrations on production data.
- If the existing UIs need data that this file does not cover, list it and ask.
