<!-- BEGIN:nextjs-agent-rules -->

# This is NOT the Next.js you know

This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.

This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.

<!-- END:nextjs-agent-rules -->

# TIAR Monetization rewrite — development guidelines

These instructions apply throughout this project. Act as a senior software engineer: prioritize correctness, readable code, maintainability, clear architecture, and appropriate performance. Read the relevant implementation before changing it. Keep this guidance aligned with user-approved changes as the application develops.

## Product goals and current scope

- Preserve the monetization experience: navigation, role-dependent behavior, layout, typography, branding, spacing, table density, forms, dialogs, charts, responsive behavior, and loading/empty/error states. A refactor is not a redesign.
- Read [README.md](README.md) for setup, the complete route inventory, fixture lifetimes, and known limitations. Resolve discrepancies against the current implementation and the requested task; report material uncertainty.
- When available, `../tiar-monetization` is the product, visual, and interaction reference. `../tiar-csms-rewrite` supplies relevant architecture and implementation patterns. Treat both as read-only unless the user explicitly requests changes there.
- Do not copy CSMS-specific navigation, device features, or unrelated API contracts. The user-approved auth integration is the exception: follow the CSMS authentication API contract documented in [AUTHENTICATION.md](AUTHENTICATION.md), including its endpoint/action behavior, headers, and `/users/me` session check; adapt it to the three supported Monetization roles and live-only auth behavior. Preserve Monetization's public URLs and inspect links, tabs, dialogs, and deep links beyond the sidebar.
- Current scope includes dashboard, locations/chargepoints and details, vouchers, analytics/ROI, financial reports/contracts, finance/pricing and transaction history, loyalty, engagement, investors/customers, payment configuration, profile, authentication, onboarding, and subscription/payment-result screens.
- Product and dashboard data use typed fixtures except for documented investor, customer/profile, voucher, payment, loyalty, subscription, and admin location API integrations. The admin Locations directory reads and mutates `/v1/admin/ocpp/locations`; the manager and investor location/report views remain fixture-backed. Dashboard access requires server-side TIAR authentication; top-up initiation, payouts, notifications, uploads, publishing, hardware commands, and infrastructure provisioning remain unconnected. Do not introduce external side effects as incidental implementation details.
- The authenticated `/organization/subscription` page loads plans, previews checkout, creates subscriptions, and shows the tenant's current contract and setup invoice status. Pending setup invoices are handled by an admin; this page does not collect card details or process the invoice. The standalone `/subscription` portal and its success/failure screens remain local previews. Monet API values are authoritative for plan prices and connector limits. The price sheet may supply additional pricing terms and optional one-time references that the plans API does not return; enter one-time amounts only from the tenant's approved quote and never invent them.
- Authentication configuration and request mapping are documented in [AUTHENTICATION.md](AUTHENTICATION.md). When configuration is missing or invalid, auth screens report that service as unavailable and dashboard entry fails closed. In configured mode, the server validates the session and derives the dashboard role from it. Never simulate auth success or convert a failed auth request into a successful operation.
- Registration intentionally shows an unavailable screen. `/withdrawals` reflects an incomplete original screen and links to `/payment-channel?mode=payout`; the former `/pricing/withdrawals` URL redirects there. Do not describe these as completed live workflows or fill them with unrelated template features.
- The admin Locations map uses Google Maps when configured and falls back to an offline Indonesia map asset; both use live API coordinates. When enabled, Google Maps receives the displayed location coordinates. The browser Maps key is intentionally delivered to the admin map and must be restricted by referrer and API. Manager/investor location maps and detail/report views remain fixture-backed. Article editing currently uses plain text. Authenticated visual parity with the original is unverified. Preserve and report these limitations until a task explicitly addresses them.
- A later request can extend these boundaries. Implement that requested scope deliberately, update documentation, and keep fixture behavior clearly separated from connected behavior.

## Engineering principles

- **KISS:** choose the simplest implementation that satisfies the requirement. Prefer obvious, idiomatic code over clever abstractions.
- **YAGNI:** avoid speculative repositories, API clients, adapters, state stores, providers, factories, generic component registries, and infrastructure.
- **DRY with restraint:** extract meaningful reuse when it clarifies responsibilities. Do not abstract every repeated line or form field.
- Keep functions and components focused. Separate presentation, domain calculations, validation, formatting, data preparation, and external access. Split large feature views along actual responsibilities.
- Use meaningful names and preserve existing conventions. Keep changes scoped; explain important behavior changes and their tradeoffs.
- Add comments for non-obvious decisions. Handle errors explicitly; avoid silent catches, fabricated success, and blanket suppression of failures or warnings.
- Before adding a dependency, identify the concrete problem it solves better than existing tools. Keep `package.json` and the lockfile consistent; avoid unused template dependencies.
- Keep plans, audit notes, temporary scripts, screenshots, and generated QA reports outside the project unless the user specifically requests repository artifacts. Product documentation and source tests belong in the project.

## Stack and code organization

Use the existing Next.js App Router, React, strict TypeScript, Tailwind CSS v4, customized shadcn/Radix primitives, Lucide, and ApexCharts. Check `package.json` and the lockfile for installed versions; read the bundled framework documentation above before version-sensitive changes.

| Location                                         | Responsibility                                                                                               |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
| `src/app/(dashboard)`                            | Server route composition for monetization screens and route states                                           |
| `src/app/(auth)`                                 | Sign-in, OTP verification, and password setup/reset routes for configured auth                               |
| `src/app/api/auth`                               | Same-origin Route Handlers that validate and forward authentication requests server-side                     |
| `src/app/api/organization/users`                 | Same-origin investor create/edit handlers; credentials remain server-only                                    |
| `src/app/api/organization/investor-groups`       | Same-origin investor group and membership handlers                                                           |
| `src/app/api/pricing`                            | Same-origin Charging Pricing handlers; credentials remain server-only                                        |
| `src/app/(registration)`                         | Registration availability and onboarding routes                                                              |
| `src/app/(payment)`                              | Subscription checkout and payment-result preview routes                                                      |
| `src/features/<feature>`                         | Domain types, typed fixtures, validation/calculations, feature components, and feature-owned preview storage |
| `src/components/ui`                              | Customized accessible Radix/shadcn primitives                                                                |
| `src/components/shared`                          | Reusable tables, URL controls, fields, panels, status presentation, charts, and export dialogs               |
| `src/components/layout`                          | Dashboard composition, session-scoped role context, navigation, sidebar state, and theme controls            |
| `src/lib`                                        | Shared query, formatting, export, role, storage-shape, and `cn()` helpers                                    |
| `src/app/globals.css`, `public`, `src/app/fonts` | Semantic tokens, purposeful shared styles, assets, and local Outfit font                                     |
| `tests`                                          | Deterministic domain, query, validation, storage, and preview-transition tests                               |

Keep domain code near its feature and fixtures outside page components. Keep route files focused on composition. Do not introduce a monorepo, shared package platform, empty architectural folders, or unnecessary barrel exports. Use the `@/` alias for application imports; retain explicit `.ts` imports where Node tests require them.

## Next.js rendering and React

- Default to Server Components for pages, layouts, data preparation, and noninteractive presentation. Add `"use client"` for actual interactivity, browser APIs, or client-only libraries.
- Dashboard routes currently await `searchParams` and compose content through `DashboardPage`. Dashboard access requires a configured, validated server session. Derive the role from that session; URL role values cannot select an identity or bypass the guard. `DashboardPage` scopes the role context to authenticated dashboard content; do not wrap public auth routes in that provider.
- Do not move a URL-reading provider into the root layout or wrap the entire app in a broad Suspense fallback. This previously replaced initial page content with a loading fallback. Verify server HTML after changing rendering boundaries.
- Keep client boundaries reasonably small. A chart, table control, or dialog does not require turning its route into a Client Component. Pass Server Component content through client shells when appropriate.
- Choose rendering intentionally: URL-dependent dashboard content renders per request; public screens can remain static where appropriate. Do not add `force-dynamic`, cache directives, or SSR disabling across the application.
- Follow the installed Next.js version's async request APIs, including awaiting `params`, `searchParams`, and cookie access when introduced. Use framework navigation, metadata, and loading/error/not-found conventions.
- For page reads from connected data, call focused server helpers directly from Server Components rather than making HTTP requests to the application's own Route Handlers. Use same-origin Route Handlers for browser-triggered mutations; do not call upstream services from client components.
- Derive values from current props/state during render. Use effects to synchronize external systems, not to maintain redundant derived state. Clean up listeners, timers, and object URLs.
- Use stable domain IDs for relationships, selection, keys, and deep links. Renaming a chargepoint must not hide its sessions. Generate unique preview IDs with `crypto.randomUUID()`; array length is not an ID allocator.
- Keep genuine shared state in the existing narrow providers. Preserve sidebar collapse state and customer/chargepoint edits across client navigation. Do not introduce Redux, Zustand, or a query library without a concrete need.
- Avoid hydration mismatches and blanket warning suppression. Use memoization only when it addresses a demonstrated cost; run independent work concurrently where useful without breaking real dependencies.
- Retain `next/font/local` for Outfit. Reuse existing assets and use `next/image` with correct intrinsic dimensions, responsive sizes, aspect ratios, and loading priorities.
- Keep ApexCharts within its client-only dynamic boundary. Load PDF/Excel libraries only when an export requests them. Do not disable SSR for an entire screen to accommodate a widget.

## Types, URL state, and preview persistence

- Preserve strict TypeScript, `noUnusedLocals`, and `noUnusedParameters`. Avoid `any`, unchecked assertions, and unnecessary generic frameworks. Treat browser storage and future API payloads as unknown until validated.
- Keep fixtures deterministic, immutable, and representative of zero values, missing optional fields, empty results, failures, and long text. Maintain coherent IDs and relationships across locations, chargepoints, users, sessions, and reports.
- Presentation should consume typed data so server-side loading can replace fixtures without rebuilding the UI. Do not add speculative transport or repository layers; use the explicitly documented investor API boundary for that feature.
- Use URL parameters for bookmarkable search, filters, sorting, pagination, and tabs. Reuse `src/lib/list-query.ts`, `useQueryUpdate`, and existing feature validators. Validate allowed values, sort keys, dates/ranges, page size, and repeated parameters. Do not use URL parameters as authenticated identity.
- Preserve unrelated parameters when updating one control. Reset pagination when changing filters/search and apply the feature's established tab-reset behavior. Keep back/forward navigation, refresh, and direct links coherent.
- Use local state for temporary dialogs, form inputs, and selection. Do not persist a temporary interaction just to avoid understanding its lifecycle.
- Non-admin location previews, contracts, and ROI investments use feature-owned, tab-scoped `sessionStorage`. Admin location changes go through the live API. Customer and chargepoint records use shared in-memory providers; other previews may reset when their feature unmounts. Document any lifetime change.
- Validate complete stored shapes, including nested terms, participants, settlements, finite numbers, and unique IDs. Reuse the feature's `storage-validation.ts` and small `src/lib/shape.ts` helpers. Checking only an ID or that a field is an array is insufficient.
- Invalid or incompatible snapshots must fall back safely to fixtures. Handle unavailable storage explicitly and retain usable in-memory behavior. Version storage keys when the schema changes; never treat preview storage as real persistence.
- Never store passwords, real OTPs, tokens, merchant secrets, or other credentials in browser storage or fixtures.

## Session roles, fixture scopes, and financial correctness

- Supported session roles are `admin`, `site_manager`, and `investor`. Use `src/lib/preview.ts`, navigation definitions, and feature rules rather than duplicating ad hoc mappings. Auth requests accept only `admin`, `site_manager`, and `investor`; map the UI label `site-manager` to `site_manager` at the auth boundary. Do not reintroduce Operator as an authentication or session role.
- Preserve role-specific labels, visible controls, assigned-location scopes, and read-only behavior using the session-derived role context. URL role parameters cannot switch roles. UI visibility is never production authorization.
- Investor views use assigned fixture locations; Site Manager uses its single assigned location. Apply scope before filtering, aggregation, pagination, and export. Hidden navigation alone is not a data boundary or authorization check.
- Local approval, transfer-proof attachment, subscription outcomes, publishing, and command dialogs must clearly describe preview behavior. Validation must not be bypassed to make a preview succeed.
- Approval and payout are separate states. Preserve withdrawal transition rules, required rejection reasons, transfer-proof validation, and the `PREVIEW_ONLY` payout result. A proof image or approved preview does not establish a transfer.
- Keep currency, units, rounding, percent-versus-ratio conventions, and financial calculations in domain/format helpers. Preserve existing IDR/USD behavior and Jakarta timezone/date boundaries; do not inherit the developer machine's timezone.
- Never calculate from formatted strings or round intermediate values merely for display. Match verified domain precision and backend contracts before changing monetary representation; test zero values, boundaries, and invalid/nonfinite inputs.
- Contract settlement estimates currently support monthly terms covering the full selected period. Fixed monthly terms require one complete calendar month. Nonmonthly terms and changes within a period must fail explicitly until backend frequency/proration rules are established.
- Preserve settlement snapshot and transition rules: draft to locked, locked to draft or paid, and no mutation of paid snapshots. Do not invent legal/accounting allocation rules to fill a missing backend contract.
- Export the intended current-page, filtered, or selected records after role scoping. Keep nested fee/schedule data readable, CSV quoting/formula protection intact, and actual PDF/Excel file formats valid. Export raw typed values rather than scraped UI text.

## Styling, interaction, and accessibility

- Use centralized semantic CSS variables in `globals.css` for surfaces, text, primary/secondary, muted/accent, destructive, border/input/ring, sidebar, and charts. Keep financial/status meaning independent of tenant branding.
- Preserve monetization's sage branding, TIAR logos, Outfit typography, light/dark defaults, layout dimensions, density, radii, and shadows. Add tokens for actual needs; do not build tenant discovery or a theme-management platform incidentally.
- Use Tailwind consistently and `cn()` for conditional classes. Keep custom CSS purposeful and centralized. Avoid scattered brand hex values, duplicated long class strings, and additional styling systems without a reason.
- Reuse and customize existing Radix primitives for dialogs, sheets, menus, and other interactions. Default shadcn styling must not change the product's appearance.
- Preserve semantic tables, labels, native controls, validation messages, keyboard operation, focus visibility/trapping/restoration, and chart text alternatives. Use ARIA to expose actual names and states, not as a substitute for correct elements.
- Keep accessible names when the sidebar is collapsed, support keyboard access to its groups, and preserve mobile navigation/close behavior. Breadcrumbs and secondary actions must lead to existing routes; do not add CSMS routes such as `/sessions/[id]` without a product requirement.
- Keep simple forms and tables simple. Add a form/schema/table library only when the actual interaction complexity warrants it.
- Check desktop, tablet, and mobile layouts, including overflowing tables, long labels, filter controls, charts, forms, sheets, and dialogs. Avoid document-level horizontal overflow while retaining intentional table scrolling.
- Compare rendered output with the original when practical. Source inspection and a passing build do not prove visual fidelity. State when unavailable credentials/backend data prevent a comparison.

## Backend and security boundaries

Authentication requires server configuration and a validated session. Investor and customer/profile reads, admin-only voucher list/detail/create/update/delete, payment account/channel/fee management and transaction/withdrawal reads, loyalty settings/ledger access, and admin subscription management have scoped connected API features; other Monetization product data remains fixture-backed. Keep these boundaries explicit in implementation, UI copy, tests, and documentation.

- Keep authentication on the same-origin `/api/auth/*` boundary and preserve its tested `/v1/admin/auth/{action}` contract plus `/v1/admin/users/me` session validation. The browser must not call the upstream auth API directly.
- The only supported auth roles are API values `admin`, `site_manager`, and `investor`; the UI label `site-manager` maps to `site_manager`. Reject other values. Confirm upstream contract changes with API evidence before editing this mapping.
- Keep API tokens and secrets server-only. `MONETIZATION_API_BASE_URL`, `MONETIZATION_FORWARDED_HOST`, and `MONETIZATION_APP_NAME` must be supplied by the environment; do not invent a production endpoint, forwarded host, or app name. Google Maps is the explicit browser-key exception: read `GOOGLE_MAPS_API_KEY` and `GOOGLE_MAPS_ID` server-side, pass them only to the Admin Locations map, and restrict the key by referrer and enabled API. Never read or copy real `.env` values, production endpoints, or tokens from either reference into fixtures or client bundles. Commit only blank sanitized values in `.env.example`.
- Keep auth tokens in HttpOnly cookies (`SameSite=Lax`, `Secure` in production); do not expose them to client JavaScript, localStorage, or URL parameters. Validate same-origin requests, session claims, API `/users/me` status, and errors through the existing server boundary.
- When authentication configuration is absent or invalid, show an unavailable auth state and block dashboard entry. Never simulate OTP, login, recovery, reset, password setup, a session, or changed credentials. Keep product fixture interactions distinct from authentication and external operations.
- Put real authorization, tenant/location scoping, financial invariants, and mutation permissions on the backend. Validate each protected handler/action independently; URL roles and UI visibility are never production authorization.
- Use focused server access boundaries, validated inputs/outputs, safe user-visible errors, appropriate timeouts, and deliberate caching. Never share private tenant/session data across users. Keep authentication tokens out of client JavaScript and browser storage.
- Treat duplicate requests, retries, idempotency, and concurrent state changes explicitly for financial mutations. Distinguish request acceptance, approval, settlement, and verified payment completion.
- Never convert an API failure into simulated success. A fixture interaction must remain clearly local; an integrated path must surface its failure. Keep automated tests independent of live services and secrets.
- Keep Organization Investors within the user-service and Postman contracts. The main Investors directory uses paginated `GET /v1/admin/users` with `role=investor` and the organization code derived from the validated session; the API's `result` contains users and `pagination` contains the page metadata. Investor Groups are a separate directory loaded from `GET /v1/admin/tenant/investor-groups` and each group's `GET /v1/admin/tenant/investor-groups/:id`. Memberships add group labels to investor records but do not determine which users appear in the main Investors directory. Create/edit investor accounts through same-origin `POST /api/organization/users` and `PATCH /api/organization/users/[id]`, forwarding to `/v1/admin/users` and `/v1/admin/users/:id`. Group writes use `POST /v1/admin/tenant/investor-groups` and `PATCH /v1/admin/tenant/investor-groups/:id` with exactly `{name, active}`; add membership with `POST /v1/admin/tenant/investor-groups/:groupId/users` and exactly `{user_id}`; remove membership with `DELETE /v1/admin/tenant/investor-groups/:groupId/users/:userId`. The add-member picker uses the paginated users endpoint filtered to active investors in the validated organization, excludes current group members, and rechecks eligibility server-side before adding. Require a validated admin session and verify the group/member relationship in the authenticated tenant before membership mutations. The collection has no saved response examples for these reads; the user-service implementation confirms the users-list pagination envelope, while group detail parsing expects `result.users`; treating an omitted `users` field as empty remains an assumption until confirmed with a sanitized API response. Do not infer other response schemas from endpoint names.
- The investor page is administrator-only. Validate the session through the existing `/v1/admin/users/me` check before trusting token claims; derive tenant and organization codes from that validated session token, validate upstream data before rendering, and scope edits to an investor in the same organization before sending PATCH. Do not pass access tokens or organization scope into client JavaScript. Keep preview records isolated from the connected API, and keep investor preview edits clearly labeled as local.
- Current investor-account write fields are first name, last name, email, phone, and active status on create; first name, last name, and active status on edit. Send the API role as `investor`. Manage group membership only through the documented investor-group endpoints; do not add unsupported profile/address fields or group fields to user payloads.
- When querying a database, use parameterized queries, select needed columns, avoid N+1 work and unnecessary scans, and paginate/batch large results. Use suitable indexes and inspect query plans for performance work. Keep transactions short and migrations compatible with existing data.
- Avoid unsafe deserialization, raw HTML from untrusted content, arbitrary upstream destinations, and unsafe shell execution. Validate local file type/size, manage preview URLs, and keep local file selection separate from an actual upload.

## Verification, documentation, and cleanup

Use Node.js 22.18 or newer and the npm lockfile. From this project directory:

```bash
npm ci
npm run dev -- --port 3002
npm test
npm run lint
npm run typecheck
npm run build
# Run the production build when needed:
npm start -- --port 3002
```

- Add/update deterministic tests for changed behavior and meaningful failure paths: queries, role scope, validation, calculations, storage corruption, and preview transitions. Current unit tests use Node's built-in runner and TypeScript support; preserve that setup unless there is a concrete need to change it.
- For code changes, run relevant tests, lint, typecheck, and a production build. For UI changes, also verify rendered behavior, deep links/refresh, responsive states, hydration, console output, and the target interactions. Include dark mode and affected role/state variants.
- Use available browser tooling for rendered QA; Playwright is already a development dependency. Confirm the app's URL/title/content, absence of framework overlays, relevant console health, screenshots, and visible results after interactions. When changing SSR boundaries, inspect production server HTML as well.
- Keep runtime screenshots/traces/reports and temporary browser scripts outside the project by default. Add durable source tests when appropriate; do not claim a repeatable browser test command exists unless it is actually configured.
- Investigate failures instead of weakening tests or disabling checks. `npm run typecheck` regenerates Next route types, which matters after route changes. Report any build fallback, skipped check, unavailable service, or unverified live flow.
- Documentation-only changes need content, path/link, command, and consistency checks; do not run the entire application test suite without a reason. Report exactly what was checked.
- Remove code, assets, dependencies, and tests only after checking imports, dynamic references, CSS variables, route conventions, storage, and test coverage. Explain removal of obsolete tests; preserve still-used fixtures and primitive helpers.
- Keep README and these guidelines aligned with actual behavior and new integrations. Preserve the generated Next.js guidance block at the top of this file; `CLAUDE.md` already points here.
- Before large changes, summarize the approach. Afterward, state what changed, why, how it was verified, and remaining risks or limitations. Never claim visual parity, successful real financial/account operations, or passing checks without evidence.
