# Bug Fixes: Invite Redirect, CAPA Owner Dropdown, Alcohol/Urine Test Split > **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:** Fix three bugs: invite emails redirect to localhost instead of live URL; CAPA "Assigned To" dropdown is empty; alcohol and urine test results share one field instead of two. **Architecture:** All three are small, independent fixes. Task 1 is one server route edit. Task 2 is one server page query edit. Task 3 requires a DB migration + form + API route changes (and adding display to incident detail). **Tech Stack:** Next.js App Router, Supabase (Postgres), Tailwind CSS. ## Global Constraints - Never commit `.env` or API keys. - Every DB mutation writes to `audit_log`. - RLS enforced at DB level — never rely on UI hiding. - Incident reference format: `SITE-YYYYMM-####`. - `NEXT_PUBLIC_APP_URL=http://64.176.82.100/ims` in production. --- ### Task 1: Fix invite email redirect URL **Root cause:** `app/api/admin/users/route.ts` line 63 falls back to `'http://localhost:3000'` when `NEXT_PUBLIC_APP_URL` is unset, so invite emails sent from local dev point to localhost. **Files:** - Modify: `app/api/admin/users/route.ts` **Interfaces:** - No interface changes — internal guard only. - [ ] **Step 1: Write the failing test** Add to `tests/api/admin/users.test.ts` (create file if it doesn't exist): ```typescript import { describe, it, expect, vi, beforeEach } from 'vitest' describe('POST /api/admin/users — invite path', () => { it('returns 503 when NEXT_PUBLIC_APP_URL is not set', async () => { const originalEnv = process.env.NEXT_PUBLIC_APP_URL delete process.env.NEXT_PUBLIC_APP_URL // Mock requireAdmin and createAdminClient so they succeed vi.mock('@/lib/auth/require-admin', () => ({ requireAdmin: async () => ({ supabase: { rpc: vi.fn() }, user: { id: 'admin-id' } }), })) vi.mock('@/lib/supabase/admin', () => ({ createAdminClient: () => ({ auth: { admin: { inviteUserByEmail: vi.fn() } }, from: () => ({ update: () => ({ eq: () => ({ error: null }) }) }), }), })) const { POST } = await import('@/app/api/admin/users/route') const req = new Request('http://localhost/api/admin/users', { method: 'POST', body: JSON.stringify({ email: 'test@example.com', name: 'Test' }), headers: { 'Content-Type': 'application/json' }, }) const res = await POST(req as any) expect(res.status).toBe(503) const body = await res.json() expect(body.error).toMatch(/NEXT_PUBLIC_APP_URL/) process.env.NEXT_PUBLIC_APP_URL = originalEnv }) }) ``` - [ ] **Step 2: Run test to verify it fails** ```bash npx vitest run tests/api/admin/users.test.ts ``` Expected: FAIL — test setup may need work, but intent is clear. - [ ] **Step 3: Apply the fix** In `app/api/admin/users/route.ts`, find the invite branch (around line 63): ```typescript // BEFORE const appUrl = process.env.NEXT_PUBLIC_APP_URL ?? 'http://localhost:3000' const { data: invited, error: inviteError } = await admin.auth.admin.inviteUserByEmail(email, { data: { full_name: body.name ?? '' }, redirectTo: `${appUrl}/api/auth/callback`, }) ``` Replace with: ```typescript // AFTER const appUrl = (process.env.NEXT_PUBLIC_APP_URL ?? '').replace(/\/$/, '') if (!appUrl) { return NextResponse.json( { error: 'Invite unavailable: NEXT_PUBLIC_APP_URL not configured' }, { status: 503 }, ) } const { data: invited, error: inviteError } = await admin.auth.admin.inviteUserByEmail(email, { data: { full_name: body.name ?? '' }, redirectTo: `${appUrl}/api/auth/callback`, }) ``` - [ ] **Step 4: Verify the happy path still works (manual check)** Confirm `NEXT_PUBLIC_APP_URL` is set in VPS `.env.production` or system env: ``` NEXT_PUBLIC_APP_URL=http://64.176.82.100/ims ``` - [ ] **Step 5: Commit** ```bash git add app/api/admin/users/route.ts git commit -m "fix(auth): fail fast when NEXT_PUBLIC_APP_URL unset for invite redirectTo" ``` --- ### Task 2: CAPA "Assigned To" — show all active users **Root cause:** `app/(protected)/hse/incidents/[id]/capa/new/page.tsx` filters users by `.eq('role', 'capa_owner')` only. Users without that exact role never appear. **Files:** - Modify: `app/(protected)/hse/incidents/[id]/capa/new/page.tsx` **Interfaces:** - No interface changes — `CapaForm` already accepts `users: Array<{ id, name, department }>`. - [ ] **Step 1: Write the failing test** This is a server component — verify by inspection. Open `app/(protected)/hse/incidents/[id]/capa/new/page.tsx` and confirm line 29–31 reads: ```typescript const { data: users } = await admin .from('users') .select('id, name, department') .eq('role', 'capa_owner') .order('name') ``` - [ ] **Step 2: Apply the fix** Replace the query: ```typescript // BEFORE const { data: users } = await admin .from('users') .select('id, name, department') .eq('role', 'capa_owner') .order('name') ``` ```typescript // AFTER const { data: users } = await admin .from('users') .select('id, name, department') .eq('active', true) .order('name') ``` - [ ] **Step 3: Verify manually** Navigate to any `capa_pending` incident → Add CAPA Action. Confirm all active users appear in the "Assigned To" dropdown. - [ ] **Step 4: Commit** ```bash git add "app/(protected)/hse/incidents/[id]/capa/new/page.tsx" git commit -m "fix(capa): show all active users in Assigned To dropdown" ``` --- ### Task 3: Split alcohol test and urine test into separate fields **Root cause:** `investigations` table has one `alcohol_test_result` column covering both tests. UI has one dropdown. Need two separate columns and two separate dropdowns. **Files:** - Create: `supabase/migrations/20260717000001_split_drug_test_results.sql` - Modify: `components/incidents/investigation-form.tsx` - Modify: `app/api/incidents/[id]/investigation/route.ts` - Modify: `components/incidents/incident-detail.tsx` (add display of both results) **Interfaces:** - POST/PATCH body gains: `urine_test_result: string | null` - `InvestigationForm` gains internal state: `urineTest: string` - `IncidentDetail` component reads `investigation.urine_test_result` #### Step 3a: Migration - [ ] **Step 1: Create migration file** Create `supabase/migrations/20260717000001_split_drug_test_results.sql`: ```sql -- Rename existing column to be explicit about alcohol-only -- Then add urine_test_result alongside it -- Existing data in alcohol_test_result is kept as-is (alcohol test result) ALTER TABLE investigations ADD COLUMN IF NOT EXISTS urine_test_result text CHECK (urine_test_result IN ('negative','positive','refused','pending')); ``` Note: `alcohol_test_result` already exists with the same constraint values — no rename needed; just add the new column. - [ ] **Step 2: Apply migration** ```bash npx supabase db push ``` Expected: `20260717000001_split_drug_test_results` applied successfully. - [ ] **Step 3: Commit migration** ```bash git add supabase/migrations/20260717000001_split_drug_test_results.sql git commit -m "feat(db): add urine_test_result column to investigations" ``` #### Step 3b: Update API route - [ ] **Step 4: Update POST handler** In `app/api/incidents/[id]/investigation/route.ts`, in the `POST` handler's `.insert({...})` block, add `urine_test_result` alongside `alcohol_test_result`: ```typescript // BEFORE (around line 47) alcohol_test_result: body.alcohol_test_result ?? null, ``` ```typescript // AFTER alcohol_test_result: body.alcohol_test_result ?? null, urine_test_result: body.urine_test_result ?? null, ``` - [ ] **Step 5: Update PATCH handler** In the same file, in the `PATCH` handler's `updateData` object (around line 95): ```typescript // BEFORE alcohol_test_result: fields.alcohol_test_result ?? null, ``` ```typescript // AFTER alcohol_test_result: fields.alcohol_test_result ?? null, urine_test_result: fields.urine_test_result ?? null, ``` - [ ] **Step 6: Commit API changes** ```bash git add app/api/incidents/[id]/investigation/route.ts git commit -m "feat(api): accept urine_test_result in investigation POST/PATCH" ``` #### Step 3c: Update investigation form UI - [ ] **Step 7: Split the single dropdown into two** In `components/incidents/investigation-form.tsx`: **Add state** (after `const [alcoholTest, setAlcoholTest] = useState('')` on line 40): ```typescript const [alcoholTest, setAlcoholTest] = useState('') const [urineTest, setUrineTest] = useState('') ``` **Update payload** in `handleSubmit` (around line 97): ```typescript // BEFORE alcohol_test_result: alcoholTest || null, ``` ```typescript // AFTER alcohol_test_result: alcoholTest || null, urine_test_result: urineTest || null, ``` **Replace the single dropdown UI** (around lines 215–227): ```tsx // BEFORE