# Navi Project Audit - 2026-05-04

## Executive Summary

Navi is now locally bootstrappable after this audit pass. The repo is a pnpm/Turbo monorepo with four apps, five shared packages, strong planning docs, a broad Prisma domain model, seeded UAE data, and a working local quality gate.

The important distinction: the foundation is green locally, but the product is still not an MVP. Many user-facing workflows are shells, placeholders, or mock-provider slices. The next phase should focus on turning the typed/scaffolded flows into real end-to-end behavior.

Latest full verification:

- `./bin/bootstrap.sh` passes end to end.
- Docker Postgres and Redis containers are running.
- Prisma generate, local DB sync, and UAE seed pass.
- `pnpm typecheck` passes: 14/14 tasks.
- `pnpm lint` passes: 9/9 tasks.
- `pnpm test` passes: 10/10 tasks.
- `pnpm build` passes: 9/9 tasks.
- API tests: 3 suites, 16 tests passing.
- Compiled API runtime starts from `apps/api/dist/main.js`.
- Runtime smoke passed: `GET http://localhost:4000/v1/health` returned `{"status":"ok","service":"navi-api",...}`.
- Mobile build is still a placeholder command: `echo 'use eas build' && exit 0`.

## Audit Scope

Checked source, config, scripts, docs, app routes, API controllers, Prisma schema, seed data, shared packages, generated artifacts, and quality gates.

Excluded generated/heavy folders from file review: `node_modules`, `dist`, `.next`, `.turbo`, `.expo`, coverage, and TypeScript build info.

Inventory snapshot from the audit sweep:

- 236 source/config/doc files under `apps`, `packages`, `docs`, and `bin`.
- 9,592 lines in those files at the time of the sweep.
- No `.git` repository exists in this folder, so there is no commit history or diff base to compare against.

## Fixes Completed During This Pass

- Fixed mobile signup typecheck failure in `apps/mobile/app/(auth)/signup.tsx` by omitting optional `locale` when absent instead of passing `undefined`.
- Ran ESLint auto-fix for `apps/api/src` to align imports with the configured `consistent-type-imports` rule.
- Fixed dashboard production build failure in `apps/dashboard/src/app/login/page.tsx` by wrapping `useSearchParams()` usage in Suspense.
- Tightened dashboard login redirect handling so `next` only accepts internal absolute paths.
- Fixed build hygiene by making clean scripts remove `tsconfig.tsbuildinfo`.
- Disabled incremental emit in build-producing TypeScript packages so `dist` cannot become half-stale.
- Moved shared package runtime entrypoints from `src/index.ts` to built `dist/index.js`.
- Changed shared package builds to CommonJS so compiled API code can require them at runtime.
- Added the missing API runtime dependency `@fastify/static` for Swagger/Fastify static assets.
- Added a `users/me` DTO mapper so API user responses match shared `@navi/types`.
- Confirmed `bin/bootstrap.sh` now completes.

## Project Shape

Apps:

- `apps/api`: NestJS + Fastify + Prisma + PostgreSQL API.
- `apps/website`: Next.js public website with `/en` and `/ar` locale routes.
- `apps/dashboard`: Next.js dashboard shell with auth middleware and login route handler.
- `apps/mobile`: Expo Router mobile app.

Shared packages:

- `@navi/types`: domain types.
- `@navi/validators`: Zod request schemas.
- `@navi/config`: constants and env helpers.
- `@navi/ui`: design tokens and formatting helpers.
- `@navi/api-client`: fetch client and endpoint wrappers.

Infrastructure/tooling:

- `pnpm-workspace.yaml`, `turbo.json`, root scripts, CI workflow, Docker Compose for local Postgres/Redis.
- `bin/bootstrap.sh` is the main local setup/verification script.
- `.env.example` files exist for root and all apps.

## API Feature Audit

API foundation present:

- Global `/v1` prefix.
- Swagger mounted at `/v1/openapi`.
- Problem-details error filter.
- Request context middleware.
- JWT auth middleware that resolves users, roles, permissions, and memberships.
- RBAC guard with `@Public()` and `@RequirePermissions()`.
- Audit interceptor for tagged controller methods.
- In-memory idempotency middleware for write requests.
- Prisma scoping helpers and tests.
- Provider abstraction modules for payment, AI, OCR, translation, SMS, email, and storage.

Public API endpoints:

- `GET /v1/health`
- `GET /v1/destinations`
- `GET /v1/destinations/:slug`
- `GET /v1/listings`
- `GET /v1/listings/:id`
- `GET /v1/emergency`
- `GET /v1/i18n/content`
- `POST /v1/auth/signup`
- `POST /v1/auth/login`
- `POST /v1/auth/refresh`
- `POST /v1/webhooks/:provider`

Protected API endpoints:

- `GET /v1/users/me`
- `GET /v1/users/me/access`
- `GET /v1/users`
- `GET /v1/roles`
- `GET /v1/permissions`
- `GET /v1/businesses`
- `POST /v1/bookings`
- `GET /v1/bookings/mine`
- `GET /v1/bookings/:id`
- `GET /v1/saved`
- `POST /v1/saved`
- `DELETE /v1/saved/:refType/:refId`
- `POST /v1/trip-planner/generate`
- `POST /v1/translator/image`
- `POST /v1/payments/intents`
- `POST /v1/refunds`
- `POST /v1/refunds/:id/approve`
- `GET /v1/refunds/mine`
- `GET /v1/audit-logs`

API gaps and risks:

- `POST /v1/auth/refresh` still throws `Refresh not implemented in Phase 1`.
- Signup creates `PENDING` users, but OTP send/verify endpoints are not implemented.
- No logout or logout-all endpoints.
- Refresh tokens are returned as JWTs but not persisted, hashed, rotated, or revoked.
- Env validation exists in `apps/api/src/config/env.ts`, but `loadApiEnv()` is not called during API boot.
- Request scoping helpers are tested, but most partner-scoped controller read endpoints are not implemented yet.
- Idempotency is process-local memory, not Redis/Postgres backed.
- Payment provider is mock-only; create intent exists, but confirm/capture/refund provider execution is not wired to API endpoints.
- Webhook HMAC uses `JSON.stringify(body)` instead of the true raw request body, so it is not ready for real providers.
- Webhook replay protection is documented but not backed by a durable event table.
- Dashboard/admin CRUD is mostly list-only on the API side.
- Categories are in the schema/docs but have no API module.
- Orders, payouts, reviews, support tickets, feature flags, content publishing, profile update, and business/listing mutations are not implemented as routes.
- Several API responses still return raw Prisma shapes, while shared DTO types expect normalized money fields. `users/me` is now mapped, but listings/bookings/payments/refunds/trips still need mappers. Example: Prisma returns `priceFromMinor`, `subtotalMinor`, and `totalEstimateMinor`, but `@navi/types` expects `priceFrom`, `subtotal`, and `totalEstimate` money objects.

## Database Audit

Present:

- Broad Prisma schema covering geography, identity/access, catalog, bookings, orders, payments, refunds, payouts, saved items, trips, reviews, support tickets, audit logs, translations, and feature flags.
- UAE seed data for country, emirates/cities, roles, permissions, emergency numbers, destinations, sample business, and sample listings.
- `UserRole` no longer uses nullable `businessId` inside a composite primary key; it now has a standalone `id`.

Missing:

- No committed Prisma migrations.
- No production migration/deploy script.
- No seed environment split for demo/dev/test/prod.
- No DB-backed integration test suite.
- No durable idempotency table or webhook event table.

Recommended:

- Create initial migration and switch deployment to `prisma migrate deploy`.
- Keep `db push` only for local/bootstrap convenience.
- Add a test DB profile with disposable seeded fixtures.
- Add DTO mappers between Prisma records and public API response types.

## Dashboard Feature Audit

Present:

- Auth-gated dashboard middleware.
- Login page posts to `/api/auth/login`.
- Next route handler calls `/v1/auth/login` and sets an HttpOnly session cookie.
- Logout route deletes the session cookie.
- Sidebar is permission-aware in shape.
- Pages exist for overview, bookings, listings, partners, businesses, users, roles, permissions, payments, reports, content, audit logs, and settings.

Gaps:

- `getCurrentPermissions()` still returns `['*']`, so every dashboard user sees super-admin navigation in dev.
- Dashboard pages are mostly static placeholders and do not fetch real API data.
- There are no dashboard API proxy routes beyond auth login/logout.
- Session refresh is not implemented.
- `/partners` links to `/memberships`, but that route does not exist.
- No forms for create/update/approve flows.
- No table filtering, pagination, detail pages, or role-aware partner views.
- Dashboard has no real tests.

Priority work:

- Replace `getCurrentPermissions()` with a server-side session/API lookup.
- Add API proxy helpers that forward the session access token.
- Wire users, roles, permissions, businesses, listings, bookings, payments/refunds, and audit logs.
- Add missing memberships page or remove that link.
- Add basic dashboard integration tests.

## Mobile Feature Audit

Present:

- Expo Router app with auth stack, tab stack, settings, emergency screen, service screens, listing detail placeholder, and trip planner routes.
- SecureStore-backed auth, onboarding, and locale stores.
- API client wired with access token, locale, idempotency key generation, and unauthorized sign-out.
- Login calls API, then `/users/me`, then persists session.
- Signup calls API, then routes to OTP.
- Tabs are auth-gated.
- Emergency screen fetches API data and falls back to seeded UAE emergency numbers.
- Locale state supports EN/AR and RTL flags.

Gaps:

- OTP verification screen is a UI stub and redirects to tabs without verifying or creating a session.
- Forgot password is a UI stub and does not call an API.
- Discover, bookings, saved, listing detail, service category screens, and trip planner result are mostly placeholder/loading screens.
- Trip planner form does not collect real inputs or call `POST /v1/trip-planner/generate`.
- Profile shows placeholder user/location content instead of `useAuth().user`.
- Profile/settings link to missing routes: `/settings/notifications`, `/settings/payment-methods`, `/settings/security`.
- Mobile `build` script is not a real native or EAS build.
- Mobile has no test coverage; Jest exits with `--passWithNoTests`.

Priority work:

- Implement OTP request/verify/reset endpoints on API, then wire mobile.
- Wire discover/listings, listing detail, bookings, saved items, and trip planner generation.
- Add the missing settings routes or remove the links.
- Replace placeholder profile copy with stored/current user data.
- Add Expo/EAS build configuration and real smoke tests.

## Website Feature Audit

Present:

- Locale-prefixed routes for `/en` and `/ar`.
- Pages for home, tourists, partners, destinations, about, contact, privacy, and terms.
- Basic Nav with language switch.
- Website builds successfully.

Gaps:

- Privacy and terms pages are placeholders.
- Contact page is static copy; no form or backend flow.
- Destination pages are static city cards, not API-backed content.
- Root `<html lang="en">` is static even for Arabic locale pages.
- No `sitemap.ts`, `robots.ts`, manifest, Open Graph images, canonical metadata, or hreflang metadata.
- No real UAE imagery or app-store links.
- Website has no tests.

Priority work:

- Add real privacy/terms copy in EN and AR.
- Add SEO assets and locale metadata.
- Add contact/partner lead capture flow.
- Pull destination/listing highlights from API or a static generated source.

## Shared Packages Audit

Strong parts:

- Package boundaries are clean and all shared packages build.
- Validators give useful request-level schemas for auth, booking, profile, and trip generation.
- UI package has design tokens and money/date/number formatters.
- API client centralizes headers, locale, auth token, idempotency key, and error shape.
- Runtime package entrypoints now point at built `dist` files instead of TypeScript source.

Main issue:

- Runtime API responses are not guaranteed to match the shared DTO types. This is the largest hidden integration risk because TypeScript passes while UI code can still receive differently shaped JSON.

Recommended:

- Add explicit API response DTOs or mapper functions.
- Add contract tests for API responses against shared schemas.
- Add validators for payments, refunds, saved items, listings filters, profile update, and dashboard forms.

## Documentation Audit

Strong:

- Product, architecture, operations, QA, strategy, and templates are unusually complete for this stage.
- Docs cover MVP phases, roles/permissions, sitemap, database/entity map, API module map, provider strategy, security/compliance, observability, infrastructure, DR, data platform, FinOps, and engineering process.

Stale or needs update:

- Older audit docs still mention blockers that are now fixed, especially JWT request context and `UserRole` nullable composite PK.
- Some docs describe features that are planned but not implemented, such as categories API, provider vendor selection, OpenAPI export, event schemas, and partner-scoped endpoints.

Recommended:

- Treat this file as the current audit source of truth.
- Update or archive older audit docs after the next implementation slice.
- Add an implementation matrix that marks each planned feature as `planned`, `scaffolded`, `wired`, `tested`, or `release-ready`.

## Generated And Cleanup Items

Generated/local files currently present and should not be treated as source:

- `.env` files at root and app level.
- `.bootstrap-bin/`
- `node_modules/`
- `dist/`
- `.next/`
- `.turbo/`
- `*.tsbuildinfo`
- `.DS_Store`

Cleanup candidates:

- Root `_tmp_3_*` empty files.
- Generated Prisma seed artifacts: `apps/api/prisma/seed.js`, `seed.d.ts`, and maps.

`.gitignore` covers generated folders, env files, TypeScript build info, `.bootstrap-bin`, root `_tmp_*` files, and generated `apps/api/prisma/seed.js*` artifacts.

## Testing And QA Audit

Passing now:

- API request context tests.
- API cross-partner scoping helper tests.
- Root typecheck/lint/test/build.

Weaknesses:

- API tests are helper-level only; no HTTP/controller tests.
- No DB-backed integration tests.
- No dashboard tests.
- No website tests.
- No mobile tests.
- No e2e tests.
- No visual/screenshot tests.
- No accessibility checks.
- No dependency audit or secret scan configured.

Recommended gates:

- API integration tests with seeded Postgres.
- Contract tests for every API client endpoint.
- Dashboard smoke tests for auth, sidebar permissions, and key pages.
- Website SEO/Lighthouse checks.
- Mobile route smoke tests with Maestro or Detox.
- Secret scanning and dependency audit in CI.

## Top Missing Work

1. Production auth lifecycle: OTP verify, user activation, refresh token persistence/rotation, logout, session revocation.
2. API response mapping/contracts so shared types match actual JSON.
3. Real dashboard data wiring and permission lookup.
4. Real mobile data wiring for discover, listing detail, bookings, saved, profile, and trip planner.
5. Payment flow beyond mock intent creation: confirm/capture/refund/webhook state changes.
6. Prisma migrations and deployment process.
7. Website legal/SEO/contact polish.
8. Missing routes: mobile settings subroutes and dashboard memberships.
9. Test coverage beyond helper-level API tests.
10. Real mobile build pipeline.

## Suggested Enhancement Roadmap

Phase 1 - Stabilize contracts:

- Add DTO mappers for listings, bookings, payments, refunds, trips, and users.
- Add contract tests for API client endpoint expectations.
- Update docs to distinguish scaffolded from wired features.

Phase 2 - Auth and sessions:

- Implement OTP request/verify and account activation.
- Persist hashed refresh tokens in `Session`.
- Rotate refresh tokens on use.
- Add logout/logout-all.
- Wire dashboard and mobile refresh behavior.

Phase 3 - User-facing MVP flows:

- Mobile discover/listing detail/saved/bookings/profile.
- Trip planner real form state and API generation.
- Dashboard users/roles/permissions/businesses/listings/bookings/audit data.
- Website contact and partner lead flows.

Phase 4 - Commerce:

- Booking availability and cancellation.
- Payment confirm/capture endpoint.
- Refund provider execution and state transitions.
- Durable idempotency.
- Real webhook raw-body verification and event persistence.

Phase 5 - Release hardening:

- Prisma migrations.
- Dockerfiles/deployment manifests.
- CI with DB services and integration tests.
- OpenAPI export.
- Security headers, CSP, secret scan, dependency audit.
- EAS/native mobile build.

## Recommended Next Task

Do not add broad new features yet. First fix the API contract layer:

1. Add DTO mappers for raw Prisma records.
2. Make `@navi/api-client` response types match real API JSON.
3. Add contract tests for `listings`, `bookings`, `payments`, `saved`, `trip-planner`, and `users/me`.
4. Then wire one complete vertical slice, preferably mobile login -> discover listings -> listing detail -> create booking with mock payment.

That gives the project a reliable path from green foundation to real MVP behavior.
