diff --git a/.dev.vars.example b/.dev.vars.example index 75b70cd..0b9cf1a 100644 --- a/.dev.vars.example +++ b/.dev.vars.example @@ -1,8 +1,5 @@ -OPENAI_API_KEY= -OPENAI_MODEL=gpt-5-mini AI_EXTRACTOR=mock # Auth (local dev: leave SESSION_SECRET unset to auto-login as the local user) SESSION_SECRET= -RESEND_API_KEY= TURNSTILE_SECRET_KEY= diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index ee90bf7..a8c479d 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -8,7 +8,7 @@ Use this folder for future development, commits, and deploys. The earlier Codex ## Live Beta -- URL: `https://cardcap.codylecates.workers.dev` +- URL: `https://cc.csi.run` - Worker name: `cardcap` - D1 database: `cardcap-db` - D1 database ID: `d3a74ece-fba4-4d92-a167-dfa21998c9ab` @@ -18,9 +18,8 @@ Use this folder for future development, commits, and deploys. The earlier Codex The Worker expects these secrets to be configured in Cloudflare: -- `OPENAI_API_KEY` - `SESSION_SECRET` (32+ random characters; rotating it signs everyone out) -- `RESEND_API_KEY` (sender domain must be verified in Resend, DKIM green) +Sign-in links are sent through the native Cloudflare EMAIL binding from `cardcap@notify.copperstateit.com`. The domain must be verified for Email Sending. - `TURNSTILE_SECRET_KEY` (paired with the public `TURNSTILE_SITE_KEY` var in wrangler.jsonc) `BETA_ACCESS_CODE` is retired and should be deleted from the Worker. @@ -33,8 +32,8 @@ Do not commit secret values. Local development secrets belong in `.dev.vars`, wh 2. Fresh start (wipes pre-auth beta data): `npx wrangler d1 execute cardcap-db --remote --command "DELETE FROM extraction_jobs; DELETE FROM contacts; DELETE FROM users;"` 3. Apply migrations: `npx wrangler d1 migrations apply cardcap-db --remote` 4. Create a Turnstile widget in the Cloudflare dashboard (Managed mode, hostname `cardcap.codylecates.workers.dev`); paste the site key into `TURNSTILE_SITE_KEY` in `wrangler.jsonc`, then `npx wrangler secret put TURNSTILE_SECRET_KEY` -5. `npx wrangler secret put SESSION_SECRET` and `npx wrangler secret put RESEND_API_KEY` -6. Confirm the `SENDER_EMAIL` var's address/domain is verified in Resend (currently `cody@copperstateit.com`; adjust the var if using a different sender) +5. `npx wrangler secret put SESSION_SECRET` +6. Verify the configured sender domain in Cloudflare Email Service 7. `npx wrangler secret delete BETA_ACCESS_CODE` 8. `npm run build && npx wrangler deploy` 9. Smoke: `/api/health` returns `ok`; full sign-in round-trip from a phone; check a corporate-style inbox's spam folder for the link; upload one card and confirm `extractionMode: "openai"`; download the iContact CSV and test-import it into iContact. @@ -77,9 +76,9 @@ npx cf auth login After deployment, verify: ```powershell -Invoke-RestMethod -Uri 'https://cardcap.codylecates.workers.dev/api/health' +Invoke-RestMethod -Uri 'https://cc.csi.run/api/health' ``` -Expected: JSON with `ok: true` and `extractor: openai`. +Expected: JSON with `ok: true` and `extractor: cloudflare`. -For full upload testing, unlock with the beta session, upload a real card image, confirm `extractionMode` is `openai`, then delete the temporary contact. +For full upload testing, unlock with the beta session, upload a real card image, confirm `extractionMode` is `cloudflare`, then delete the temporary contact. diff --git a/README.md b/README.md index e394ad7..493177c 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Phone-first business card capture for turning card photos into a searchable mini - Review the source card beside or above editable contact fields. - Save searchable contacts with email, phone, website, map, notes, tags, status, and next step. - Export CSV, vCard, JSON, standalone HTML, or an iContact-ready CSV for email-marketing imports. -- Run AI extraction in mock mode locally, or switch to OpenAI with an API key. +- Extract card photos with Cloudflare Workers AI, or use mock photo extraction locally. Paste a signature, business details, or a website to review and save a contact. - Abuse guards: Turnstile on sign-in, per-minute rate limits, and a 25-cards/day extraction quota per user. ## Local Development @@ -43,22 +43,14 @@ npm run build npm run deploy -- --dry-run ``` -## Turn On OpenAI Extraction Locally +## Cloudflare extraction in development -Copy `.dev.vars.example` to `.dev.vars`, then set: - -```text -OPENAI_API_KEY=your_key_here -OPENAI_MODEL=gpt-5-mini -AI_EXTRACTOR=openai -``` - -Restart the dev server after changing `.dev.vars`. +Sign in with `npx cf auth login`. The Worker uses the remote AI binding for photo and text extraction and the Browser Run binding for website lookup. Set `AI_EXTRACTOR=cloudflare` in `.dev.vars` for live photo extraction or `AI_EXTRACTOR=mock` for local photo fixtures. ## Auth in Local Dev - Leave `SESSION_SECRET` unset in `.dev.vars` to auto-sign-in as the local user (no email needed). -- Set `SESSION_SECRET` to any 32+ character string to exercise the real magic-link flow; with no `RESEND_API_KEY`, the sign-in link is printed to the dev-server console instead of emailed. +- Set `SESSION_SECRET` to any 32+ character string to exercise the real magic-link flow. Sign-in links use the Cloudflare EMAIL binding. - `TURNSTILE_SECRET_KEY` unset means the Turnstile check is skipped locally. ## Production deployment diff --git a/cloudflare.config.ts b/cloudflare.config.ts index 7269054..d107c35 100644 --- a/cloudflare.config.ts +++ b/cloudflare.config.ts @@ -1,9 +1,14 @@ import { bindings, defineConfig } from 'cf/config' +const sender = 'cardcap@notify.copperstateit.com' +const hostname = 'cc.csi.run' + export default defineConfig({ accountId: '584b3d4e1cb07efb65c315c7efcce589', worker: { name: 'cardcap', + domains: [hostname], + workersDev: true, entrypoint: './src/worker/index.ts', compatibilityDate: '2026-06-07', compatibilityFlags: ['nodejs_compat'], @@ -13,12 +18,13 @@ export default defineConfig({ }, observability: { enabled: true, redactQueryString: true, headSamplingRate: 1 }, env: { - AI_EXTRACTOR: bindings.text('openai'), - OPENAI_MODEL: bindings.text('gpt-5.4-mini'), - SENDER_EMAIL: bindings.text('cody@copperstateit.com'), + AI: bindings.ai({ dev: { remote: true } }), + BROWSER: bindings.browser({ dev: { remote: true } }), + AI_EXTRACTOR: bindings.text('cloudflare'), + SENDER_EMAIL: bindings.text(sender), + PUBLIC_ORIGIN: bindings.text(`https://${hostname}`), + EMAIL: bindings.sendEmail({ allowedSenderAddresses: [sender] }), TURNSTILE_SITE_KEY: bindings.text('0x4AAAAAADix1GoVxjHxnCXP'), - OPENAI_API_KEY: bindings.secret(), - RESEND_API_KEY: bindings.secret(), SESSION_SECRET: bindings.secret(), TURNSTILE_SECRET_KEY: bindings.secret(), // CF's D1 CLI reads ./migrations by default. diff --git a/e2e/access.e2e.test.ts b/e2e/access.e2e.test.ts index 7204f1a..eb2f2fc 100644 --- a/e2e/access.e2e.test.ts +++ b/e2e/access.e2e.test.ts @@ -16,7 +16,7 @@ let h: Harness beforeEach(async () => { h = await startHarness({ access: true }) - h.openai.mode = { + h.inference.mode = { kind: 'card', card: { name: 'Maria Okafor', company: 'Sunrise Realty Group', role: 'Broker', emails: ['maria@sunrise.example'], phones: ['(602) 555-0142'], website: '', address: '', tags: [], notes: '', confidence: 0.95, needs_review: false }, } diff --git a/e2e/browser/access.spec.ts b/e2e/browser/access.spec.ts index 15f16d4..356e9f9 100644 --- a/e2e/browser/access.spec.ts +++ b/e2e/browser/access.spec.ts @@ -29,7 +29,32 @@ async function upload(page: Page) { } test.beforeEach(async ({ request }) => { - await request.get('/__test/openai?mode=card') + await request.get('/__test/inference?mode=card') +}) + +test('reviewing and cancelling a website draft leaves the collection empty, saving retains its source', async ({ page }) => { + await openApp(page, uniqueEmail('capture')) + const company = 'Example Landscape' + const url = 'https://example.com/contact' + await page.route('**/api/contact-drafts', route => route.fulfill({ json: { contact: { + id: crypto.randomUUID(), name: '', company, role: '', email: '', phones: ['480-555-0101'], address: '', website: 'https://example.com', + tags: [], notes: '', status: 'New', nextStep: '', sourceImageKey: '', sourceImageUrl: '', + extractionConfidence: 0.9, needsReview: true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), + source: { url, text: company + ' 480-555-0101', checkedAt: new Date().toISOString() }, + } } })) + await page.getByLabel('Paste a signature, business details, or a website').fill('example.com') + await page.getByRole('button', { name: 'Review contact' }).click() + await page.getByRole('button', { name: 'Cancel' }).click() + await expect(page.getByRole('heading', { name: WELCOME_HEADING })).toBeVisible() + await page.getByRole('button', { name: 'Review contact' }).click() + await page.getByRole('button', { name: 'Save contact' }).click() + await expect(page.getByRole('status')).toContainText('Saved') + await page.reload() + await openContact(page, company) + await expect(page.getByRole('link', { name: 'View source page' })).toHaveAttribute('href', url) + const csv = await (await page.request.get('/api/export.csv')).text() + expect(csv).toContain(company) + expect(csv).toContain(url) }) test('first visit goes through the edge, returns to the same address, and shows no CardCap sign-in or password screens', async ({ page, baseURL }) => { diff --git a/e2e/browser/cardcap.spec.ts b/e2e/browser/cardcap.spec.ts index aa94f00..fee2715 100644 --- a/e2e/browser/cardcap.spec.ts +++ b/e2e/browser/cardcap.spec.ts @@ -4,7 +4,7 @@ import { PNG_BUFFER, PNG_HEIGHT, PNG_WIDTH } from '../fixtures' import { chooseFromMenu, openContact, WELCOME_HEADING } from './helpers' // Real Chromium against the built SPA + the real Worker on local Miniflare (see e2e/browser/server.ts). -// OpenAI/Resend are intercepted by the server; data is synthetic. +// Cloudflare inference and email are intercepted by the server; data is synthetic. const UPSTREAM_SECRET = 'upstream-internal-detail-abc123' @@ -37,7 +37,7 @@ async function downloadText(page: Page, itemName: string): Promise<{ text: strin } test.beforeEach(async ({ request }) => { - await request.get('/__test/openai?mode=card') + await request.get('/__test/inference?mode=card') }) test('upload → review/edit → save → reload → export keeps exactly the corrected values', async ({ page, request }) => { @@ -99,7 +99,7 @@ test('a failed extraction shows a safe message, leaves nothing behind, and a ret await signIn(page, request, uniqueEmail('alice')) const r2Before = await r2Keys(request) - await request.get('/__test/openai?mode=error') + await request.get('/__test/inference?mode=error') await uploadCard(page) const banner = page.locator('.banner.error') await expect(banner).toBeVisible() @@ -108,7 +108,7 @@ test('a failed extraction shows a safe message, leaves nothing behind, and a ret expect(await r2Keys(request)).toEqual(r2Before) await expect(page.getByRole('heading', { name: WELCOME_HEADING })).toBeVisible() - await request.get('/__test/openai?mode=card') + await request.get('/__test/inference?mode=card') await uploadCard(page) await expect(page.getByLabel('Name', { exact: true })).toHaveValue('Maria Okafor') expect((await r2Keys(request)).length).toBe(r2Before.length + 1) diff --git a/e2e/browser/layout.spec.ts b/e2e/browser/layout.spec.ts index f09e9c7..333748c 100644 --- a/e2e/browser/layout.spec.ts +++ b/e2e/browser/layout.spec.ts @@ -10,7 +10,7 @@ const uniqueEmail = () => `layout-${Date.now()}-${++counter}@example.test` async function signIn(page: Page, request: APIRequestContext) { const email = uniqueEmail() - await request.get('/__test/openai?mode=card') + await request.get('/__test/inference?mode=card') await page.goto('/') await page.getByRole('button', { name: 'Use email link' }).click() await page.getByPlaceholder('you@company.com').fill(email) diff --git a/e2e/browser/server.ts b/e2e/browser/server.ts index 944d24b..ccab34a 100644 --- a/e2e/browser/server.ts +++ b/e2e/browser/server.ts @@ -22,7 +22,7 @@ async function main() { const [email, seen] = decodeURIComponent(simCookie(req) || '').split('|') return email && Number(seen) === epoch ? email : '' } - h.openai.mode = { + h.inference.mode = { kind: 'card', card: { name: 'Maria Okafor', company: 'Sunrise Realty Group', role: 'Broker', emails: ['maria@sunrise.example'], @@ -67,11 +67,11 @@ async function main() { res.writeHead(link ? 200 : 404, { 'content-type': 'text/plain' }).end(link ? new URL(link).pathname + new URL(link).search : '') return } - if (url.pathname === '/__test/openai') { + if (url.pathname === '/__test/inference') { const kind = url.searchParams.get('mode') - if (kind === 'error') h.openai.mode = { kind: 'http-error', status: 500, body: 'upstream-internal-detail-abc123' } - else if (kind === 'garbage') h.openai.mode = { kind: 'garbage' } - else h.openai.mode = { kind: 'card', card: { name: 'Maria Okafor', company: 'Sunrise Realty Group', role: 'Broker', emails: ['maria@sunrise.example'], phones: ['(602) 555-0142'], website: 'sunrise.example', address: '12 Main St, Phoenix, AZ', tags: ['Luxury'], notes: 'Met at expo', confidence: 0.62, needs_review: true } } + if (kind === 'error') h.inference.mode = { kind: 'http-error', status: 500, body: 'upstream-internal-detail-abc123' } + else if (kind === 'garbage') h.inference.mode = { kind: 'garbage' } + else h.inference.mode = { kind: 'card', card: { name: 'Maria Okafor', company: 'Sunrise Realty Group', role: 'Broker', emails: ['maria@sunrise.example'], phones: ['(602) 555-0142'], website: 'sunrise.example', address: '12 Main St, Phoenix, AZ', tags: ['Luxury'], notes: 'Met at expo', confidence: 0.62, needs_review: true } } res.writeHead(200).end('ok') return } diff --git a/e2e/browser/session-states.spec.ts b/e2e/browser/session-states.spec.ts index d69a5c3..f8ea044 100644 --- a/e2e/browser/session-states.spec.ts +++ b/e2e/browser/session-states.spec.ts @@ -20,7 +20,7 @@ async function signIn(page: Page, request: APIRequestContext, email: string) { } async function withContact(page: Page, request: APIRequestContext) { - await request.get('/__test/openai?mode=card') + await request.get('/__test/inference?mode=card') await signIn(page, request, uniqueEmail()) await page.locator('input[type=file][accept="image/*"]').setInputFiles({ name: 'maria.png', mimeType: 'image/png', buffer: PNG_BUFFER }) await expect(page.getByLabel('Name', { exact: true })).toHaveValue('Maria Okafor') diff --git a/e2e/cardcap.e2e.test.ts b/e2e/cardcap.e2e.test.ts index 086907f..fb0d03f 100644 --- a/e2e/cardcap.e2e.test.ts +++ b/e2e/cardcap.e2e.test.ts @@ -21,7 +21,7 @@ let h: Harness beforeEach(async () => { h = await startHarness() - h.openai.mode = { kind: 'card', card: CARD } + h.inference.mode = { kind: 'card', card: CARD } }) afterEach(async () => { @@ -163,7 +163,7 @@ describe('upload → review/edit → save → reload → export', () => { describe('failed extraction', () => { scenario('an extraction service error fails the upload cleanly: no contact, no orphaned image, no upstream detail leaked', async () => { const alice = await h.signIn('alice@example.test') - h.openai.mode = { kind: 'http-error', status: 500, body: 'upstream-internal-detail-abc123' } + h.inference.mode = { kind: 'http-error', status: 500, body: 'upstream-internal-detail-abc123' } const { res, text } = await uploadCard(alice) expect(res.status).toBe(502) @@ -176,7 +176,7 @@ describe('failed extraction', () => { scenario('unparseable model output fails the upload cleanly with no contact and no orphaned image', async () => { const alice = await h.signIn('alice@example.test') - h.openai.mode = { kind: 'garbage' } + h.inference.mode = { kind: 'garbage' } const { res } = await uploadCard(alice) expect([422, 502]).toContain(res.status) @@ -188,10 +188,10 @@ describe('failed extraction', () => { scenario('after a failed extraction the user can retry the same card and get one correct contact', async () => { const alice = await h.signIn('alice@example.test') - h.openai.mode = { kind: 'http-error', status: 503, body: 'overloaded' } + h.inference.mode = { kind: 'http-error', status: 503, body: 'overloaded' } expect((await uploadCard(alice)).res.status).toBe(502) - h.openai.mode = { kind: 'card', card: CARD } + h.inference.mode = { kind: 'card', card: CARD } const retry = await uploadCard(alice) expect(retry.res.status).toBe(201) @@ -207,7 +207,7 @@ describe('failed extraction', () => { const noFile = await alice.request('/api/cards/upload', { method: 'POST', body: emptyForm() }) expect(noFile.status).toBe(400) expect(await h.r2Keys()).toEqual([]) - expect(h.openai.calls).toBe(0) + expect(h.inference.calls).toBe(0) }) }) diff --git a/e2e/contact-capture.e2e.test.ts b/e2e/contact-capture.e2e.test.ts new file mode 100644 index 0000000..d82cf2e --- /dev/null +++ b/e2e/contact-capture.e2e.test.ts @@ -0,0 +1,34 @@ +import { expect, it, vi } from 'vitest' +import worker from '../src/worker/index' +import type { Contact } from '../src/shared/types' +import { SESSION_SECRET, startHarness } from './harness' +import { utcDayStartIso } from '../src/shared/quota' + +it('limits capture per account, returns an unsaved draft, and preserves its source after review', async () => { + const h = await startHarness() + try { + const db = await h.mf.getD1Database('DB') + const alice = await h.signIn('capture@example.test') + const run = vi.fn(async () => ({ response: { company: 'Acme Studio', phones: ['480-555-0101'] } })) + const env = { DB: db, SESSION_SECRET, AI: { run } } as unknown as Env + const input = 'Acme Studio\n480-555-0101' + const capture = (cookie: string) => worker.fetch(new Request('https://cardcap.test/api/contact-drafts', { + method: 'POST', headers: { cookie, 'content-type': 'application/json' }, body: JSON.stringify({ input }), + }), env, { waitUntil() {} } as unknown as ExecutionContext) + expect((await capture('')).status).toBe(401) + const response = await capture(alice.cookie) + expect(response.status).toBe(200) + const { contact } = await response.json() as { contact: Contact } + expect(contact.source?.text).toBe(input) + expect(await (await alice.request('/api/contacts')).json()).toEqual({ contacts: [] }) + const saved = await alice.request('/api/contacts', { method: 'POST', body: JSON.stringify({ contact: { ...contact, needsReview: false } }) }) + expect(saved.status).toBe(201) + const list = await (await alice.request('/api/contacts')).json() as { contacts: Contact[] } + expect(list.contacts[0]).toMatchObject({ name: '', company: 'Acme Studio', needsReview: false, source: contact.source }) + await db.prepare('UPDATE capture_usage SET attempts = 25 WHERE day = ?').bind(utcDayStartIso()).run() + expect((await capture(alice.cookie)).status).toBe(429) + expect(run).toHaveBeenCalledTimes(1) + } finally { + await h.dispose() + } +}) diff --git a/e2e/harness.ts b/e2e/harness.ts index e0080b5..0b57c1c 100644 --- a/e2e/harness.ts +++ b/e2e/harness.ts @@ -11,13 +11,11 @@ import { FormData as MfFormData, Miniflare, Response as MfResponse } from 'minif const here = dirname(fileURLToPath(import.meta.url)) // Runs the real Worker (src/worker/index.ts) on local Miniflare with in-memory D1/R2. -// Outbound fetches (OpenAI, Resend) are intercepted: nothing leaves the machine and no paid AI call is made. +// Inference and outbound mail are intercepted: nothing leaves the machine and no paid AI call is made. export const SESSION_SECRET = 'e2e-session-secret-not-real' -export const OPENAI_HOST = 'api.openai.com' -export const RESEND_HOST = 'api.resend.com' -export type OpenAiMode = +export type InferenceMode = | { kind: 'card'; card: Record } | { kind: 'http-error'; status: number; body: string } | { kind: 'garbage' } @@ -44,7 +42,7 @@ export type AccessSim = { export type Harness = { access: AccessSim mf: Miniflare - openai: { mode: OpenAiMode; calls: number } + inference: { mode: InferenceMode; calls: number } trace: TraceEntry[] signIn(email: string): Promise anonymous(): Session @@ -66,7 +64,29 @@ export async function startHarness(options: HarnessOptions = {}): Promise = [] const accessKey = makeAccessKey('test-key-1') const access = { keys: [accessKey], published: [accessKey], jwksFetches: 0 } @@ -93,37 +113,35 @@ export async function startHarness(options: HarnessOptions = {}): Promise { + const message = await request.json() as { to: string; text: string } + sentEmails.push({ to: message.to, text: message.text }) + return MfResponse.json({ messageId: 'fixture-message' }) + }, + INFERENCE_FIXTURE: async (request: Request) => { + const { model, input } = await request.json() as { model: string; input: { messages: Array<{ content: unknown }> } } + if (!model.includes('llama-4-scout') || !JSON.stringify(input.messages).includes('data:image/')) { + return new MfResponse('Expected vision model and image input', { status: 400 }) + } + inference.calls += 1 + const mode = inference.mode + if (mode.kind === 'http-error') return new MfResponse(mode.body, { status: mode.status }) + return MfResponse.json({ response: mode.kind === 'garbage' ? 'invalid JSON' : mode.card }) + }, + }, outboundService: async (request: Request) => { - const url = new URL(request.url) - const body = request.method === 'GET' ? '' : await request.text() - if (url.hostname === RESEND_HOST) { - const payload = JSON.parse(body) as { to: string[]; text: string } - sentEmails.push({ to: payload.to[0], text: payload.text }) - trace.push({ at: new Date().toISOString(), kind: 'outbound', method: request.method, url: request.url, status: 200, note: 'resend intercepted' }) - return MfResponse.json({ id: 'email-test' }) - } if (request.url === JWKS_URL) { access.jwksFetches += 1 trace.push({ at: new Date().toISOString(), kind: 'outbound', method: request.method, url: request.url, status: 200, note: 'access jwks intercepted' }) return MfResponse.json({ keys: access.published.map((k) => k.jwk) }) } - if (url.hostname === OPENAI_HOST) { - openai.calls += 1 - const mode = openai.mode - trace.push({ at: new Date().toISOString(), kind: 'outbound', method: request.method, url: request.url, note: `openai intercepted (${mode.kind}); request body ${body.length} bytes` }) - if (mode.kind === 'http-error') return new MfResponse(mode.body, { status: mode.status }) - if (mode.kind === 'garbage') return MfResponse.json({ output_text: 'this is not json' }) - return MfResponse.json({ output_text: JSON.stringify(mode.card) }) - } trace.push({ at: new Date().toISOString(), kind: 'outbound', method: request.method, url: request.url, status: 599, note: 'UNEXPECTED outbound host blocked' }) return new MfResponse('blocked by e2e harness', { status: 599 }) }, @@ -170,7 +188,7 @@ export async function startHarness(options: HarnessOptions = {}): Promise ({ email: '', cookie: '', request: (path, init) => send('', path, init) }), async signIn(email) { diff --git a/e2e/password.e2e.test.ts b/e2e/password.e2e.test.ts index c6beb89..baac53f 100644 --- a/e2e/password.e2e.test.ts +++ b/e2e/password.e2e.test.ts @@ -7,7 +7,7 @@ let h: Harness beforeEach(async () => { h = await startHarness() - h.openai.mode = { + h.inference.mode = { kind: 'card', card: { name: 'Maria Okafor', company: 'Sunrise Realty Group', role: 'Broker', emails: ['maria@sunrise.example'], phones: ['(602) 555-0142'], website: '', address: '', tags: [], notes: '', confidence: 0.95, needs_review: false }, } diff --git a/migrations/0005_contact_sources.sql b/migrations/0005_contact_sources.sql new file mode 100644 index 0000000..5059093 --- /dev/null +++ b/migrations/0005_contact_sources.sql @@ -0,0 +1,11 @@ +CREATE TABLE IF NOT EXISTS contact_sources ( + contact_id TEXT PRIMARY KEY REFERENCES contacts(id) ON DELETE CASCADE, + capture_source TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS capture_usage ( + user_id TEXT NOT NULL, + day TEXT NOT NULL, + attempts INTEGER NOT NULL, + PRIMARY KEY (user_id, day) +); diff --git a/src/App.css b/src/App.css index 5230e7b..c0a4202 100644 --- a/src/App.css +++ b/src/App.css @@ -376,3 +376,11 @@ html { color-scheme: light dark; } @media (prefers-reduced-motion: reduce) { .app-shell *, .app-shell *::before, .app-shell *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; } } +.capture-form { display: grid; gap: 10px; width: 100%; max-width: 760px; margin-bottom: 28px; } +.capture-form label { font-weight: 600; } +.capture-form textarea { min-height: 64px; padding: 12px; border: var(--csi-border); border-radius: 6px; background: var(--csi-paper); color: var(--csi-ink); font: inherit; resize: vertical; } +.capture-form .btn { justify-self: start; } +.capture-evidence { padding: 16px; min-width: 0; color: var(--csi-ink); } +.capture-evidence small { display: block; margin-top: 6px; } +.capture-evidence p { white-space: pre-wrap; overflow-wrap: anywhere; } +.capture-match { flex-basis: 100%; } diff --git a/src/App.tsx b/src/App.tsx index 9dc78f5..36bd986 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -9,6 +9,7 @@ import { ApiError, apiGet, apiJson, apiUpload, relativeEdgeUrl } from './lib/api import { contactDisplayName, groupContactsByInitial, sortContactsByName } from './shared/contacts' import { contactNeedsReview, reviewedContact } from './shared/review' import type { Contact, ContactStatus } from './shared/types' +import { findDuplicateContact } from './shared/duplicates' function App() { const [contacts, setContacts] = useState([]) @@ -18,6 +19,8 @@ function App() { const [draft, setDraft] = useState(null) const [loading, setLoading] = useState(true) const [busy, setBusy] = useState(false) + const [captureInput, setCaptureInput] = useState('') + const [capturing, setCapturing] = useState(false) const [authRequired, setAuthRequired] = useState(false) const [userEmail, setUserEmail] = useState('') const [accessMode, setAccessMode] = useState(false) @@ -202,6 +205,22 @@ function App() { } } + async function prepareContact() { + setBusy(true) + setCapturing(true) + setError('') + setNotice('') + try { + const result = await apiJson<{ contact: Contact }>('/api/contact-drafts', 'POST', { input: captureInput.trim() }) + if (!signedOutRef.current) selectContact(result.contact) + } catch (err) { + fail(err) + } finally { + setBusy(false) + setCapturing(false) + } + } + async function handleImport(files: FileList | null) { const file = files?.[0] if (!file) return @@ -269,6 +288,7 @@ function App() { setSessionProblem(null) setUserEmail('') setContacts([]) + setCaptureInput('') setPasswordPanelOpen(false) setAccountPassword('') setAccountPasswordConfirm('') @@ -298,17 +318,18 @@ function App() { async function saveDraft() { if (!draft) return - if (!draft.name.trim()) { - setError('Name is required before saving.') + if (!draft.name.trim() && !draft.company.trim()) { + setError('Enter a name or company before saving.') return } setBusy(true) setError('') try { - const data = await apiJson<{ contact: Contact }>(`/api/contacts/${encodeURIComponent(draft.id)}`, 'PUT', { - contact: draft, + const data = await apiJson<{ contact: Contact }>(isPreview ? '/api/contacts' : `/api/contacts/${encodeURIComponent(draft.id)}`, isPreview ? 'POST' : 'PUT', { + contact: isPreview ? reviewedContact(draft) : draft, }) - setContacts((current) => sortContactsByName(current.map((contact) => (contact.id === data.contact.id ? data.contact : contact)))) + setContacts((current) => sortContactsByName([...current.filter(contact => contact.id !== data.contact.id), data.contact])) + if (isPreview) setCaptureInput('') selectContact(data.contact) setNotice('Saved.') } catch (err) { @@ -339,8 +360,8 @@ function App() { async function markReviewed() { if (!draft) return - if (!draft.name.trim()) { - setError('Name is required before marking reviewed.') + if (!draft.name.trim() && !draft.company.trim()) { + setError('Enter a name or company before marking reviewed.') return } const next = reviewedContact(draft) @@ -368,8 +389,9 @@ function App() { window.location.href = path } - const view: 'loading' | 'empty' | 'list' | 'edit' = - contacts.length === 0 ? (loading ? 'loading' : 'empty') : draft ? 'edit' : 'list' + const isPreview = Boolean(draft?.source && !contacts.some(contact => contact.id === draft.id)) + const duplicate = isPreview && draft ? findDuplicateContact(draft, contacts) : null + const view = draft ? 'edit' : contacts.length ? 'list' : loading ? 'loading' : 'empty' return (
@@ -507,6 +529,17 @@ function App() {
{view === 'loading' &&
Loading contacts...
} + {(view === 'empty' || view === 'list') && ( +
{ event.preventDefault(); void prepareContact() }}> + +