import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; import { createApp } from '../src/app.js'; import { bootstrapAdmin } from '../src/auth/bootstrap.js'; import { loadConfig } from '../src/config.js'; import { CONTACT_CSV_BINARY, CONTACT_CSV_COLUMNS, CONTACT_CSV_EMPTY, CONTACT_CSV_LARGE, CONTACT_CSV_LIMIT, CONTACT_CSV_READ, CONTACT_LIST_PAGE, contactImportSentence, contactListLimit, exportContacts, importContactCsv, rememberSignupContact, } from '../src/contacts.js'; import { openAppDatabase } from '../src/db.js'; import { devEnv } from './env.js'; const NOW = '2026-10-14T18:00:00.000Z'; const ORIGIN = 'http://127.0.0.1:3000'; const dirs: string[] = []; const databases: { close: () => void }[] = []; const PEOPLE = [ 'First Name,Last Name,Email,Phone,Address', 'kristi ,ANDERSON,Kristi@Example.invalid,712441076,123 Main', 'Kara,Acevedo,kara@example.invalid,,', 'Kara,Acevedo,kara.other@example.invalid,7125550100,456 Oak', 'Not An,Email,not-an-email,,', ].join('\r\n'); afterEach(() => { for (const database of databases.splice(0)) database.close(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); describe('contact spreadsheet', () => { it('keeps two emails for one name, ignores address, and skips a bad email', async () => { const db = await openDb(); const imported = importContactCsv(db, null, PEOPLE, NOW); expect(imported.ok).toBe(true); if (!imported.ok) return; expect(imported.result.added).toBe(3); expect(imported.result.skipped).toBe(1); expect(imported.result.skips).toEqual([{ line: 5, code: 'e' }]); expect(contactImportSentence(imported.result)).toBe('Saved 3 new contacts. Skipped 1 row.'); const rows = db .prepare('SELECT first_name, last_name, email, phone FROM contacts ORDER BY id') .all() as { first_name: string; last_name: string; email: string; phone: string | null }[]; expect(rows).toEqual([ { first_name: 'Kristi', last_name: 'Anderson', email: 'kristi@example.invalid', phone: '712441076' }, { first_name: 'Kara', last_name: 'Acevedo', email: 'kara@example.invalid', phone: null }, { first_name: 'Kara', last_name: 'Acevedo', email: 'kara.other@example.invalid', phone: '712-555-0100' }, ]); expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0); expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(0); const audit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.import'`).get() as { detail_json: string }; expect(JSON.parse(audit.detail_json)).toEqual({ added: 3, changed: 0, unchanged: 0, skipped: 1 }); expect(audit.detail_json).not.toContain('@'); }); it('keeps two names that share an email and updates only the matching name', async () => { const db = await openDb(); importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,One,ada@example.invalid,111\n', NOW); const renamed = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ADA@example.invalid,\n', NOW); expect(renamed.ok && renamed.result.added).toBe(1); expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([ { first_name: 'Ada', last_name: 'One', phone: '111' }, { first_name: 'Ada', last_name: 'Two', phone: null }, ]); const replaced = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nada,two,ada@example.invalid,(712) 555-0100\n', NOW); expect(replaced.ok && replaced.result.changed).toBe(1); expect(db.prepare('SELECT phone FROM contacts ORDER BY id').all()).toEqual([{ phone: '111' }, { phone: '712-555-0100' }]); const same = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,\n', NOW); expect(same.ok && same.result.unchanged).toBe(1); expect(db.prepare("SELECT phone FROM contacts WHERE last_name = 'Two'").get()).toEqual({ phone: '712-555-0100' }); const shaped = importContactCsv( db, null, 'First Name,Last Name,Email,Phone\nMcDonald,O\'BRIEN,mac@example.invalid,17125550199\njohn,SMITH,john@example.invalid,712 555 0199\n', NOW, ); expect(shaped.ok && shaped.result.added).toBe(2); expect(db.prepare('SELECT first_name, last_name, phone FROM contacts WHERE email = ?').all('mac@example.invalid')).toEqual([ { first_name: 'McDonald', last_name: "O'Brien", phone: '712-555-0199' }, ]); expect(db.prepare('SELECT first_name, last_name, phone FROM contacts WHERE email = ?').get('john@example.invalid')).toEqual({ first_name: 'John', last_name: 'Smith', phone: '712-555-0199', }); expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(4); }); it('round-trips a formula-looking name and a comma in the last name', async () => { const db = await openDb(); const first = importContactCsv( db, null, 'First Name,Last Name,Email,Phone,Address\n=Ada,"De Jong, Jr",ada@example.invalid,+1 712,\n', NOW, ); expect(first.ok && first.result.added).toBe(1); const exported = exportContacts(db); expect(exported.csv.startsWith('\uFEFFFirst Name,Last Name,Email,Phone,Address\r\n')).toBe(true); expect(exported.csv).toContain("'=Ada"); expect(exported.csv).toContain("'+1 712"); expect(exported.csv).toContain('"De Jong, Jr"'); const again = importContactCsv(db, null, exported.csv, NOW); expect(again.ok && again.result.unchanged).toBe(1); expect(db.prepare('SELECT first_name, last_name, phone FROM contacts').get()).toEqual({ first_name: '=Ada', last_name: 'De Jong, Jr', phone: '+1 712', }); }); it('refuses a roster file, an empty file, a broken quote, and too many rows', async () => { const db = await openDb(); expect(importContactCsv(db, null, 'Date,Start,Name,Email\n2026-10-15,9:00,Ada,ada@example.invalid\n', NOW)).toEqual({ ok: false, error: CONTACT_CSV_COLUMNS, }); expect(importContactCsv(db, null, ' ', NOW)).toEqual({ ok: false, error: CONTACT_CSV_EMPTY }); expect(importContactCsv(db, null, 'First Name,Last Name,Email\n"Ada,One,ada@example.invalid\n', NOW)).toEqual({ ok: false, error: CONTACT_CSV_READ, }); expect(importContactCsv(db, null, 'First Name,Last Name,Email\0\n', NOW)).toEqual({ ok: false, error: CONTACT_CSV_BINARY }); expect(importContactCsv(db, null, `First Name,Last Name,Email\n${'x'.repeat(64 * 1024)}`, NOW)).toEqual({ ok: false, error: CONTACT_CSV_LIMIT, }); const lines = ['First Name,Last Name,Email']; for (let i = 0; i < 2001; i += 1) lines.push(`A,B,a${i}@b.c`); expect(importContactCsv(db, null, lines.join('\n'), NOW)).toEqual({ ok: false, error: CONTACT_CSV_LARGE }); expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(0); }); it('saves each signup name as its own contact and keeps a short phone as written', async () => { const db = await openDb(); rememberSignupContact(db, { name: 'pat review', email: ' Pat@Example.invalid ', phone: '7125550199' }, NOW); expect(db.prepare('SELECT first_name, last_name, email, phone FROM contacts').get()).toEqual({ first_name: 'Pat', last_name: 'Review', email: 'pat@example.invalid', phone: '712-555-0199', }); rememberSignupContact(db, { name: 'Pat', email: 'pat@example.invalid', phone: null }, NOW); expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([ { first_name: 'Pat', last_name: 'Review', phone: '712-555-0199' }, { first_name: 'Pat', last_name: '-', phone: null }, ]); rememberSignupContact(db, { name: 'Sam', email: 'sam@example.invalid', phone: '' }, NOW); rememberSignupContact(db, { name: 'sam other', email: 'sam@example.invalid', phone: null }, NOW); expect(db.prepare("SELECT first_name, last_name, phone FROM contacts WHERE email = 'sam@example.invalid' ORDER BY id").all()).toEqual([ { first_name: 'Sam', last_name: '-', phone: null }, { first_name: 'Sam', last_name: 'Other', phone: null }, ]); rememberSignupContact(db, { name: 'PAT REVIEW', email: 'pat@example.invalid', phone: '555' }, NOW); expect(db.prepare("SELECT phone FROM contacts WHERE last_name = 'Review'").get()).toEqual({ phone: '555' }); expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(4); expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0); expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'contacts.manual'")).toBe(0); }); it('starts the list at one page and ignores a smaller shown count', () => { expect(contactListLimit(undefined)).toBe(CONTACT_LIST_PAGE); expect(contactListLimit('5')).toBe(CONTACT_LIST_PAGE); expect(contactListLimit('shown')).toBe(CONTACT_LIST_PAGE); expect(contactListLimit('40')).toBe(40); }); }); describe('contact pages', () => { it('shows the next page of contacts and keeps the search', async () => { const { app, db } = await buildApp(); const cookie = await signIn(app, db); const lines = ['First Name,Last Name,Email']; for (let i = 0; i <= CONTACT_LIST_PAGE; i += 1) { const name = String(i).padStart(2, '0'); lines.push(`Ada,N${name},n${name}@example.invalid`); } const imported = await postFile(app, cookie, lines.join('\n')); expect(imported.status).toBe(303); const first = await app.request('/admin/contacts', { headers: { cookie } }); const firstHtml = await first.text(); expect(firstHtml).toContain('Ada N00'); expect(firstHtml).toContain(`Ada N${String(CONTACT_LIST_PAGE - 1).padStart(2, '0')}`); expect(rowMarkup(firstHtml, 'Ada N00')).not.toContain('hidden'); expect(rowMarkup(firstHtml, `Ada N${String(CONTACT_LIST_PAGE).padStart(2, '0')}`)).toContain('hidden'); expect(firstHtml).toContain('See more'); expect(firstHtml).toContain(`data-see-more="${CONTACT_LIST_PAGE}"`); expect(firstHtml).toContain(`shown=${CONTACT_LIST_PAGE * 2}#contact-more`); expect(firstHtml).not.toContain('#contacts-list'); expect(firstHtml).toMatch(/href="\/admin\/contacts\/\d+"/); const searched = await app.request('/admin/contacts?q=ada', { headers: { cookie } }); const searchedHtml = await searched.text(); expect(searchedHtml).toContain('See more'); expect(searchedHtml).toContain('q=ada'); expect(searchedHtml).toContain(`shown=${CONTACT_LIST_PAGE * 2}`); const rest = await app.request(`/admin/contacts?shown=${CONTACT_LIST_PAGE * 2}`, { headers: { cookie } }); const restHtml = await rest.text(); expect(rowMarkup(restHtml, `Ada N${String(CONTACT_LIST_PAGE).padStart(2, '0')}`)).not.toContain('hidden'); expect(restHtml).not.toContain('See more'); expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(CONTACT_LIST_PAGE + 1); }); it('imports a file for a coordinator and keeps it off the public site', async () => { const { app, db } = await buildApp(); const loggedOut = await app.request('/admin/contacts'); expect(loggedOut.status).toBe(303); expect(await loggedOut.text()).not.toContain('example.invalid'); const cookie = await signIn(app, db); const home = await app.request('/admin', { headers: { cookie } }); expect(await home.text()).toContain('href="/admin/contacts"'); const stale = await postFile(app, cookie, PEOPLE, 'nope'); expect(stale.status).toBe(403); expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(0); const imported = await postFile(app, cookie, PEOPLE); expect(imported.status).toBe(303); const page = await app.request(imported.headers.get('location') ?? '', { headers: { cookie } }); const html = await page.text(); expect(html).toContain('Saved 3 new contacts. Skipped 1 row.'); expect(html).toContain('Row 5 was skipped because the email is not an address.'); expect(html).toContain('Kristi Anderson'); expect(html).toContain('kara.other@example.invalid'); expect(html).not.toContain('not-an-email'); expect(html).not.toContain('123 Main'); expect(await (await app.request('/')).text()).not.toContain('kristi@example.invalid'); expect(await (await app.request('/')).text()).not.toContain('Kristi Anderson'); const searched = await app.request('/admin/contacts?q=%3Cscript%3E', { headers: { cookie } }); const searchHtml = await searched.text(); expect(searchHtml).toContain('value="<script>"'); expect(searchHtml).not.toContain('value="