From aeacf1449396590b18748e2e251bc4ca98b633b1 Mon Sep 17 00:00:00 2001 From: Cody LeCates Date: Wed, 18 Nov 2026 13:39:24 -0700 Subject: [PATCH 1/3] Capture business contacts from photos, text and websites with Cloudflare --- .dev.vars.example | 2 - DEPLOYMENT.md | 5 +- README.md | 14 +--- cloudflare.config.ts | 6 +- e2e/access.e2e.test.ts | 2 +- e2e/browser/access.spec.ts | 27 ++++++- e2e/browser/cardcap.spec.ts | 6 +- e2e/browser/layout.spec.ts | 2 +- e2e/browser/server.ts | 10 +-- e2e/browser/session-states.spec.ts | 2 +- e2e/cardcap.e2e.test.ts | 12 +-- e2e/contact-capture.e2e.test.ts | 34 +++++++++ e2e/harness.ts | 54 +++++++++----- e2e/password.e2e.test.ts | 2 +- migrations/0005_contact_sources.sql | 11 +++ src/App.css | 8 ++ src/App.tsx | 78 ++++++++++++++----- src/shared/exporters.ts | 7 +- src/shared/review.ts | 2 +- src/shared/types.ts | 1 + src/worker/bindings.d.ts | 4 + src/worker/capture.test.ts | 32 ++++++++ src/worker/capture.ts | 112 ++++++++++++++++++++++++++++ src/worker/extract.ts | 93 ++++++----------------- src/worker/index.ts | 25 ++++++- src/worker/repository.ts | 47 ++++++++++-- 26 files changed, 444 insertions(+), 154 deletions(-) create mode 100644 e2e/contact-capture.e2e.test.ts create mode 100644 migrations/0005_contact_sources.sql create mode 100644 src/worker/bindings.d.ts create mode 100644 src/worker/capture.test.ts create mode 100644 src/worker/capture.ts diff --git a/.dev.vars.example b/.dev.vars.example index 75b70cd..a284df8 100644 --- a/.dev.vars.example +++ b/.dev.vars.example @@ -1,5 +1,3 @@ -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) diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index ee90bf7..decd238 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -18,7 +18,6 @@ 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) - `TURNSTILE_SECRET_KEY` (paired with the public `TURNSTILE_SITE_KEY` var in wrangler.jsonc) @@ -80,6 +79,6 @@ After deployment, verify: Invoke-RestMethod -Uri 'https://cardcap.codylecates.workers.dev/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..ce97c35 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,17 +43,9 @@ 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 diff --git a/cloudflare.config.ts b/cloudflare.config.ts index 7269054..d5380f3 100644 --- a/cloudflare.config.ts +++ b/cloudflare.config.ts @@ -13,11 +13,11 @@ export default defineConfig({ }, observability: { enabled: true, redactQueryString: true, headSamplingRate: 1 }, env: { - AI_EXTRACTOR: bindings.text('openai'), - OPENAI_MODEL: bindings.text('gpt-5.4-mini'), + AI: bindings.ai({ dev: { remote: true } }), + BROWSER: bindings.browser({ dev: { remote: true } }), + AI_EXTRACTOR: bindings.text('cloudflare'), SENDER_EMAIL: bindings.text('cody@copperstateit.com'), 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(), 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..531ce4e 100644 --- a/e2e/browser/cardcap.spec.ts +++ b/e2e/browser/cardcap.spec.ts @@ -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..5a63a02 100644 --- a/e2e/harness.ts +++ b/e2e/harness.ts @@ -11,13 +11,12 @@ 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 +43,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 +65,24 @@ export async function startHarness(options: HarnessOptions = {}): Promise = [] const accessKey = makeAccessKey('test-key-1') const access = { keys: [accessKey], published: [accessKey], jwksFetches: 0 } @@ -93,15 +109,25 @@ export async function startHarness(options: HarnessOptions = {}): Promise { + 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() @@ -116,14 +142,6 @@ export async function startHarness(options: HarnessOptions = {}): Promise 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() }}> + +