# Unionists

One Next.js 16 app (App Router, React 19) on one domain:

| URL | What |
| --- | --- |
| `/`, `/fr`, `/we`, `/we/fr`, … | Home page per region and language, content from the CMS (see below) |
| `/about`, `/contact`, … | Public website inner pages (global, English) |
| `/login`, `/signup` | The only login screen, for every user type |
| `/admin/*` | Admin CMS (admin roles only) |
| `/forgot-password`, `/reset-password` | Password recovery (linked from `/login` and from reset emails) |
| `/api/v1/*` | Proxied to the CMS API (`/api/v1/auth/login` goes through a route handler) |
| `/sitemap.xml`, `/robots.txt` | Generated (`app/sitemap.ts`, `app/robots.ts`) |

## Setup

```bash
cp .env.example .env.local   # then fill in the values
npm install
npm run dev                  # http://localhost:3000
```

Production: `npm run build && npm start` behind Apache/nginx. The site is no longer static files: the API proxy, `proxy.ts` and the admin need the Node server.

| Variable | Purpose |
| --- | --- |
| `API_ORIGIN` | CMS API host, without `/api/v1`. Default `https://unionistbackend.sofrik.com`. |
| `NEXT_PUBLIC_SITE_URL` | Public website origin. Used for canonical / hreflang / sitemap URLs (**set it in production**; default `http://localhost:3000`) and by the admin's editor preview to load content images. |
| `GEO_REDIRECT` | `1` turns on the first-visit geo redirect on `/` (see below). Leave off until the API trusts `X-Forwarded-For`. |
| `NEXT_PUBLIC_MEDIA_ORIGIN` | Host serving uploaded files (`/uploads/…`). Uploaded or picked media is saved into content as this origin + the file's `path`. Default: the API host. |

## Login and roles

`/login` signs in against `POST /api/v1/auth/login` and sends the user on by role (`app/(admin)/_lib/roles.ts`):

- `super_admin`, `admin` → `/admin/dashboard`
- any other role → `/` (add donor / partner / consumer dashboards there when the API has those roles)

Visiting `/admin/*` without an admin session redirects to `/login`. A signed-in user who opens `/login` is forwarded straight to their landing page. The old `/admin/login` URL redirects to `/login`.

## Layout

One app; the website and the admin each live in their own route group inside `app/`. Folders starting with `_` hold code, not routes (Next.js private folders).

```
app/
  (site)/                website: root layout + pages (/, /about, /login, …)
    _components/         SitePage, SiteHeader, SiteFooter, LoginForm, scripts.ts (old script.js)
    _styles/             styles.css (unchanged design), Tailwind entry files
  (site-auth)/           sign-up and alternate login: own root layout and Tailwind config
  (admin)/               admin: root layout, /admin/*, /forgot-password, /reset-password
    _components/         admin UI (dashboard, home editor, media library, …)
    _lib/                API client, auth, roles, queries, data
    admin.css
public/assets/images/    website images (same URLs as before)
```

Each group has its own root layout, so website CSS and admin CSS never load on the same page. Import with the `@/` alias, e.g. `@/app/(admin)/_lib/api`.

### Website styling: keep it identical

The website was static HTML using the Tailwind CDN. To render exactly the same:

- Tailwind is pinned to **3.4.17** (the CDN's version). `tailwind.config.ts` and `tailwind.auth.config.ts` are copies of the pages' inline configs.
- `tailwind.css` is imported **after** `styles.css`, as the CDN injected its styles after the stylesheet.
- Per-page body classes (`about-page`, `page-home`, …) sit on `SitePage`'s wrapper, which is `display: contents`, so it doesn't affect layout.
- Images use plain `<img>`, not `next/image`, which would change markup and layout.

All 30 pages were checked against the old static site with full-page screenshots (desktop 1440px and mobile 390px) and are pixel-identical. Menus, dropdowns, scrolled header, sign-up steps, filters and pagination were checked too.

Old URLs redirect permanently: `/index.html` → `/`, `/pages/<name>.html` → `/<name>`.

## How it talks to the API

The browser never calls the API host directly. `next.config.ts` rewrites `/api/v1/*` to `API_ORIGIN/api/v1/*`, because the API has no CORS and its refresh cookie is `SameSite=Lax`. Through the proxy the cookie belongs to this origin, so the website and the admin share one session.

- Access token: memory only, 15 minutes. On a 401 the client refreshes once and retries.
- Refresh token: HttpOnly cookie (7 days). It is single-use, and reusing one revokes the session, so all refreshes share one in-flight request (`app/(admin)/_lib/api.ts`).
- Admin data fetching and caching use TanStack Query (`app/(admin)/_lib/queries.tsx`).
- `proxy.ts` forwards the visitor's IP (`X-Forwarded-For`) on `/api/v1/*` (`lib/clientIp.ts`: the rightmost entry, the one a reverse proxy added).
- Login goes through `app/api/v1/auth/login/route.ts`, which adds the visitor's IP as `clientIp` in the body (replacing any value the browser sent) and passes status, body and every `Set-Cookie` back unchanged. Login also sends `clientRegion` when `GET /public/locale` detected it from the IP.

## Home page: regions, languages and CMS content

| URL | Region | Language |
| --- | --- | --- |
| `/` | Global | its default (English) |
| `/fr`, `/de`, … | Global | that language |
| `/we` | Western Europe | the region's default language |
| `/we/fr` | Western Europe | French |

- A region's default language never has a suffix: `/we/en` → 308 → `/we` (also `/en` → `/`, `/global` → `/`). A language the region doesn't offer, e.g. `/we/xx`, is a 404. `proxy.ts` does these redirects and 404s before rendering so they get real status codes; the pages (`app/(site)/[region]/…`) resolve the same rules (`app/(site)/_lib/landing.ts`).
- Each landing page has a canonical URL and hreflang links to the same region's other languages (`x-default` = the region's default language). Inner pages are global.
- Content: `GET /public/home-page?region=&lang=` on the server (`app/(site)/_lib/cms.ts`), cached with a 5-second refresh (`HOME_CACHE`), so a published change shows up on the second page load after publishing. Sections render in the CMS order; hidden ones are left out.
- The section components (`app/(site)/_components/home/sections.tsx`) use the static site's markup unchanged. `defaults.ts` holds the static site's content in the CMS shape. It is shown when the API is unreachable or serves another region, and it renders pixel-identical to the old page.
- Content clean-up (`app/(site)/_lib/content.ts`): links saved as `/pages/<name>.html` become `/<name>`. Images saved as `/images/home/<file>` (old seed content) map to `/assets/images/<section folder>/<file>`. The API's internal `http://localhost:…/uploads/…` URLs map to `NEXT_PUBLIC_MEDIA_ORIGIN`.
- A section not yet translated is served in a fallback language and marked up with that `lang`. For RTL languages (Arabic) `<main>` gets `dir="rtl"`; the header and footer keep the current design (there is no RTL design yet).
- **Geo redirect (`GEO_REDIRECT=1`):** a person's first visit to `/` gets a 302 to their detected region (`GET /public/locale` with their IP). A cookie (`ug_region`) makes it happen once; a failed or timed-out lookup (3 s cap) sets no cookie, so the next visit tries again. Bots and link previews are never redirected. To re-test, use a new private window or delete the cookie.

## Inner pages: CMS content

Inner pages are global and English. A page that reads the CMS calls `GET /public/pages/<key>?lang=en` on the server (`getPage` in `app/(site)/_lib/cms.ts`, same 5-second refresh as the home page) and renders its sections in the CMS order (`renderSections` in `app/(site)/_components/pages/render.tsx`).

- Each page has a folder in `app/(site)/_components/pages/<key>/`: `defaults.ts` (the static page's content in the CMS shape) and `sections.tsx` (the static markup, one renderer per section **key**: the same section type looks different on each page).
- **Until something on the page is published, the website shows the built-in content.** After that it shows only the published, visible sections. Hidden and unpublished sections are not in the API response, so the two can't be told apart.
- A section whose CMS content can't be rendered falls back to its built-in version.
- `lang=en` is always sent: without it the API answers in the default language of the region it detects from the caller's IP, which here is the server.
- Pages connected so far (listed in `app/(site)/_components/pages/registry.ts`): About Us, Our Partners & Clients, Why Choose Us, Careers & Opportunities, Global Strategy Division, Awards & Recognition, Testimonials & Case Studies, Partner With Us, Sustainability & ESG, Social Responsibility & Charity, Industry Roadmap, Thought Leadership & Articles (list labels; the articles come from the articles API, see below), AI & Innovation Lab, Media & Press Releases, Unionists Group Magazine, Global Presence, Donations, Contact, Product & Services, Global Agriculture & Food Ingredients (catalogue labels; the products come from the product API, see below), Services, Industries We Serve. Every inner page now reads the CMS. Still built in: the news cards of Media & Press Releases (until a news API exists) and the campaign cards of Donations (until the campaigns API is connected); the inquiry forms show their CMS options but don't submit yet. The press-kit banner has its text drawn into the picture, so its CMS text is the picture's accessible text. Global Presence: the map pins are the offices that have a position; while the page shows its built-in content the map keeps the static page's pins. To connect a page, add its folder, switch its `page.tsx` to `getPage` + `renderSections`, add it to the registry and to `PAGE_RENDERERS` (`pages/renderers.ts`, for the admin preview), list in `pages/designFields.ts` the fields each section's design shows when it shows fewer than the API accepts, and compare screenshots against the current page.

### Services (`/services` cards and `/services/<slug>`)

A service is a card under one of the four Services page divisions plus its own page (API: `/public/services`, `/public/services/<slug>`). The four division sections of the Services page are `service-listing`: the CMS holds their heading and intro, and the API adds the published cards as `services`.

- `/services/<slug>` renders the service's sections (`SERVICE_SECTIONS` in `app/(site)/_components/pages/service/sections.tsx`, the old `/service-details` markup). A service whose page isn't written yet shows a title from its card.
- **Until a service is published in the CMS**, the website shows the 12 built-in services (`app/(site)/_lib/divisions.ts`): their cards on `/services` and their pages. Once one is published, the CMS alone decides which services exist (the same rule applies in `proxy.ts`, the page and the sitemap). Since 2026-11-23 the API has all 12 published, and they render identically to the built-in ones (checked with screenshots).
- An unknown slug is a real 404 (`proxy.ts`, using the published list, cached a minute). `/service-details` redirects to the Biotech page.

### Products (`/global-agriculture` catalogue and `/products/<slug>`)

- **Catalogue** (`app/(site)/_components/products/ProductCatalog.tsx`): the designed markup, filled from `GET /public/products`. The server renders the first unfiltered page (the route stays static); filters live in the page URL (`?category=…&origin=IR,ES&farming=&volume=&certification=&q=&page=`) so filtered views can be shared, and the browser fetches them through `/api/v1`. Filter options come from the API's facets; options without results are disabled. The labels stay in the CMS catalog section. **Until the API has a published product** (or when it can't be reached) the designed static catalogue is shown (`StaticCatalog.tsx`), linking to the old `/product-details`.
- **Product page** (`app/(site)/products/[slug]`): the `/product-details` layout plus what the design didn't have: price (cents → `€480.00 / kg`, struck-through market price), one select per attribute, SKU / size / weight / volume / minimum order, "Request a quote" (→ `/contact?product=&sku=` until there's a leads module), download buttons for the PDFs, and related products. Picking a value that has no variant with the other picks switches to the closest variant, so a price is always shown. An old slug is a 308 to the current one (`proxy.ts`); unknown slugs are 404.
- Product data is cached under the `cms:products` tag; the admin clears it after publish / unpublish / archive and catalog changes.

### Articles (`/thought-leadership-articles` list and `/articles/<slug>`)

- **List** (`app/(site)/_components/articles/ArticleListing.tsx`): the designed tabs, cards and pagination, filled from `GET /public/article-categories` (tabs, with counts) and `GET /public/articles` (9 cards a page). The server renders "All", page 1 (the route stays static); the tab and page live in the URL (`?category=ai-supply-chain&page=2`) and the browser fetches them through `/api/v1`. A card's blue category line opens that tab. A tab with no articles shows the section's `noResultsText`; without that text such tabs are hidden. **Until the API has a published article** (or when it can't be reached) the designed placeholder list is shown (`StaticArticles.tsx`).
- **Article page** (`app/(site)/articles/[slug]`, `ArticleView.tsx`): the design has no article page, so it is built from the site's parts: page hero with breadcrumb, category / date / reading time / author, the excerpt as lead, the cover image, the body blocks (paragraph, H2/H3, bullet or numbered list, quote, image with caption) and up to 3 related articles. `seo` fills the title, description and Open Graph tags (falling back to title / excerpt). An old slug is a 308 to the current one (`proxy.ts`); unknown slugs are 404.
- Article data is cached under the `cms:articles` tag; the admin clears it after publish / unpublish / archive, after saving a live article (shared fields change at once) and after category changes.

### Inquiry forms (Contact, Home, Media & Insights)

- The three forms keep their markup; `app/(site)/_components/InquiryForm.tsx` wraps them and sends `POST /public/inquiries` through `/api/v1` with `page` (`contact` / `home` / `media-insights`), the fields, `lang` (`<html lang>`) and `pageUrl`. Inquiry types send their key; meeting options send the text shown. The Home form's phone is sent with the design's country code in front (`+31 …`) unless the visitor typed a `+` number. The Media form has no person-name field, so the outlet / company name is sent as `name` and `company`.
- Feedback is the design's: "Sending…", then "✓ Message Sent" for 3 seconds and the form is cleared. Problems (missing name, bad email, no inquiry type, a closed form, 429 "Too many requests…") are listed under the button and the fields are outlined.
- Product "Request a quote" still links to the Contact page (`/contact?product=&sku=`); the API's product quote (`product: { slug, sku, quantity }`) isn't wired yet.

### Admin: Services, Products, Product Catalog

- **Services** (`/admin/services`): services by division; create (slug suggested from the title), settings (slug, division, position), delete. **Import website services** creates the built-in services that don't exist yet, with their card and page as English drafts. Each service opens in the page editor (`/admin/services/<id>`, `PageEditor` with `serviceEditorApi`), previewed by the website's own renderers (`/cms-preview/service`). Hiding the card section takes the whole service off the website.
- **Product Catalog** (`/admin/catalog`): category groups and categories, certifications, attributes with their values, and detail labels; names per language (English required), reorder with ↑/↓, and the API's "used by products" message when a delete is refused.
- **Import website products** (Products list) creates the 12 products the designed catalogue shows as English drafts, after adding the category groups, categories, certifications and "Used in" label its filters show (items with the same slug are reused). Data: `app/(site)/_components/pages/global-agriculture/builtInProducts.ts`. The design has no prices or volumes, so they get price on request, volume from 0 MT and the product template's origin, certification and text: review before publishing.
- **Products** (`/admin/products`, `/admin/products/new`, `/admin/products/<id>`): list with filters and row actions (duplicate, archive/unarchive, delete for never-published products). The form is one Save for the whole product: General, Content (a tab per language), Media (thumbnail, gallery, PDFs) and Variants (pick 1-3 attributes and their values; a row per combination, existing rows keep their id). Prices are typed as `480.00` and sent in cents. Only languages whose text changed are sent. Publish / submit / reject / unpublish work per language. A stale version (409) offers Reload; removing variants that are live asks for confirmation (`confirmRemovals`). Preview renders the website's product page with drafts (`/cms-preview/product`).
- **Inquiries** (`/admin/inquiries`, `/admin/inquiries/<id>`; the old `/admin/leads` redirects): the inbox of every website form. Tabs per source with counts, status filter, search, date range and **Export CSV** with the same filters (`inquiries.csv`). The detail shows the contact (mailto / tel), inquiry type, meeting, product / SKU / quantity, message, language / country / page, a notes timeline with Add note (the first note moves a new inquiry to In progress), a status dropdown and a permanent Delete. The menu badge is the number of new inquiries, checked every minute.
- **Articles** (`/admin/articles`, `/admin/articles/new`, `/admin/articles/<id>`): list with search, category, status and per-language state filters, language chips and live state; archive / restore, delete for never-published articles. A **Categories** tab manages the website's filter tabs (name per language, reorder, deactivate, delete when unused). The form has the shared fields (category, cover image, author, address) and the text per language: title, excerpt, a block editor for the body and SEO. Only languages whose text changed are sent; "Remove <language> text" sends `null`. Submit / publish / reject / unpublish per language; a stale version (409) offers Reload. Preview renders the website's article page with drafts (`/cms-preview/article`). **Add sample articles** (Articles list, shown while any are missing) creates 4 ready-written English drafts and the design's 4 categories; the site pictures they use are uploaded to the Media library first (an earlier upload with the same title is reused). Content: `app/(admin)/_lib/sampleArticles.ts`.
- The `[id]` editor routes set `instant = false`: ids exist only at runtime, and the admin shell reads the URL.
- Media: PDFs (`kind=document`, up to 20 MB) can be uploaded and picked.

### Admin: Inner Pages

`/admin/pages` lists the CMS pages (`GET /admin/pages`) and `/admin/pages/<key>` opens the section editor. The home page editor and this editor are one component (`PageEditor`): the region picker and inheritance appear only on regional pages (the home page). Forms come from `SCHEMAS` in `app/(admin)/_lib/cms.ts`, one entry per section type.

- **Import website content** saves the built-in content into the empty sections as drafts (English only), so a page can go live without retyping it. An empty section also offers "Start from the website's current content".
- The editor URL is prerendered for each key in `INNER_PAGE_KEYS` (`app/(admin)/_lib/cms.ts`). A page the API adds later needs its key there.
- **Preview.** For a connected inner page, the preview is the website itself: an iframe loads `/cms-preview/<key>` (not indexed), the editor posts it the draft sections and unsaved edits (`app/(site)/_lib/previewProtocol.ts`), and it renders them with the page's own renderers and CSS. A section whose content is incomplete shows a note instead. The home page and inner pages the website doesn't read yet use the simplified preview (`PreviewSection`).
- **Fields.** Forms follow the API's section types, minus the fields a section's website design doesn't show (`DESIGN_FIELDS` in `app/(site)/_components/pages/designFields.ts`). Hidden fields that already hold content keep it when saving.

## What is real vs mock

| Screen | Data |
| --- | --- |
| Login, forgot / reset password, Account (change password) | API |
| Regions, Languages, Home Page and Inner Pages editors, Media library, Services, Products, Product Catalog, Articles, Inquiries | API |
| Admin dashboard figures, Campaigns, Donations, Users, other modules | Mock data (no API yet) |
| Home page (`/` and regional landing pages) | API (`/public/home-page`), with built-in fallback |
| About Us, Partners & Clients, Why Choose Us, Careers, Global Strategy, Awards, Testimonials, Partner With Us, Sustainability & ESG, Social Responsibility, Roadmap, Thought Leadership, AI & Innovation Lab, Media & Press Releases, Magazine, Global Presence, Donations, Contact, Product & Services, Global Agriculture, Services, Industries We Serve | API (`/public/pages/<key>`), with built-in fallback |
| Service pages (`/services/<slug>`) and the Services page cards | API (`/public/services…`); the 12 built-in services until one is published |
| Product catalogue (`/global-agriculture`) and product pages (`/products/<slug>`) | API (`/public/products…`); the static catalogue until a product is published. `/product-details` stays static |
| Thought Leadership list and article pages (`/articles/<slug>`) | API (`/public/articles…`, `/public/article-categories`); the placeholder list until an article is published |
| Contact, Home and Media & Insights forms | API (`POST /public/inquiries`) |
| Other website pages, sign-up, other forms | Static content; forms are not connected to an API yet |

## Known gaps on the backend

- Media `url` in API responses is the API's internal address (`http://localhost:4012/…`). The admin ignores it and saves `NEXT_PUBLIC_MEDIA_ORIGIN + path`.
- Uploads occasionally fail with a 500 on valid files; the admin retries once automatically.
- No endpoint lists sections waiting for review across regions, so approval happens inside the editor per region and language.
- The API ignores `X-Forwarded-For` / `X-Real-IP` (rechecked 2026-11-18), so `/public/locale` reports the server's location until the backend trusts the forwarded IP. `GEO_REDIRECT` must stay off until then.
- Login `clientIp` is sent, but the API uses it only when the connection IP has no known country. Behind this app, the connection is always the server, which has one, so login history still shows the server's location. The backend should prefer `clientIp` (or a trusted `X-Forwarded-For`) for requests from this app.
- `/public/home-page?region=` is ignored when the caller's IP has a known country (checked 2026-11-18: `region=we` returns Global). Server-side requests therefore always get the server's region. Regional pages show the built-in content and log `[cms] asked for region …` until the backend treats `region` as authoritative.
- The home page seed content uses `/images/home/*` paths and `/pages/*.html` links from the old static site. The website maps them, but they should be updated in the CMS.
- No sign-up endpoint and no donor / partner / consumer roles yet.
- The API reference's product examples contradict its own rule: `"min": 440` next to "prices are in cents: 48000 = €480.00". The website and admin follow the rule (cents).
- The inquiry limit (5 per 10 minutes) is per IP, and the API keys it on the connection IP, ignoring `X-Forwarded-For` (checked 2026-11-26: requests with different forwarded IPs shared one limit). The browser posts through this app's `/api/v1` proxy, so in production **all visitors share the website server's limit: 5 inquiries per 10 minutes for the whole site**. The backend must trust the forwarded IP from the website server.
- "Request a quote" still links to the Contact page with the product and SKU in the query (the API's product quote isn't wired yet).
