# Qwakk — Migration / Handoff Brief

Copy-paste this whole file into another AI dev tool as the project context. It describes what the app is, how it is built, what exists in the database, and what still hurts.

---

## 1. Product

**Qwakk** (earlier names: VORA, Technical Inspector, Bene Inspector AI) is an **AI Operating System for construction professionals**, focused on the Hungarian market.

Core loop: a technical inspector (műszaki ellenőr) walks a site → uploads dated photos → the AI writes a **műszaki ellenőri jegyzőkönyv** (technical inspection report) grounded in Hungarian regulations (esp. **191/2009. (IX. 15.) Korm. rendelet**) → the report is reviewed, approved, issued, exported to PDF/DOCX, and published back into the project knowledge base ("Brain").

Key product rules:
- Photo `taken_at` dates are mandatory — they drive progress comparison across visits.
- Report generation must use context from: previous reports of the project, weekly reports, and Brain documents/plans.
- Every finalized report can be published back to the Brain.
- Reports must be **white-label**: no markdown stars/hashes in output text.
- Roles are first-class (see §5); actions and AI drafts are role-dependent.

## 2. Stack

- **TanStack Start v1** (React 19, file-based routing under `src/routes/`, `createServerFn` for server logic, server routes under `src/routes/api/`), **Vite 8**, deployed to a **Cloudflare Worker** edge runtime.
- **Tailwind CSS v4** via `src/styles.css` (no tailwind.config.js), **shadcn/ui** + Radix, **lucide-react**, **framer-motion**.
- **TanStack Query** for data, **sonner** for toasts, **react-hook-form + zod** for forms.
- **Supabase** (Lovable Cloud) for Postgres + Auth + Storage.
- **Lovable AI Gateway** for LLM calls: `POST https://ai.gateway.lovable.dev/v1/chat/completions`, `Authorization: Bearer ${process.env.LOVABLE_API_KEY}`, OpenAI-compatible body. Model in use: `google/gemini-3-flash-preview`.
- Exports: `jspdf` + `html2canvas-pro` (aliased over `html2canvas`) for PDF, `docx` for DOCX, `pdfjs-dist` for plan rendering.
- MCP server exposed at `/mcp` via `@lovable.dev/mcp-js` (OAuth issuer = Supabase auth), tools: list-projects, list-inspections, list-findings, list-reports, get-report.

If migrating off TanStack Start: `createServerFn` → any RPC/server action; `src/routes/api/public/*` → public HTTP endpoints (they bypass site auth, so verify callers inside the handler).

## 3. Repo map

```
src/routes/
  __root.tsx                 shell, head meta, Toaster, supabase auth listener
  index.tsx                  marketing landing page (framer-motion, construction photos)
  auth.tsx / auth.index.tsx / auth.reset-password.tsx   dark branded auth
  accept-invite.tsx          token-based org invitation acceptance
  download-ready.tsx         export delivery helper page
  api/public/pdf-download.ts, api/public/docx-download.ts   same-origin download endpoints
  mcp.ts, [.mcp]/*, [.well-known]/*, [.]lovable.oauth.consent.tsx   MCP + OAuth
  _authenticated/route.tsx   auth gate (ssr:false, redirects to /auth)
  _authenticated/app.tsx     app shell + 14-module sidebar
  _authenticated/app.*.tsx   modules: index (dashboard), projects, inspections,
                             reports, drawings, hse, orgs, settings, activity,
                             assistant, portal + stubs (issues, knowledge, meetings,
                             ncr, photos, qaqc, regulations, snag)
src/lib/
  api.ts                     main Supabase data layer (~1.5k lines)
  hse-api.ts                 HSE data layer
  report-generation.server.ts  report AI pipeline (context gathering + prompts)
  hse-generation.server.ts   HSE findings AI pipeline
  reports.functions.ts, hse.functions.ts, ediary.functions.ts   server functions
  export-pdf.ts, export-docx.ts, export-download-center.ts, report-visible-download.ts
  role-catalog.ts, acting-role.ts, hse-catalog.ts   role & legal catalogs
  mcp/                       MCP server definition + tools
src/components/              panels: brain, ediary, hse, handover, progress-compare,
                             location-progress, project-roles, invite-members,
                             branded-report-header, export-progress, auth-shell
supabase/migrations/         19 SQL migrations (source of truth for schema)
```

## 4. Database (Supabase, all `public`, RLS enabled everywhere)

**Tenancy & people:** `organizations`, `organization_members`, `organization_invitations` (SHA-256 hashed tokens), `platform_admins`, `profiles`, `projects`, `project_members`, `project_role_assignments`.

**Inspection core:** `inspections`, `inspection_photos`, `inspection_checklists`, `inspection_checklist_items` (checklist UI removed but tables remain), `findings`, `corrective_actions`, `issues`, `issue_comments`.

**Reporting & knowledge:** `reports`, `report_revisions`, `templates`, `documents`, `knowledge_sources` (Brain), `handover_categories`, `handover_items`, `notifications`, `audit_logs`, `ediary_entries`.

**Branding:** `company_branding`, `company_signatories`.

**Plans:** `drawings`, `drawing_markups` (discipline-coded pins: Építészet / Elektromos / Gépész), `drawing_markup_comments`.

**HSE (munkavédelem):** `hse_inspections`, `hse_inspection_photos`, `hse_findings` (5×5 risk matrix: likelihood × severity → score/level), `hse_actions`, `hse_legal_sources`, `hse_legal_versions`.

**Enums:** `app_role`, `professional_role`, `professional_discipline`, `inspection_status`, `issue_status`, `report_status` (draft → in_review → approved → issued), `severity_level`, `template_kind`, `knowledge_source_type`, `handover_item_status`, `hse_risk_level`, `hse_inspection_status`, `hse_finding_status`, `hse_action_status`, `hse_confidence`.

**Security-definer helper functions** (used by RLS to avoid recursion): `is_org_member`, `org_role`, `has_org_role`, `is_platform_admin`, `is_project_member`, `project_role`, `effective_project_role`, `project_org`, `can_view_project`, `can_edit_project_content`, `can_manage_project`, `can_view_inspection`, `can_edit_inspection`, `inspection_project`, `can_view_report`, `can_approve_report`, `can_view_issues`, `can_view_handover_item`. Triggers: `handle_new_user`, `tg_org_add_creator` (auto-adds creator as owner — do NOT also insert client-side), `tg_set_updated_at`, `tg_block_self_role_change`, audit triggers per table.

**Storage buckets (private, signed URLs):** `inspection-photos`, `hse-photos`, `project-documents`, `knowledge-sources`, `organization-branding`, `report-files`.

Every table needs `GRANT SELECT, INSERT, UPDATE, DELETE ... TO authenticated;` plus `GRANT ALL ... TO service_role;` — RLS alone is not enough with PostgREST.

## 5. Roles

Organization roles (`app_role`) + professional roles (`professional_role`, e.g. `muszaki_ellenor`, `felelos_muszaki_vezeto`, `tervezo`, `beruhazo`, `kivitelezo`, `munkavedelmi_szakember`) and disciplines (`professional_discipline`). `role-catalog.ts` / `acting-role.ts` hold labels and permission mapping; the UI shows an "acting role" badge and gates report approval/issuance by role.

## 6. Design system

Dark-only. Midnight Indigo palette (navy backgrounds, electric indigo accent, amber accents on auth), display font **Urbanist**, body font **Epilogue** (loaded via `<link>` in `__root.tsx`, never `@import` in CSS). All colors are semantic tokens in `src/styles.css` — no hardcoded `text-white` / hex utilities in components. Avoid generic Inter/Poppins and purple-on-white AI aesthetics.

## 7. AI pipelines

1. **Report from photos** (`report-generation.server.ts`): gathers inspection photos (signed URLs + `taken_at`), previous reports, weekly reports, Brain documents, plans → prompts Gemini as a Hungarian technical inspector citing 191/2009 → returns structured JSON (per-photo observation, non-conformity, severity, corrective action, progress assessment vs. previous visits). Includes `extractJson` to strip markdown fences and repair truncated output, and a `clean()` pass to remove `*`/`#` for white-label output. Rendered by `StructuredReportView` in `app.reports.$reportId.tsx`.
2. **HSE findings** (`hse-generation.server.ts`): photo → hazard categories, 5×5 risk scoring, Hungarian legal citation, immediate + recommended action.
3. **E-diary** (`ediary.functions.ts`): role-specific e-napló draft entries from photos.

## 8. Known open issue (important)

**PDF/DOCX export delivery on Safari 18.1 / inside the Lovable preview iframe is unresolved.** Blob generation works (real report: ~21 MB PDF, ~1.5 MB DOCX). Delivery has been attempted via service worker (`public/export-download-sw.js`), hidden iframe/form POST, same-origin API routes, and programmatic anchor clicks — all get canceled or silently blocked in some environments. Current approach (`src/lib/report-visible-download.ts`): validate the blob (>5 KB, correct MIME), create an object URL, and render a **visible** "Download PDF/DOCX" anchor the user clicks themselves; warn when `window.self !== window.top`. **Not verified in real Safari** — only Chromium via Playwright. On a new platform, start from the visible-anchor approach and test in a standalone tab first; consider server-side rendering of the PDF to cut the 21 MB payload.

Other leftovers: several sidebar modules (issues, knowledge, meetings, ncr, photos, qaqc, regulations, snag) are 19-line placeholder stubs.

## 9. Environment variables

Client: `VITE_SUPABASE_URL`, `VITE_SUPABASE_PUBLISHABLE_KEY`, `VITE_SUPABASE_PROJECT_ID`.
Server: `SUPABASE_URL`, `SUPABASE_PUBLISHABLE_KEY`, `SUPABASE_SERVICE_ROLE_KEY`, `LOVABLE_API_KEY` (replace with your own OpenAI/Gemini key + endpoint if you leave Lovable).

## 10. Migration checklist

1. Copy `supabase/migrations/` in timestamp order into the new Supabase/Postgres project; recreate the 6 storage buckets as private.
2. Copy `src/` wholesale; regenerate `src/routeTree.gen.ts` by running the dev server (never hand-edit it).
3. Regenerate `src/integrations/supabase/types.ts` against the new project.
4. Swap the AI gateway URL/key if not on Lovable; keep the OpenAI-compatible request shape.
5. Set env vars, run `bun install`, `bun run dev`.
6. Smoke test in this order: sign up → create organization → create project → create inspection → upload dated photos → generate report → approve/issue → export PDF in a standalone browser tab.
