diff --git a/README.md b/README.md index e8e383f..61212e7 100644 --- a/README.md +++ b/README.md @@ -34,12 +34,12 @@ Stage 1 is the dashboard. Stage 2 adds saving a job from the page you are on, pl - **Applications list** with search, filters, manual entry, and a next-action date and who acts next. - **Save a job.** After you click the toolbar button (or press Alt+Shift+S by default; you can rebind it in about:addons), the popup reads the current tab once and offers the job for saving. Nothing is read before the click. -- **Fill a form.** In the popup, Fill writes your saved details and answers into the empty fields it recognises with certainty, then lists what it did not fill and why. It never changes a field that already has a value, and it never submits. Custom dropdowns and file uploads are listed for you to do yourself. +- **Fill a form.** In the popup, Fill writes your saved details and answers into the empty fields it recognises with certainty, then lists what it did not fill and why. It never changes a field that already has a value, and it never submits. Custom dropdowns and file uploads are listed for you to do yourself. When the form is linked to an application, the answers it filled are recorded as what you told them, with the form's question, and you can tick the ones you pasted yourself and mark the application Applied. - **Duplicate and repost facts.** When a job matches an application you already have, the popup says so ("already applied" or "possible match"). It also states the fact when you saved the same posting earlier, without judging it. - **Automatic backup.** Countersign saves `Countersign/countersign-backup.json` to your downloads folder, and the dashboard shows how old the last backup is. The backup file holds all your data, including your details and contacts, as plain text, so keep your downloads folder out of cloud sync if that matters to you. - **What I told them.** Per application, record the answers you gave. A warning appears when one differs from your canonical answer. - **Quiet list** (`#/quiet`) of applications with no response for a set number of days (a setting). You can close several at once. -- **Fill log.** On an application, record the application site type and how filling went. You enter it by hand. +- **Fill log.** On an application, record the application site type and how filling went. The site type is set by a fill when empty; how filling went is still yours to enter. - **Contacts** (`#/contacts`) with a log of reaching out, replies and referrals. The popup and the application page ask "anyone here?" and let you record that you checked and nobody was there. - **Deadlines** (`#/deadlines`): open tasks, next-action dates and quiet applications on one list, dated rows first. - **My details** (`#/details`): 14 profile fields (name, first and last name, email, phone, address, links) and your canonical answers, each with a copy button. Copying uses a click only. diff --git a/core/src/duplicates.test.ts b/core/src/duplicates.test.ts index 9850c5e..848e7f9 100644 --- a/core/src/duplicates.test.ts +++ b/core/src/duplicates.test.ts @@ -206,6 +206,62 @@ describe('findApplicationMatch', () => { }); }); +describe('form apply-page addresses', () => { + const stored = 'https://jobs.lever.co/example/abc'; + const data = snap({ + jobs: [{ id: 'j1', createdAt: `2026-06-12${AT}`, canonicalUrl: stored }], + applications: [{ id: 'a1', createdAt: `2026-06-13${AT}`, jobId: 'j1' }], + }); + + it('findApplicationMatch matches the /apply address of a stored job', () => { + expect( + findApplicationMatch(data, { canonicalUrl: `${stored}/apply` }), + ).toEqual({ kind: 'already_applied', applicationId: 'a1' }); + expect( + findApplicationMatch(data, { + canonicalUrl: 'https://jobs.lever.co/example/other/apply', + }), + ).toBeUndefined(); + }); + + it('matches the Ashby /application address of a stored job', () => { + const ashby = 'https://jobs.ashbyhq.com/example/abc'; + const ashbyData = snap({ + jobs: [{ id: 'j2', createdAt: `2026-06-12${AT}`, canonicalUrl: ashby }], + applications: [{ id: 'a2', createdAt: `2026-06-13${AT}`, jobId: 'j2' }], + }); + expect( + findApplicationMatch(ashbyData, { canonicalUrl: `${ashby}/application` }), + ).toEqual({ kind: 'already_applied', applicationId: 'a2' }); + expect( + repostFact( + ashbyData, + { canonicalUrl: `${ashby}/application` }, + '2026-11-15', + )?.firstSavedOn, + ).toBe('2026-06-12'); + expect( + findApplicationMatch(ashbyData, { + canonicalUrl: 'https://jobs.ashbyhq.com/example/zzz/application', + }), + ).toBeUndefined(); + }); + + it('repostFact matches the /apply address of a stored job', () => { + expect( + repostFact(data, { canonicalUrl: `${stored}/apply` }, '2026-11-15') + ?.firstSavedOn, + ).toBe('2026-06-12'); + expect( + repostFact( + data, + { canonicalUrl: 'https://jobs.lever.co/example/other/apply' }, + '2026-11-15', + ), + ).toBeUndefined(); + }); +}); + describe('repostFact', () => { const job = (id: string, day: string, extra: Partial = {}): Job => ({ id, diff --git a/core/src/duplicates.ts b/core/src/duplicates.ts index 4259da0..735c4cf 100644 --- a/core/src/duplicates.ts +++ b/core/src/duplicates.ts @@ -1,5 +1,6 @@ import { normalizeName } from './application-ops'; import { isLocalDate, toLocalDate } from './dates'; +import { formUrlKey } from './form-link'; import type { Application, Id, Job, LocalDate, Snapshot } from './types'; import { canonicalizeUrl } from './url'; @@ -45,6 +46,14 @@ function safeCanonical(url: string): string | undefined { } } +// Equal, or both the same posting once a form's apply segment is dropped. +function urlsMatch(have: string | undefined, want: string): boolean { + if (have === undefined) return false; + if (have === want) return true; + const key = formUrlKey(want); + return key !== undefined && key === formUrlKey(have); +} + function applicationCanonicalUrl( app: Application, jobsById: Map, @@ -110,7 +119,7 @@ export function findApplicationMatch( const appTitle = nameKey(app.title); if ( wantUrl !== undefined && - url === wantUrl && + urlsMatch(url, wantUrl) && !contradicts(wantCompany, company, wantTitle, appTitle) ) { if ( @@ -169,7 +178,7 @@ export function repostFact( const jobTitle = nameKey(job.title); const sameUrl = wantUrl !== undefined && - str(job.canonicalUrl) === wantUrl && + urlsMatch(str(job.canonicalUrl), wantUrl) && !contradicts(wantCompany, jobCompany, wantTitle, jobTitle); const sameName = wantCompany !== undefined && diff --git a/core/src/export.test.ts b/core/src/export.test.ts index f83154d..09b279f 100644 --- a/core/src/export.test.ts +++ b/core/src/export.test.ts @@ -149,6 +149,35 @@ describe('parseExport', () => { expect(parsed.file.settings).toEqual(settings); }); + it('round-trips fill statement fields and formUrls', () => { + const app = { + id: 'a1', + createdAt: T, + formUrls: ['https://jobs.example.com/acme/1'], + }; + const statement = { + id: 's1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsorship', + value: { type: 'yes_no' as const, value: false }, + source: 'fill' as const, + question: 'Will you require sponsorship?', + }; + const snap: Snapshot = { + ...emptySnapshot(), + applications: [app], + statements: [statement], + }; + const parsed = parseExport( + JSON.stringify(buildExport(snap, {}, { now: () => T })), + ); + expect(parsed.ok).toBe(true); + if (!parsed.ok) return; + expect(parsed.file.data.applications).toEqual([app]); + expect(parsed.file.data.statements).toEqual([statement]); + }); + it('restores an export without the new fields', () => { const result = parseExport(fixtureText); expect(result.ok).toBe(true); diff --git a/core/src/fill-records.test.ts b/core/src/fill-records.test.ts new file mode 100644 index 0000000..89ee994 --- /dev/null +++ b/core/src/fill-records.test.ts @@ -0,0 +1,292 @@ +import { describe, expect, it } from 'vitest'; +import { fillRecordOps, MAX_QUESTION, sameAnswerValue } from './fill-records'; +import type { FillResult, FillResultRow } from './fill/result'; +import { emptySnapshot } from './schema'; +import type { Application, Snapshot, Statement } from './types'; + +const T = '2026-01-01T00:00:00.000Z'; + +function makeDeps() { + let n = 0; + return { now: () => T, newId: () => `n${(n += 1)}` }; +} + +function makeData(app: Partial = {}): Snapshot { + const data = emptySnapshot(); + data.applications.push({ id: 'a1', createdAt: T, ...app }); + return data; +} + +function result( + rows: FillResultRow[], + siteType: FillResult['siteType'] = 'other', +): FillResult { + return { url: 'https://example.com/apply', siteType, at: T, rows }; +} + +const yes = { type: 'yes_no', value: true } as const; +const range = { type: 'money_range', min: 100, max: 200 } as const; + +function baseRows(): FillResultRow[] { + return [ + { + label: 'Email', + target: { kind: 'profile', key: 'email' }, + status: 'will_fill', + outcome: 'written', + answerValue: { type: 'text', value: 'a@example.com' }, + }, + { + label: 'Need sponsorship?', + target: { kind: 'answer', key: 'sponsorship' }, + status: 'will_fill', + outcome: 'written', + answerValue: yes, + }, + { + label: 'Salary range', + target: { kind: 'answer', key: 'salary_range' }, + status: 'matches', + answerValue: range, + }, + { + label: 'Relocate?', + target: { kind: 'answer', key: 'relocation' }, + status: 'differs', + answerValue: yes, + }, + { + label: 'Start date', + target: { kind: 'answer', key: 'earliest_start_date' }, + status: 'will_fill', + outcome: 'not_empty', + answerValue: { type: 'date', value: '2026-02-01' }, + }, + { + label: 'Reason for leaving', + target: { kind: 'answer', key: 'reason_for_leaving' }, + status: 'will_fill', + outcome: 'gone', + answerValue: { type: 'text', value: 'x' }, + }, + { + label: 'Work authorization', + target: { kind: 'answer', key: 'work_authorization' }, + status: 'will_fill', + outcome: 'failed', + answerValue: yes, + }, + { + label: 'X', + target: { kind: 'answer', key: 'x' }, + status: 'not_filled', + answerValue: yes, + }, + ] as FillResultRow[]; +} + +function puts(ops: ReturnType['ops']): Statement[] { + return ops + .filter((o) => o.kind === 'put' && o.store === 'statements') + .map((o) => (o as { record: Statement }).record); +} + +describe('fillRecordOps', () => { + it('records written and matching answer rows only', () => { + const r = fillRecordOps(makeData(), result(baseRows()), 'a1', makeDeps()); + expect(r.recorded).toBe(2); + expect(r.alreadyOnForm).toBe(1); + expect(r.missing).toBe(false); + const st = puts(r.ops); + expect(st.map((s) => s.answerKey)).toEqual(['sponsorship', 'salary_range']); + expect(st[0]).toMatchObject({ + id: 'n1', + createdAt: T, + applicationId: 'a1', + value: yes, + source: 'fill', + question: 'Need sponsorship?', + }); + expect(st[1]?.question).toBe('Salary range'); + }); + + it('skips a value already recorded', () => { + const data = makeData(); + data.statements.push({ + id: 's1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsorship', + value: { type: 'yes_no', value: true }, + }); + const r = fillRecordOps(data, result(baseRows()), 'a1', makeDeps()); + expect(r.recorded).toBe(1); + expect(puts(r.ops).map((s) => s.answerKey)).toEqual(['salary_range']); + }); + + it('adds a different value for the same key', () => { + const data = makeData(); + data.statements.push({ + id: 's1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsorship', + value: { type: 'yes_no', value: false }, + }); + const r = fillRecordOps(data, result(baseRows()), 'a1', makeDeps()); + expect(r.recorded).toBe(2); + }); + + it('records one statement for two rows with the same key and value', () => { + const rows: FillResultRow[] = [ + { + label: 'First', + target: { kind: 'answer', key: 'sponsorship' }, + status: 'will_fill', + outcome: 'written', + answerValue: yes, + }, + { + label: 'Second', + target: { kind: 'answer', key: 'sponsorship' }, + status: 'matches', + answerValue: { ...yes }, + }, + ]; + const r = fillRecordOps(makeData(), result(rows), 'a1', makeDeps()); + expect(r.recorded).toBe(1); + expect(r.alreadyOnForm).toBe(0); + expect(puts(r.ops)[0]?.question).toBe('First'); + }); + + it('trims the question and cuts it at 300 characters', () => { + const rows = baseRows().slice(1, 2); + rows[0] = { ...rows[0]!, label: ` ${'q'.repeat(400)} ` }; + const r = fillRecordOps(makeData(), result(rows), 'a1', makeDeps()); + expect(puts(r.ops)[0]?.question).toBe('q'.repeat(MAX_QUESTION)); + expect(MAX_QUESTION).toBe(300); + }); + + it('omits a blank question', () => { + const rows = baseRows().slice(1, 2); + rows[0] = { ...rows[0]!, label: ' ' }; + const r = fillRecordOps(makeData(), result(rows), 'a1', makeDeps()); + expect(puts(r.ops)[0]).not.toHaveProperty('question'); + }); + + it('sets site type only when empty and not other', () => { + const set = fillRecordOps( + makeData(), + result([], 'lever'), + 'a1', + makeDeps(), + ); + expect(set.ops).toHaveLength(1); + expect(set.ops[0]).toMatchObject({ + kind: 'put', + store: 'applications', + record: { id: 'a1', siteType: 'lever' }, + }); + const kept = fillRecordOps( + makeData({ siteType: 'greenhouse' }), + result([], 'lever'), + 'a1', + makeDeps(), + ); + expect(kept.ops).toEqual([]); + const other = fillRecordOps( + makeData(), + result([], 'other'), + 'a1', + makeDeps(), + ); + expect(other.ops).toEqual([]); + }); + + it('gives no ops when nothing is told', () => { + const r = fillRecordOps( + makeData(), + result(baseRows().slice(3)), + 'a1', + makeDeps(), + ); + expect(r).toEqual({ + ops: [], + recorded: 0, + alreadyOnForm: 0, + missing: false, + }); + }); + + it('gives missing: true for a missing application', () => { + const r = fillRecordOps(makeData(), result(baseRows()), 'nope', makeDeps()); + expect(r).toEqual({ + ops: [], + recorded: 0, + alreadyOnForm: 0, + missing: true, + }); + }); + + it('tolerates a null statement value and a non-object answerValue', () => { + const data = makeData(); + data.statements.push( + { + id: 's1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsorship', + value: null, + } as unknown as Statement, + { + id: 's2', + createdAt: T, + applicationId: 'a1', + answerKey: 'salary_range', + value: 'str', + } as unknown as Statement, + ); + const rows = baseRows(); + rows[2] = { ...rows[2]!, answerValue: 'oops' as never }; + const r = fillRecordOps(data, result(rows), 'a1', makeDeps()); + expect(r.recorded).toBe(1); + expect(r.alreadyOnForm).toBe(0); + expect(puts(r.ops).map((s) => s.answerKey)).toEqual(['sponsorship']); + }); +}); + +describe('sameAnswerValue', () => { + it('treats money ranges as equal with both currency missing', () => { + expect( + sameAnswerValue( + { type: 'money_range', min: 1, max: 2 }, + { type: 'money_range', min: 1, max: 2 }, + ), + ).toBe(true); + }); + + it('differs on period', () => { + expect( + sameAnswerValue( + { type: 'money_range', min: 1, period: 'year' }, + { type: 'money_range', min: 1, period: 'hour' }, + ), + ).toBe(false); + }); + + it('is false for different types and for null', () => { + expect( + sameAnswerValue( + { type: 'text', value: 'a' }, + { type: 'choice', value: 'a' }, + ), + ).toBe(false); + expect(sameAnswerValue(null, null)).toBe(false); + expect(sameAnswerValue(yes, null)).toBe(false); + }); + + it('compares the value field for other types', () => { + expect(sameAnswerValue(yes, { type: 'yes_no', value: true })).toBe(true); + expect(sameAnswerValue(yes, { type: 'yes_no', value: false })).toBe(false); + }); +}); diff --git a/core/src/fill-records.ts b/core/src/fill-records.ts new file mode 100644 index 0000000..303cc8f --- /dev/null +++ b/core/src/fill-records.ts @@ -0,0 +1,100 @@ +import { updateApplicationOps } from './application-ops'; +import type { FillResult } from './fill/result'; +import { isSiteType } from './formhand'; +import type { WriteOp } from './repository'; +import { statementsFor } from './statements'; +import type { Deps, Id, Snapshot, Statement } from './types'; + +export const MAX_QUESTION = 300; + +export interface FillRecord { + ops: WriteOp[]; + recorded: number; + alreadyOnForm: number; + missing: boolean; +} + +// Restored records are not field-checked, so a value may be null, a primitive or an array. +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +const MONEY_FIELDS = ['min', 'max', 'currency', 'period'] as const; + +/** Same type and equal fields for that type. Anything that is not a plain object is never equal. */ +export function sameAnswerValue(a: unknown, b: unknown): boolean { + if (!isPlainObject(a) || !isPlainObject(b)) return false; + if (a.type !== b.type) return false; + if (a.type === 'money_range') { + return MONEY_FIELDS.every((field) => a[field] === b[field]); + } + return a.value === b.value; +} + +/** + * The "what I told them" statements a fill implies, plus a site-type update, + * as one op list. Never throws on odd restored data. + */ +export function fillRecordOps( + data: Snapshot, + result: FillResult, + applicationId: Id, + deps: Deps, +): FillRecord { + const app = data.applications.find((a) => a.id === applicationId); + if (app === undefined) { + return { ops: [], recorded: 0, alreadyOnForm: 0, missing: true }; + } + + const told: { key: string; value: unknown }[] = statementsFor( + data, + applicationId, + ).flatMap((s) => + typeof s.answerKey === 'string' + ? [{ key: s.answerKey, value: s.value }] + : [], + ); + + const ops: WriteOp[] = []; + let recorded = 0; + let alreadyOnForm = 0; + + for (const row of result.rows) { + if (row.target?.kind !== 'answer') continue; + const value: unknown = row.answerValue; + if (!isPlainObject(value)) continue; + const written = row.status === 'will_fill' && row.outcome === 'written'; + const matches = row.status === 'matches'; + if (!written && !matches) continue; + + const key = row.target.key; + if (told.some((t) => t.key === key && sameAnswerValue(t.value, value))) { + continue; + } + told.push({ key, value }); + + const statement: Statement = { + id: deps.newId(), + createdAt: deps.now(), + applicationId, + answerKey: key, + value: { ...value } as Statement['value'], + source: 'fill', + }; + const question = + typeof row.label === 'string' + ? row.label.trim().slice(0, MAX_QUESTION) + : ''; + if (question !== '') statement.question = question; + + ops.push({ kind: 'put', store: 'statements', record: statement }); + recorded += 1; + if (matches) alreadyOnForm += 1; + } + + if (!isSiteType(app.siteType) && result.siteType !== 'other') { + ops.push(...updateApplicationOps(app, { siteType: result.siteType })); + } + + return { ops, recorded, alreadyOnForm, missing: false }; +} diff --git a/core/src/form-application.test.ts b/core/src/form-application.test.ts new file mode 100644 index 0000000..62f58e7 --- /dev/null +++ b/core/src/form-application.test.ts @@ -0,0 +1,254 @@ +import { describe, expect, it } from 'vitest'; +import { + linkFormAndRecordOps, + newApplicationFromFormOps, +} from './form-application'; +import { formUrlKey, linkFormOps } from './form-link'; +import type { FillResult } from './fill/result'; +import type { WriteOp } from './repository'; +import { emptySnapshot } from './schema'; +import type { + Application, + Job, + Snapshot, + Statement, + StatusEvent, +} from './types'; + +const T = '2026-01-01T00:00:00.000Z'; +const URL = 'https://jobs.lever.co/acme/1/apply'; + +function makeDeps() { + let n = 0; + return { now: () => T, newId: () => `n${(n += 1)}` }; +} + +function held(siteType: FillResult['siteType'] = 'other'): FillResult { + return { + url: URL, + siteType, + at: T, + rows: [ + { + label: 'Need sponsorship?', + target: { kind: 'answer', key: 'sponsorship' }, + status: 'will_fill', + outcome: 'written', + answerValue: { type: 'yes_no', value: true }, + }, + { + label: 'Relocate?', + target: { kind: 'answer', key: 'relocation' }, + status: 'matches', + answerValue: { type: 'yes_no', value: false }, + }, + ], + }; +} + +function stores(ops: WriteOp[], store: string): WriteOp[] { + return ops.filter((o) => o.kind === 'put' && o.store === store); +} + +describe('newApplicationFromFormOps facts', () => { + const archivedJob: Job = { + id: 'oldjob', + source: 'paste', + title: 'Dev', + companyName: 'Acme', + canonicalUrl: 'https://jobs.lever.co/acme/1', + createdAt: '2025-12-01T00:00:00.000Z', + }; + + it('reports a duplicate and a repost of an earlier job at the form key', () => { + const data: Snapshot = { + ...emptySnapshot(), + jobs: [archivedJob], + applications: [ + { + id: 'oldapp', + jobId: 'oldjob', + title: 'Dev', + createdAt: '2025-12-01T00:00:00.000Z', + }, + ], + }; + const built = newApplicationFromFormOps( + data, + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + ); + expect(built.match).toBe('already_applied'); + expect(built.repost).toMatch(/^You saved this posting on /); + }); + + it('reports nothing for a new posting and never counts itself', () => { + const built = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + ); + expect(built.match).toBeUndefined(); + expect(built.repost).toBeUndefined(); + }); +}); + +describe('newApplicationFromFormOps', () => { + it('makes one job and one linked interested application', () => { + const { ops, applicationId, record } = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + ); + const jobs = stores(ops, 'jobs'); + const apps = stores(ops, 'applications'); + expect(jobs).toHaveLength(1); + expect(apps).toHaveLength(1); + const job = (jobs[0] as { record: Job }).record; + const app = (apps[0] as { record: Application }).record; + expect(app.jobId).toBe(job.id); + expect(app.id).toBe(applicationId); + const ev = (stores(ops, 'statusEvents')[0] as { record: StatusEvent }) + .record; + expect(ev.applicationId).toBe(app.id); + expect(ev.status).toBe('interested'); + expect(record).toBeUndefined(); + }); + + it('keys the job by the form url key', () => { + const { ops } = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL }, + makeDeps(), + ); + const job = (stores(ops, 'jobs')[0] as { record: Job }).record; + expect(job.canonicalUrl).toBe(formUrlKey(URL)); + expect(job.canonicalUrl).toBeDefined(); + }); + + it('orders company, job, application, status event', () => { + const { ops } = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + ); + const order = ops.map((o) => (o.kind === 'put' ? o.store : o.kind)); + expect(order).toEqual([ + 'companies', + 'jobs', + 'applications', + 'statusEvents', + ]); + }); + + it('records held statements against the new application', () => { + const { ops, applicationId, record } = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + held(), + ); + expect(record?.recorded).toBe(2); + expect(record?.alreadyOnForm).toBe(1); + const statements = stores(ops, 'statements').map( + (o) => (o as { record: Statement }).record, + ); + expect(statements).toHaveLength(2); + expect(statements.every((s) => s.applicationId === applicationId)).toBe( + true, + ); + const order = ops.map((o) => (o.kind === 'put' ? o.store : o.kind)); + expect(order.indexOf('statements')).toBeGreaterThan( + order.indexOf('statusEvents'), + ); + }); + + it('keeps jobId on the last applications put when the site type is set', () => { + const { ops } = newApplicationFromFormOps( + emptySnapshot(), + { source: 'paste', url: URL, title: 'Dev', companyName: 'Acme' }, + makeDeps(), + held('lever'), + ); + const job = (stores(ops, 'jobs')[0] as { record: Job }).record; + const apps = stores(ops, 'applications'); + expect(apps.length).toBeGreaterThan(1); + const last = (apps[apps.length - 1] as { record: Application }).record; + expect(last.jobId).toBe(job.id); + expect(last.siteType).toBe('lever'); + }); + + it('accepts a blank title and company and does not mutate data', () => { + const data = emptySnapshot(); + const { ops, record } = newApplicationFromFormOps( + data, + { source: 'paste', url: URL, title: ' ', companyName: '' }, + makeDeps(), + held(), + ); + expect(stores(ops, 'applications')).toHaveLength(1); + expect(stores(ops, 'companies')).toHaveLength(0); + expect(record?.missing).toBe(false); + expect(data.jobs).toHaveLength(0); + expect(data.applications).toHaveLength(0); + expect(data.statusEvents).toHaveLength(0); + }); +}); + +describe('linkFormAndRecordOps', () => { + function snapshotWithApp(): Snapshot { + const data = emptySnapshot(); + data.applications.push({ + id: 'a1', + companyId: 'c1', + status: 'interested', + createdAt: T, + updatedAt: T, + } as Application); + return data; + } + + it('keeps both formUrls and siteType on the last put of the application', () => { + const key = formUrlKey(URL) ?? URL; + const { ops, record } = linkFormAndRecordOps( + snapshotWithApp(), + 'a1', + key, + held('lever'), + makeDeps(), + ); + const apps = stores(ops, 'applications').filter( + (o) => (o as { record: Application }).record.id === 'a1', + ); + expect(apps.length).toBeGreaterThan(1); + const last = (apps[apps.length - 1] as { record: Application }).record; + expect(last.formUrls).toContain(key); + expect(last.siteType).toBe('lever'); + expect(record?.missing).toBe(false); + }); + + it('equals linkFormOps without a held result', () => { + const data = snapshotWithApp(); + const { ops, record } = linkFormAndRecordOps( + data, + 'a1', + 'k', + undefined, + makeDeps(), + ); + expect(ops).toEqual(linkFormOps(data, 'a1', 'k')); + expect(record).toBeUndefined(); + }); + + it('reports a missing application and writes nothing', () => { + const { ops, record } = linkFormAndRecordOps( + emptySnapshot(), + 'gone', + 'k', + held(), + makeDeps(), + ); + expect(ops).toEqual([]); + expect(record?.missing).toBe(true); + }); +}); diff --git a/core/src/form-application.ts b/core/src/form-application.ts new file mode 100644 index 0000000..f21f9fb --- /dev/null +++ b/core/src/form-application.ts @@ -0,0 +1,124 @@ +import { toLocalDate } from './dates'; +import { + findApplicationMatch, + repostFact, + type ApplicationMatch, + type JobCandidate, +} from './duplicates'; +import type { FillResult } from './fill/result'; +import { fillRecordOps, type FillRecord } from './fill-records'; +import { formUrlKey, linkFormOps } from './form-link'; +import { + createApplicationFromJobOps, + saveJobOps, + type JobInput, +} from './job-ops'; +import type { WriteOp } from './repository'; +import type { Application, Deps, Id, Job, Snapshot } from './types'; + +/** + * Link an application to a form and, with a held fill result, record that fill + * on it, as one op list. Both writes put the whole application, so the record + * step runs on a snapshot that already carries the link; otherwise the later + * put would drop the earlier one's change. + */ +export function linkFormAndRecordOps( + data: Snapshot, + applicationId: Id, + key: string, + held: FillResult | undefined, + deps: Deps, +): { ops: WriteOp[]; record?: FillRecord } { + const ops = linkFormOps(data, applicationId, key); + if (held === undefined) return { ops }; + const replaced = new Map(); + for (const op of ops) { + if (op.kind === 'put' && op.store === 'applications') { + replaced.set(op.record.id, op.record); + } + } + const next: Snapshot = { + ...data, + applications: data.applications.map((a) => replaced.get(a.id) ?? a), + }; + const record = fillRecordOps(next, held, applicationId, deps); + return { ops: [...ops, ...record.ops], record }; +} + +/** + * A job, an application from it and, with a held fill result, the statements + * and site type that fill implies, as one op list for a single apply. + * Order: company (if new), job, application, status event, statements, site type. + */ +export function newApplicationFromFormOps( + data: Snapshot, + input: JobInput, + deps: Deps, + held?: FillResult, +): { + ops: WriteOp[]; + applicationId: Id; + record?: FillRecord; + match?: ApplicationMatch['kind']; + repost?: string; +} { + const saved = saveJobOps(input, deps); + const jobPut = saved.ops[0]; + if (jobPut?.kind !== 'put' || jobPut.store !== 'jobs') { + throw new Error('saveJobOps returned no job put'); + } + const job: Job = { ...jobPut.record }; + if (typeof input.url === 'string') { + const key = formUrlKey(input.url, input.relCanonical); + if (key !== undefined) job.canonicalUrl = key; + } + const jobOp: WriteOp = { kind: 'put', store: 'jobs', record: job }; + + const created = createApplicationFromJobOps(job, data, deps); + const companyIndex = created.ops.findIndex( + (op) => op.kind === 'put' && op.store === 'companies', + ); + const ops: WriteOp[] = [...created.ops]; + ops.splice(companyIndex + 1, 0, jobOp); + + // Facts only inform, as in Save job: computed on the data before this write, + // for a candidate stored the way the job is (form key as its canonical URL). + const candidate: JobCandidate = {}; + if (job.canonicalUrl !== undefined) candidate.canonicalUrl = job.canonicalUrl; + if (job.companyName !== undefined) candidate.companyName = job.companyName; + if (job.title !== undefined) candidate.title = job.title; + const match = findApplicationMatch(data, candidate)?.kind; + const repost = repostFact( + data, + { ...candidate, excludeJobId: job.id }, + toLocalDate(new Date(deps.now())), + )?.text; + const facts = { + ...(match !== undefined ? { match } : {}), + ...(repost !== undefined ? { repost } : {}), + }; + + if (held === undefined) { + return { ops, applicationId: created.applicationId, ...facts }; + } + + const next: Snapshot = { + ...data, + companies: [...data.companies], + jobs: [...data.jobs, job], + applications: [...data.applications], + statusEvents: [...data.statusEvents], + }; + for (const op of created.ops) { + if (op.kind !== 'put') continue; + if (op.store === 'companies') next.companies.push(op.record); + else if (op.store === 'applications') { + next.applications.push(op.record); + } else if (op.store === 'statusEvents') { + next.statusEvents.push(op.record); + } + } + const record = fillRecordOps(next, held, created.applicationId, deps); + ops.push(...record.ops); + return { ops, applicationId: created.applicationId, record, ...facts }; +} diff --git a/core/src/form-link.test.ts b/core/src/form-link.test.ts new file mode 100644 index 0000000..80c5b64 --- /dev/null +++ b/core/src/form-link.test.ts @@ -0,0 +1,219 @@ +import { describe, expect, it } from 'vitest'; +import { + MAX_FORM_URLS, + findApplicationsForForm, + formUrlKey, + linkFormOps, +} from './form-link'; +import { emptySnapshot } from './schema'; +import type { Application, Job, Snapshot, StatusEvent } from './types'; +import { canonicalizeUrl } from './url'; + +const AT = 'T12:00:00.000Z'; + +function snap(parts: { + applications?: Application[]; + jobs?: Job[]; + statusEvents?: StatusEvent[]; +}): Snapshot { + return { ...emptySnapshot(), ...parts }; +} + +function app(id: string, day: string, extra: object = {}): Application { + return { id, createdAt: `2026-01-${day}${AT}`, ...extra }; +} + +const KEY = 'https://example.com/jobs/1'; + +describe('formUrlKey', () => { + it('ignores an address longer than the capture cap', () => { + const long = `https://example.com/${'a'.repeat(8_001 - 20)}`; + expect(long).toHaveLength(8_001); + expect(formUrlKey(long)).toBeUndefined(); + expect(formUrlKey('https://example.com/jobs/1')).toBe( + 'https://example.com/jobs/1', + ); + }); + + it('strips the Lever apply segment', () => { + expect(formUrlKey('https://jobs.lever.co/acme/123/apply')).toBe( + formUrlKey('https://jobs.lever.co/acme/123'), + ); + expect(formUrlKey('https://jobs.eu.lever.co/acme/123/apply/')).toBe( + formUrlKey('https://jobs.eu.lever.co/acme/123'), + ); + }); + + it('strips the Ashby application segment', () => { + expect(formUrlKey('https://jobs.ashbyhq.com/acme/abc/application')).toBe( + formUrlKey('https://jobs.ashbyhq.com/acme/abc'), + ); + }); + + it('otherwise equals canonicalizeUrl', () => { + const url = 'https://job-boards.greenhouse.io/acme/jobs/9?gh_src=x#app'; + expect(formUrlKey(url)).toBe(canonicalizeUrl(url)); + }); + + it('leaves other hosts and other segments alone', () => { + expect(formUrlKey('https://example.com/careers/apply')).toBe( + 'https://example.com/careers/apply', + ); + expect(formUrlKey('https://jobs.lever.co/acme/applyx')).toBe( + 'https://jobs.lever.co/acme/applyx', + ); + }); + + it('is undefined for non-http(s) and unparseable input', () => { + expect(formUrlKey('not a url')).toBeUndefined(); + expect(formUrlKey('javascript:alert(1)')).toBeUndefined(); + expect(formUrlKey('')).toBeUndefined(); + }); +}); + +describe('findApplicationsForForm', () => { + it('matches by formUrls, job canonicalUrl and own url', () => { + const data = snap({ + jobs: [{ id: 'j1', createdAt: `2026-01-01${AT}`, canonicalUrl: KEY }], + applications: [ + app('a1', '02', { formUrls: [KEY] }), + app('a2', '03', { jobId: 'j1' }), + app('a3', '04', { url: `${KEY}?utm_source=x` }), + app('a4', '05', { url: 'https://example.com/other' }), + ], + }); + expect(findApplicationsForForm(data, KEY)).toEqual(['a1', 'a2', 'a3']); + }); + + it('ranks a formUrls match before a newer job match', () => { + const data = snap({ + jobs: [{ id: 'j1', createdAt: `2026-01-01${AT}`, canonicalUrl: KEY }], + applications: [ + app('old', '02', { formUrls: [KEY] }), + app('new', '09', { jobId: 'j1' }), + ], + }); + expect(findApplicationsForForm(data, KEY)).toEqual(['old', 'new']); + }); + + it('orders newest first within a group and does not duplicate', () => { + const data = snap({ + applications: [ + app('a1', '02', { formUrls: [KEY], url: KEY }), + app('a2', '08', { formUrls: [KEY] }), + ], + }); + expect(findApplicationsForForm(data, KEY)).toEqual(['a2', 'a1']); + }); + + it('excludes archived applications', () => { + const data = snap({ + applications: [app('a1', '02', { formUrls: [KEY] })], + statusEvents: [ + { + id: 'e1', + createdAt: `2026-01-03${AT}`, + applicationId: 'a1', + status: 'rejected', + }, + ], + }); + expect(findApplicationsForForm(data, KEY)).toEqual([]); + }); + + it('tolerates odd formUrls', () => { + const data = snap({ + applications: [ + app('a1', '02', { formUrls: 'x' }), + app('a2', '03', { formUrls: [3, null] }), + app('a3', '04', { formUrls: null }), + ], + }); + expect(findApplicationsForForm(data, KEY)).toEqual([]); + expect(findApplicationsForForm(data, 'x')).toEqual([]); + }); + + it('matches a job saved from the Lever apply page', () => { + const applyUrl = 'https://jobs.lever.co/acme/123/apply'; + const data = snap({ + jobs: [ + { id: 'j1', createdAt: `2026-01-01${AT}`, canonicalUrl: applyUrl }, + ], + applications: [app('a1', '02', { jobId: 'j1' })], + }); + expect( + findApplicationsForForm(data, formUrlKey(applyUrl) as string), + ).toEqual(['a1']); + }); +}); + +describe('linkFormOps', () => { + function put(ops: ReturnType, id: string): Application { + const op = ops.find( + (o) => o.kind === 'put' && (o.record as Application).id === id, + ); + return (op as { record: Application }).record; + } + + it('adds the key once', () => { + const data = snap({ applications: [app('a1', '02')] }); + const ops = linkFormOps(data, 'a1', KEY); + expect(ops).toHaveLength(1); + expect(put(ops, 'a1').formUrls).toEqual([KEY]); + }); + + it('returns nothing the second time', () => { + const data = snap({ applications: [app('a1', '02', { formUrls: [KEY] })] }); + expect(linkFormOps(data, 'a1', KEY)).toEqual([]); + }); + + it('moves the key from one application to another', () => { + const data = snap({ + applications: [ + app('a', '02'), + app('b', '03', { formUrls: [KEY], title: 'B' }), + ], + }); + const ops = linkFormOps(data, 'a', KEY); + expect(ops).toHaveLength(2); + expect(put(ops, 'a').formUrls).toEqual([KEY]); + const b = put(ops, 'b'); + expect('formUrls' in b).toBe(false); + expect(b.title).toBe('B'); + }); + + it('keeps the other keys on the application it removes from', () => { + const data = snap({ + applications: [ + app('a', '02'), + app('b', '03', { formUrls: ['https://example.com/x', KEY] }), + ], + }); + expect(put(linkFormOps(data, 'a', KEY), 'b').formUrls).toEqual([ + 'https://example.com/x', + ]); + }); + + it('drops the oldest past the cap and non-strings', () => { + const existing = Array.from( + { length: MAX_FORM_URLS }, + (_, i) => `https://example.com/k${i}`, + ); + const data = snap({ + applications: [app('a', '02', { formUrls: [...existing, 7, null] })], + }); + const urls = put(linkFormOps(data, 'a', KEY), 'a').formUrls; + expect(urls).toHaveLength(MAX_FORM_URLS); + expect(urls?.[0]).toBe('https://example.com/k1'); + expect(urls?.at(-1)).toBe(KEY); + }); + + it('returns nothing for a missing application', () => { + expect(linkFormOps(snap({}), 'nope', KEY)).toEqual([]); + }); + + it('survives a non-array formUrls', () => { + const data = snap({ applications: [app('a', '02', { formUrls: 'x' })] }); + expect(put(linkFormOps(data, 'a', KEY), 'a').formUrls).toEqual([KEY]); + }); +}); diff --git a/core/src/form-link.ts b/core/src/form-link.ts new file mode 100644 index 0000000..7e46f34 --- /dev/null +++ b/core/src/form-link.ts @@ -0,0 +1,126 @@ +import type { WriteOp } from './repository'; +import { currentStatus, isArchived } from './status'; +import type { Application, Id, Snapshot } from './types'; +import { canonicalizeUrl } from './url'; + +// core/ declares no URL global (lib ES2023, types []), so declare the subset used here. +interface UrlLike { + protocol: string; + hostname: string; +} +declare const URL: { new (url: string, base?: string): UrlLike }; + +export const MAX_FORM_URLS = 20; +// Matches the capture URL cap (shell/capture MAX_CAPTURE_URL); core cannot import it. +export const MAX_FORM_URL = 8_000; + +// Hosts whose application form lives one path segment below the posting. +const TRAILING_SEGMENTS: Readonly> = { + 'jobs.lever.co': 'apply', + 'jobs.eu.lever.co': 'apply', + 'jobs.ashbyhq.com': 'application', +}; + +/** The key a form is stored and matched under, or undefined for a non-http(s) address. Never throws. */ +export function formUrlKey( + url: string, + relCanonical?: string, +): string | undefined { + if (url.length > MAX_FORM_URL) return undefined; + try { + const parsed = new URL(url.trim()); + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + return undefined; + } + const canonical = canonicalizeUrl(url, relCanonical); + const canonicalUrl = new URL(canonical); + const segment = TRAILING_SEGMENTS[canonicalUrl.hostname.toLowerCase()]; + if (segment === undefined) return canonical; + const queryIndex = canonical.indexOf('?'); + const base = queryIndex >= 0 ? canonical.slice(0, queryIndex) : canonical; + const query = queryIndex >= 0 ? canonical.slice(queryIndex) : ''; + const trimmed = base.replace(/\/+$/, ''); + const suffix = `/${segment}`; + if (!trimmed.endsWith(suffix)) return canonical; + return trimmed.slice(0, -suffix.length) + query; + } catch { + return undefined; + } +} + +function formUrlsOf(app: Application): string[] { + const raw: unknown = app.formUrls; + return Array.isArray(raw) + ? raw.filter((v): v is string => typeof v === 'string') + : []; +} + +function newestFirst(a: Application, b: Application): number { + const x = typeof a.createdAt === 'string' ? a.createdAt : ''; + const y = typeof b.createdAt === 'string' ? b.createdAt : ''; + return x < y ? 1 : x > y ? -1 : 0; +} + +/** Active applications a form may belong to, best first: saved form addresses, then job link, then own URL. */ +export function findApplicationsForForm(data: Snapshot, key: string): Id[] { + const jobUrls = new Map(); + for (const job of data.jobs) { + if (typeof job.canonicalUrl === 'string') + jobUrls.set(job.id, job.canonicalUrl); + } + const active = data.applications + .filter((a) => !isArchived(currentStatus(data.statusEvents, a.id))) + .sort(newestFirst); + + const byForm = active.filter((a) => formUrlsOf(a).includes(key)); + const byJob = active.filter((a) => { + if (typeof a.jobId !== 'string') return false; + const url = jobUrls.get(a.jobId); + return url !== undefined && (formUrlKey(url) ?? url) === key; + }); + const byUrl = active.filter( + (a) => typeof a.url === 'string' && formUrlKey(a.url) === key, + ); + + const seen = new Set(); + const result: Id[] = []; + for (const a of [...byForm, ...byJob, ...byUrl]) { + if (seen.has(a.id)) continue; + seen.add(a.id); + result.push(a.id); + } + return result; +} + +/** Links a form to an application, moving the key off any other application that held it. */ +export function linkFormOps( + data: Snapshot, + applicationId: Id, + key: string, +): WriteOp[] { + const target = data.applications.find((a) => a.id === applicationId); + if (!target) return []; + const ops: WriteOp[] = []; + + const held = formUrlsOf(target); + if (!held.includes(key)) { + const next = [...held, key].slice(-MAX_FORM_URLS); + ops.push({ + kind: 'put', + store: 'applications', + record: { ...target, formUrls: next }, + }); + } + + for (const other of data.applications) { + if (other.id === applicationId) continue; + const urls = formUrlsOf(other); + if (!urls.includes(key)) continue; + const record: Application = { ...other }; + const rest = urls.filter((u) => u !== key); + if (rest.length > 0) record.formUrls = rest; + else delete record.formUrls; + ops.push({ kind: 'put', store: 'applications', record }); + } + return ops; +} diff --git a/core/src/pack.test.ts b/core/src/pack.test.ts index b880353..78cd4f2 100644 --- a/core/src/pack.test.ts +++ b/core/src/pack.test.ts @@ -174,6 +174,7 @@ describe('interviewPack', () => { label: 'Willing to relocate', told: 'No', canonical: 'Yes', + fromFill: false, result: 'mismatch', }); // No label on the answer: falls back to its key. @@ -204,6 +205,58 @@ describe('interviewPack', () => { expect(pack?.unresolved).toBe(0); }); + it('marks fill statements and carries their question', () => { + const data = snap({ + applications: [{ id: 'a1', createdAt: T }], + statements: [ + { + id: 's1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsor', + value: { type: 'text', value: 'No' }, + source: 'fill', + question: 'Will you require sponsorship?', + }, + { + id: 's2', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsor', + value: { type: 'text', value: 'No' }, + }, + { + id: 's3', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsor', + value: { type: 'text', value: 'No' }, + source: 'other', + question: 42, + }, + { + id: 's4', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsor', + value: { type: 'text', value: 'No' }, + source: 'fill', + question: ' ', + }, + ], + }); + const pack = interviewPack(data, 'a1', {}); + const [first, second, third, fourth] = pack?.statements ?? []; + expect(first?.fromFill).toBe(true); + expect(first?.question).toBe('Will you require sponsorship?'); + expect(second?.fromFill).toBe(false); + expect(second && 'question' in second).toBe(false); + expect(third?.fromFill).toBe(false); + expect(third && 'question' in third).toBe(false); + expect(fourth?.fromFill).toBe(true); + expect(fourth && 'question' in fourth).toBe(false); + }); + it('lists rounds in order with resolved interviewers and kind labels', () => { const data = snap({ applications: [{ id: 'a1', createdAt: T }], diff --git a/core/src/pack.ts b/core/src/pack.ts index c65e566..ec5344f 100644 --- a/core/src/pack.ts +++ b/core/src/pack.ts @@ -24,6 +24,8 @@ export interface PackStatement { label: string; told: string; canonical?: string; + question?: string; + fromFill: boolean; result: MismatchResult; } @@ -112,9 +114,16 @@ export function interviewPack( nonEmpty(statement.answerKey) ?? 'Unknown answer', told: formatAnswer(statement.value), + fromFill: statement.source === 'fill', result, }; if (answer) item.canonical = formatAnswer(answer.value); + if ( + typeof statement.question === 'string' && + statement.question.trim() !== '' + ) { + item.question = statement.question; + } if (result === 'mismatch') pack.unresolved += 1; pack.statements.push(item); } diff --git a/core/src/statements.test.ts b/core/src/statements.test.ts index e306166..7a52dee 100644 --- a/core/src/statements.test.ts +++ b/core/src/statements.test.ts @@ -76,6 +76,40 @@ describe('putStatementOps', () => { .record; expect('value' in rec).toBe(false); }); + + it('drops source when the owner edits a fill statement', () => { + const fill: Statement = { + id: 's1', + createdAt: '2026-01-01T00:00:00.000Z', + applicationId: 'a1', + answerKey: 'salary_range', + value: { type: 'text', value: 'x' }, + source: 'fill', + question: 'Expected salary?', + }; + const rec = ( + putStatementOps(fill, { type: 'text', value: 'y' })[0] as { + record: Statement; + } + ).record; + expect('source' in rec).toBe(false); + expect(rec.question).toBe('Expected salary?'); + expect(rec.value).toEqual({ type: 'text', value: 'y' }); + }); + + it('keeps question and still clears exception', () => { + const withQuestion: Statement = { + ...base, + question: 'Expected salary?', + }; + const rec = ( + putStatementOps(withQuestion, { type: 'text', value: 'new' })[0] as { + record: Statement; + } + ).record; + expect(rec.question).toBe('Expected salary?'); + expect('exception' in rec).toBe(false); + }); }); describe('deleteStatementOps', () => { diff --git a/core/src/statements.ts b/core/src/statements.ts index d185c9a..5573e38 100644 --- a/core/src/statements.ts +++ b/core/src/statements.ts @@ -44,13 +44,14 @@ export function newStatement( return statement; } -/** Saves the told value and clears any exception mark. */ +/** Saves the told value, clears any exception mark and drops the fill source. */ export function putStatementOps( statement: Statement, value: AnswerValue | undefined, ): WriteOp[] { const record: Statement = { ...statement }; delete record.exception; + delete record.source; if (value === undefined) delete record.value; else record.value = value; return [{ kind: 'put', store: 'statements', record }]; diff --git a/core/src/told-panel.test.ts b/core/src/told-panel.test.ts new file mode 100644 index 0000000..8bf3da8 --- /dev/null +++ b/core/src/told-panel.test.ts @@ -0,0 +1,321 @@ +import { describe, expect, it } from 'vitest'; +import { fixedDeps } from '../testing/fixed-deps'; +import { emptySnapshot } from './schema'; +import { markAppliedOps, recordTickedOps, toldPanel } from './told-panel'; +import type { + Application, + AnswerValue, + CanonicalAnswer, + Snapshot, + Statement, + StatusEvent, +} from './types'; + +const T = '2026-01-05T09:00:00.000Z'; +const yes: AnswerValue = { type: 'yes_no', value: true }; +const notice: AnswerValue = { type: 'text', value: '2 weeks' }; + +const app: Application = { id: 'a1', createdAt: T }; + +function answer( + id: string, + key: string | undefined, + value: AnswerValue = yes, +): CanonicalAnswer { + const c: CanonicalAnswer = { id, createdAt: T }; + if (key !== undefined) c.key = key; + c.value = value; + return c; +} + +/** A canonical answer with no value field at all. */ +function valueless(id: string, key: string): CanonicalAnswer { + return { id, createdAt: T, key }; +} + +function statement( + id: string, + answerKey: string | undefined, + applicationId = 'a1', +): Statement { + const s: Statement = { id, createdAt: T, applicationId }; + if (answerKey !== undefined) s.answerKey = answerKey; + return s; +} + +function event( + id: string, + status: StatusEvent['status'], + extra: Partial = {}, +): StatusEvent { + return { + id, + createdAt: T, + applicationId: 'a1', + status, + occurredOn: '2026-01-05', + ...extra, + }; +} + +function snapshot(parts: Partial = {}): Snapshot { + return { ...emptySnapshot(), applications: [app], ...parts }; +} + +describe('toldPanel', () => { + it('lists canonical answers not yet stated on the application, in canonical order', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', 'sponsorship'), + answer('c2', 'notice', notice), + answer('c3', 'relocation'), + ], + }); + const panel = toldPanel(data, 'a1'); + expect(panel.unrecorded.map((c) => c.key)).toEqual([ + 'sponsorship', + 'notice', + 'relocation', + ]); + expect(panel.missing).toBe(false); + }); + + it('excludes keys already stated on this application, by fill or by hand', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', 'sponsorship'), + answer('c2', 'notice', notice), + answer('c3', 'relocation'), + ], + statements: [ + { ...statement('s1', 'sponsorship'), source: 'fill', value: yes }, + statement('s2', 'notice'), + ], + }); + expect(toldPanel(data, 'a1').unrecorded.map((c) => c.key)).toEqual([ + 'relocation', + ]); + }); + + it('counts a statement as stating its key whatever its value', () => { + const data = snapshot({ + canonicalAnswers: [answer('c1', 'sponsorship')], + statements: [statement('s1', 'sponsorship')], + }); + expect(toldPanel(data, 'a1').unrecorded).toEqual([]); + }); + + it('ignores statements that belong to another application', () => { + const data = snapshot({ + canonicalAnswers: [answer('c1', 'sponsorship')], + statements: [statement('s1', 'sponsorship', 'a2')], + }); + expect(toldPanel(data, 'a1').unrecorded.map((c) => c.key)).toEqual([ + 'sponsorship', + ]); + }); + + it('skips keyless, empty-key, valueless and malformed-value answers', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', undefined), + answer('c2', ''), + valueless('c3', 'no_value'), + answer('c4', 'null_value', null as unknown as AnswerValue), + answer('c5', 'array_value', [] as unknown as AnswerValue), + answer('c6', 'string_value', 'yes' as unknown as AnswerValue), + answer('c7', 'sponsorship'), + ], + }); + expect(toldPanel(data, 'a1').unrecorded.map((c) => c.key)).toEqual([ + 'sponsorship', + ]); + }); + + it('keeps only the first canonical answer for a duplicate key', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', 'sponsorship', yes), + answer('c2', 'sponsorship', { type: 'yes_no', value: false }), + ], + }); + const panel = toldPanel(data, 'a1'); + expect(panel.unrecorded.map((c) => c.id)).toEqual(['c1']); + }); + + it('uses the first valid answer when an earlier duplicate has no usable value', () => { + const data = snapshot({ + canonicalAnswers: [ + valueless('c1', 'sponsorship'), + answer('c2', 'sponsorship', yes), + ], + }); + expect(toldPanel(data, 'a1').unrecorded.map((c) => c.id)).toEqual(['c2']); + }); + + it('offers Mark Applied when there are no status events', () => { + expect(toldPanel(snapshot(), 'a1').offerApplied).toBe(true); + }); + + it('offers Mark Applied at interested', () => { + const data = snapshot({ statusEvents: [event('e1', 'interested')] }); + expect(toldPanel(data, 'a1').offerApplied).toBe(true); + }); + + it.each(['applied', 'interview', 'rejected'] as const)( + 'does not offer Mark Applied at %s', + (status) => { + const data = snapshot({ statusEvents: [event('e1', status)] }); + expect(toldPanel(data, 'a1').offerApplied).toBe(false); + }, + ); + + it('offers Mark Applied again once the applied event is voided', () => { + const data = snapshot({ + statusEvents: [ + event('e1', 'interested', { occurredOn: '2026-01-04' }), + event('e2', 'applied', { voidedAt: '2026-01-06T09:00:00.000Z' }), + ], + }); + expect(toldPanel(data, 'a1').offerApplied).toBe(true); + }); + + it('reports a missing application with an empty, unoffered panel', () => { + expect(toldPanel(snapshot(), 'nope')).toEqual({ + unrecorded: [], + offerApplied: false, + missing: true, + }); + }); +}); + +describe('recordTickedOps', () => { + it('puts one hand-ticked statement per ticked unrecorded key', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', 'sponsorship'), + answer('c2', 'notice', notice), + ], + }); + const result = recordTickedOps( + data, + 'a1', + ['notice', 'sponsorship'], + fixedDeps(), + ); + expect(result.missing).toBe(false); + expect(result.ops).toEqual([ + { + kind: 'put', + store: 'statements', + record: { + id: 'id-1', + createdAt: T, + applicationId: 'a1', + answerKey: 'sponsorship', + value: yes, + }, + }, + { + kind: 'put', + store: 'statements', + record: { + id: 'id-2', + // fixedDeps advances one second per now() call + createdAt: '2026-01-05T09:00:01.000Z', + applicationId: 'a1', + answerKey: 'notice', + value: notice, + }, + }, + ]); + }); + + it('writes no source or question on hand-ticked statements', () => { + const data = snapshot({ canonicalAnswers: [answer('c1', 'sponsorship')] }); + const { ops } = recordTickedOps(data, 'a1', ['sponsorship'], fixedDeps()); + expect(ops).toHaveLength(1); + const op = ops[0]; + expect(op?.kind === 'put' && op.store === 'statements').toBe(true); + const record = (op as { record: Statement }).record; + expect('source' in record).toBe(false); + expect('question' in record).toBe(false); + }); + + it('ignores a key that is already recorded and an unknown key', () => { + const data = snapshot({ + canonicalAnswers: [ + answer('c1', 'sponsorship'), + answer('c2', 'notice', notice), + ], + statements: [statement('s1', 'sponsorship')], + }); + const result = recordTickedOps( + data, + 'a1', + ['sponsorship', 'unknown_key', 'notice'], + fixedDeps(), + ); + expect(result.ops).toHaveLength(1); + expect(result.ops[0]).toMatchObject({ + kind: 'put', + store: 'statements', + record: { answerKey: 'notice' }, + }); + }); + + it('gives one statement for a key ticked twice', () => { + const data = snapshot({ canonicalAnswers: [answer('c1', 'sponsorship')] }); + const result = recordTickedOps( + data, + 'a1', + ['sponsorship', 'sponsorship'], + fixedDeps(), + ); + expect(result.ops).toHaveLength(1); + }); + + it('returns no ops and missing when the application does not exist', () => { + const data = snapshot({ canonicalAnswers: [answer('c1', 'sponsorship')] }); + expect(recordTickedOps(data, 'nope', ['sponsorship'], fixedDeps())).toEqual( + { ops: [], missing: true }, + ); + }); +}); + +describe('markAppliedOps', () => { + it('puts an applied event dated today and reports its id', () => { + const result = markAppliedOps(snapshot(), 'a1', '2026-01-21', fixedDeps()); + expect(result).toEqual({ + ops: [ + { + kind: 'put', + store: 'statusEvents', + record: { + id: 'id-1', + createdAt: T, + applicationId: 'a1', + status: 'applied', + occurredOn: '2026-01-21', + }, + }, + ], + eventId: 'id-1', + missing: false, + }); + }); + + it('returns no ops when the application is already applied', () => { + const data = snapshot({ statusEvents: [event('e1', 'applied')] }); + expect(markAppliedOps(data, 'a1', '2026-01-21', fixedDeps())).toEqual({ + ops: [], + missing: false, + }); + }); + + it('returns no ops and missing when the application does not exist', () => { + expect( + markAppliedOps(snapshot(), 'nope', '2026-01-21', fixedDeps()), + ).toEqual({ ops: [], missing: true }); + }); +}); diff --git a/core/src/told-panel.ts b/core/src/told-panel.ts new file mode 100644 index 0000000..dfa389b --- /dev/null +++ b/core/src/told-panel.ts @@ -0,0 +1,99 @@ +import { addStatusEventOps } from './application-ops'; +import type { WriteOp } from './repository'; +import { currentStatus } from './status'; +import { newStatement, statementsFor } from './statements'; +import type { + AnswerValue, + CanonicalAnswer, + Deps, + Id, + LocalDate, + Snapshot, +} from './types'; + +export interface ToldPanel { + unrecorded: CanonicalAnswer[]; + offerApplied: boolean; + missing: boolean; +} + +// Restored records are not field-checked, so a value may be null, a primitive or an array. +function isPlainObject(value: unknown): value is AnswerValue { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function applicationExists(data: Snapshot, applicationId: Id): boolean { + return data.applications.some((a) => a.id === applicationId); +} + +/** + * The canonical answers this application has no statement for yet, first record + * per key, in canonical order. Malformed answers are skipped, never thrown on. + */ +export function toldPanel(data: Snapshot, applicationId: Id): ToldPanel { + if (!applicationExists(data, applicationId)) { + return { unrecorded: [], offerApplied: false, missing: true }; + } + + const stated = new Set( + statementsFor(data, applicationId).map((s) => s.answerKey), + ); + const seen = new Set(); + const unrecorded: CanonicalAnswer[] = []; + for (const answer of data.canonicalAnswers) { + const key: unknown = answer.key; + if (typeof key !== 'string' || key === '') continue; + if (!isPlainObject(answer.value)) continue; + if (stated.has(key) || seen.has(key)) continue; + seen.add(key); + unrecorded.push(answer); + } + + const current = currentStatus(data.statusEvents, applicationId); + const offerApplied = current === undefined || current.status === 'interested'; + return { unrecorded, offerApplied, missing: false }; +} + +/** One hand-ticked statement per ticked key still unrecorded. Other keys are ignored. */ +export function recordTickedOps( + data: Snapshot, + applicationId: Id, + answerKeys: readonly string[], + deps: Deps, +): { ops: WriteOp[]; missing: boolean } { + const panel = toldPanel(data, applicationId); + if (panel.missing) return { ops: [], missing: true }; + + const ticked = new Set(answerKeys); + const ops: WriteOp[] = panel.unrecorded + .filter((answer) => ticked.has(answer.key ?? '')) + .map((answer): WriteOp => ({ + kind: 'put', + store: 'statements', + record: newStatement(answer, applicationId, deps), + })); + return { ops, missing: false }; +} + +/** Marks the application applied on `today`, only when the panel offers it. */ +export function markAppliedOps( + data: Snapshot, + applicationId: Id, + today: LocalDate, + deps: Deps, +): { ops: WriteOp[]; eventId?: Id; missing: boolean } { + const panel = toldPanel(data, applicationId); + if (panel.missing) return { ops: [], missing: true }; + if (!panel.offerApplied) return { ops: [], missing: false }; + + const ops = addStatusEventOps( + applicationId, + { status: 'applied', occurredOn: today }, + deps, + ); + const eventOp = ops.find( + (op): op is Extract => + op.kind === 'put' && op.store === 'statusEvents', + ); + return { ops, eventId: eventOp?.record.id, missing: false }; +} diff --git a/core/src/types.ts b/core/src/types.ts index 40cc69c..37ba88b 100644 --- a/core/src/types.ts +++ b/core/src/types.ts @@ -30,6 +30,7 @@ export interface Application extends BaseRecord { fillOutcome?: FillOutcome; fillNote?: string; projectsShown?: string; + formUrls?: string[]; } export interface StatusEvent extends BaseRecord { applicationId?: Id; @@ -86,6 +87,8 @@ export interface Statement extends BaseRecord { answerKey?: string; value?: AnswerValue; exception?: boolean; + source?: 'fill'; + question?: string; } export interface Contact extends BaseRecord { companyId?: Id; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index fde58ba..9f255ed 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -27,6 +27,8 @@ The repository interface (`core/src/repository.ts`) has three methods: To change data, a function in `core/` takes a snapshot and returns a list of operations. It does not write anything itself. The shell applies the list. Views filter the snapshot in memory; the data set is hundreds of records, so there are no secondary indexes. +A fill's result is recorded by `core/src/fill-records.ts` in one write; nothing else about a fill is stored. + Two details in the shell: - Writes are serialised and each is built from a fresh snapshot (`shell/ui/write-queue.ts`). Two quick clicks cannot overwrite each other with stale data. @@ -40,6 +42,7 @@ An in-memory repository (`core/src/memory-repository.ts`) is used in tests. The - A round (`Round`) belongs to an application and holds a kind, date, time, interviewer ids and four flat debrief fields. A story (`Story`) holds situation, task, action, result and tags. A weekly review (`WeeklyReview`) holds a week start, an outreach target and an application cap. - New optional fields: `Company.isTarget`, `Application.projectsShown`, `Contact.followUpOn`, `Contact.followUpApplicationId` and `ContactEvent.voidedAt`. A contact event is undone by setting `voidedAt`; voided events are hidden and never counted. +- Optional fields for fills: `Statement.source` (`'fill'` when a fill recorded it), `Statement.question` (the form's question text) and `Application.formUrls` (the form pages linked to this application). - Weekly counts (`core/src/weekly.ts`) are derived on read from live contact events and status events whose date falls in Monday to Sunday. Nothing is stored except the plan. - `Company.anyoneHere` is `'checked_nobody'` when you have recorded that nobody you know works there. Contacts are otherwise linked by `companyId`. diff --git a/shell/ui/FormLink.tsx b/shell/ui/FormLink.tsx new file mode 100644 index 0000000..5291369 --- /dev/null +++ b/shell/ui/FormLink.tsx @@ -0,0 +1,230 @@ +import type { VNode } from 'preact'; +import { useState } from 'preact/hooks'; +import { applicationRows } from '../../core/src/application-list'; +import type { Id, Snapshot } from '../../core/src/types'; +import { Button } from './components/Button'; +import { Field } from './components/Field'; +import { Text } from './components/Text'; + +const MAX_ROWS = 20; + +type Mode = 'idle' | 'choose' | 'new'; + +function nameOf(value: string | undefined, fallback: string): string { + return value !== undefined && value.trim() !== '' ? value : fallback; +} + +/** "Company · Title" with the fallbacks the link line uses. */ +export function displayName( + company: string | undefined, + title: string | undefined, +): string { + return `${nameOf(company, 'Unknown company')} · ${nameOf(title, 'Untitled')}`; +} + +/** The display name of an application in a snapshot. */ +export function applicationLabel(data: Snapshot, id: Id): string { + const row = applicationRows(data).find((r) => r.id === id); + return displayName(row?.companyName, row?.title); +} + +export interface RecordLine { + recorded: number; + alreadyOnForm: number; + name: string; +} + +function recordedText(line: RecordLine): string { + const answers = line.recorded === 1 ? '1 answer' : `${line.recorded} answers`; + const already = + line.alreadyOnForm > 0 + ? ` (${line.alreadyOnForm} ${line.alreadyOnForm === 1 ? 'was' : 'were'} already on the form)` + : ''; + return `Recorded ${answers} on ${line.name}${already}.`; +} + +/** + * Candidate application ids for the picker: active applications, newest + * created first. + */ +export function pickerCandidates(data: Snapshot): Id[] { + return applicationRows(data) + .filter((r) => !r.archived) + .sort((a, b) => + a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0, + ) + .map((r) => r.id); +} + +export function FormLink(props: { + data: Snapshot; + linkedId?: Id; + candidates: Id[]; + initialCompany?: string; + initialTitle?: string; + /** Resolves true when the write succeeded. */ + onLink: (id: Id) => Promise; + onNew: (input: { companyName: string; title: string }) => Promise; + busy: boolean; + error?: string; + /** Called when the mode changes or Cancel is pressed. */ + onClearError?: () => void; + /** A fill is held until an application is linked. */ + heldNotice?: boolean; + notice?: string; + recordLine?: RecordLine; +}): VNode { + const [mode, setMode] = useState('idle'); + const [query, setQuery] = useState(''); + const [company, setCompany] = useState(undefined); + const [title, setTitle] = useState(undefined); + + const changeMode = (next: Mode): void => { + props.onClearError?.(); + setMode(next); + }; + + const rows = applicationRows(props.data); + const byId = new Map(rows.map((r) => [r.id, r] as const)); + const label = (id: Id): string => { + const row = byId.get(id); + return displayName(row?.companyName, row?.title); + }; + + const done = (ok: boolean): void => { + if (ok) setMode('idle'); + }; + + let panel: VNode | null = null; + if (mode === 'choose') { + const needle = query.trim().toLowerCase(); + const matching = props.candidates.filter((id) => { + if (needle === '') return true; + const row = byId.get(id); + return ( + (row?.companyName ?? '').toLowerCase().includes(needle) || + (row?.title ?? '').toLowerCase().includes(needle) + ); + }); + panel = ( + + ); + } else if (mode === 'new') { + const companyValue = company ?? props.initialCompany ?? ''; + const titleValue = title ?? props.initialTitle ?? ''; + panel = ( + + ); + } + + const linked = props.linkedId !== undefined; + return ( + + ); +} diff --git a/shell/ui/PackPage.tsx b/shell/ui/PackPage.tsx index 983faf6..83f1179 100644 --- a/shell/ui/PackPage.tsx +++ b/shell/ui/PackPage.tsx @@ -43,6 +43,8 @@ function StatementItem(props: { item: PackStatement }): VNode { return (
  • {item.label}: {item.told} + {item.question ?
    They asked: {item.question}
    : null} + {item.fromFill ? From a fill : null} {differs ?
    Your canonical answer: {item.canonical}
    : null} {item.result === 'mismatch' ? ( Unresolved mismatch diff --git a/shell/ui/Popup.tsx b/shell/ui/Popup.tsx index e237910..9cdbfea 100644 --- a/shell/ui/Popup.tsx +++ b/shell/ui/Popup.tsx @@ -8,7 +8,17 @@ import { saveJobOps, } from '../../core/src/job-ops'; import type { JobInput } from '../../core/src/job-ops'; +import type { FillResult } from '../../core/src/fill/result'; +import { fillRecordOps } from '../../core/src/fill-records'; +import type { FillRecord } from '../../core/src/fill-records'; +import { + linkFormAndRecordOps, + newApplicationFromFormOps, +} from '../../core/src/form-application'; +import { findApplicationsForForm, formUrlKey } from '../../core/src/form-link'; import { profileValues } from '../../core/src/profile'; +import type { WriteOp } from '../../core/src/repository'; +import type { Id, Snapshot } from '../../core/src/types'; import { canonicalizeUrl } from '../../core/src/url'; import { capturePage } from '../capture/inject'; import type { CaptureOutcome } from '../capture/inject'; @@ -17,7 +27,16 @@ import type { FillController } from '../fill/controller'; import { openDashboard } from '../open-dashboard'; import { useAppData } from './app-data'; import { AnyoneHere } from './AnyoneHere'; +import { currentStatus, statusLabel } from '../../core/src/status'; import { FillSection } from './FillSection'; +import { ToldPanel } from './ToldPanel'; +import { + FormLink, + applicationLabel, + displayName, + pickerCandidates, +} from './FormLink'; +import type { RecordLine } from './FormLink'; import { Button } from './components/Button'; import { Fact } from './components/Fact'; import { Field } from './components/Field'; @@ -115,10 +134,57 @@ export function Popup(): VNode { } const controller = controllerRef.current; + const [fillStatus, setFillStatus] = useState(() => controller.state().status); + useEffect(() => { + const unsubscribe = controller.subscribe((s) => setFillStatus(s.status)); + setFillStatus(controller.state().status); + return unsubscribe; + }, [controller]); + + // Set by Choose… and Create and link; see linkedId below. + const [chosenId, setChosenId] = useState(undefined); + const [linking, setLinking] = useState(false); + const [linkError, setLinkError] = useState(undefined); + // A fill result waiting for an application to record it on. + const [held, setHeld] = useState(undefined); + const heldRef = useRef(undefined); + heldRef.current = held; + const [recordLine, setRecordLine] = useState( + undefined, + ); + const [recordNotice, setRecordNotice] = useState( + undefined, + ); + // Duplicate and repost facts for the application just made from this form. + const [newFacts, setNewFacts] = useState< + { match: Facts['match']; repost: string | undefined } | undefined + >(undefined); + const linkingRef = useRef(false); + const keepHeldRef = useRef(false); + const linkedIdRef = useRef(undefined); + useEffect(() => { controller.refresh(); }, [data]); + // A match linked the form without the owner's click: drop the stale held + // fill rather than let a later Choose… record it. The owner's own link + // path records and clears held itself, and is excluded while in flight. + // Exception: onFilled holds a result on two recoverable paths (application + // gone, write rejected) where the popup still offers to record it; those + // keep it until the owner's next link (runLink resets this). + useEffect(() => { + if ( + linkedIdRef.current !== undefined && + heldRef.current !== undefined && + !linkingRef.current && + !keepHeldRef.current + ) { + heldRef.current = undefined; + setHeld(undefined); + } + }); + useEffect(() => { if (started.current) return; started.current = true; @@ -208,6 +274,193 @@ export function Popup(): VNode { const outcomeUrl = outcome.ok ? outcome.capture.url : outcome.url; const linkValue = pasteLink ?? (isHttp(outcomeUrl) ? outcomeUrl.trim() : ''); + const formKey = + outcomeUrl === undefined + ? undefined + : formUrlKey(outcomeUrl, captured?.relCanonical); + // A chosen application that still exists wins; otherwise the first match. + // Task 8 records a fill to linkedId; Task 9 shows a panel for it. + const linkedId: Id | undefined = + chosenId !== undefined && data.applications.some((a) => a.id === chosenId) + ? chosenId + : formKey === undefined + ? undefined + : findApplicationsForForm(data, formKey)[0]; + + linkedIdRef.current = linkedId; + + const MISSING = 'The application is no longer there. Choose another.'; + + // One apply per write, with the held fill result recorded in the same one. + const runLink = ( + build: (d: Snapshot) => { + ops: WriteOp[]; + id: Id; + name: string; + record?: FillRecord; + match?: Facts['match']; + repost?: string; + }, + ): Promise => { + if (linkingRef.current) return Promise.resolve(false); + linkingRef.current = true; + setLinking(true); + setLinkError(undefined); + const got: { + id?: Id; + name: string; + record?: FillRecord; + held?: FillResult; + match?: Facts['match']; + repost?: string; + } = { name: '' }; + return app + .apply((d) => { + // The held result the builder reads, captured in the same sync step. + got.held = heldRef.current; + const built = build(d); + got.id = built.id; + got.name = built.name; + got.record = built.record; + got.match = built.match; + got.repost = built.repost; + if (built.record?.missing) throw new Error(MISSING); + return built.ops; + }) + .then( + () => { + linkingRef.current = false; + // Only a successful owner link ends the keep; a failed one leaves + // the held result offered for a retry. + keepHeldRef.current = false; + setChosenId(got.id); + setLinking(false); + setRecordNotice(undefined); + setNewFacts( + got.match !== undefined || got.repost !== undefined + ? { match: got.match, repost: got.repost } + : undefined, + ); + if (got.record !== undefined) { + // Clear only the result this link recorded; a Fill that finished + // during the write has replaced it and must survive. + if (got.held !== undefined && heldRef.current === got.held) { + setHeld(undefined); + } + setRecordLine( + got.record.recorded > 0 + ? { + recorded: got.record.recorded, + alreadyOnForm: got.record.alreadyOnForm, + name: got.name, + } + : undefined, + ); + } + return true; + }, + (err: unknown) => { + linkingRef.current = false; + setLinkError(messageOf(err)); + setLinking(false); + return false; + }, + ); + }; + const linkExisting = (id: Id): Promise => + runLink((d) => { + const built = linkFormAndRecordOps( + d, + id, + formKey ?? '', + heldRef.current, + deps, + ); + return { + ops: built.ops, + id, + name: applicationLabel(d, id), + record: built.record, + }; + }); + + const onFilled = (result: FillResult): void => { + setRecordLine(undefined); + setRecordNotice(undefined); + // Read when the fill completes, not at the click (FillSection is fixed). + const id = linkedIdRef.current; + if (id === undefined) { + keepHeldRef.current = false; + setHeld(result); + return; + } + const got: { name: string; record?: FillRecord } = { name: '' }; + app + .apply((d) => { + const record = fillRecordOps(d, result, id, deps); + got.record = record; + got.name = applicationLabel(d, id); + return record.ops; + }) + .then( + () => { + const record = got.record; + if (record === undefined) return; + if (record.missing) { + keepHeldRef.current = true; + heldRef.current = result; + setHeld(result); + setChosenId(undefined); + setRecordNotice(MISSING); + return; + } + keepHeldRef.current = false; + setHeld(undefined); + if (record.recorded > 0) { + setRecordLine({ + recorded: record.recorded, + alreadyOnForm: record.alreadyOnForm, + name: got.name, + }); + } + }, + (err: unknown) => { + keepHeldRef.current = true; + heldRef.current = result; + setHeld(result); + setLinkError(messageOf(err)); + }, + ); + }; + const linkNew = (names: { + companyName: string; + title: string; + }): Promise => + runLink((d) => { + const input: JobInput = { + source: captured + ? captured.source === 'jsonld' + ? 'jsonld' + : 'selection' + : 'paste', + url: isHttp(outcomeUrl) ? outcomeUrl.trim() : undefined, + relCanonical: captured?.relCanonical, + title: names.title, + companyName: names.companyName, + location: captured?.location, + text: captured?.text ?? '', + }; + const built = newApplicationFromFormOps(d, input, deps, heldRef.current); + return { + ops: built.ops, + id: built.applicationId, + name: displayName(names.companyName, names.title), + record: built.record, + match: built.match, + repost: built.repost, + }; + }); + let body: VNode; if (captured) { const input: JobInput = { @@ -367,7 +620,48 @@ export function Popup(): VNode { ) : null} - + {fillStatus === 'ready' && formKey !== undefined ? ( + setLinkError(undefined)} + heldNotice={held !== undefined && linkedId === undefined} + notice={recordNotice} + recordLine={recordLine} + /> + ) : null} + {newFacts?.match === 'already_applied' ? ( + Already applied here. + ) : null} + {newFacts?.match === 'possible_match' ? ( + + Possible match: an application for the same company and title. + + ) : null} + {newFacts?.repost ? ( + {newFacts.repost} + ) : null} + + {fillStatus === 'ready' && linkedId !== undefined ? ( + app.apply(build)} + /> + ) : null} + {typeof s.question === 'string' && + s.question.trim() !== '' ? ( +
    They asked: {s.question}
    + ) : null} + {s.source === 'fill' ? ( + From a fill + ) : null} {check === 'mismatch' ? ( Differs from your answer: {canonical}{' '} diff --git a/shell/ui/ToldPanel.tsx b/shell/ui/ToldPanel.tsx new file mode 100644 index 0000000..ff1989b --- /dev/null +++ b/shell/ui/ToldPanel.tsx @@ -0,0 +1,161 @@ +import type { VNode } from 'preact'; +import { useRef, useState } from 'preact/hooks'; +import { voidStatusEventOps } from '../../core/src/application-ops'; +import { toLocalDate } from '../../core/src/dates'; +import type { WriteOp } from '../../core/src/repository'; +import { + markAppliedOps, + recordTickedOps, + toldPanel, +} from '../../core/src/told-panel'; +import type { Deps, Id, Snapshot } from '../../core/src/types'; +import { Button } from './components/Button'; +import { Text } from './components/Text'; + +const MISSING = 'The application is no longer there. Choose another.'; + +export interface ToldPanelProps { + data: Snapshot; + applicationId: Id; + statusLabel: string; + deps: Deps; + onApply(build: (d: Snapshot) => WriteOp[]): Promise; +} + +export function ToldPanel(props: ToldPanelProps): VNode | null { + const { data, applicationId, deps } = props; + const [ticked, setTicked] = useState([]); + const [markedEvent, setMarkedEvent] = useState(undefined); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(undefined); + const busyRef = useRef(false); + + const panel = toldPanel(data, applicationId); + if ( + panel.unrecorded.length === 0 && + !panel.offerApplied && + markedEvent === undefined + ) { + return null; + } + + // One write at a time; the decision is made against the builder's fresh data. + const run = ( + build: (d: Snapshot, got: { missing: boolean }) => WriteOp[], + done: () => void, + ): void => { + if (busyRef.current) return; + busyRef.current = true; + setBusy(true); + setError(undefined); + const got = { missing: false }; + props + .onApply((d) => { + const ops = build(d, got); + return got.missing ? [] : ops; + }) + .then( + () => { + busyRef.current = false; + setBusy(false); + if (got.missing) setError(MISSING); + else done(); + }, + (err: unknown) => { + busyRef.current = false; + setBusy(false); + setError(err instanceof Error ? err.message : String(err)); + }, + ); + }; + + const toggle = (key: string, on: boolean): void => + setTicked((t) => (on ? [...t, key] : t.filter((k) => k !== key))); + + const record = (): void => + run( + (d, got) => { + const r = recordTickedOps(d, applicationId, ticked, deps); + got.missing = r.missing; + return r.ops; + }, + () => setTicked([]), + ); + + let newEventId: Id | undefined; + const markApplied = (): void => + run( + (d, got) => { + const r = markAppliedOps( + d, + applicationId, + toLocalDate(new Date()), + deps, + ); + got.missing = r.missing; + newEventId = r.eventId; + return r.ops; + }, + () => setMarkedEvent(newEventId), + ); + + const undo = (): void => { + const id = markedEvent; + run( + (d) => { + const event = d.statusEvents.find((e) => e.id === id); + return event === undefined ? [] : voidStatusEventOps(event, deps); + }, + () => setMarkedEvent(undefined), + ); + }; + + return ( + + ); +} diff --git a/shell/ui/theme/popup-layout.css b/shell/ui/theme/popup-layout.css index d60fc68..811a7db 100644 --- a/shell/ui/theme/popup-layout.css +++ b/shell/ui/theme/popup-layout.css @@ -25,6 +25,25 @@ margin: 0.5rem 0; } +.popup-formlink, +.popup-told, +.popup-told-list, +.popup-formlink-panel, +.popup-formlink-list { + display: flex; + flex-direction: column; + gap: var(--space-1); + overflow-wrap: anywhere; +} + +.popup-formlink { + padding: var(--space-1) 0; +} + +.popup-formlink-list { + align-items: flex-start; +} + .popup-fill { display: flex; flex-direction: column;