# bdMedicine API contract

**Status: approved 2026-11-26** with the recommended answers to Q1–Q9 (see §5). Q7 (MySQL vs MariaDB) is still open: code targets both MySQL 8 and MariaDB 10.6+.

One Express app, one MySQL database, two route groups:

| Group | Base | Auth | Used by |
|---|---|---|---|
| Public | `/api/v1` | none, read-only (+ `POST /contact`) | website (`/` … `src/`) |
| Admin | `/api/v1/admin` | httpOnly JWT cookie | admin UI (`admin-dashboard/`) |

Both UIs use the same `VITE_API_URL` (e.g. `https://api.bdmedicine.com/api/v1`).

The response shapes below are taken from the types the UIs **already use**:
`src/lib/types.ts` (website), `admin-dashboard/src/lib/types.ts` and `admin-dashboard/src/lib/schemas.ts` (admin).
Fields marked **(new)** don't exist in the UI types yet. Each section lists the screens it serves.

---

## 0. Conventions

- **JSON in camelCase** (matches the TS types). DB columns stay snake_case; repos map them.
- **Lists:** `{ items: T[], page: number, pageSize: number, total: number }`.
  - `?page=` is 1-based. `?pageSize=` defaults to 10, max 50.
  - The UIs pass their Figma page sizes: A–Z 8, generics 9, company 6, conditions 7, new medicines 6.
- **Errors:** `{ error: { code, message, details? } }`.
  - `details` holds field errors for admin forms: `{ fieldErrors: { "slug": ["Another medicine already uses this slug"] } }`.
  - Status codes: 400 (validation), 401, 403, 404, 409 (conflict / still referenced), 429.
- **Public:** only `status = 'published'` rows. `Cache-Control: public, max-age=300` + ETag.
- **Prices** (`unitPrice`, `packPrice`, `priceUpdated`, `priceSource`) appear **only** in `GET /medicines/:slug` and in admin endpoints. Unknown prices are `null`; the UI renders `৳ [price]`.
- **Sort whitelist:** `name | popularity | company | newest`. Any other value → 400.
- **Text convention** (already used by the UI): in `Lang.en` / `Lang.bn`, `\n` separates paragraphs and a line starting with `!` is a caution line.

---

## 1. Shared types

```ts
type Lang = { en: string; bn?: string };
type Catalogue = 'human' | 'vet' | 'agro';
type FormIconKey = 'tablet'|'capsule'|'syrup'|'suspension'|'drops'|'injection'|'iv'|'suppository'|'cream'|'powder';
type InfoKey = 'indications'|'dosage'|'sideEffects'|'precautions'|'pregnancy'|'contraindications'|'interactions'|'pharmacology'|'overdose'|'storage';
type Review = { status: 'approved' | 'pending'; reviewer?: string; date?: string }; // date = YYYY-MM-DD
type Ref = { slug: string; name: string };

/** List item: used in A–Z, search, company, dosage form, new medicines, alternate brands. NO prices. */
type BrandSummary = {
  id: string; slug: string; name: string;
  form: string; formIcon: FormIconKey; strength: string; catalogue: Catalogue;
  genericSlug: string; companySlug: string;   // kept: the UI types use them
  generic: Ref; company: Ref;                 // (new) embedded, so the UI needs no extra lookups
  pack: string | null; addedAt: string; popularity: number;
};

type PackImage = { url: string; credit: string; date: string };

/** Brand detail = the UI's `Brand` + resolved relations. */
type BrandDetail = BrandSummary & {
  unitPrice: number | null; packPrice: number | null; priceUpdated: string | null;
  priceSource: 'DGDA';                                    // (new)
  packImage: PackImage | null;
  status: 'published' | 'discontinued';                   // see question Q4
  siblings: { slug: string; strength: string }[];         // strength selector (same family_key)
  info: Record<InfoKey, Lang & { source: 'brand' | 'generic' }>; // brand_form_info overrides generic_info
  genericDetail: { slug: string; name: string; classSlug: string; className: string; review: Review; sources: string[] };
  otherBrands: BrandSummary[];                             // same generic + same form, other companies (max 12)
};

type GenericSummary = { id: string; slug: string; name: string; classSlug: string; className: string; tagline?: string; brandCount: number };
type GenericDetail = GenericSummary & {
  catalogue: Catalogue; classLabel?: string;
  conditionSlugs: string[]; combinations: (Ref & { brandCount: number })[];
  info: Record<InfoKey, Lang>; review: Review; sources: string[]; updatedAt: string;
  brandGroups: { key: string; label: string; formSlug: string; brands: BrandSummary[] }[]; // "Tablet · 500 mg"
  quickFacts: { brandCount: number; companyCount: number; forms: { slug: string; name: string; icon: FormIconKey }[] };
};

type Company = { id: string; slug: string; name: string; catalogue: Catalogue[]; brandCount: number };
type DrugClass = { slug: string; name: string; description: string; genericCount: number };
type DrugClassGroup = { slug: string; name: string; classes: DrugClass[] };
type DosageForm = { slug: string; name: string; icon: FormIconKey; description: string; match: string[]; brandCount: number };
type Condition = { slug: string; name: string; guidance: string; relatedSlugs: string[]; genericCount: number };

/** Vet/agro product as the website renders it today (built from `brands` + `catalogue_tags`). */
type CatalogueProduct = {
  slug: string; name: string; catalogue: 'vet' | 'agro'; type: string; animalsOrCrops: string[];
  form: string; formIcon: FormIconKey; strength: string; genericName: string; companySlug: string;
  company: Ref;
};
```

---

## 2. Public API (`/api/v1`)

| # | Endpoint | Query | Response | Website screen |
|---|---|---|---|---|
| P1 | `GET /health` | – | `{ ok: true, db: 'up' }` | monitoring |
| P2 | `GET /search/suggest` | `q` (min 2), `scope=all\|human\|vet\|agro` | `{ brands: SuggestBrand[] (max 4), generics: SuggestGeneric[] (max 2) }` | live search dropdown (navbar, mobile header, home hero) |
| P3 | `GET /search` | `q`, `scope`, `type=all\|brand\|generic`, `page`, `pageSize` | `{ q, counts: { all, brands, generics }, genericMatch: GenericSummary \| null, generics: GenericSummary[], brands: Page<BrandSummary> }` | Search results |
| P4 | `GET /search/did-you-mean` | `q` | `{ items: { title, sub, href, formIcon? }[] }` (max 2; `formIcon` on brand rows) | No results |
| P5 | `GET /medicines` | `letter=a..z`, `page`, `pageSize` | `Page<BrandSummary> & { totalAll: number }` (`totalAll` = all brands, for "· 20 brands") | Medicine names A–Z |
| P6 | `GET /medicines/:slug` | – | `BrandDetail` (+ Phase 8: `alternatives: PriceRow[]` = every brand with the same generic, strength and form, cheapest first; `summary: QuickSummary \| null`). Unknown slug: 404, or `301`-style `{ redirect: newSlug }` if found in `slug_redirects` | Brand detail (EN + বাংলা) |
| P7 | `GET /generics` | `letter`, `page`, `pageSize` | `Page<GenericSummary> & { totalAll }` | Generics A–Z |
| P8 | `GET /generics/:slug` | `form=tablet\|syrup\|suppository\|injection` (tab) | `GenericDetail` with every brand group, `summary`, `related` (same drug class) | Generic detail |
| P9 | `GET /generics/:slug/brands` | `tab`, `form` (csv), `strength` (csv), `company` (csv), `sort`, `page`, `pageSize` | `Page<BrandSummary> & { generic: Ref, totalAll, facets: { form: Facet[], strength: Facet[], company: Facet[] }, combinations: (Ref & {brandCount})[] }` with `Facet = { value, label, count }` | Alternate brands (filters, sort, combinations, empty state) |
| P10 | `GET /companies` | `q` | `{ items: Company[] }` | Companies |
| P11 | `GET /companies/:slug` | `form`, `q`, `page`, `pageSize` | `{ company: Company } & Page<BrandSummary>`, or `{ redirect: newSlug }` for a renamed slug | Company detail |
| P12 | `GET /drug-classes` | – | `{ items: DrugClassGroup[] }` | Drug classes |
| P13 | `GET /drug-classes/:slug` | – | `{ class: DrugClass, group: Ref, generics: GenericSummary[], otherClasses: Ref[] }`, or `{ redirect }` | Drug class detail |
| P14 | `GET /dosage-forms` | – | `{ items: DosageForm[] }` | Dosage forms, Home |
| P15 | `GET /dosage-forms/:slug` | `generic` (csv), `sort`, `page`, `pageSize` | `{ form: DosageForm, facets: { generic: Facet[] } } & Page<BrandSummary>`, or `{ redirect }` | Dosage form detail |
| P16 | `GET /conditions` | `letter`, `q` | `{ items: Condition[], totalAll }` | Conditions A–Z |
| P17 | `GET /conditions/:slug` | – | `{ condition: Condition, generics: (GenericSummary & { formsLine: string })[], related: Ref[] }`, or `{ redirect }` | Condition detail |
| P18 | `GET /catalogues/:cat` (`vet\|agro`) | `tag` (animal/crop slug), `type` (product-type slug), `q` | `{ tags: (Ref & {count})[], types: (Ref & {count})[], products: CatalogueProduct[] }` | Vet medicines, Agro products |
| P26 | `GET /catalogues/:cat/products/:slug` | – | `CatalogueProductDetail` (type, animals/crops, form, strength, ingredient, company, price, pack image, `withdrawalPeriod`, `targetPest`, `doseRate`), `{ redirect }` or 404 | Vet / agro product page (SEO Phase 12) |
| P19 | `GET /new-medicines` | `period=month\|3months\|year`, `page`, `pageSize` | `Page<BrandSummary>` (newest first) | New medicines |
| P24 | `GET /reviewers` | – | `{ items: (Reviewer & { reviewedCount })[] }`, `Reviewer = { slug, name, qualification, registrationNo, bio, photo }` | Medical reviewers (SEO Phase 7) |
| P25 | `GET /reviewers/:slug` | – | `{ reviewer: Reviewer, generics: GenericSummary[] }`, `{ redirect }` for a renamed slug, or 404 | Reviewer profile |
| P20 | `GET /redirects` | `entity`, `slug` | `{ newSlug: string } \| 404` | any detail page whose slug changed |
| P21 | `GET /sitemap-data` | `type=medicines\|generics\|companies\|classes\|forms\|conditions`, `page` | `Page<{ slug, updatedAt, image?: string }>` (only indexable rows) | build-time sitemap script |
| P22 | `POST /contact` | body: `{ name?, contact, topic: 'mistake'\|'missing'\|'photo'\|'other', message, ref?, website: '' }` (`website` = honeypot) | `201 { ok: true }`; 400 with fieldErrors; 429 | Contact form |
| P23 | `GET /settings/public` | – | `{ contactEmail, replyDays, legalEntity, maintenanceMode }` | Contact, Terms, maintenance notice |

```ts
type SuggestBrand = { id: string; slug: string; name: string; displayName: string; form: string; formIcon: FormIconKey; strength: string; genericName: string };
type SuggestGeneric = { id: string; slug: string; name: string; tagline: string };
```

Notes:
- Search results and suggestions **never** include prices.
- **Rate limits:** contact 3/min/IP, all public routes 120/min/IP.
- **Home page:** uses no medicine lists (product rule). It only needs P14 and the static condition chips.

---

## 3. Admin API (`/api/v1/admin`)

Every write: zod validation → field errors on failure → audit_log entry → response with the saved record.
State-changing requests check the `Origin` header.

### Auth
| Endpoint | Body / response | Admin screen |
|---|---|---|
| `POST /auth/login` | `{ email, password, remember }` → `{ user: AdminUser }` + cookie. 401 `{ code: 'invalid_credentials' }`, 403 `{ code: 'inactive' }`. 5/min/IP | Login |
| `POST /auth/logout` | → 204, clears cookie | Sign out |
| `GET /auth/me` | → `{ user: AdminUser }` or 401 | app start, route guard |
| `POST /auth/forgot` | `{ email }` → always 202 (no account enumeration) | Forgot password dialog (needs SMTP) |

`AdminUser = { id, name, email, role: 'admin'|'editor'|'pharmacist', status: 'active'|'invited'|'disabled', lastActive: string|null }`. See **Q1** about roles.

### Dashboard and log
| Endpoint | Response | Screen |
|---|---|---|
| `GET /dashboard` | `{ brands, placeholders, generics, approved, pendingReview, companies, openRequests, noPrice, noImage, vet, agro, byForm: { label, count }[], pending: GenericSummary[5], inbox: ContactMessage[5], activity: ActivityEntry[6] }` | Dashboard |
| `GET /audit-log` | `?q&page&pageSize` → `Page<ActivityEntry>`, `ActivityEntry = { id, at, who, action, target }` | Activity log |

### CRUD collections

Every collection has the same five routes:

| Route | Purpose |
|---|---|
| `GET /x` | list: `?q, filters, sort, page, pageSize` → `Page<T>` |
| `GET /x/:id` | one record |
| `POST /x` | create |
| `PUT /x/:id` | update |
| `DELETE /x/:id` | delete; 409 if still referenced |

The bodies are exactly the admin's zod schemas in `admin-dashboard/src/lib/schemas.ts`, shared by moving them to a common file (see **Q8**).

| Collection | Body schema | List filters | Extra routes | Admin screen |
|---|---|---|---|---|
| `brands` | `brandSchema` (formInfo en/bn, prices, status, pack image ref) | `q, catalogue, company, status=active\|discontinued\|noprice\|noimage` | `DELETE /brands` body `{ ids }` (bulk); `GET /brands/export.csv` | Medicines list, Add/Edit medicine |
| `brands/import` | `{ rows: CsvRow[] }` (parsed in the browser) → `{ created, updated, skipped, errors: { line, messages }[] }`; `?dryRun=1` validates only | – | – | Import CSV (see **Q2**) |
| `generics` | `genericSchema` (info en/bn, review with `reviewerSlug`, sources, conditions, combinations). The list returns summaries `{ id, slug, name, catalogue, classSlug, className, brandCount, completeness, conditionSlugs, hasIndications, review, updatedAt }`; open one with `GET /generics/:id` for the full record | `q, reviewStatus` | `POST /generics/:id/approve` `{ reviewerSlug, date }` | Generics, Generic form, Review queue |
| `companies` | `companySchema` | `q` | – | Companies |
| `drug-classes` | `drugClassSchema` | `q, group` | `GET /drug-class-groups` | Drug classes |
| `dosage-forms` | `dosageFormSchema` (`match` as string[]) | – | – | Dosage forms |
| `conditions` | `conditionSchema` | `q` | – | Conditions |
| `catalogue-products` | `productSchema` (stored as brands + tags) | `catalogue=vet\|agro` | `GET /catalogue-tags?kind=animal\|crop\|product_type` | Vet & agro (see **Q3**) |
| `messages` | `PATCH /messages/:id` `{ status }` | `status=open\|resolved` | – | Inbox (see **Q5**) |
| `users` | `userSchema` | – | – | Users & roles (see **Q1**) |
| `reviewers` | `reviewerSchema` (name, slug, qualification, registrationNo, bio, photoUrl). List: every role; write: admin only. Delete → 409 while they have approved pages | – | – | Reviewers (SEO Phase 7) |
| `settings` | `PUT /settings` body `settingsSchema` → `SiteSettings` | – | `GET /settings` | Settings |
| `images` | `POST /images/presign` `{ filename, mime, size }` → `{ uploadUrl, key, publicUrl }`; `POST /images/confirm` `{ key, credit, photoDate, permissionNote, brandId?, side? }` → `PackImage & { id }`; `DELETE /images/:id` | – | – | Medicine form → Pack image |

**409 cases** (the UI already blocks these):
- a company that still has brands
- a drug class that still has generics
- a generic that still has brands

**Slug changes:** writing a new slug on a brand, generic or company inserts the old one into `slug_redirects`.

---

## 4. UI field ↔ DB column (where they differ)

| UI field | DB |
|---|---|
| `Brand.genericSlug` / `companySlug` | `brands.generic_id` / `company_id` (joined to slug) |
| `Brand.form` + `formIcon` | `brands.form_label` + `dosage_forms.icon` via `dosage_form_id` |
| `Brand.siblingSlugs` | derived from `brands.family_key` |
| `Brand.pack` | `brands.pack_label` |
| `Brand.packImage` | `brand_images` (side = front) → `images` |
| `Brand.formInfo` | `brand_form_info` rows |
| `Brand.popularity` | **(new column)** `brands.popularity INT DEFAULT 0` (see **Q6**) |
| `Generic.info` | `generic_info` rows (10 sections × en/bn) |
| `Generic.combinations` | derived from `generic_components` (combos whose components include this generic) |
| `Generic.classLabel`, `tagline` | **(new columns)** on `generics` |
| `Generic.review` | `generics.review_status`, `reviewer_name`, `reviewed_at` |
| `DosageForm.match` | **(new)** `dosage_forms.match_labels JSON` (brand form labels that belong to the form) |
| `Condition.relatedSlugs` | `condition_related` |
| `AgroVetProduct.type`, `animalsOrCrops` | `brand_tags` → `catalogue_tags` (kind = product_type / animal / crop) |
| `InboxRequest` | `contact_messages` (`ref` = `page_ref`) |
| `ActivityEntry` | `audit_log` joined to `admins.name` |

---

## 5. Decisions (approved with the recommendations below)

The UIs I built differ from BACKEND.md in these places. Each has my recommendation.

- **Q1. Roles.** The admin UI has admin / editor / pharmacist and a Users page. BACKEND.md says one role only.
  *Recommend:* add `admins.role` (default `admin`) and keep the users endpoints. It's small and the UI already depends on it.
- **Q2. CSV import.** The admin UI has it. BACKEND.md lists bulk imports as "not in this phase" (that refers to DGDA/openFDA feeds).
  *Recommend:* keep `POST /admin/brands/import` for the admin's own CSV, since the browser already parses and validates it.
- **Q3. Vet/agro products.** The admin treats them as a separate product type. BACKEND.md stores them as `brands` with `catalogue_tags`.
  *Recommend:* follow BACKEND.md in the database, and keep the `catalogue-products` endpoint returning the shape the UIs already use (no UI change).
- **Q4. Brand status.** The UI has `active | discontinued`. The database has `draft | published | archived`.
  *Recommend:* use `draft | published | archived` plus a `discontinued_at` date (SEO.md: a discontinued page stays live with a notice). The admin Status field then gets the options Draft / Published / Discontinued / Archived. That's a small admin UI change in step 9.
- **Q5. Message status.** The UI has `new | in-progress | resolved`. BACKEND.md has `new | read | done`.
  *Recommend:* use the UI's values.
- **Q6. `popularity`.** The "Popularity" sort needs a column.
  *Recommend:* `brands.popularity`, set manually for now and later from analytics.
- **Q7. Database.** Does your cPanel host have **MySQL 8 or MariaDB**, and which version? The JSON and FULLTEXT details differ slightly.
- **Q8. Shared validation.** I'd move the zod schemas into a shared folder (`/shared/schemas.ts`) used by the admin UI and the backend, so the rules can never drift apart.
- **Q9. Folder layout.** I'd put the backend in `bdMedicine/backend/` next to the website and `admin-dashboard/`: one repo, one backend.
