# Tenant Branding and Support v1 Migration Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Move all tenant branding and support presentation data in `tiar-webapp` to v1 endpoints or local source-code fallbacks, with zero `/v1.1` reads for those categories.

**Architecture:** Add a server-only v1 tenant adapter with typed normalizers for the flat branding and support contracts. Use the public branding endpoint for shell/metadata/PWA data and the authenticated support endpoint for the support page; merge neither response into the legacy organization object. On errors, return local defaults rather than calling `/v1.1`.

**Tech Stack:** Next.js App Router, React Server Components, TypeScript, Zod, Vitest, existing `requestV1` client.

**Spec:** `docs/superpowers/specs/2026-09-16-tenant-branding-support-v1.md`

## Global Constraints

- Branding source is `GET /v1/tenant/branding`; support source is `GET /v1/tenant/support`.
- `/v1.1/organizations` must not provide branding or support values.
- Support requests may use only the server-held `access_token` cookie; never expose or log it.
- Failed v1 requests fall back to local source-code defaults, never to `/v1.1`.
- Normalize `website_url` when the backend omits `https://`.
- Preserve existing UI and browser routes.
- Do not stage or modify the existing unrelated payment-method-label changes in the same commits.
- Do not commit until the user explicitly requests it.

## File map

- Create `src/services/v1/tenantAdapter.ts`: v1 branding/support response types, request functions, and field normalizers.
- Create `src/services/v1/tenantAdapter.test.ts`: isolated request-path, header, response-shape, URL-normalization, and failure tests.
- Create `src/lib/tenantPresentation.server.ts`: server-only resolver that obtains the support token, applies local defaults, and exposes safe presentation data.
- Create `src/lib/tenantPresentation.server.test.ts`: fallback and token-forwarding tests using injected adapter functions.
- Create or modify `src/lib/tenantPresentationDefaults.ts`: local branding/support defaults used only when v1 is unavailable.
- Modify `src/app/layout.tsx`, `src/app/manifest.ts`, `src/app/api/manifest/route.ts`, `src/app/api/pwa/icon/route.ts`, and `src/app/api/organization/logo/route.ts`: consume the branding resolver instead of `organization.branding` or `organization.avatar_url` for branding assets.
- Modify auth and page metadata files that currently use `organization.avatar_url` for icons: `src/app/(auth)/layout.tsx`, `src/app/(auth)/check-email/page.tsx`, `src/app/(auth)/onboarding/page.tsx`, `src/app/(auth)/otp-verify/page.tsx`, `src/app/(auth)/signin/page.tsx`, `src/app/(auth)/signup/page.tsx`, `src/app/(auth)/verify-email/page.tsx`, `src/app/(tiar)/page.tsx`, `src/app/(tiar)/wallet/page.tsx`, `src/app/(tiar)/sessions/page.tsx`, `src/app/(tiar)/map/page.tsx`, `src/app/(tiar)/scan/page.tsx`, `src/app/(tiar)/news/page.tsx`, `src/app/(tiar)/stations/page.tsx`, and `src/app/(tiar)/profile/page.tsx`.
- Modify support page and components: `src/app/(tiar)/support/page.tsx`, `src/components/support/Hero.tsx`, `src/components/support/ContactInfo.tsx`, `src/components/support/QuickActions.tsx`, and `src/components/support/Resources.tsx`.
- Create `src/components/support/supportViewModel.ts`: pure mapping from `TenantSupport` to the support component view model.
- Create `src/components/support/supportViewModel.test.ts`: support-field mapping and optional-link tests.
- Review branding consumers in `src/layout/DesktopNavBar.tsx`, `src/modules/chargepointModule/map/sections/MapContent.tsx`, `src/modules/sessionModule/detail/components/SessionReceiptOverlay.tsx`, and `src/modules/sessionModule/list/index.tsx`; replace only reads of legacy organization branding with the safe branding presentation object.
- Update `docs/migration/05-legacy-v1-1-endpoint-inventory.md` after verification to record that branding/support are no longer active legacy reads.

---

### Task 1: Add typed v1 tenant adapters

**Files:**

- Create: `src/services/v1/tenantAdapter.ts`
- Create: `src/services/v1/tenantAdapter.test.ts`

**Interfaces:**

- Consumes: `requestV1` from `src/services/v1/client.ts` and `V1Requester`-style injected request functions in tests.
- Produces:

```ts
export type TenantBranding = {
  displayName: string | null;
  logoUrl: string | null;
  primaryColor: string | null;
  secondaryColor: string | null;
  accentColor: string | null;
  backgroundColor: string | null;
  textColor: string | null;
  successColor: string | null;
  warningColor: string | null;
  dangerColor: string | null;
  fontFamily: string | null;
  themeTokens: Record<string, unknown> | null;
};

export type TenantSupport = {
  name: string | null;
  phone: string | null;
  email: string | null;
  requestChargerPhoneNumber: string | null;
  requestChargerWhatsappUrl: string | null;
  websiteUrl: string | null;
  address: {
    streetAndNumber: string | null;
    city: string | null;
    state: string | null;
    postalCode: string | null;
    country: string | null;
  } | null;
  socialMedia: {
    whatsappUrl: string | null;
    instagramUrl: string | null;
    linkedinUrl: string | null;
    youtubeUrl: string | null;
  } | null;
};

export function getTenantBrandingV1(requester?: V1Requester): Promise<TenantBranding>;
export function getTenantSupportV1(accessToken: string, requester?: V1Requester): Promise<TenantSupport>;
```

- [ ] **Step 1: Write failing branding request and normalization tests**

Assert that `getTenantBrandingV1` requests exactly `/v1/tenant/branding`, preserves the configured tenant headers through `requestV1`, maps every snake_case field, and converts an absent field to `null`.

- [ ] **Step 2: Run the focused test and verify RED**

Run:

```bash
npm test -- src/services/v1/tenantAdapter.test.ts
```

Expected: FAIL because the adapter and tests do not exist yet.

- [ ] **Step 3: Write failing support request and URL-normalization tests**

Assert that `getTenantSupportV1("token")` requests exactly `/v1/tenant/support`, sends `Authorization: Bearer token`, maps address/social fields, and normalizes `parkingplus.xyz` to `https://parkingplus.xyz`.

- [ ] **Step 4: Implement the minimal adapter**

Use the existing `requestV1` helper. Keep the access token in the request header only. Do not log request headers or response payloads.

- [ ] **Step 5: Add failure-shape tests and run GREEN**

Test that non-2xx errors are propagated as `V1ApiError` and that a malformed optional support field does not crash the whole mapper. Run the focused test again and expect all adapter tests to pass.

- [ ] **Step 6: Commit only the adapter group when explicitly authorized**

```bash
git add src/services/v1/tenantAdapter.ts src/services/v1/tenantAdapter.test.ts
git commit -m "feat(tenant): add v1 branding and support adapters"
```

Do not run this step unless the user explicitly requests committing.

### Task 2: Add server-side presentation resolution and local fallback

**Files:**

- Create: `src/lib/tenantPresentationDefaults.ts`
- Create: `src/lib/tenantPresentation.server.ts`
- Create: `src/lib/tenantPresentation.server.test.ts`

**Interfaces:**

- Consumes: `TenantBranding`, `TenantSupport`, `getTenantBrandingV1`, `getTenantSupportV1`, and `getServerAuthData`.
- Produces:

```ts
export type TenantPresentation = {
  branding: TenantBranding;
  support: TenantSupport;
};

export async function resolveTenantBranding(): Promise<TenantBranding>;
export async function resolveTenantSupport(): Promise<TenantSupport>;
```

- [ ] **Step 1: Write failing fallback tests**

Test these cases with injected adapter functions:

```ts
branding success -> returns v1 branding
branding failure -> returns local branding defaults
missing access token -> returns local support defaults without calling v1
support success -> returns v1 support
support failure -> returns local support defaults
```

- [ ] **Step 2: Run focused tests and verify RED**

Run:

```bash
npm test -- src/lib/tenantPresentation.server.test.ts
```

Expected: FAIL because the resolver/defaults do not exist.

- [ ] **Step 3: Add local defaults without legacy API calls**

Define safe defaults using existing local fallback values: `/images/favicon.ico`, fallback theme color `#0f172a`, fallback title `Tiar`, and the current support placeholders. Do not import `organizationService` or `resolveOrganization` into this resolver.

- [ ] **Step 4: Implement server-only resolution**

Add `"use server"` to the resolver module. Call `getServerAuthData()` only for support. Forward its `accessToken` to `getTenantSupportV1`; never return it. Use v1 branding without a bearer token.

- [ ] **Step 5: Run resolver tests and verify GREEN**

Run:

```bash
npm test -- src/lib/tenantPresentation.server.test.ts
```

Expected: PASS, including the assertion that missing support authentication does not issue a network request.

- [ ] **Step 6: Commit only the resolver group when explicitly authorized**

```bash
git add src/lib/tenantPresentationDefaults.ts src/lib/tenantPresentation.server.ts src/lib/tenantPresentation.server.test.ts
git commit -m "feat(tenant): add server presentation fallback"
```

Do not run this step unless the user explicitly requests committing.

### Task 3: Replace legacy branding reads in the application shell

**Files:**

- Modify: the root layout, manifest, PWA/logo routes, auth metadata, and page metadata files listed in the file map.
- Test: extend `src/lib/tenantPresentation.server.test.ts` or add focused metadata tests where existing test conventions support them.

**Interfaces:**

- Consumes: `resolveTenantBranding()` and its `TenantBranding` result.
- Produces: shell/metadata/PWA output whose logo, display name, colors, and theme never originate from `organization.branding` or `organization.avatar_url`.

- [ ] **Step 1: Inventory and write a failing static guard**

Add a test or verification script that reads the branding consumer files and fails if they contain `organization.branding` or use `organization.avatar_url` as a branding asset. The guard must allow unrelated organization identity reads such as `organization.enable_reservation`.

- [ ] **Step 2: Run the guard and verify RED**

Run:

```bash
npm test -- src/lib/tenantPresentation.server.test.ts
```

Expected: the guard identifies the current legacy branding reads.

- [ ] **Step 3: Migrate root layout and metadata**

Use `branding.displayName` for title text, `branding.logoUrl` for icon/logo selection, and `branding.primaryColor` (falling back to local theme defaults) for CSS palette/theme color. Keep `resolveOrganization()` only where the page truly needs organization identity/configuration.

- [ ] **Step 4: Migrate manifest and PWA/logo routes**

Use the v1 branding resolver in `src/app/manifest.ts`, `src/app/api/manifest/route.ts`, `src/app/api/pwa/icon/route.ts`, and `src/app/api/organization/logo/route.ts`. Preserve existing fallback assets and do not add a browser-visible token flow.

- [ ] **Step 5: Migrate remaining metadata and UI branding consumers**

Replace legacy avatar/logo/color reads in the listed auth/page metadata, navbar, map, receipt, and session-list consumers. Pass only the safe branding object to client components.

- [ ] **Step 6: Run static guard, typecheck, and diff checks**

Run:

```bash
npm test -- src/lib/tenantPresentation.server.test.ts
npx tsc --noEmit
git diff --check
```

Expected: the legacy branding guard passes, TypeScript passes, and no whitespace errors are reported.

### Task 4: Migrate the support page to the v1 support contract

**Files:**

- Modify: `src/app/(tiar)/support/page.tsx`
- Create: `src/components/support/supportViewModel.ts`
- Create: `src/components/support/supportViewModel.test.ts`
- Modify: `src/components/support/Hero.tsx`
- Modify: `src/components/support/ContactInfo.tsx`
- Modify: `src/components/support/QuickActions.tsx`
- Modify: `src/components/support/Resources.tsx`

**Interfaces:**

- Consumes: `TenantSupport` from `resolveTenantSupport()` and branding color from `resolveTenantBranding()`.
- Produces: `SupportViewModel` props that are independent of `Organization` and never read support fields from `/v1.1/organizations`.

- [ ] **Step 1: Write failing support mapping tests**

Define `SupportViewModel` and test `buildSupportViewModel(support, displayName, brandColor)` against these exact mappings:

```text
phone -> ContactInfo phone
email -> ContactInfo email
address.* -> ContactInfo address lines
request_charger_whatsapp_url -> live chat href
request_charger_phone_number -> request-charger contact
website_url -> website href
social_media.* -> resource hrefs
```

- [ ] **Step 2: Run focused tests and verify RED**

Run:

```bash
npm test -- src/components/support/supportViewModel.test.ts
```

Expected: the new mapping assertions fail against the current `Organization`-based props.

- [ ] **Step 3: Update page data loading**

Load `resolveTenantSupport()` in the server page. Pass `TenantSupport` and safe branding color/display name to components; do not pass `Organization` solely for support fields.

- [ ] **Step 4: Update component props and links**

Replace `Organization` props with focused support props. Render empty/missing optional links as hidden or disabled rather than using `#`. Keep the withdrawal-policy copy based on the local tenant display name.

- [ ] **Step 5: Normalize links and verify UI-safe output**

Ensure website links always have a scheme, WhatsApp links are used as received, and no undefined social URL is rendered as an anchor.

- [ ] **Step 6: Run support tests and static search**

Run:

```bash
npm test -- src/components/support/supportViewModel.test.ts src/services/v1/tenantAdapter.test.ts
npx tsc --noEmit
rg -n 'organization\.(phone|email|address|social_media|website_url)|organization\?\.(phone|email|address|social_media|website_url)' src/app/'(tiar)'/support src/components/support
```

Expected: adapter/type checks pass and the final search returns no legacy organization support reads in the support page/components.

### Task 5: Document and verify the migration boundary

**Files:**

- Modify: `docs/migration/05-legacy-v1-1-endpoint-inventory.md`
- Modify: `docs/migration/04-new-web-feature-validation.md`

**Interfaces:**

- Consumes: verified adapter and application-shell behavior from Tasks 1–4.
- Produces: auditable documentation that branding/support are v1-backed with local fallback and that unrelated organization migration remains separate.

- [ ] **Step 1: Update the legacy inventory**

Remove branding/support from active legacy usage and add the v1 endpoints, auth requirement, and local fallback behavior.

- [ ] **Step 2: Add validation evidence**

Record the observed `200` branding response, the authenticated support response, and the expected `401` behavior when support is called with an empty bearer token. Do not include real tokens or personal secrets.

- [ ] **Step 3: Run complete verification**

Run:

```bash
npm test
npx tsc --noEmit
git diff --check
rg -n 'v1\.1/organizations|organization\.(branding|avatar_url)' src/lib/tenantPresentation.server.ts src/services/v1 src/app/layout.tsx src/app/manifest.ts src/app/api/manifest src/app/api/pwa src/app/api/organization/logo src/components/support src/app/'(tiar)'/support
```

Expected: no `/v1.1` reference exists in the new tenant presentation adapter/resolver or support/branding consumers. Any remaining `/v1.1/organizations` reference must belong to an explicitly unrelated organization-data path, not branding/support.

- [ ] **Step 4: Commit only the tenant migration groups when explicitly authorized**

Use separate commits for adapter/resolver, shell branding, support UI, and docs. Before each commit, stage explicit paths and inspect `git diff --cached`; never use `git add .`.
