diff --git a/apps/backend/worker/src/main.ts b/apps/backend/worker/src/main.ts index 4bfd506f..5629ff02 100644 --- a/apps/backend/worker/src/main.ts +++ b/apps/backend/worker/src/main.ts @@ -88,12 +88,14 @@ const { readEvidenceForJobAsSystem, } = await import('@credalent/evidence/composition'); const { createIdentity } = await import('@credalent/identity/composition'); -const { PackMembersAddedV1, PackReadyV1 } = await import('@credalent/decisions'); -const { createPackSummaryHandlers, PACK_SUMMARY_QUEUE } = await import('@credalent/decisions/composition'); +const { DecisionsRecordedV1, PackMembersAddedV1, PackReadyV1 } = await import('@credalent/decisions'); +const { createPackSummaryHandlers, PACK_SUMMARY_QUEUE, readDecisionsAsSystem } = + await import('@credalent/decisions/composition'); const { InterviewCompletedV1, InterviewScheduledV1, MeetingSummarySubmittedV1 } = await import('@credalent/interviews'); const { createSummaryHandlers, SUMMARY_QUEUE } = await import('@credalent/interviews/composition'); const { ApplicationReceivedV1 } = await import('@credalent/intake'); -const { createApplicationReads, readApplicationSourceAsSystem } = await import('@credalent/intake/composition'); +const { createApplicationReads, createDecisionStageHandler, readApplicationSourceAsSystem } = + await import('@credalent/intake/composition'); const { createAiTokenBudget } = await import('@credalent/workspaces/composition'); const { CatalogueEvalRequestedV1, JobPublishedV1, JobUnpublishedV1, RubricApprovedV1 } = await import('@credalent/jobs'); @@ -121,9 +123,8 @@ const githubApp = env.GITHUB_APP_ID && env.GITHUB_APP_PRIVATE_KEY && env.GITHUB_ const fileReading = Boolean(env.AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT && env.AZURE_STORAGE_BLOB_URL); // shortcut: `files` (FileClean.v1, FileRejected.v1) is relayed only with file reading, their one consumer (AIV-P1-025). // `interviews` is relayed for MeetingSummarySubmitted.v1 (AIV-P1-115); its other two events are parked in QUEUES below. -// `decisions` is relayed for PackReady.v1 and PackMembersAdded.v1, the pack summaries (AIV-P2-011). -// shortcut: DecisionsRecorded.v1 (AIV-P2-009) has no queue: it waits unsent in decisions.outbox, retried by the relay, -// until its consumers exist (the stage change in intake, the decision email drafts in notifications) and map it. +// `decisions` is relayed for PackReady.v1 and PackMembersAdded.v1, the pack summaries (AIV-P2-011), and for +// DecisionsRecorded.v1, the stage change in intake (AIV-P2-012). const OUTBOXES = [ 'candidates', 'jobs', @@ -153,6 +154,10 @@ const QUEUES: Record = { // A pack's members to summarise (AIV-P2-011): always consumed; with no model each is stored "Summary unavailable". [PackReadyV1.type]: PACK_SUMMARY_QUEUE, [PackMembersAddedV1.type]: PACK_SUMMARY_QUEUE, + // A hiring owner's recorded decisions (AIV-P2-012): intake moves each decided candidate's stage. Always consumed. + // shortcut: on the pack summaries' queue, which every environment has; move both to a `decisions` queue + // (infra/modules/messaging.bicep) when the decision email drafts (AIV-P2-073) add a consumer of their own. + [DecisionsRecordedV1.type]: PACK_SUMMARY_QUEUE, // shortcut: nothing consumes these yet (applying from the candidate site is AIV-P3-008), so they dead-letter after the // 14-day TTL like PersonCreated.v1 above; that ticket's consumer replaces this note. [JobPublishedV1.type]: 'candidates', @@ -303,6 +308,14 @@ const identity = createIdentity(appDb, { trustedIssuer: 'worker: reads display n now, }), ); +// The stage after a recorded decision (AIV-P2-012): "Round 2 shortlist" or "Not advanced", audited as the hiring owner's. +(CONSUMERS[PACK_SUMMARY_QUEUE] ??= []).push( + createDecisionStageHandler({ + event: DecisionsRecordedV1, + decisionsOf: readDecisionsAsSystem, + audit: createAudit(appDb, now), + }), +); if (mapping) evidenceHandlers.push( ...createEvidenceMappingHandlers({ diff --git a/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/candidates/Ranking.test.tsx b/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/candidates/Ranking.test.tsx index 85f1114d..b73b0eb3 100644 --- a/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/candidates/Ranking.test.tsx +++ b/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/candidates/Ranking.test.tsx @@ -462,6 +462,10 @@ describe('Scenario: Preview, then confirm (AIV-P1-114)', () => { }); }); +/** AIV-P2-012: Sara on the Round 2 shortlist and Arjun not advanced, by the hiring owner's recorded decision. */ +const decidedStage = (name: string | null) => + name === 'Sara Al Qahtani' ? 'round2_shortlist' : name === 'Arjun Menon' ? 'not_advanced' : null; + describe('Scenario: Someone already chosen is not chosen twice (AIV-P1-114)', () => { it('marks them "Already chosen for interview", counts only the others, and their row shows the next action', async () => { const rows = nine.map((row) => (row.name === 'Sara Al Qahtani' ? { ...row, stage: 'interview' as const } : row)); @@ -475,6 +479,27 @@ describe('Scenario: Someone already chosen is not chosen twice (AIV-P1-114)', () expect(preview().textContent).toContain('Sara Al QahtaniAlready chosen for interview'); expect(within(preview()).getByRole('button', { name: 'Choose 1 for interview' })).toBeTruthy(); }); + + // AIV-P2-012: a recorded decision is never reversed by choosing the person for Round 1 again. + // SAFETY: mutation check: chosenOrDecided returned `stage === 'interview'` only -> this test failed (Sara and Arjun counted to choose) + it('someone on the Round 2 shortlist or not advanced is not counted, the preview says why, and their row shows the stage', async () => { + choosable(nine.map((row) => ({ ...row, stage: decidedStage(row.name) ?? row.stage }))); + const rows = bodyRows(); + expect(rows.find((row) => row.textContent.includes('Sara Al Qahtani'))?.textContent).toContain('Round 2 shortlist'); + expect(rows.find((row) => row.textContent.includes('Arjun Menon'))?.textContent).toContain('Not advanced'); + await pick('Sara Al Qahtani'); + await pick('Arjun Menon'); + await pick('Daniel Novak'); + await userEvent.click(within(bar()).getByRole('button', { name: 'Choose for interview' })); + expect(within(preview()).getByRole('heading').textContent).toBe('Preview: 1 person chosen for interview'); + expect(preview().textContent).toContain( + 'Sara Al QahtaniOn the Round 2 shortlist by the hiring owner’s decision, so not chosen again', + ); + expect(preview().textContent).toContain( + 'Arjun MenonNot advanced by the hiring owner’s decision, so not chosen again', + ); + expect(within(preview()).getByRole('button', { name: 'Choose 1 for interview' })).toBeTruthy(); + }); }); describe('Scenario: Cancel changes nothing (AIV-P1-114)', () => { diff --git a/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/packs/[packId]/PackClient.test.tsx b/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/packs/[packId]/PackClient.test.tsx new file mode 100644 index 00000000..b28f5046 --- /dev/null +++ b/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/packs/[packId]/PackClient.test.tsx @@ -0,0 +1,204 @@ +// @vitest-environment jsdom +import { intlConfig } from '@credalent/i18n'; +import { IntlProvider } from '@credalent/i18n/react'; +import { cleanup, render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { PackPage } from '@/features/decision-pack/domain/pack.ts'; +import { PackClient } from './PackClient.tsx'; + +// AIV-P2-012: "Record the decision" on the pack, with its controller; the server action and the router are faked. The +// hiring owner's authority and the stored decisions are proven against PostgreSQL in tests/integration. Synthetic cast. +const fake = vi.hoisted(() => ({ record: vi.fn(), refresh: vi.fn() })); +vi.mock('@/features/decision-pack/services/recordDecisions.ts', () => ({ recordDecisions: fake.record })); +vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: fake.refresh }) })); +vi.mock('next/link', () => ({ + default: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => ( + + {children} + + ), +})); + +let intl: Awaited>; +beforeAll(async () => { + intl = await intlConfig('en', 'Asia/Dubai'); +}); +afterEach(() => { + cleanup(); + vi.resetAllMocks(); +}); + +const id = (n: number) => `0190d4a2-0000-7000-9000-${String(n).padStart(12, '0')}`; +const [JOB, PACK, SARA, ARJUN, HUDA] = [id(1), id(2), id(21), id(22), id(23)]; +const NAMES = ['Sara Al Qahtani', 'Arjun Menon', 'Huda Al Mansoori']; +const WHY = 'Strong on the two heaviest competencies.'; +const decidedAt = new Date('2026-11-18T09:30:00.000Z'); +beforeEach(() => fake.record.mockResolvedValue({ ok: true, decidedAt })); + +const pack = (over: Partial = {}): PackPage => ({ + jobId: JOB, + packId: PACK, + name: 'Round 2 shortlist', + job: 'Senior AI Engineer', + preparedAt: new Date('2026-11-17T08:00:00.000Z'), + rubricVersion: 2, + role: null, + members: [SARA, ARJUN, HUDA].map((candidateId, i) => ({ + candidateId, + name: NAMES[i] ?? null, + backedScore: 68, + upperBound: 84, + added: null, + // Credalent recommends advancing Sara: it must not pre-select her decision. + summary: { + status: 'ready', + summary: { + strengths: [], + risks: [], + round1: null, + recommendation: { action: 'advance', focus: null, citations: [] }, + }, + }, + decision: null, + })), + others: 2, + mayDecide: true, + decided: null, + ...over, +}); +const show = (page: PackPage) => + render( + + + , + ); +const group = (name: string) => screen.getByRole('radiogroup', { name: `Your decision for ${name}` }); +const choose = (name: string, option: string) => + userEvent.click(within(group(name)).getByRole('radio', { name: option })); + +describe('Scenario: Record decisions', () => { + it('nothing is chosen at first, even where Credalent recommends advancing', () => { + show(pack()); + for (const name of NAMES) + expect( + within(group(name)) + .getAllByRole('radio') + .map((r) => (r as HTMLInputElement).checked), + ).toEqual([false, false, false]); + expect(screen.getByText(/No candidate is contacted until you send a message yourself\./)).toBeTruthy(); + }); + + // SAFETY: mutation check: onRecord opened the preview without the undecided() check -> this test failed (preview shown) + it('Scenario: Every candidate needs a choice: nothing for Huda, "Record decisions" says so and records nothing', async () => { + show(pack()); + await choose('Sara Al Qahtani', 'Advance to Round 2'); + await choose('Arjun Menon', 'Advance to Round 2'); + await userEvent.click(screen.getByRole('button', { name: 'Record decisions' })); + expect(screen.getByRole('alert').textContent).toBe('Choose a decision for Huda Al Mansoori'); + expect(group('Huda Al Mansoori').getAttribute('aria-invalid')).toBe('true'); + expect(screen.queryByRole('region', { name: /^Preview/ })).toBeNull(); + expect(fake.record).not.toHaveBeenCalled(); + }); + + // SAFETY: mutation check: dropped `|| Boolean(record?.recordedAt)` from readOnly in DecisionPack -> this test failed (choices editable before the refresh) + it('advance for all three, previewed with each stage and a reason, then recorded once on Confirm', async () => { + const { rerender } = show(pack()); + for (const name of NAMES) await choose(name, 'Advance to Round 2'); + await userEvent.click(screen.getByRole('button', { name: 'Record decisions' })); + const preview = screen.getByRole('region', { name: 'Preview: record 3 decisions' }); + expect(within(preview).getAllByText('Advance to Round 2. The stage becomes Round 2 shortlist.')).toHaveLength(3); + expect(preview.textContent).toContain('Nothing changes until you confirm.'); + // One primary button in view: "Record decisions" gives way to the preview's Confirm. + expect(screen.queryByRole('button', { name: 'Record decisions' })).toBeNull(); + const confirm = within(preview).getByRole('button', { name: 'Record 3 decisions' }); + expect((confirm as HTMLButtonElement).disabled).toBe(true); + await userEvent.type(within(preview).getByRole('textbox', { name: /^Reason/ }), WHY); + await userEvent.click(confirm); + expect(fake.record).toHaveBeenCalledTimes(1); + expect(fake.record).toHaveBeenCalledWith({ + packId: PACK, + decisions: [SARA, ARJUN, HUDA].map((candidateId) => ({ candidateId, decision: 'advance' })), + reason: WHY, + }); + expect(fake.refresh).toHaveBeenCalled(); + // Before the page is read again: the confirmation, the choices read-only as recorded, and no way to record twice. + expect(screen.getByRole('status').textContent).toBe( + 'Decisions recorded by you on 18 Nov 2026 and added to the audit trail. Schedule Round 2 interviews', + ); + for (const name of NAMES) { + const advance = within(group(name)).getByRole('radio', { name: 'Advance to Round 2' }); + expect([(advance as HTMLInputElement).checked, advance.matches(':disabled')]).toEqual([true, true]); + } + expect(screen.queryByRole('button', { name: 'Record decisions' })).toBeNull(); + // The page re-reads the decided pack. + rerender( + + ({ ...m, decision: 'advance' })), + })} + /> + , + ); + expect(screen.getByRole('status').textContent).toBe( + 'Decisions recorded by you on 18 Nov 2026 and added to the audit trail. Schedule Round 2 interviews', + ); + expect(screen.getByRole('link', { name: 'Schedule Round 2 interviews' }).getAttribute('href')).toBe( + `/app/jobs/${JOB}/interviews`, + ); + }); + + it('do not advance and hold say what happens to the stage; a refused record keeps the preview and says nothing was recorded', async () => { + fake.record.mockResolvedValue({ ok: false, error: 'failed' }); + show(pack()); + await choose('Sara Al Qahtani', 'Advance to Round 2'); + await choose('Arjun Menon', 'Do not advance'); + await choose('Huda Al Mansoori', 'Hold'); + await userEvent.click(screen.getByRole('button', { name: 'Record decisions' })); + const preview = screen.getByRole('region', { name: 'Preview: record 3 decisions' }); + expect(within(preview).getByText('Do not advance. The stage becomes Not advanced.')).toBeTruthy(); + expect(within(preview).getByText('Hold. The stage stays as it is.')).toBeTruthy(); + await userEvent.type(within(preview).getByRole('textbox', { name: /^Reason/ }), WHY); + await userEvent.click(within(preview).getByRole('button', { name: 'Record 3 decisions' })); + expect(within(preview).getByRole('alert').textContent).toBe( + 'That did not go through. Nothing was recorded. Try again.', + ); + expect(fake.refresh).not.toHaveBeenCalled(); + }); +}); + +describe('Scenario: Only the authorised hiring owner', () => { + it('a recruiter sees the choices read-only with "Only the hiring owner can record decisions", and no way to record', () => { + show(pack({ mayDecide: false })); + for (const name of NAMES) + expect( + within(group(name)) + .getAllByRole('radio') + .every((r) => r.matches(':disabled')), + ).toBe(true); + expect(screen.getByText('Only the hiring owner can record decisions.')).toBeTruthy(); + expect(screen.queryByRole('button', { name: 'Record decisions' })).toBeNull(); + }); +}); + +describe('Scenario: Already decided', () => { + it('reopened, the decisions are read-only, each shown, with who recorded them and when', () => { + show( + pack({ + decided: { by: 'Hassan Haddad', at: decidedAt }, + members: pack().members.map((m, i) => ({ ...m, decision: i === 1 ? 'do_not_advance' : 'advance' })), + }), + ); + const arjun = within(group('Arjun Menon')).getByRole('radio', { name: 'Do not advance' }) as HTMLInputElement; + expect([arjun.checked, arjun.matches(':disabled')]).toEqual([true, true]); + expect( + (within(group('Sara Al Qahtani')).getByRole('radio', { name: 'Advance to Round 2' }) as HTMLInputElement).checked, + ).toBe(true); + expect( + screen.getByText(/^Decisions recorded by Hassan Haddad on 18 Nov 2026 and added to the audit trail\./), + ).toBeTruthy(); + expect(screen.queryByRole('button', { name: 'Record decisions' })).toBeNull(); + }); +}); diff --git a/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/packs/[packId]/PackClient.tsx b/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/packs/[packId]/PackClient.tsx new file mode 100644 index 00000000..188b7489 --- /dev/null +++ b/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/packs/[packId]/PackClient.tsx @@ -0,0 +1,11 @@ +'use client'; + +import { DecisionPack } from '@/features/decision-pack/components/DecisionPack.tsx'; +import type { PackPage } from '@/features/decision-pack/domain/pack.ts'; +import { useRecordDecisionsController } from '@/features/decision-pack/hooks/useRecordDecisionsController.ts'; + +/** The decision pack with "Record the decision" (AIV-P2-012): the hiring owner's choices live in the controller. */ +export function PackClient({ pack }: { pack: PackPage }) { + const record = useRecordDecisionsController(pack); + return ; +} diff --git a/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/packs/[packId]/page.tsx b/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/packs/[packId]/page.tsx index 9bce9d2a..81304cbb 100644 --- a/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/packs/[packId]/page.tsx +++ b/apps/web/src/app/(recruiter)/app/jobs/(job)/[jobId]/packs/[packId]/page.tsx @@ -1,17 +1,18 @@ import { notFound } from 'next/navigation'; -import { DecisionPack } from '@/features/decision-pack/components/DecisionPack.tsx'; import { loadPack } from '@/features/decision-pack/services/loadPack.ts'; import { jobPageMetadata } from '../../metadata.ts'; +import { PackClient } from './PackClient.tsx'; export const generateMetadata = jobPageMetadata('pack'); -// A decision pack built from the ranking (AIV-P2-010). Loading and error states: loading.tsx and error.tsx beside this -// page. The decisions module checks the member's job scope itself. +// A decision pack built from the ranking (AIV-P2-010), where the hiring owner records its decisions (AIV-P2-012). +// Loading and error states: loading.tsx and error.tsx beside this page. The decisions module checks the member's job +// scope itself. export default async function PackPage({ params }: PageProps<'/app/jobs/[jobId]/packs/[packId]'>) { const { jobId, packId } = await params; const pack = await loadPack(jobId, packId); // No workspace: the recruiter layout shows the create-workspace page instead. if (!pack) return null; if (pack === 'notFound') notFound(); - return ; + return ; } diff --git a/apps/web/src/features/decision-pack/components/DecisionPack.test.tsx b/apps/web/src/features/decision-pack/components/DecisionPack.test.tsx index 65ec03f5..18e05ce2 100644 --- a/apps/web/src/features/decision-pack/components/DecisionPack.test.tsx +++ b/apps/web/src/features/decision-pack/components/DecisionPack.test.tsx @@ -55,7 +55,7 @@ const member = ( name: string, summary: CardSummary, added: PackPage['members'][number]['added'] = null, -) => ({ candidateId, name, backedScore: 68, upperBound: 84, added, summary }); +) => ({ candidateId, name, backedScore: 68, upperBound: 84, added, summary, decision: null }); const page = (members: PackPage['members']): PackPage => ({ jobId: JOB, packId: PACK, @@ -76,6 +76,8 @@ const page = (members: PackPage['members']): PackPage => ({ }, members, others: 4, + mayDecide: false, + decided: null, }); const show = (pack: PackPage) => render( @@ -150,14 +152,19 @@ describe('DecisionPack', () => { }); // SAFETY: mutation check: set hasFocus to 'no' in SummaryText -> this test failed (no focus) - it("Scenario: Recommendation is labelled as Credalent's, and no decision option is offered or pre-selected", () => { + // AIV-P2-012 adds the hiring owner's choices: offered, read-only here (no controller), and none pre-selected. + it("Scenario: Recommendation is labelled as Credalent's, and no decision option is pre-selected", () => { const huda = { ...sara, recommendation: { ...sara.recommendation, focus: 'Cost and reliability' } }; show(page([member('p3', 'Huda Al Mansoori', { status: 'ready', summary: huda })])); const card = screen.getByRole('region', { name: 'Huda Al Mansoori' }); expect(within(card).getByText("Credalent's recommendation:").textContent).toBe( "Credalent's recommendation: advance, and look into Cost and reliability next", ); - expect(screen.queryAllByRole('radio')).toEqual([]); + expect( + within(card) + .getAllByRole('radio') + .map((r) => (r as HTMLInputElement).checked), + ).toEqual([false, false, false]); expect(screen.queryAllByRole('checkbox')).toEqual([]); expect( document.querySelectorAll('[aria-pressed="true"], [aria-checked="true"], [aria-selected="true"]'), diff --git a/apps/web/src/features/decision-pack/components/DecisionPack.tsx b/apps/web/src/features/decision-pack/components/DecisionPack.tsx index e2c29d09..8faa5113 100644 --- a/apps/web/src/features/decision-pack/components/DecisionPack.tsx +++ b/apps/web/src/features/decision-pack/components/DecisionPack.tsx @@ -4,11 +4,13 @@ import { useTranslations } from '@credalent/i18n/react'; import { Button, Card, ScoreWithUncertainty, Skeleton, ValueBasis, buttonClassName } from '@credalent/ui'; import type { Route } from 'next'; import Link from 'next/link'; +import type { ReactNode } from 'react'; import { evidenceAnchor, profileHref } from '@/features/evidence-profile/domain/profile.ts'; import { jobPageHref } from '@/features/job-header/domain/jobHeader.ts'; import { packHref } from '@/features/ranking/domain/pack.ts'; -import type { DecisionPackView, PackPage } from '../domain/pack.ts'; +import type { DecisionPackView, PackPage, RecordView } from '../domain/pack.ts'; import { Needs, SummaryText } from './CardSummary.tsx'; +import { DecisionChoice, RecordSection } from './RecordDecisions.tsx'; // AIV-P2-010, AIV-P2-011: the decision pack, from the Pack artboard (docs/01-design/artboards/Pack.dc.html). Ported: // the pack's name, "prepared · rubric vN", "What the job needs" and "Competencies and weights", one card per @@ -34,8 +36,7 @@ import { Needs, SummaryText } from './CardSummary.tsx'; // - the recommendation reads "advance" or "hold" (decided in code from the snapshot), then "and look into next" // with the gap the model names ("Product judgement"), not "probe cost in Round 2"; "hold" is not on the artboard, // which only shows advance (Credalent never recommends rejecting: AGENTS.md 1.6); -// - no decision buttons ("Advance to Round 2", "Hold", "Do not advance"), "Record the decision", "Record decisions" or -// the decision emails: recording decisions is AIV-P2-012 (#126), so no decision option is shown, let alone chosen; +// - the decision choices and "Record the decision" (AIV-P2-012) are in RecordDecisions.tsx, with their deviations; // - no "Open comparison" (AIV-P1-047, #111); // - "Preview the client view" reads "Preview as the hiring owner sees it" (AIV-P1-116's wording) and opens the branded // preview inside Credalent; sharing it is AIV-P2-013 (#127); @@ -43,7 +44,8 @@ import { Needs, SummaryText } from './CardSummary.tsx'; // - no "Decision packs" sidebar count: that item waits behind its flag for the packs list (AIV-P2-E02, #19); // - no Credalent assistant panel: the assistant is AIV-P2-028 (#142). -export function DecisionPack({ view }: { view: DecisionPackView }) { +/** `record`: the hiring owner's choices and "Record decisions" (AIV-P2-012); without it the choices are read-only. */ +export function DecisionPack({ view, record }: { view: DecisionPackView; record?: RecordView }) { const t = useTranslations(); if (view.status === 'loading') return ( @@ -60,11 +62,14 @@ export function DecisionPack({ view }: { view: DecisionPackView }) { ); - return ; + return ; } -function Pack({ pack }: { pack: PackPage }) { +function Pack({ pack, record }: { pack: PackPage; record: RecordView | undefined }) { const t = useTranslations(); + const names = new Map(pack.members.map((m) => [m.candidateId, m.name ?? t('ranking.unnamed')] as const)); + // Read-only once recorded, before the page is read again too, and for anyone but the job's hiring owner. + const readOnly = pack.decided !== null || !pack.mayDecide || Boolean(record?.recordedAt); return (
@@ -104,8 +109,13 @@ function Pack({ pack }: { pack: PackPage }) { {pack.members.length === 0 ? (

{t('decisionPack.empty')}

) : ( - pack.members.map((m) => ) + pack.members.map((m) => ( + + + + )) )} + {pack.members.length > 0 && }

{t('decisionPack.basis')} @@ -124,7 +134,15 @@ function Pack({ pack }: { pack: PackPage }) { ); } -function Member({ jobId, member: m }: { jobId: string; member: PackPage['members'][number] }) { +function Member({ + jobId, + member: m, + children, +}: { + jobId: string; + member: PackPage['members'][number]; + children: ReactNode; +}) { const t = useTranslations(); const titleId = `member-${m.candidateId}`; const profile = profileHref(m.candidateId, jobId); @@ -176,6 +194,7 @@ function Member({ jobId, member: m }: { jobId: string; member: PackPage['members /> )} + {children}

diff --git a/apps/web/src/features/decision-pack/components/RecordDecisions.tsx b/apps/web/src/features/decision-pack/components/RecordDecisions.tsx new file mode 100644 index 00000000..5f8c72fb --- /dev/null +++ b/apps/web/src/features/decision-pack/components/RecordDecisions.tsx @@ -0,0 +1,188 @@ +'use client'; + +import { useTranslations } from '@credalent/i18n/react'; +import { Button, Card, Label, PreviewBanner, SegmentedControl, SuccessBanner, Textarea } from '@credalent/ui'; +import type { Route } from 'next'; +import Link from 'next/link'; +import { useId } from 'react'; +import { jobPageHref } from '@/features/job-header/domain/jobHeader.ts'; +import { DECISIONS, NOTE_MAX, type DecisionValue, type PackPage, type RecordView } from '../domain/pack.ts'; + +// AIV-P2-012: "Record the decision" on the Pack artboard (docs/01-design/artboards/Pack.dc.html), ported as its own +// card (the shared Card) under the members. Deviations: +// - each member's choice is the shared SegmentedControl (a radio group named "Your decision for "), not three +// toggle buttons, and nothing is chosen at first: Credalent's recommendation decides nothing (AGENTS.md 1.5); +// - that group has a visible legend, "Your decision for ", where the artboard has an aria-label only, and it sits +// on its own ruled-off row at the foot of the member's card, not on the row of "Credalent's recommendation: …": the +// recommendation belongs to the cited summary, with its sources under it (AIV-P2-011), and the person's decision must +// never read as Credalent's (AGENTS.md 1.5), so the two are labelled and kept apart; a member still being summarised, +// or with no summary, has no recommendation row to share; +// - the cards' padding is the shared Card's 16 px, not 24 px, as for the rest of the pack (AIV-P2-010); +// - the lead is the ticket's ("updates stages in Credalent only. No candidate is contacted until you send a message +// yourself"), and the confirmation offers "Schedule Round 2 interviews", not the artboard's "3 decision emails are +// ready. Review and send them": decision email drafts are AIV-P2-073 (#515), which changes this copy with them; +// - "Record decisions" opens the shared preview-confirm banner ("Nothing changes until you confirm.") with each +// decision, the stage it leads to and a required reason, written to each decision's audit entry (AGENTS.md 1.5: who, +// when and why); the artboard records at once and asks for no reason; +// - "Back to ranking" stays at the foot of the pack, where AIV-P2-010 put it, not beside "Record decisions"; +// - a recruiter, an admin or another hiring owner sees the choices read-only with "Only the hiring owner can record +// decisions"; a decided pack shows them read-only with who recorded them and when (the ticket's scenarios). + +const focusOnMount = (element: HTMLElement | null) => element?.focus(); + +/** One member's decision: chosen by the hiring owner, or read-only (recorded, or anyone else). */ +export function DecisionChoice({ + member, + name, + record, + readOnly, +}: { + member: PackPage['members'][number]; + name: string; + record: RecordView | undefined; + readOnly: boolean; +}) { + const t = useTranslations('decisionPack.record'); + const errorId = useId(); + const missing = record?.missing.includes(member.candidateId) ?? false; + const value = member.decision ?? record?.choices[member.candidateId]; + return ( +
+ ({ value: decision, label: t(`options.${decision}`) }))} + // '' checks no option: the group stays controlled before anything is chosen. + value={value ?? ''} + disabled={readOnly || !record} + onValueChange={(decision) => record?.onChoose(member.candidateId, decision as DecisionValue)} + aria-invalid={missing} + {...(missing && { 'aria-describedby': errorId })} + /> + {missing && ( + + )} +
+ ); +} + +/** "Record the decision": the hiring owner's one primary action, its preview, and what happened after. */ +export function RecordSection({ + pack, + record, + names, +}: { + pack: PackPage; + record: RecordView | undefined; + /** Each member's name by candidate id, as the cards show it. */ + names: ReadonlyMap; +}) { + const t = useTranslations('decisionPack.record'); + const tStage = useTranslations('ranking.stages'); + const reasonId = useId(); + const reasonErrorId = useId(); + const schedule = ( + // jobPageHref builds the path from the job id, which typed routes cannot check. + + {t('schedule')} + + ); + const recordedAt = record?.recordedAt ?? null; + return ( +
+ +
+

+ {t('title')} +

+ {pack.mayDecide && ( + // Mounted empty first, so the confirmation is announced when it arrives. + + {recordedAt && ( + <> + {t('done', { date: recordedAt })} {schedule} + + )} + + )} + {recordedAt ? null : pack.decided ? ( +

+ {pack.decided.by + ? t('recorded', { name: pack.decided.by, date: pack.decided.at }) + : t('recordedUnknown', { date: pack.decided.at })}{' '} + {schedule} +

+ ) : !pack.mayDecide || !record ? ( +

{t('onlyOwner')}

+ ) : ( + <> +

{t('lead')}

+ {record.previewing ? ( + +
    + {pack.members.map((m) => { + const decision = record.choices[m.candidateId]; + return ( +
  • + {names.get(m.candidateId)} + + {decision === 'advance' + ? t('preview.stage', { + decision: t('options.advance'), + stage: tStage('round2_shortlist'), + }) + : decision === 'do_not_advance' + ? t('preview.stage', { + decision: t('options.do_not_advance'), + stage: tStage('not_advanced'), + }) + : t('preview.hold')} + +
  • + ); + })} +
+
+ +