phase-2: identity, from the landing hook to the profile screen
Flows A1 to A6 and E3 end to end. A visitor types a RUC on the landing page, sees their real filing dates, registers, verifies a six digit code, grants consent, completes a three step setup and lands on the first run screen, with the profile, consent and audit rows to show for it. API: public RUC lookup behind a token bucket (10/min/IP), the full /me surface (profile, dependents, consents, notification prefs, data export, account deletion), an append-only audit module that exports an insert and nothing else, and a PII module that is the only thing allowed near those tables. Deletion and consent revocation both freeze the account and drop every session, reusing better-auth's ban flag rather than adding a second notion of disabled. Nothing is destroyed yet: the purge is a job for phase 4. deadlineDigit is always derived server side, never accepted from the client. Web: landing with the RUC hook, registration, OTP verification, consent, the setup wizard, the profile screen with "Tus datos", and legal pages that ship as marked placeholders per COPY.md section 13. Money, Skeleton, Switch and EmptyState components added. The seed is now complete for identity: Maria at 4123456-1, filing digit 6 and day 19, with a dependant, consents and prefs; Carlos as an IVA-only company. Two real defects found by building the screens and fixed with tests: the OTP boxes dropped a digit because the handler fired effects inside a setState updater that React 19 invokes twice, and the switch knob rendered outside its track because translate-x-5.5 does not resolve. 232 vitest tests, 26 Playwright tests across mobile and desktop, coverage still 100% on the rules, typecheck and lint clean. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
80b10c958e
commit
0d7651b17c
@@ -0,0 +1,67 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/**
|
||||
* Read only access to the stack's database, used to assert the rows a flow was supposed
|
||||
* to write and to read the emailed verification code (which development prints to the
|
||||
* server console rather than sending). Only valid against a local SQLite stack.
|
||||
*/
|
||||
const DB_PATH =
|
||||
process.env['E2E_DB_PATH'] ?? fileURLToPath(new URL('../apps/api/data/app.db', import.meta.url));
|
||||
|
||||
function open(): Database.Database {
|
||||
return new Database(DB_PATH, { readonly: true, fileMustExist: true });
|
||||
}
|
||||
|
||||
function query<T>(run: (db: Database.Database) => T): T {
|
||||
const db = open();
|
||||
try {
|
||||
return run(db);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** better-auth stores the code as `<otp>:<attempts>` against the recipient's address. */
|
||||
export function readVerificationOtp(email: string): string {
|
||||
return query((db) => {
|
||||
const row = db
|
||||
.prepare('select value from verification where identifier = ? order by createdAt desc limit 1')
|
||||
.get(`email-verification-otp-${email}`) as { value: string } | undefined;
|
||||
if (!row) throw new Error(`no verification code was issued for ${email}`);
|
||||
return (row.value.split(':')[0] ?? '').trim();
|
||||
});
|
||||
}
|
||||
|
||||
export function readProfile(email: string): Record<string, unknown> | undefined {
|
||||
return query(
|
||||
(db) =>
|
||||
db
|
||||
.prepare(
|
||||
'select p.* from profiles p join user u on u.id = p.user_id where u.email = ?',
|
||||
)
|
||||
.get(email) as Record<string, unknown> | undefined,
|
||||
);
|
||||
}
|
||||
|
||||
export function readAuditActions(email: string): string[] {
|
||||
return query((db) => {
|
||||
const rows = db
|
||||
.prepare(
|
||||
'select a.action from audit_log a join user u on u.id = a.subject_user_id where u.email = ? order by a.created_at',
|
||||
)
|
||||
.all(email) as { action: string }[];
|
||||
return rows.map((row) => row.action);
|
||||
});
|
||||
}
|
||||
|
||||
export function readConsents(email: string): { kind: string; revoked: boolean }[] {
|
||||
return query((db) => {
|
||||
const rows = db
|
||||
.prepare(
|
||||
'select c.kind, c.revoked_at from consents c join user u on u.id = c.user_id where u.email = ?',
|
||||
)
|
||||
.all(email) as { kind: string; revoked_at: string | null }[];
|
||||
return rows.map((row) => ({ kind: row.kind, revoked: row.revoked_at !== null }));
|
||||
});
|
||||
}
|
||||
@@ -26,11 +26,11 @@ test.describe('sign in screen', () => {
|
||||
|
||||
// The en catalog exists for expats and international users (COPY.md section 0-EN),
|
||||
// so the root honours the browser language and falls back to es, the default.
|
||||
test('the root follows the browser language', async ({ browser }) => {
|
||||
test('the landing page follows the browser language', async ({ browser }) => {
|
||||
for (const [locale, expected] of [
|
||||
['es-PY', /\/es\/login$/],
|
||||
['en-US', /\/en\/login$/],
|
||||
['pt-BR', /\/es\/login$/],
|
||||
['es-PY', /\/es$/],
|
||||
['en-US', /\/en$/],
|
||||
['pt-BR', /\/es$/],
|
||||
] as const) {
|
||||
const context = await browser.newContext({ locale });
|
||||
const page = await context.newPage();
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { es } from '@impuestos/i18n';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { readAuditActions, readConsents, readProfile, readVerificationOtp } from './db';
|
||||
|
||||
/**
|
||||
* Golden path 1 (SPEC.md section 13): a stranger arrives at the landing page and leaves
|
||||
* with a working account, a consent record and a profile. Every step is the real thing,
|
||||
* including the six digit code, which is read back out of the database because
|
||||
* development prints it to the server console instead of sending it.
|
||||
*/
|
||||
test.describe('onboarding', () => {
|
||||
test('takes a new visitor from the landing page to their first run screen', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const email = `nuevo-${testInfo.project.name}-${Date.now()}@demo.local`;
|
||||
const password = 'una-contrasena-larga';
|
||||
|
||||
// A1 and A2: the landing hook answers with this taxpayer's real filing day.
|
||||
await page.goto('/es');
|
||||
await expect(page.getByRole('heading', { name: es['landing.hero.title'] })).toBeVisible();
|
||||
|
||||
await page.getByLabel(es['landing.hero.inputLabel']).fill('4123456-1');
|
||||
await page.getByRole('button', { name: es['landing.hero.cta'] }).click();
|
||||
|
||||
// Base ends in 6, so RULES.md puts the deadline on the 19th.
|
||||
await expect(page.getByText('19', { exact: false }).first()).toBeVisible();
|
||||
await page.getByRole('link', { name: es['landing.preview.cta'] }).click();
|
||||
|
||||
// A3: account creation, then the six digit code.
|
||||
await expect(page).toHaveURL(/\/es\/registro$/);
|
||||
await page.getByLabel(es['auth.register.email']).fill(email);
|
||||
await page.getByLabel(es['auth.register.password']).fill(password);
|
||||
await page.getByRole('button', { name: es['auth.register.submit'] }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/es\/verificar/);
|
||||
await expect(page.getByRole('heading', { name: es['auth.otp.title'] })).toBeVisible();
|
||||
|
||||
await expect.poll(() => safeOtp(email), { timeout: 10_000 }).toMatch(/^\d{6}$/);
|
||||
const otp = readVerificationOtp(email);
|
||||
// The first box takes the whole pasted code and spreads it across the six.
|
||||
await page.getByLabel('1', { exact: true }).fill(otp);
|
||||
|
||||
// A4: consent. The primary action stays disabled until data processing is granted.
|
||||
await expect(page).toHaveURL(/\/es\/consentimiento$/);
|
||||
const accept = page.getByRole('button', { name: es['consent.accept'] });
|
||||
await expect(accept).toBeDisabled();
|
||||
|
||||
await page.getByRole('switch', { name: es['consent.dataProcessing'] }).click();
|
||||
await expect(accept).toBeEnabled();
|
||||
await accept.click();
|
||||
|
||||
// A5: three steps.
|
||||
await expect(page).toHaveURL(/\/es\/configuracion$/);
|
||||
await page.getByLabel(es['setup.fullName']).fill('Nueva Contribuyente');
|
||||
await page.getByLabel(es['setup.docLabel']).fill('4123456-1');
|
||||
await page.getByLabel(es['setup.docLabel']).blur();
|
||||
await expect(page.getByText(es['setup.deadlineNote'].replace('{day}', '19'))).toBeVisible();
|
||||
|
||||
await page.getByRole('button', { name: es['common.continue'] }).click();
|
||||
await page.getByRole('button', { name: es['setup.oblig.iva.title'] }).click();
|
||||
await page.getByRole('button', { name: es['common.continue'] }).click();
|
||||
await page.getByRole('button', { name: es['setup.finish'] }).click();
|
||||
|
||||
// A6: the guided first run state.
|
||||
await expect(page).toHaveURL(/\/es\/inicio$/);
|
||||
await expect(page.getByRole('heading', { name: es['home.firstRun.title'] })).toBeVisible();
|
||||
await expect(page.getByRole('link', { name: es['home.firstRun.scan'] })).toBeVisible();
|
||||
|
||||
// The flow left the rows behind that it was supposed to.
|
||||
const profile = readProfile(email);
|
||||
expect(profile?.['full_name']).toBe('Nueva Contribuyente');
|
||||
expect(profile?.['ruc']).toBe('4123456');
|
||||
expect(profile?.['deadline_digit']).toBe(6);
|
||||
|
||||
expect(readConsents(email)).toContainEqual({ kind: 'data_processing', revoked: false });
|
||||
expect(readAuditActions(email)).toContain('consent.grant');
|
||||
expect(readAuditActions(email)).toContain('profile.create');
|
||||
});
|
||||
});
|
||||
|
||||
function safeOtp(email: string): string {
|
||||
try {
|
||||
return readVerificationOtp(email);
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { es } from '@impuestos/i18n';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { readAuditActions } from './db';
|
||||
|
||||
/** Flow E3. The trust screen: what we hold, and the two ways to take it back. */
|
||||
test.describe('profile', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/es/login');
|
||||
await page.getByLabel(es['auth.register.email']).fill('maria@demo.local');
|
||||
await page.getByLabel(es['auth.login.password']).fill('demo-maria-1');
|
||||
await page.getByRole('button', { name: es['auth.login.submit'] }).click();
|
||||
await expect(page).toHaveURL(/\/es\/inicio$/);
|
||||
});
|
||||
|
||||
test('shows the seeded identity, dependants and the data section', async ({ page }) => {
|
||||
await page.goto('/es/perfil');
|
||||
|
||||
await expect(page.getByLabel(es['setup.fullName'])).toHaveValue('Maria Gonzalez');
|
||||
await expect(page.getByLabel(es['setup.docLabel'])).toHaveValue('4123456-1');
|
||||
// Base ends in 6, so RULES.md puts her deadline on the 19th.
|
||||
await expect(page.getByText(es['vto.explainer'].replace('{digit}', '6').replace('{day}', '19'))).toBeVisible();
|
||||
|
||||
await expect(page.getByText('Lucas Gonzalez')).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole('heading', { name: es['profile.myData.title'], exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole('link', { name: es['profile.myData.export'] })).toBeVisible();
|
||||
});
|
||||
|
||||
test('adds and removes a dependant', async ({ page }) => {
|
||||
await page.goto('/es/perfil');
|
||||
|
||||
const name = `Prueba ${Date.now()}`;
|
||||
await page.getByLabel(es['setup.dependents.name'], { exact: true }).fill(name);
|
||||
await page.getByRole('button', { name: es['setup.dependents.add'] }).click();
|
||||
await expect(page.getByText(name)).toBeVisible();
|
||||
|
||||
await page
|
||||
.getByRole('listitem')
|
||||
.filter({ hasText: name })
|
||||
.getByRole('button', { name: es['common.remove'] })
|
||||
.click();
|
||||
await expect(page.getByText(name)).toBeHidden();
|
||||
|
||||
expect(readAuditActions('maria@demo.local')).toContain('dependent.create');
|
||||
expect(readAuditActions('maria@demo.local')).toContain('dependent.delete');
|
||||
});
|
||||
|
||||
test('the export downloads a file holding the profile', async ({ page }) => {
|
||||
await page.goto('/es/perfil');
|
||||
|
||||
const download = page.waitForEvent('download');
|
||||
await page.getByRole('link', { name: es['profile.myData.export'] }).click();
|
||||
const file = await download;
|
||||
|
||||
expect(file.suggestedFilename()).toMatch(/^impuestos-datos-\d{4}-\d{2}-\d{2}\.json$/);
|
||||
const stream = await file.createReadStream();
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of stream) chunks.push(chunk as Buffer);
|
||||
const data = JSON.parse(Buffer.concat(chunks).toString('utf8')) as {
|
||||
profile: { fullName: string } | null;
|
||||
account: { email: string };
|
||||
};
|
||||
|
||||
expect(data.account.email).toBe('maria@demo.local');
|
||||
expect(data.profile?.fullName).toBe('Maria Gonzalez');
|
||||
expect(readAuditActions('maria@demo.local')).toContain('data.export');
|
||||
});
|
||||
|
||||
test('deleting the account asks for the email before it will proceed', async ({ page }) => {
|
||||
await page.goto('/es/perfil');
|
||||
await page.getByRole('button', { name: es['profile.myData.delete'] }).click();
|
||||
|
||||
const confirm = page.getByRole('button', { name: es['profile.myData.deleteCta'] });
|
||||
await expect(confirm).toBeDisabled();
|
||||
|
||||
await page.getByLabel(es['profile.myData.deletePrompt'].replace('{email}', 'maria@demo.local')).fill('nope@demo.local');
|
||||
await expect(confirm).toBeDisabled();
|
||||
|
||||
// Stops short of confirming: this account is the showcase data for every other test.
|
||||
await page.getByRole('button', { name: es['common.cancel'] }).click();
|
||||
});
|
||||
});
|
||||
|
||||
/** The toggle knob used to render outside its track, which read as a broken control. */
|
||||
test.describe('switch', () => {
|
||||
test('keeps its knob inside the track in both states', async ({ page }) => {
|
||||
await page.goto('/es/login');
|
||||
await page.getByLabel(es['auth.register.email']).fill('maria@demo.local');
|
||||
await page.getByLabel(es['auth.login.password']).fill('demo-maria-1');
|
||||
await page.getByRole('button', { name: es['auth.login.submit'] }).click();
|
||||
await expect(page).toHaveURL(/\/es\/inicio$/);
|
||||
await page.goto('/es/perfil');
|
||||
|
||||
const toggle = page.getByRole('switch', { name: es['setup.oblig.iva.title'] });
|
||||
await expect(toggle).toBeVisible();
|
||||
|
||||
for (const _ of [0, 1]) {
|
||||
const track = await toggle.boundingBox();
|
||||
const knob = await toggle.locator('span').boundingBox();
|
||||
expect(track).not.toBeNull();
|
||||
expect(knob).not.toBeNull();
|
||||
expect(knob?.x ?? 0).toBeGreaterThanOrEqual(track?.x ?? 0);
|
||||
expect((knob?.x ?? 0) + (knob?.width ?? 0)).toBeLessThanOrEqual(
|
||||
(track?.x ?? 0) + (track?.width ?? 0),
|
||||
);
|
||||
await toggle.click();
|
||||
await page.waitForTimeout(250);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user