From 7a51c15d34e351f3d61b4dd5b7296b8356e96996 Mon Sep 17 00:00:00 2001 From: joshunrau Date: Thu, 19 Nov 2026 10:33:46 -0500 Subject: [PATCH 1/4] fix(web): date an in-person session when it is submitted, not when the page loaded The Start Session form computed the current date once, at module scope, and used it as the in-person session date, the upper bound for a retrospective date and the reference for the group's minimum age. Every session started later in the same page load was backdated to when the page first opened. Each check now reads the clock when the form is validated, and the in-person default is built at submission. Closes #1675 Co-Authored-By: Claude Opus 5.5 --- .../StartSessionForm/StartSessionForm.tsx | 21 ++++---- .../__tests__/StartSessionForm.test.tsx | 54 +++++++++++++++++++ testing/src/specs/start-session.spec.ts | 23 ++++++++ 3 files changed, 88 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/StartSessionForm/StartSessionForm.tsx b/apps/web/src/components/StartSessionForm/StartSessionForm.tsx index a001937f2..aeea01ca1 100644 --- a/apps/web/src/components/StartSessionForm/StartSessionForm.tsx +++ b/apps/web/src/components/StartSessionForm/StartSessionForm.tsx @@ -19,7 +19,9 @@ import { z } from 'zod/v4'; import { useSubjectDemographicsLookup } from '@/hooks/useSubjectDemographicsLookup'; import { getValueForLanguage } from '@/utils/language'; -const currentDate = new Date(); +const MILLISECONDS_PER_YEAR = 31556952000; + +const isNotInFuture = (date: Date) => date <= new Date(); type StartSessionFormValues = FormTypes.PartialData; @@ -62,9 +64,6 @@ export const StartSessionForm = ({ const lookupDemographics = useSubjectDemographicsLookup(); const [autofilled, setAutofilled] = useState({}); const latestCustomId = useRef(''); - const minDateOfBirth = currentGroup?.settings.minimumAge - ? new Date(currentDate.getTime() - currentGroup.settings.minimumAge * 31556952000) - : undefined; const scopeCustomId = (customId: string) => { return encodeScopedSubjectId(customId, { groupName: currentGroup?.name ?? DEFAULT_GROUP_NAME }); @@ -230,8 +229,8 @@ export const StartSessionForm = ({ sessionType: $SessionType.exclude(['REMOTE']), sessionDate: z .date() - .max(currentDate, { message: t('session.errors.assessmentMustBeInPast') }) - .default(currentDate) + .refine(isNotInFuture, { message: t('session.errors.assessmentMustBeInPast') }) + .default(() => new Date()) }) .superRefine((val, ctx) => { if (val.subjectIdentificationMethod === 'CUSTOM_ID') { @@ -287,7 +286,9 @@ export const StartSessionForm = ({ } } } - if (val.subjectDateOfBirth && val.subjectDateOfBirth > currentDate) { + const minimumAge = currentGroup?.settings.minimumAge; + const minDateOfBirth = minimumAge ? new Date(Date.now() - minimumAge * MILLISECONDS_PER_YEAR) : undefined; + if (val.subjectDateOfBirth && !isNotInFuture(val.subjectDateOfBirth)) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: t({ @@ -301,9 +302,9 @@ export const StartSessionForm = ({ ctx.addIssue({ code: z.ZodIssueCode.custom, message: t({ - en: `Subject must be above age of ${currentGroup?.settings.minimumAge}`, - es: `El sujeto debe tener más de ${currentGroup?.settings.minimumAge} años`, - fr: `Le sujet doit avoir au moins ${currentGroup?.settings.minimumAge} ans` + en: `Subject must be above age of ${minimumAge}`, + es: `El sujeto debe tener más de ${minimumAge} años`, + fr: `Le sujet doit avoir au moins ${minimumAge} ans` }), path: ['subjectDateOfBirth'] }); diff --git a/apps/web/src/components/StartSessionForm/__tests__/StartSessionForm.test.tsx b/apps/web/src/components/StartSessionForm/__tests__/StartSessionForm.test.tsx index 27b424c79..d628d5d6b 100644 --- a/apps/web/src/components/StartSessionForm/__tests__/StartSessionForm.test.tsx +++ b/apps/web/src/components/StartSessionForm/__tests__/StartSessionForm.test.tsx @@ -440,6 +440,60 @@ describe('StartSessionForm', () => { }); }); + describe('timing', () => { + const DAY = 24 * 60 * 60 * 1000; + + const pageLoadedAt = Date.now(); + + const toDateString = (time: number) => new Date(time).toISOString().slice(0, 10); + + const moveClock = (time: number) => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(time); + }; + + const enterSessionDate = (form: HTMLElement, date: string) => { + const input = form.querySelector('[name="sessionDate"]')!; + fireEvent.focus(input); + fireEvent.change(input, { target: { value: date } }); + fireEvent.blur(input); + }; + + afterEach(() => { + vi.useRealTimers(); + }); + + it('should date an in-person session at submission, so a session started later in the same page load is not backdated to when the page opened', async () => { + const startedAt = pageLoadedAt + 2 * 60 * 60 * 1000; + const form = renderForm([]); + typeIdentifier('abc'); + closeIdentifierPopup(); + moveClock(startedAt); + await submitAndSettle(form); + expect(onSubmit.mock.lastCall?.[0].date).toStrictEqual(new Date(startedAt)); + }); + + it('should accept a retrospective date later than when the page opened once that date has passed', async () => { + const form = renderForm([]); + typeIdentifier('abc'); + closeIdentifierPopup(); + fireEvent.change(form.querySelector('[name="sessionType"]')!, { target: { value: 'RETROSPECTIVE' } }); + enterSessionDate(form, toDateString(pageLoadedAt + DAY)); + moveClock(pageLoadedAt + 2 * DAY); + fireEvent.click(submitButton()); + await waitFor(() => expect(onSubmit).toHaveBeenCalled()); + expect(onSubmit.mock.lastCall?.[0].date).toStrictEqual(new Date(toDateString(pageLoadedAt + DAY))); + }); + + it("should accept a date of birth that reaches the group's minimum age only after the page opened", async () => { + const minimumAgeReachedAt = pageLoadedAt - 18 * 31556952000 + 5 * DAY; + const form = renderForm([], groupWithSettings({ minimumAge: 18 }), 'PERSONAL_INFO'); + fillPersonalInfo(form, { dateOfBirth: toDateString(minimumAgeReachedAt), firstName: 'Jane' }); + moveClock(pageLoadedAt + 10 * DAY); + await submitAndSettle(form); + }); + }); + describe('date of birth', () => { const futureDateOfBirth = `${new Date().getFullYear() + 1}-01-01`; diff --git a/testing/src/specs/start-session.spec.ts b/testing/src/specs/start-session.spec.ts index 251c35c10..a56da335c 100644 --- a/testing/src/specs/start-session.spec.ts +++ b/testing/src/specs/start-session.spec.ts @@ -54,6 +54,29 @@ test.describe('start session', () => { await startSessionPage.submitForm(); await expect(startSessionPage.successMessage).toBeVisible(); }); + + // The form used to compute the session date once, when its code first loaded, so every in-person + // session started later in the same page load was backdated to that moment. + test('should date an in-person session when it is submitted, not when the page opened', async ({ + getPageModel, + page, + uniqueId + }) => { + const openedAt = new Date(); + await page.clock.install({ time: openedAt }); + const startSessionPage = await getPageModel('/session/start-session'); + await startSessionPage.selectIdentificationMethod('CUSTOM_ID'); + await startSessionPage.typeSubjectId(`timed-${uniqueId}`); + await startSessionPage.dismissSubjectIdOptions(); + await page.clock.fastForward('02:00:00'); + + const sessionCreated = page.waitForResponse( + (response) => response.url().endsWith('/v1/sessions') && response.request().method() === 'POST' + ); + await startSessionPage.submitForm(); + const session = (await (await sessionCreated).json()) as { date: string }; + expect(new Date(session.date).getTime()).toBeGreaterThanOrEqual(openedAt.getTime() + 2 * 60 * 60 * 1000); + }); }); // A custom id says nothing about the subject behind it, so the form fills in what an existing From 3fcf3cd9bb3d893e66b8f8c10dfb95b3d2bd9b60 Mon Sep 17 00:00:00 2001 From: joshunrau Date: Thu, 19 Nov 2026 10:39:39 -0500 Subject: [PATCH 2/4] feat(web): record the time of day of a retrospective session A retrospective session's date is now a date and time, so the time of collection is kept (for MouseODC, the time of day is a proxy for hormonal variation). The date is required: a blank one used to be read as the moment the form was submitted, and a time typed without a date was lost. Closes #1029 Co-Authored-By: Claude Opus 5.5 --- .../StartSessionForm/StartSessionForm.tsx | 30 ++++-- .../__tests__/StartSessionForm.test.tsx | 97 +++++++++++++++---- apps/web/src/translations/session.json | 6 +- .../3.4-how-to-get-started-with-odc.mdx | 2 +- .../pages/_app/session/start-session.page.ts | 30 ++++-- testing/src/specs/start-session.spec.ts | 24 +++++ 6 files changed, 149 insertions(+), 40 deletions(-) diff --git a/apps/web/src/components/StartSessionForm/StartSessionForm.tsx b/apps/web/src/components/StartSessionForm/StartSessionForm.tsx index aeea01ca1..855cf056c 100644 --- a/apps/web/src/components/StartSessionForm/StartSessionForm.tsx +++ b/apps/web/src/components/StartSessionForm/StartSessionForm.tsx @@ -33,7 +33,7 @@ const selectedCustomId = (values: StartSessionFormValues) => { }; type StartSessionFormData = { - sessionDate: Date; + sessionDate?: Date; sessionType: 'IN_PERSON' | 'RETROSPECTIVE'; subjectDateOfBirth?: Date; subjectFirstName?: string; @@ -198,7 +198,8 @@ export const StartSessionForm = ({ ? { description: t('session.dateAssessed.description'), kind: 'date', - label: t('session.dateAssessed.label') + label: t('session.dateAssessed.label'), + variant: 'datetime' } : null; } @@ -219,7 +220,7 @@ export const StartSessionForm = ({ subjectFirstName: z.string().optional(), subjectLastName: z.string().optional(), subjectIdentificationMethod: $SubjectIdentificationMethod, - // Every check on the identifier and the date of birth lives in the refinement below: zod v4 + // Every check on the identifier and the two dates lives in the refinement below: zod v4 // omits an optional property that failed its own checks from the value it hands the // refinement, which then reads the field as missing and adds a contradictory required-field // error. @@ -227,12 +228,24 @@ export const StartSessionForm = ({ subjectDateOfBirth: z.date().optional(), subjectSex: z.enum(['MALE', 'FEMALE']).optional(), sessionType: $SessionType.exclude(['REMOTE']), - sessionDate: z - .date() - .refine(isNotInFuture, { message: t('session.errors.assessmentMustBeInPast') }) - .default(() => new Date()) + sessionDate: z.date().optional() }) .superRefine((val, ctx) => { + if (val.sessionType === 'RETROSPECTIVE') { + if (!val.sessionDate) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t('core.form.requiredField'), + path: ['sessionDate'] + }); + } else if (!isNotInFuture(val.sessionDate)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: t('session.errors.assessmentMustBeInPast'), + path: ['sessionDate'] + }); + } + } if (val.subjectIdentificationMethod === 'CUSTOM_ID') { if (!val.subjectId) { ctx.addIssue({ @@ -330,7 +343,8 @@ export const StartSessionForm = ({ subjectId = scopeCustomId(subjectId); } await onSubmit({ - date: sessionDate, + // Only a retrospective session has a date of its own; an in-person one starts now. + date: sessionDate ?? new Date(), groupId: currentGroup?.id ?? null, username: username ?? null, type: sessionType, diff --git a/apps/web/src/components/StartSessionForm/__tests__/StartSessionForm.test.tsx b/apps/web/src/components/StartSessionForm/__tests__/StartSessionForm.test.tsx index d628d5d6b..1b4698148 100644 --- a/apps/web/src/components/StartSessionForm/__tests__/StartSessionForm.test.tsx +++ b/apps/web/src/components/StartSessionForm/__tests__/StartSessionForm.test.tsx @@ -2,7 +2,7 @@ import { DEFAULT_GROUP_NAME } from '@opendatacapture/schemas/core'; import type { Group, GroupSettings } from '@opendatacapture/schemas/group'; import { generateSubjectHash } from '@opendatacapture/subject-utils'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { act, cleanup, fireEvent, getByText, render, screen, waitFor } from '@testing-library/react'; import axios from 'axios'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -452,13 +452,6 @@ describe('StartSessionForm', () => { vi.setSystemTime(time); }; - const enterSessionDate = (form: HTMLElement, date: string) => { - const input = form.querySelector('[name="sessionDate"]')!; - fireEvent.focus(input); - fireEvent.change(input, { target: { value: date } }); - fireEvent.blur(input); - }; - afterEach(() => { vi.useRealTimers(); }); @@ -473,24 +466,90 @@ describe('StartSessionForm', () => { expect(onSubmit.mock.lastCall?.[0].date).toStrictEqual(new Date(startedAt)); }); - it('should accept a retrospective date later than when the page opened once that date has passed', async () => { + it("should accept a date of birth that reaches the group's minimum age only after the page opened", async () => { + const minimumAgeReachedAt = pageLoadedAt - 18 * 31556952000 + 5 * DAY; + const form = renderForm([], groupWithSettings({ minimumAge: 18 }), 'PERSONAL_INFO'); + fillPersonalInfo(form, { dateOfBirth: toDateString(minimumAgeReachedAt), firstName: 'Jane' }); + moveClock(pageLoadedAt + 10 * DAY); + await submitAndSettle(form); + }); + }); + + describe('retrospective session', () => { + // A fixed local date a year ahead, so the picker opens on a known month and a date frozen when + // the module loaded would lie before every time used here. + const pageOpenedAt = new Date(new Date().getFullYear() + 1, 5, 15, 9, 0, 0); + + const chooseRetrospective = (form: HTMLElement) => { + fireEvent.change(form.querySelector('[name="sessionType"]')!, { target: { value: 'RETROSPECTIVE' } }); + }; + + const pickSessionDay = (day: number) => { + fireEvent.click(screen.getByTestId('datetime-date-trigger')); + fireEvent.click(getByText(screen.getByTestId('datepicker'), String(day))); + }; + + const enterSessionTime = (time: string) => { + fireEvent.change(screen.getByTestId('datetime-time-input'), { target: { value: time } }); + }; + + const renderWithNewIdentifier = () => { const form = renderForm([]); typeIdentifier('abc'); closeIdentifierPopup(); - fireEvent.change(form.querySelector('[name="sessionType"]')!, { target: { value: 'RETROSPECTIVE' } }); - enterSessionDate(form, toDateString(pageLoadedAt + DAY)); - moveClock(pageLoadedAt + 2 * DAY); + chooseRetrospective(form); + return form; + }; + + beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(pageOpenedAt); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('should submit the time of day entered for a retrospective session, so the collection time is kept', async () => { + renderWithNewIdentifier(); + pickSessionDay(15); + enterSessionTime('08:30:15'); fireEvent.click(submitButton()); await waitFor(() => expect(onSubmit).toHaveBeenCalled()); - expect(onSubmit.mock.lastCall?.[0].date).toStrictEqual(new Date(toDateString(pageLoadedAt + DAY))); + expect(onSubmit.mock.lastCall?.[0]).toMatchObject({ + date: new Date(pageOpenedAt.getFullYear(), 5, 15, 8, 30, 15), + type: 'RETROSPECTIVE' + }); }); - it("should accept a date of birth that reaches the group's minimum age only after the page opened", async () => { - const minimumAgeReachedAt = pageLoadedAt - 18 * 31556952000 + 5 * DAY; - const form = renderForm([], groupWithSettings({ minimumAge: 18 }), 'PERSONAL_INFO'); - fillPersonalInfo(form, { dateOfBirth: toDateString(minimumAgeReachedAt), firstName: 'Jane' }); - moveClock(pageLoadedAt + 10 * DAY); - await submitAndSettle(form); + it('should accept a retrospective time later than when the page opened once that time has passed', async () => { + renderWithNewIdentifier(); + pickSessionDay(15); + enterSessionTime('10:30:00'); + vi.setSystemTime(new Date(pageOpenedAt.getFullYear(), 5, 15, 11, 0, 0)); + fireEvent.click(submitButton()); + await waitFor(() => expect(onSubmit).toHaveBeenCalled()); + }); + + it('should reject a retrospective time that has not happened yet', async () => { + renderWithNewIdentifier(); + pickSessionDay(15); + enterSessionTime('10:30:00'); + fireEvent.click(submitButton()); + await waitFor(() => { + expect(errorMessages()).toEqual([{ field: 'sessionDate', message: 'The assessment must be in the past' }]); + }); + expect(onSubmit).not.toHaveBeenCalled(); + }); + + it('should reject a retrospective session with no date, rather than dating it when the page loaded', async () => { + renderWithNewIdentifier(); + enterSessionTime('08:30:00'); + fireEvent.click(submitButton()); + await waitFor(() => { + expect(errorMessages()).toEqual([{ field: 'sessionDate', message: 'This field is required' }]); + }); + expect(onSubmit).not.toHaveBeenCalled(); }); }); diff --git a/apps/web/src/translations/session.json b/apps/web/src/translations/session.json index 8b45222d7..8969cac48 100644 --- a/apps/web/src/translations/session.json +++ b/apps/web/src/translations/session.json @@ -8,9 +8,9 @@ }, "dateAssessed": { "description": { - "en": "If the session took place on a date other than today, you can change it here.", - "es": "Si la sesión tuvo lugar en una fecha distinta a hoy, puede modificarla aquí.", - "fr": "Si la session a eu lieu à une autre date qu'aujourd'hui, vous pouvez la modifier ici." + "en": "The date and time the session took place.", + "es": "La fecha y la hora en que tuvo lugar la sesión.", + "fr": "La date et l'heure auxquelles la session a eu lieu." }, "label": { "en": "Date Assessed", diff --git a/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx b/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx index 87eec2ebd..205aa86b0 100644 --- a/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx +++ b/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx @@ -100,7 +100,7 @@ Use **Start Session** to begin work with a subject. 3. **Choose the session type** - Use an in-person session for new data collection. Use a retrospective session when entering data that was collected earlier using another system. + Use an in-person session for new data collection; it is dated when it starts. Use a retrospective session when entering data that was collected earlier using another system, and enter the date and time the data was collected. 4. **Confirm the session is active** diff --git a/testing/src/pages/_app/session/start-session.page.ts b/testing/src/pages/_app/session/start-session.page.ts index 05e7590f9..8a7054c9c 100644 --- a/testing/src/pages/_app/session/start-session.page.ts +++ b/testing/src/pages/_app/session/start-session.page.ts @@ -67,16 +67,10 @@ export class StartSessionPage extends AppPage { await this.fillSessionDetails(sex); } - /** A retrospective session dated today, without touching the subject's details. */ + /** A retrospective session dated today at midnight, without touching the subject's details. */ async fillSessionTiming() { - const sessionTypeSelector = this.sessionForm.locator('[name="sessionType"]'); - const sessionDate = this.sessionForm.locator('[name="sessionDate"]'); - - await sessionTypeSelector.selectOption('Retrospective'); - - await sessionDate.waitFor({ state: 'visible' }); - const expectedSessionDate = new Date().toISOString().split('T')[0]!; - await sessionDate.fill(expectedSessionDate); + await this.selectRetrospective(); + await this.pickSessionDay(new Date().getDate()); } /** The subject's date of birth and sex, leaving the session at its in-person default. */ @@ -85,10 +79,28 @@ export class StartSessionPage extends AppPage { await this.sexField.selectOption(sex); } + /** A day of the month the date picker opens on, which is the browser's current month. */ + async pickSessionDay(day: number) { + await this.sessionForm.getByTestId('datetime-date-trigger').click(); + await this.$ref + .getByTestId('datepicker') + .getByRole('button', { exact: true, name: String(day) }) + .click(); + } + async selectIdentificationMethod(methodName: string) { await this.selectField.selectOption(methodName); } + async selectRetrospective() { + await this.sessionForm.locator('[name="sessionType"]').selectOption('Retrospective'); + } + + /** The time of day of a retrospective session, as `HH:MM:SS`. */ + async setSessionTime(time: string) { + await this.sessionForm.getByTestId('datetime-time-input').fill(time); + } + /** An identifier already in use by a subject in the current group, offered in the popup. */ subjectIdOption(identifier: string) { return this.$ref.getByTestId(`subjectId-combobox-item-${identifier}`); diff --git a/testing/src/specs/start-session.spec.ts b/testing/src/specs/start-session.spec.ts index a56da335c..fdd515c71 100644 --- a/testing/src/specs/start-session.spec.ts +++ b/testing/src/specs/start-session.spec.ts @@ -79,6 +79,30 @@ test.describe('start session', () => { }); }); +// The date picker opens on the browser's current month, so the clock is fixed to a known day; the +// timezone makes the stored instant, which is what the API receives, the same wherever the suite runs. +test.describe('retrospective session time', () => { + test.use({ timezoneId: 'America/Toronto' }); + + test('should keep the time of day entered for a retrospective session', async ({ getPageModel, page, uniqueId }) => { + await page.clock.install({ time: new Date('2025-06-20T16:00:00Z') }); + const startSessionPage = await getPageModel('/session/start-session'); + await startSessionPage.selectIdentificationMethod('CUSTOM_ID'); + await startSessionPage.typeSubjectId(`retro-${uniqueId}`); + await startSessionPage.dismissSubjectIdOptions(); + await startSessionPage.selectRetrospective(); + await startSessionPage.pickSessionDay(10); + await startSessionPage.setSessionTime('14:30:00'); + + const sessionCreated = page.waitForRequest( + (request) => request.url().endsWith('/v1/sessions') && request.method() === 'POST' + ); + await startSessionPage.submitForm(); + expect((await sessionCreated).postDataJSON()).toMatchObject({ date: '2025-06-10T18:30:00.000Z' }); + await expect(startSessionPage.successMessage).toBeVisible(); + }); +}); + // A custom id says nothing about the subject behind it, so the form fills in what an existing // subject already records. An admin with no group has their custom ids scoped as `root$`. test.describe('existing subject details', () => { From 2cbbecb8566bd0b26304b9bad1d834de7a837264 Mon Sep 17 00:00:00 2001 From: joshunrau Date: Thu, 19 Nov 2026 10:42:53 -0500 Subject: [PATCH 3/4] fix(api): export when each record and session was collected, with the time of day The export projected each row's timestamp from the day the record was inserted, so a retrospective session, a bulk upload or a remote assignment exported with the wrong date, and every row lost its time. It now takes the record's own date, and both it and the session date keep their full ISO timestamp. Closes #1717 Co-Authored-By: Claude Opus 5.5 --- .../instrument-records.service.test.ts | 22 +++++++++++++ .../instrument-records.service.ts | 14 ++------ testing/src/specs/datahub.spec.ts | 33 +++++++++++++++++++ 3 files changed, 57 insertions(+), 12 deletions(-) diff --git a/apps/api/src/instrument-records/__tests__/instrument-records.service.test.ts b/apps/api/src/instrument-records/__tests__/instrument-records.service.test.ts index 04084bb5b..7df0322fa 100644 --- a/apps/api/src/instrument-records/__tests__/instrument-records.service.test.ts +++ b/apps/api/src/instrument-records/__tests__/instrument-records.service.test.ts @@ -971,6 +971,28 @@ describe('InstrumentRecordsService', () => { expect(projectStage.$project.session.user.username).toBe('$sessionUser.username'); }); + // `$dateToString` without a format gives a full ISO timestamp, so the time of collection survives + // and two records collected on one day stay distinguishable. + it('should export the record collection date as the timestamp, not the insertion date', async () => { + instrumentRecordModel.aggregateRaw.mockResolvedValueOnce([]); + + await instrumentRecordsService.exportRecords({}, { ability: createAppAbility([]) }); + + const [{ pipeline }] = instrumentRecordModel.aggregateRaw.mock.lastCall as [{ pipeline: any[] }]; + const projectStage = pipeline.find((stage) => stage.$project); + expect(projectStage.$project.date).toStrictEqual({ $dateToString: { date: '$date' } }); + }); + + it('should export the session date with its time of day, so a session started at a known time keeps it', async () => { + instrumentRecordModel.aggregateRaw.mockResolvedValueOnce([]); + + await instrumentRecordsService.exportRecords({}, { ability: createAppAbility([]) }); + + const [{ pipeline }] = instrumentRecordModel.aggregateRaw.mock.lastCall as [{ pipeline: any[] }]; + const projectStage = pipeline.find((stage) => stage.$project); + expect(projectStage.$project.session.date).toStrictEqual({ $dateToString: { date: '$session.date' } }); + }); + it('should match only the requested group in the aggregation, so a scoped export reads no other group', async () => { instrumentRecordModel.aggregateRaw.mockResolvedValueOnce([]); diff --git a/apps/api/src/instrument-records/instrument-records.service.ts b/apps/api/src/instrument-records/instrument-records.service.ts index d3c99bcc1..e7170427e 100644 --- a/apps/api/src/instrument-records/instrument-records.service.ts +++ b/apps/api/src/instrument-records/instrument-records.service.ts @@ -649,12 +649,7 @@ export class InstrumentRecordsService { { $project: { computedMeasures: 1, - date: { - $dateToString: { - date: '$createdAt', - format: '%Y-%m-%d' - } - }, + date: { $dateToString: { date: '$date' } }, // `$ifNull` for the same reason as in `summarizeRecords`: `$toString` of a missing field is // itself missing, so a record belonging to no group would drop `groupId` from the row // entirely and arrive as undefined behind a type that says it is a string. @@ -665,12 +660,7 @@ export class InstrumentRecordsService { instrumentId: 1, seriesInstrumentId: { $ifNull: ['$seriesInstrumentId', null] }, session: { - date: { - $dateToString: { - date: '$session.date', - format: '%Y-%m-%d' - } - }, + date: { $dateToString: { date: '$session.date' } }, id: { $toString: '$session._id' }, diff --git a/testing/src/specs/datahub.spec.ts b/testing/src/specs/datahub.spec.ts index 663a096a6..94a3869f1 100644 --- a/testing/src/specs/datahub.spec.ts +++ b/testing/src/specs/datahub.spec.ts @@ -121,3 +121,36 @@ test.describe('data hub', () => { await expect(datahubPage.rows).toHaveCount(1); }); }); + +test.describe('data hub export', () => { + // The export used to date each row by the day the record was inserted, which loses both the + // collection date of anything entered later and the time of day of everything. + test('should export the collection date and time of each record and its session', async ({ + api, + isolatedGroupManager, + page, + uniqueId + }) => { + const group = await isolatedGroupManager(); + const instrumentId = await api.findInstrumentIdByName('DNP_HAPPINESS_QUESTIONNAIRE'); + const collectedAt = '2024-01-15T10:30:00.000Z'; + await api.uploadRecords(group.id, instrumentId, [ + { data: HAPPINESS_RECORD, date: new Date(collectedAt), subjectId: `dated-${uniqueId}` } + ]); + + const datahubPage = new DatahubPage(page); + await datahubPage.goto('/datahub/subjects'); + await expect(datahubPage.rows).toHaveCount(1); + + const download = await datahubPage.exportAs('JSON'); + const payload = JSON.parse(await readFile(await download.path(), 'utf8')) as { + sessionDate: string; + timestamp: string; + }[]; + + expect(payload.length).toBeGreaterThan(0); + for (const row of payload) { + expect(row).toMatchObject({ sessionDate: collectedAt, timestamp: collectedAt }); + } + }); +}); From d5d749dc793a6f3bddae252cba6fbc9e5c67ad7b Mon Sep 17 00:00:00 2001 From: joshunrau Date: Thu, 19 Nov 2026 11:10:27 -0500 Subject: [PATCH 4/4] feat: let a group require a form to be completed when a session starts A group manager can choose one form instrument as the group's Session Instrument. Start Session then shows that form after the session details, with a Back control, and the session is created only once the form is submitted: POST /v1/sessions carries the answers and creates the session and a record of them, dated as the session is, or neither. If the record fails to save, the session is deleted, and so is the subject if this request created it. The server refuses a session in such a group without the answers, and answers for a group that requires none. The setting follows a new edition of the form once that edition is saved, an update that would take the form away from the group is refused, and a group is never created with one. The gateway synchronizer, CSV upload and demo seeding create sessions in process and are not asked for it. The group's manage page now reads the group fresh rather than as it was at sign-in, since a save sends back every setting it was seeded with and so could undo a change made since. Refs #1546 Co-Authored-By: Claude Opus 5.5 --- .../docs/architecture/auth-and-permissions.md | 4 + apps/api/prisma/schema.prisma | 2 + .../groups/__tests__/groups.service.test.ts | 72 ++++++- apps/api/src/groups/groups.module.ts | 3 + apps/api/src/groups/groups.service.ts | 52 ++++- .../instrument-records.service.ts | 36 ++-- .../__tests__/instruments.service.test.ts | 32 +++ .../src/instruments/instruments.service.ts | 42 ++-- apps/api/src/main.ts | 2 + .../__tests__/sessions.controller.test.ts | 13 -- apps/api/src/sessions/sessions.controller.ts | 11 +- .../start-session.controller.test.ts | 38 ++++ .../__tests__/start-session.service.test.ts | 196 ++++++++++++++++++ .../start-session/start-session.controller.ts | 25 +++ .../src/start-session/start-session.module.ts | 19 ++ .../start-session/start-session.service.ts | 81 ++++++++ .../__tests__/subjects.service.test.ts | 8 + apps/api/src/subjects/subjects.service.ts | 8 + apps/api/test/helpers.ts | 11 +- .../suites/10-session-instrument.suite.ts | 153 ++++++++++++++ .../SessionInstrumentStep.tsx | 40 ++++ .../__tests__/SessionInstrumentStep.test.tsx | 58 ++++++ .../components/SessionInstrumentStep/index.ts | 1 + .../__tests__/useUpdateGroupMutation.test.ts | 8 +- .../web/src/hooks/useCreateSessionMutation.ts | 4 +- apps/web/src/hooks/useUpdateGroupMutation.ts | 9 +- .../_app/group/__tests__/manage.test.tsx | 134 +++++++++++- apps/web/src/routes/_app/group/manage.tsx | 129 ++++++++---- .../session/__tests__/start-session.test.tsx | 138 ++++++++++++ .../src/routes/_app/session/start-session.tsx | 67 +++++- .../3.4-how-to-get-started-with-odc.mdx | 10 +- .../schemas/src/group/__tests__/group.test.ts | 13 +- packages/schemas/src/group/group.ts | 5 +- packages/schemas/src/session/session.ts | 8 +- .../pages/_app/session/start-session.page.ts | 6 + testing/src/specs/start-session.spec.ts | 51 +++++ testing/src/support/api-client.ts | 11 +- 37 files changed, 1378 insertions(+), 122 deletions(-) create mode 100644 apps/api/src/start-session/__tests__/start-session.controller.test.ts create mode 100644 apps/api/src/start-session/__tests__/start-session.service.test.ts create mode 100644 apps/api/src/start-session/start-session.controller.ts create mode 100644 apps/api/src/start-session/start-session.module.ts create mode 100644 apps/api/src/start-session/start-session.service.ts create mode 100644 apps/api/test/suites/10-session-instrument.suite.ts create mode 100644 apps/web/src/components/SessionInstrumentStep/SessionInstrumentStep.tsx create mode 100644 apps/web/src/components/SessionInstrumentStep/__tests__/SessionInstrumentStep.test.tsx create mode 100644 apps/web/src/components/SessionInstrumentStep/index.ts diff --git a/.agents/docs/architecture/auth-and-permissions.md b/.agents/docs/architecture/auth-and-permissions.md index dedd85c91..321103650 100644 --- a/.agents/docs/architecture/auth-and-permissions.md +++ b/.agents/docs/architecture/auth-and-permissions.md @@ -50,6 +50,10 @@ route. `ADMIN_ONLY` guard; and `InstrumentsService.findBundleById` called without a `currentUser`, which the API's gateway module does to resolve an assignment's bundle. That parameter is optional for this reason, so a new call site that omits it compiles and reads every group's instruments. +`StartSessionService` rolls back unscoped: when the record of a session instrument fails to save, +it deletes the session it just created and, if `SubjectsService.exists` (a boolean, unscoped +because a scoped lookup would miss a subject in another group) found no subject beforehand, the +subject too. `SessionsService.createMany` rolls back the same way. ## Layer 2: row scoping diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index fa8598208..f8c0e7acd 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -107,6 +107,8 @@ type GroupSettings { idValidationRegexErrorMessage LocalizedString? subjectIdDisplayLength Int? minimumAge Int? + // A form instrument that must be completed to start a session in the group, if any. + sessionInstrumentId String? } // Mirrors $LocalizedString in @opendatacapture/schemas/core; each field is optional so diff --git a/apps/api/src/groups/__tests__/groups.service.test.ts b/apps/api/src/groups/__tests__/groups.service.test.ts index 0728a6657..26f543ff8 100644 --- a/apps/api/src/groups/__tests__/groups.service.test.ts +++ b/apps/api/src/groups/__tests__/groups.service.test.ts @@ -9,6 +9,7 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { AuditLogger } from '@/audit/audit.logger'; import { createAppAbility } from '@/auth/ability.utils'; +import { InstrumentsService } from '@/instruments/instruments.service'; import { GroupsService } from '../groups.service'; @@ -30,6 +31,7 @@ describe('GroupsService', () => { let groupsService: GroupsService; let groupModel: MockedInstance>; let instrumentModel: MockedInstance>; + let instrumentsService: MockedInstance; beforeEach(async () => { const moduleRef = await Test.createTestingModule({ @@ -37,13 +39,15 @@ describe('GroupsService', () => { GroupsService, MockFactory.createForModelToken(getModelToken('Group')), MockFactory.createForModelToken(getModelToken('Instrument')), - MockFactory.createForService(AuditLogger) + MockFactory.createForService(AuditLogger), + MockFactory.createForService(InstrumentsService) ] }).compile(); auditLogger = moduleRef.get(AuditLogger); groupModel = moduleRef.get(getModelToken('Group')); instrumentModel = moduleRef.get(getModelToken('Instrument')); groupsService = moduleRef.get(GroupsService); + instrumentsService = moduleRef.get(InstrumentsService); instrumentModel.findMany.mockResolvedValue([]); }); @@ -335,6 +339,72 @@ describe('GroupsService', () => { }); }); + describe('updateById with a session instrument', () => { + const groupRequiring = (sessionInstrumentId: null | string) => ({ + accessibleInstrumentIds: ['form-1', 'form-2'], + name: 'Test Group', + settings: { sessionInstrumentId } + }); + + const accessibleInstruments = (...ids: string[]) => { + instrumentModel.findMany.mockResolvedValueOnce(ids.map((id) => ({ id }))); + }; + + it("should refuse an update dropping the session instrument from the group's instruments, even one not naming the setting", async () => { + groupModel.findFirst.mockResolvedValueOnce(groupRequiring('form-1')); + accessibleInstruments('form-2'); + await expect(groupsService.updateById('123', { accessibleInstrumentIds: ['form-2'] })).rejects.toThrow( + /before removing instrument 'form-1'/ + ); + expect(groupModel.update).not.toHaveBeenCalled(); + }); + + it('should refuse a session instrument the group cannot access, saying so rather than asking to remove it', async () => { + groupModel.findFirst.mockResolvedValueOnce(groupRequiring(null)); + const update = groupsService.updateById('123', { settings: { sessionInstrumentId: 'form-3' } }); + await expect(update).rejects.toBeInstanceOf(BadRequestException); + await expect(update).rejects.toThrow(/instrument 'form-3' is not$/); + expect(groupModel.update).not.toHaveBeenCalled(); + }); + + it('should refuse a session instrument that is not a form, since only a form is rendered when a session starts', async () => { + groupModel.findFirst.mockResolvedValueOnce(groupRequiring(null)); + instrumentsService.findById.mockResolvedValueOnce({ kind: 'INTERACTIVE' }); + await expect( + groupsService.updateById('123', { settings: { sessionInstrumentId: 'form-1' } }) + ).rejects.toBeInstanceOf(BadRequestException); + expect(groupModel.update).not.toHaveBeenCalled(); + }); + + it("should look the new session instrument up within the caller's ability and the group", async () => { + const ability = createAppAbility([{ action: 'manage', subject: 'all' }]); + groupModel.findFirst.mockResolvedValueOnce(groupRequiring(null)); + instrumentsService.findById.mockResolvedValueOnce({ kind: 'FORM' }); + await groupsService.updateById('123', { settings: { sessionInstrumentId: 'form-1' } }, { ability }); + expect(instrumentsService.findById).toHaveBeenCalledWith('form-1', { ability }, ['123']); + expect(groupModel.update.mock.lastCall?.[0]).toMatchObject({ + data: { settings: { sessionInstrumentId: 'form-1' } } + }); + }); + + it('should accept dropping the session instrument from the group once the setting is cleared in the same update', async () => { + groupModel.findFirst.mockResolvedValueOnce(groupRequiring('form-1')); + accessibleInstruments('form-2'); + await groupsService.updateById('123', { + accessibleInstrumentIds: ['form-2'], + settings: { sessionInstrumentId: null } + }); + expect(groupModel.update.mock.lastCall?.[0]).toMatchObject({ data: { settings: { sessionInstrumentId: null } } }); + }); + + it('should not look the session instrument up again when the update leaves it as it was', async () => { + groupModel.findFirst.mockResolvedValueOnce(groupRequiring('form-1')); + await groupsService.updateById('123', { settings: { sessionInstrumentId: 'form-1' } }); + expect(instrumentsService.findById).not.toHaveBeenCalled(); + expect(groupModel.update).toHaveBeenCalled(); + }); + }); + describe('findAll', () => { it('should return the array returned by the group model', async () => { groupModel.findMany.mockResolvedValueOnce([{ name: 'Test Group' }]); diff --git a/apps/api/src/groups/groups.module.ts b/apps/api/src/groups/groups.module.ts index 4524965a6..7b713a980 100644 --- a/apps/api/src/groups/groups.module.ts +++ b/apps/api/src/groups/groups.module.ts @@ -1,11 +1,14 @@ import { Module } from '@nestjs/common'; +import { InstrumentsModule } from '@/instruments/instruments.module'; + import { GroupsController } from './groups.controller'; import { GroupsService } from './groups.service'; @Module({ controllers: [GroupsController], exports: [GroupsService], + imports: [InstrumentsModule], providers: [GroupsService] }) export class GroupsModule {} diff --git a/apps/api/src/groups/groups.service.ts b/apps/api/src/groups/groups.service.ts index 347207c65..3af5040e6 100644 --- a/apps/api/src/groups/groups.service.ts +++ b/apps/api/src/groups/groups.service.ts @@ -9,13 +9,15 @@ import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'; import { AuditLogger } from '@/audit/audit.logger'; import { accessibleQuery } from '@/auth/ability.utils'; import type { EntityOperationOptions } from '@/core/types'; +import { InstrumentsService } from '@/instruments/instruments.service'; @Injectable() export class GroupsService { constructor( @InjectModel('Group') private readonly groupModel: Model<'Group'>, @InjectModel('Instrument') private readonly instrumentModel: Model<'Instrument'>, - private readonly auditLogger: AuditLogger + private readonly auditLogger: AuditLogger, + private readonly instrumentsService: InstrumentsService ) {} async archiveById(id: string, currentUser: RequestUser) { @@ -124,6 +126,15 @@ export class GroupsService { }); validInstrumentIds = existingInstruments.map(({ id }) => id); } + await this.validateSessionInstrument( + { + accessibleInstrumentIds: validInstrumentIds ?? group.accessibleInstrumentIds, + groupId: id, + sessionInstrumentId: settings?.sessionInstrumentId, + storedSessionInstrumentId: group.settings.sessionInstrumentId + }, + { ability } + ); try { return await this.groupModel.update({ @@ -204,4 +215,43 @@ export class GroupsService { throw new BadRequestException(`No email template with id '${nextActiveId}' exists in this group`); } } + + /** + * Every update is checked, not only one naming the session instrument: removing the instrument from + * the group's accessible list would otherwise leave every Start Session in the group requiring a + * form no one in it can open. + */ + private async validateSessionInstrument( + { + accessibleInstrumentIds, + groupId, + sessionInstrumentId, + storedSessionInstrumentId + }: { + accessibleInstrumentIds: string[]; + groupId: string; + sessionInstrumentId: null | string | undefined; + storedSessionInstrumentId: null | string | undefined; + }, + options: EntityOperationOptions + ): Promise { + // `undefined` leaves the stored value alone; `null` removes it. + const nextSessionInstrumentId = sessionInstrumentId === undefined ? storedSessionInstrumentId : sessionInstrumentId; + if (!nextSessionInstrumentId) { + return; + } + if (!accessibleInstrumentIds.includes(nextSessionInstrumentId)) { + throw new BadRequestException( + nextSessionInstrumentId === storedSessionInstrumentId + ? `The group's Session Instrument must be one of its accessible instruments: set the Session Instrument to another form, or to none, before removing instrument '${nextSessionInstrumentId}'` + : `The group's Session Instrument must be one of its accessible instruments, and instrument '${nextSessionInstrumentId}' is not` + ); + } + if (nextSessionInstrumentId !== storedSessionInstrumentId) { + const instrument = await this.instrumentsService.findById(nextSessionInstrumentId, options, [groupId]); + if (instrument.kind !== 'FORM') { + throw new BadRequestException(`The group's Session Instrument must be a form, not '${instrument.kind}'`); + } + } + } } diff --git a/apps/api/src/instrument-records/instrument-records.service.ts b/apps/api/src/instrument-records/instrument-records.service.ts index e7170427e..cce91fbb8 100644 --- a/apps/api/src/instrument-records/instrument-records.service.ts +++ b/apps/api/src/instrument-records/instrument-records.service.ts @@ -15,7 +15,7 @@ import { UnprocessableEntityException } from '@nestjs/common'; import { translateInstrument } from '@opendatacapture/instrument-utils'; -import type { Json, ScalarInstrument } from '@opendatacapture/runtime-core'; +import type { FormInstrument, InstrumentValidationSchema, Json, ScalarInstrument } from '@opendatacapture/runtime-core'; import type { CreateInstrumentRecordData, InstrumentRecord, @@ -141,15 +141,7 @@ export class InstrumentRecordsService { await this.subjectsService.findById(subjectId); await this.sessionsService.findById(sessionId); - const parseResult = instrument.validationSchema.safeParse(this.parseJson(rawData)); - if (!parseResult.success) { - throw new UnprocessableEntityException({ - error: 'Unprocessable Entity', - issues: parseResult.error.issues, - message: `Data received for record does not pass validation schema of instrument '${instrument.id}'`, - statusCode: 422 - }); - } + const data = this.parseData(instrument, rawData); return this.instrumentRecordModel.create({ data: { @@ -159,9 +151,9 @@ export class InstrumentRecordsService { } : undefined, computedMeasures: instrument.measures - ? this.instrumentMeasuresService.computeMeasures(instrument.measures, parseResult.data) + ? this.instrumentMeasuresService.computeMeasures(instrument.measures, data) : null, - data: this.serializeData(parseResult.data), + data: this.serializeData(data), date, group: groupId ? { @@ -410,6 +402,26 @@ export class InstrumentRecordsService { return results; } + /** Throws exactly as `create` does for data the instrument's schema rejects. */ + parseData( + instrument: { + id: string; + validationSchema: InstrumentValidationSchema | InstrumentValidationSchema; + }, + rawData: unknown + ) { + const parseResult = instrument.validationSchema.safeParse(this.parseJson(rawData)); + if (!parseResult.success) { + throw new UnprocessableEntityException({ + error: 'Unprocessable Entity', + issues: parseResult.error.issues, + message: `Data received for record does not pass validation schema of instrument '${instrument.id}'`, + statusCode: 422 + }); + } + return parseResult.data; + } + /** * Per-instrument collection statistics for the instrument hub's listing. * diff --git a/apps/api/src/instruments/__tests__/instruments.service.test.ts b/apps/api/src/instruments/__tests__/instruments.service.test.ts index 03cb5f230..d7264f25a 100644 --- a/apps/api/src/instruments/__tests__/instruments.service.test.ts +++ b/apps/api/src/instruments/__tests__/instruments.service.test.ts @@ -728,6 +728,38 @@ describe('InstrumentsService', () => { where: { accessibleInstrumentIds: { has: 'hash:REACTION_TIME-1' } } }); }); + + it('should require a new edition of a form at the start of a session wherever the previous edition was required', async () => { + virtualizationService.eval.mockReturnValue(okAsync(formInstance('INTAKE', 2))); + instrumentModel.exists.mockResolvedValue(false); + + await instrumentsService.create({ bundle: '__BUNDLE__' }); + + expect(groupModel.updateMany).toHaveBeenCalledWith({ + data: { settings: { update: { sessionInstrumentId: 'hash:INTAKE-2' } } }, + where: { settings: { is: { sessionInstrumentId: 'hash:INTAKE-1' } } } + }); + }); + + it('should leave every group on the previous edition when the new one fails to save, so none requires a missing form', async () => { + virtualizationService.eval.mockReturnValue(okAsync(formInstance('INTAKE', 2))); + instrumentModel.exists.mockResolvedValue(false); + instrumentModel.create.mockRejectedValueOnce(new Error('connection reset')); + + await expect(instrumentsService.create({ bundle: '__BUNDLE__' })).rejects.toThrowError('connection reset'); + expect(groupModel.updateMany).not.toHaveBeenCalled(); + }); + + it('should leave a session instrument on its edition when the new edition is not a form, since only a form can be required', async () => { + virtualizationService.eval.mockReturnValue( + okAsync({ ...interactiveInstrument, internal: { edition: 2, name: 'REACTION_TIME' } }) + ); + instrumentModel.exists.mockResolvedValue(false); + + await instrumentsService.create({ bundle: '__BUNDLE__' }); + + expect(groupModel.updateMany).toHaveBeenCalledTimes(1); + }); }); describe('generateSeriesInstrumentId', () => { diff --git a/apps/api/src/instruments/instruments.service.ts b/apps/api/src/instruments/instruments.service.ts index bcc8a42ff..4d84b73de 100644 --- a/apps/api/src/instruments/instruments.service.ts +++ b/apps/api/src/instruments/instruments.service.ts @@ -138,21 +138,6 @@ export class InstrumentsService { if (!result.success) { throw new UnprocessableEntityException(result.message); } - } else if (instance.internal.edition > 1) { - await this.groupModel.updateMany({ - data: { - accessibleInstrumentIds: { - push: [id] - } - }, - where: { - accessibleInstrumentIds: { - has: this.generateScalarInstrumentId({ - internal: { edition: instance.internal.edition - 1, name: instance.internal.name } - }) - } - } - }); } try { @@ -173,6 +158,33 @@ export class InstrumentsService { } throw err; } + + // Only once the edition is stored, so a failed insert leaves no group requiring a missing instrument. + if (instance.kind !== 'SERIES' && instance.internal.edition > 1) { + const previousEditionId = this.generateScalarInstrumentId({ + internal: { edition: instance.internal.edition - 1, name: instance.internal.name } + }); + await this.groupModel.updateMany({ + data: { + accessibleInstrumentIds: { + push: [id] + } + }, + where: { + accessibleInstrumentIds: { + has: previousEditionId + } + } + }); + // A group requiring the previous edition at the start of a session requires this one instead. + // The previous edition stays accessible, so a new edition that is not a form leaves it in place. + if (instance.kind === 'FORM') { + await this.groupModel.updateMany({ + data: { settings: { update: { sessionInstrumentId: id } } }, + where: { settings: { is: { sessionInstrumentId: previousEditionId } } } + }); + } + } return { ...instance, id }; } diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index ee0d3908b..fd1f4abb3 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -16,6 +16,7 @@ import { MailModule } from './mail/mail.module'; import { PermissionSetsModule } from './permission-sets/permission-sets.module'; import { SessionsModule } from './sessions/sessions.module'; import { SetupModule } from './setup/setup.module'; +import { StartSessionModule } from './start-session/start-session.module'; import { StorageModule } from './storage/storage.module'; import { SubjectsModule } from './subjects/subjects.module'; import { SummaryModule } from './summary/summary.module'; @@ -79,6 +80,7 @@ export default AppFactory.create({ }), SessionsModule, SetupModule, + StartSessionModule, StorageModule, SubjectsModule, SummaryModule, diff --git a/apps/api/src/sessions/__tests__/sessions.controller.test.ts b/apps/api/src/sessions/__tests__/sessions.controller.test.ts index ef9d1fcf1..2a6263b04 100644 --- a/apps/api/src/sessions/__tests__/sessions.controller.test.ts +++ b/apps/api/src/sessions/__tests__/sessions.controller.test.ts @@ -23,19 +23,6 @@ describe('SessionsController', () => { sessionsService = moduleRef.get(SessionsService); }); - it('should create a session with the caller ability, so the group and user are looked up within it', async () => { - const data = { - date: new Date('2024-01-01T00:00:00.000Z'), - groupId: 'group-1', - subjectData: { id: 'subject-1' }, - type: 'IN_PERSON' as const - }; - sessionsService.create.mockResolvedValue({ id: 'session-1' }); - - await expect(sessionsController.create(data, ability)).resolves.toEqual({ id: 'session-1' }); - expect(sessionsService.create).toHaveBeenCalledWith(data, { ability }); - }); - it('should list the requested group sessions within what the caller may read', async () => { const sessions = [{ id: 'session-1' }]; sessionsService.findAllIncludeUsernames.mockResolvedValue(sessions); diff --git a/apps/api/src/sessions/sessions.controller.ts b/apps/api/src/sessions/sessions.controller.ts index e69428ddd..aea55a842 100644 --- a/apps/api/src/sessions/sessions.controller.ts +++ b/apps/api/src/sessions/sessions.controller.ts @@ -1,8 +1,6 @@ import { ApiOperation, CurrentUser } from '@douglasneuroinformatics/libnest'; -import { Body, Controller, Get, Post, Query } from '@nestjs/common'; -import { $CreateSessionData } from '@opendatacapture/schemas/session'; +import { Controller, Get, Query } from '@nestjs/common'; import type { SessionWithUser } from '@opendatacapture/schemas/session'; -import type { Session } from '@prisma/client'; import type { AppAbility } from '@/auth/auth.types'; import { RouteAccess } from '@/core/decorators/route-access.decorator'; @@ -13,13 +11,6 @@ import { SessionsService } from './sessions.service'; export class SessionsController { constructor(private readonly sessionsService: SessionsService) {} - @ApiOperation({ description: 'Create Session' }) - @Post() - @RouteAccess({ action: 'create', subject: 'Session' }) - create(@Body() data: $CreateSessionData, @CurrentUser('ability') ability: AppAbility): Promise { - return this.sessionsService.create(data, { ability }); - } - @ApiOperation({ description: 'Find all sessions and usernames attached to them' }) @Get() @RouteAccess({ action: 'read', subject: 'Session' }) diff --git a/apps/api/src/start-session/__tests__/start-session.controller.test.ts b/apps/api/src/start-session/__tests__/start-session.controller.test.ts new file mode 100644 index 000000000..a33f9f8e4 --- /dev/null +++ b/apps/api/src/start-session/__tests__/start-session.controller.test.ts @@ -0,0 +1,38 @@ +import { MockFactory } from '@douglasneuroinformatics/libnest/testing'; +import type { MockedInstance } from '@douglasneuroinformatics/libnest/testing'; +import { Test } from '@nestjs/testing'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { createAppAbility } from '@/auth/ability.utils'; + +import { StartSessionController } from '../start-session.controller'; +import { StartSessionService } from '../start-session.service'; + +const ability = createAppAbility([{ action: 'manage', subject: 'Session' }]); + +describe('StartSessionController', () => { + let startSessionController: StartSessionController; + let startSessionService: MockedInstance; + + beforeEach(async () => { + const moduleRef = await Test.createTestingModule({ + controllers: [StartSessionController], + providers: [MockFactory.createForService(StartSessionService)] + }).compile(); + startSessionController = moduleRef.get(StartSessionController); + startSessionService = moduleRef.get(StartSessionService); + }); + + it('should start a session with the caller ability, so the group and user are looked up within it', async () => { + const data = { + date: new Date('2024-01-01T00:00:00.000Z'), + groupId: 'group-1', + subjectData: { id: 'subject-1' }, + type: 'IN_PERSON' as const + }; + startSessionService.start.mockResolvedValue({ id: 'session-1' }); + + await expect(startSessionController.create(data, ability)).resolves.toEqual({ id: 'session-1' }); + expect(startSessionService.start).toHaveBeenCalledWith(data, ability); + }); +}); diff --git a/apps/api/src/start-session/__tests__/start-session.service.test.ts b/apps/api/src/start-session/__tests__/start-session.service.test.ts new file mode 100644 index 000000000..5e5b69a2e --- /dev/null +++ b/apps/api/src/start-session/__tests__/start-session.service.test.ts @@ -0,0 +1,196 @@ +import { MockFactory } from '@douglasneuroinformatics/libnest/testing'; +import type { MockedInstance } from '@douglasneuroinformatics/libnest/testing'; +import { ForbiddenException, UnprocessableEntityException } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import type { $StartSessionData } from '@opendatacapture/schemas/session'; +import { beforeEach, describe, expect, it } from 'vitest'; + +import { createAppAbility } from '@/auth/ability.utils'; +import { GroupsService } from '@/groups/groups.service'; +import { InstrumentRecordsService } from '@/instrument-records/instrument-records.service'; +import { InstrumentsService } from '@/instruments/instruments.service'; +import { SessionsService } from '@/sessions/sessions.service'; +import { SubjectsService } from '@/subjects/subjects.service'; + +import { StartSessionService } from '../start-session.service'; + +const ability = createAppAbility([ + { action: 'create', subject: 'Session' }, + { action: 'create', subject: 'InstrumentRecord' } +]); + +const sessionDate = new Date('2026-01-01T09:00:00.000Z'); + +const session = { date: sessionDate, id: 'session-1', subjectId: 'subject-1' }; + +const details: $StartSessionData = { + date: sessionDate, + groupId: 'group-1', + subjectData: { id: 'subject-1' }, + type: 'IN_PERSON' +}; + +const answers = { data: { score: 1 }, instrumentId: 'form-1' }; + +const group = (sessionInstrumentId: null | string) => ({ + id: 'group-1', + name: 'Group One', + settings: { sessionInstrumentId } +}); + +describe('StartSessionService', () => { + let groupsService: MockedInstance; + let instrumentRecordsService: MockedInstance; + let instrumentsService: MockedInstance; + let sessionsService: MockedInstance; + let startSessionService: StartSessionService; + let subjectsService: MockedInstance; + + beforeEach(async () => { + const moduleRef = await Test.createTestingModule({ + providers: [ + StartSessionService, + MockFactory.createForService(GroupsService), + MockFactory.createForService(InstrumentRecordsService), + MockFactory.createForService(InstrumentsService), + MockFactory.createForService(SessionsService), + MockFactory.createForService(SubjectsService) + ] + }).compile(); + groupsService = moduleRef.get(GroupsService); + instrumentRecordsService = moduleRef.get(InstrumentRecordsService); + instrumentsService = moduleRef.get(InstrumentsService); + sessionsService = moduleRef.get(SessionsService); + startSessionService = moduleRef.get(StartSessionService); + subjectsService = moduleRef.get(SubjectsService); + sessionsService.create.mockResolvedValue(session); + instrumentsService.findById.mockResolvedValue({ id: 'form-1', kind: 'FORM' }); + }); + + describe('in a group requiring no session instrument', () => { + beforeEach(() => { + groupsService.findById.mockResolvedValue(group(null)); + }); + + it("should create the session within the caller's ability", async () => { + await expect(startSessionService.start(details, ability)).resolves.toBe(session); + expect(groupsService.findById).toHaveBeenCalledWith('group-1', { ability }); + expect(sessionsService.create).toHaveBeenCalledWith(details, { ability }); + }); + + it('should refuse answers to a session instrument rather than drop them, so a misconfigured client is noticed', async () => { + await expect( + startSessionService.start({ ...details, sessionInstrumentAnswers: answers }, ability) + ).rejects.toThrow(UnprocessableEntityException); + expect(sessionsService.create).not.toHaveBeenCalled(); + }); + }); + + describe('outside any group', () => { + it('should create the session without looking up a group', async () => { + await startSessionService.start({ ...details, groupId: null }, ability); + expect(groupsService.findById).not.toHaveBeenCalled(); + expect(sessionsService.create).toHaveBeenCalledWith({ ...details, groupId: null }, { ability }); + }); + + it('should refuse answers to a session instrument, since no group requires one', async () => { + await expect( + startSessionService.start({ ...details, groupId: null, sessionInstrumentAnswers: answers }, ability) + ).rejects.toThrow(UnprocessableEntityException); + expect(sessionsService.create).not.toHaveBeenCalled(); + }); + }); + + describe('in a group requiring a session instrument', () => { + beforeEach(() => { + groupsService.findById.mockResolvedValue(group('form-1')); + }); + + it('should refuse to start a session without the answers', async () => { + await expect(startSessionService.start(details, ability)).rejects.toThrow(UnprocessableEntityException); + expect(sessionsService.create).not.toHaveBeenCalled(); + }); + + it('should refuse answers to any instrument but the one the group requires', async () => { + await expect( + startSessionService.start( + { ...details, sessionInstrumentAnswers: { ...answers, instrumentId: 'form-2' } }, + ability + ) + ).rejects.toThrow(UnprocessableEntityException); + expect(sessionsService.create).not.toHaveBeenCalled(); + }); + + it('should refuse a caller who may not create records, since the session would bring one with it', async () => { + const sessionOnly = createAppAbility([{ action: 'create', subject: 'Session' }]); + await expect( + startSessionService.start({ ...details, sessionInstrumentAnswers: answers }, sessionOnly) + ).rejects.toThrow(ForbiddenException); + expect(sessionsService.create).not.toHaveBeenCalled(); + }); + + it('should refuse a session instrument that is not a form', async () => { + instrumentsService.findById.mockResolvedValueOnce({ id: 'form-1', kind: 'INTERACTIVE' }); + await expect( + startSessionService.start({ ...details, sessionInstrumentAnswers: answers }, ability) + ).rejects.toThrow(UnprocessableEntityException); + expect(sessionsService.create).not.toHaveBeenCalled(); + }); + + it('should refuse answers the instrument rejects before creating anything, so no subject is left behind', async () => { + const rejection = new UnprocessableEntityException('invalid'); + instrumentRecordsService.parseData.mockImplementationOnce(() => { + throw rejection; + }); + await expect(startSessionService.start({ ...details, sessionInstrumentAnswers: answers }, ability)).rejects.toBe( + rejection + ); + expect(sessionsService.create).not.toHaveBeenCalled(); + }); + + it("should look the instrument up within the caller's ability and the session's group", async () => { + await startSessionService.start({ ...details, sessionInstrumentAnswers: answers }, ability); + expect(instrumentsService.findById).toHaveBeenCalledWith('form-1', { ability }, ['group-1']); + }); + + it('should create the record of the answers in the new session, dated as the session is', async () => { + await expect(startSessionService.start({ ...details, sessionInstrumentAnswers: answers }, ability)).resolves.toBe( + session + ); + expect(sessionsService.create).toHaveBeenCalledWith(details, { ability }); + expect(instrumentRecordsService.create).toHaveBeenCalledWith( + { + data: answers.data, + date: sessionDate, + groupId: 'group-1', + instrumentId: 'form-1', + sessionId: 'session-1', + subjectId: 'subject-1' + }, + { ability } + ); + }); + + it('should delete the session and the subject it created when its record cannot be created, so none is kept', async () => { + const failure = new Error('write failed'); + subjectsService.exists.mockResolvedValueOnce(false); + instrumentRecordsService.create.mockRejectedValueOnce(failure); + await expect(startSessionService.start({ ...details, sessionInstrumentAnswers: answers }, ability)).rejects.toBe( + failure + ); + expect(sessionsService.deleteById).toHaveBeenCalledWith('session-1'); + expect(subjectsService.deleteById).toHaveBeenCalledWith('subject-1'); + }); + + it('should keep a subject that existed before the session when its record cannot be created', async () => { + const failure = new Error('write failed'); + subjectsService.exists.mockResolvedValueOnce(true); + instrumentRecordsService.create.mockRejectedValueOnce(failure); + await expect(startSessionService.start({ ...details, sessionInstrumentAnswers: answers }, ability)).rejects.toBe( + failure + ); + expect(sessionsService.deleteById).toHaveBeenCalledWith('session-1'); + expect(subjectsService.deleteById).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/apps/api/src/start-session/start-session.controller.ts b/apps/api/src/start-session/start-session.controller.ts new file mode 100644 index 000000000..e74a7e3d8 --- /dev/null +++ b/apps/api/src/start-session/start-session.controller.ts @@ -0,0 +1,25 @@ +import { ApiOperation, CurrentUser } from '@douglasneuroinformatics/libnest'; +import { Body, Controller, Post } from '@nestjs/common'; +import { $StartSessionData } from '@opendatacapture/schemas/session'; +import type { Session } from '@prisma/client'; + +import type { AppAbility } from '@/auth/auth.types'; +import { RouteAccess } from '@/core/decorators/route-access.decorator'; + +import { StartSessionService } from './start-session.service'; + +@Controller('sessions') +export class StartSessionController { + constructor(private readonly startSessionService: StartSessionService) {} + + @ApiOperation({ + description: + "Create a session. When the session's group requires a session instrument, the answers to it are created as a record of the session in the same request, or neither is created.", + summary: 'Create Session' + }) + @Post() + @RouteAccess({ action: 'create', subject: 'Session' }) + create(@Body() data: $StartSessionData, @CurrentUser('ability') ability: AppAbility): Promise { + return this.startSessionService.start(data, ability); + } +} diff --git a/apps/api/src/start-session/start-session.module.ts b/apps/api/src/start-session/start-session.module.ts new file mode 100644 index 000000000..38f0a2e95 --- /dev/null +++ b/apps/api/src/start-session/start-session.module.ts @@ -0,0 +1,19 @@ +import { Module } from '@nestjs/common'; + +import { GroupsModule } from '@/groups/groups.module'; +import { InstrumentRecordsModule } from '@/instrument-records/instrument-records.module'; +import { InstrumentsModule } from '@/instruments/instruments.module'; +import { SessionsModule } from '@/sessions/sessions.module'; +import { SubjectsModule } from '@/subjects/subjects.module'; + +import { StartSessionController } from './start-session.controller'; +import { StartSessionService } from './start-session.service'; + +// Starting a session creates the record of the group's session instrument with it, and +// `InstrumentRecordsModule` already imports `SessionsModule`, so the two meet here rather than in either. +@Module({ + controllers: [StartSessionController], + imports: [GroupsModule, InstrumentRecordsModule, InstrumentsModule, SessionsModule, SubjectsModule], + providers: [StartSessionService] +}) +export class StartSessionModule {} diff --git a/apps/api/src/start-session/start-session.service.ts b/apps/api/src/start-session/start-session.service.ts new file mode 100644 index 000000000..18a1eab3e --- /dev/null +++ b/apps/api/src/start-session/start-session.service.ts @@ -0,0 +1,81 @@ +import { ForbiddenException, Injectable, UnprocessableEntityException } from '@nestjs/common'; +import type { $StartSessionData } from '@opendatacapture/schemas/session'; +import type { Session } from '@prisma/client'; + +import type { AppAbility } from '@/auth/auth.types'; +import { GroupsService } from '@/groups/groups.service'; +import { InstrumentRecordsService } from '@/instrument-records/instrument-records.service'; +import { InstrumentsService } from '@/instruments/instruments.service'; +import { SessionsService } from '@/sessions/sessions.service'; +import { SubjectsService } from '@/subjects/subjects.service'; + +/** + * A session started over HTTP, which is where a group's session instrument is required. The gateway + * synchronizer, CSV upload and the demo seeder create sessions through `SessionsService` directly, so + * none of them is asked for one. + */ +@Injectable() +export class StartSessionService { + constructor( + private readonly groupsService: GroupsService, + private readonly instrumentRecordsService: InstrumentRecordsService, + private readonly instrumentsService: InstrumentsService, + private readonly sessionsService: SessionsService, + private readonly subjectsService: SubjectsService + ) {} + + async start({ sessionInstrumentAnswers, ...data }: $StartSessionData, ability: AppAbility): Promise { + const group = data.groupId ? await this.groupsService.findById(data.groupId, { ability }) : null; + const sessionInstrumentId = group?.settings.sessionInstrumentId; + if (!group || !sessionInstrumentId) { + if (sessionInstrumentAnswers) { + throw new UnprocessableEntityException( + "Answers to a session instrument were sent, but the session's group requires no session instrument" + ); + } + return this.sessionsService.create(data, { ability }); + } + if (sessionInstrumentAnswers?.instrumentId !== sessionInstrumentId) { + throw new UnprocessableEntityException( + `Group '${group.name}' requires its session instrument '${sessionInstrumentId}' to be completed to start a session` + ); + } + if (!ability.can('create', 'InstrumentRecord')) { + throw new ForbiddenException( + `Starting a session in group '${group.name}' creates a record of its session instrument, which requires permission to create instrument records` + ); + } + + // Refused before anything is written, so answers the instrument rejects create no subject either. + const instrument = await this.instrumentsService.findById(sessionInstrumentId, { ability }, [group.id]); + if (instrument.kind !== 'FORM') { + throw new UnprocessableEntityException(`Session instrument '${sessionInstrumentId}' is not a form`); + } + this.instrumentRecordsService.parseData(instrument, sessionInstrumentAnswers.data); + + const isNewSubject = !(await this.subjectsService.exists(data.subjectData.id)); + const session = await this.sessionsService.create(data, { ability }); + try { + await this.instrumentRecordsService.create( + { + data: sessionInstrumentAnswers.data, + date: session.date, + groupId: group.id, + instrumentId: sessionInstrumentId, + sessionId: session.id, + subjectId: session.subjectId + }, + { ability } + ); + } catch (err) { + // Unscoped, as `SessionsService.createMany` rolls back: the caller may create sessions and + // subjects without being allowed to delete them, and these were created by this request a moment ago. + await this.sessionsService.deleteById(session.id); + if (isNewSubject) { + await this.subjectsService.deleteById(session.subjectId); + } + throw err; + } + return session; + } +} diff --git a/apps/api/src/subjects/__tests__/subjects.service.test.ts b/apps/api/src/subjects/__tests__/subjects.service.test.ts index 15f2c5b88..c0a9a5a1c 100644 --- a/apps/api/src/subjects/__tests__/subjects.service.test.ts +++ b/apps/api/src/subjects/__tests__/subjects.service.test.ts @@ -192,6 +192,14 @@ describe('SubjectsService', () => { }); }); + describe('exists', () => { + it('should look the id up in every group, so a subject the caller cannot read still counts', async () => { + subjectModel.exists.mockResolvedValueOnce(true); + await expect(subjectsService.exists('subject-1')).resolves.toBe(true); + expect(subjectModel.exists).toHaveBeenCalledWith({ id: 'subject-1' }); + }); + }); + describe('find', () => { it('should return the array returned by the subject model', async () => { subjectModel.findMany.mockResolvedValueOnce([{ id: '123' }]); diff --git a/apps/api/src/subjects/subjects.service.ts b/apps/api/src/subjects/subjects.service.ts index 382e64d1d..8a722accd 100644 --- a/apps/api/src/subjects/subjects.service.ts +++ b/apps/api/src/subjects/subjects.service.ts @@ -170,6 +170,14 @@ export class SubjectsService { return { success: true }; } + /** + * Unscoped, because a subject in a group the caller cannot read is still the subject with this id, + * and only whether it exists leaves the service. + */ + async exists(id: string): Promise { + return this.subjectModel.exists({ id }); + } + async find( { groupId, hasRecord }: { groupId?: string; hasRecord?: boolean } = {}, { ability }: EntityOperationOptions = {} diff --git a/apps/api/test/helpers.ts b/apps/api/test/helpers.ts index 590dab547..f891ec391 100644 --- a/apps/api/test/helpers.ts +++ b/apps/api/test/helpers.ts @@ -62,17 +62,20 @@ export function defineSuite(name: string, fn: (this: TestSuiteThis) => Promise { const { z } = await import(${JSON.stringify(import.meta.resolve('zod/v4'))}); return { __runtimeVersion: 1, content: { score: { kind: 'number', label: 'Score', variant: 'input' } }, details: { description: 'A form with one number field', license: 'Apache-2.0', title: ${JSON.stringify(name)} }, - internal: { edition: 1, name: ${JSON.stringify(name)} }, + internal: { edition: ${edition}, name: ${JSON.stringify(name)} }, kind: 'FORM', language: 'en', measures: ${measured ? "{ score: { kind: 'const', label: 'Score', ref: 'score' } }" : 'null'}, diff --git a/apps/api/test/suites/10-session-instrument.suite.ts b/apps/api/test/suites/10-session-instrument.suite.ts new file mode 100644 index 000000000..a72943cf7 --- /dev/null +++ b/apps/api/test/suites/10-session-instrument.suite.ts @@ -0,0 +1,153 @@ +import { randomUUID } from 'node:crypto'; + +import { beforeAll, describe, expect, it } from 'vitest'; + +import { InstrumentsService } from '@/instruments/instruments.service'; + +import { defineSuite, scoreFormBundle } from '../helpers'; + +type Group = { accessibleInstrumentIds: string[]; id: string; settings: { sessionInstrumentId?: null | string } }; + +export default defineSuite('session instrument', function () { + let adminHeaders: { authorization: string }; + let otherFormId: string; + let sessionInstrumentId: string; + + const createGroup = async (settings?: { [key: string]: unknown }) => { + const response = await this.app.inject({ + headers: adminHeaders, + method: 'POST', + payload: { name: `Session Instrument ${randomUUID()}`, settings, type: 'RESEARCH' }, + url: '/v1/groups' + }); + expect(response.statusCode).toBe(201); + return response.json(); + }; + + const updateGroup = (groupId: string, payload: { [key: string]: unknown }) => { + return this.app.inject({ headers: adminHeaders, method: 'PATCH', payload, url: `/v1/groups/${groupId}` }); + }; + + const groupRequiringSessionInstrument = async () => { + const group = await createGroup(); + const response = await updateGroup(group.id, { + accessibleInstrumentIds: [sessionInstrumentId, otherFormId], + settings: { sessionInstrumentId } + }); + expect(response.statusCode).toBe(200); + return response.json(); + }; + + const startSession = (groupId: string, extra: { [key: string]: unknown } = {}) => { + const subjectId = `session-instrument-${randomUUID()}`; + const request = this.app.inject({ + headers: adminHeaders, + method: 'POST', + payload: { + date: '2026-03-04T05:06:07.000Z', + groupId, + subjectData: { id: subjectId }, + type: 'RETROSPECTIVE', + ...extra + }, + url: '/v1/sessions' + }); + return { request, subjectId }; + }; + + const subjectExists = async (subjectId: string) => { + const response = await this.app.inject({ headers: adminHeaders, method: 'GET', url: `/v1/subjects/${subjectId}` }); + return response.statusCode === 200; + }; + + beforeAll(async () => { + const login = await this.app.inject({ + method: 'POST', + payload: { password: 'DataCapture2025_Test', username: 'admin' }, + url: '/v1/auth/login' + }); + expect(login.statusCode).toBe(200); + adminHeaders = { authorization: `Bearer ${login.json<{ accessToken: string }>().accessToken}` }; + const instruments = this.app.get(InstrumentsService); + sessionInstrumentId = (await instruments.create({ bundle: scoreFormBundle('SESSION_INSTRUMENT') })).id; + otherFormId = (await instruments.create({ bundle: scoreFormBundle('SESSION_INSTRUMENT_OTHER') })).id; + }); + + describe('POST /v1/sessions', () => { + it('should create the session and a record of the answers in it, dated as the session is', async () => { + const group = await groupRequiringSessionInstrument(); + const { request, subjectId } = startSession(group.id, { + sessionInstrumentAnswers: { data: { score: 7 }, instrumentId: sessionInstrumentId } + }); + const response = await request; + expect(response.statusCode).toBe(201); + const session = response.json<{ id: string }>(); + + const records = await this.app.inject({ + headers: adminHeaders, + method: 'GET', + url: `/v1/instrument-records?subjectId=${subjectId}` + }); + expect(records.json()).toMatchObject([ + { + data: { score: 7 }, + date: '2026-03-04T05:06:07.000Z', + instrumentId: sessionInstrumentId, + sessionId: session.id + } + ]); + }); + + it('should refuse a session without the answers, creating neither it nor its subject', async () => { + const group = await groupRequiringSessionInstrument(); + const { request, subjectId } = startSession(group.id); + expect((await request).statusCode).toBe(422); + expect(await subjectExists(subjectId)).toBe(false); + }); + + it('should refuse answers the instrument rejects, creating neither the session nor its subject', async () => { + const group = await groupRequiringSessionInstrument(); + const { request, subjectId } = startSession(group.id, { + sessionInstrumentAnswers: { data: { score: 'seven' }, instrumentId: sessionInstrumentId } + }); + expect((await request).statusCode).toBe(422); + expect(await subjectExists(subjectId)).toBe(false); + }); + + it('should refuse answers sent for a group that requires none, rather than drop them', async () => { + const group = await createGroup(); + const { request } = startSession(group.id, { + sessionInstrumentAnswers: { data: { score: 7 }, instrumentId: sessionInstrumentId } + }); + expect((await request).statusCode).toBe(422); + }); + }); + + describe('PATCH /v1/groups/:id', () => { + it("should refuse to remove the session instrument from the group's instruments, naming the setting", async () => { + const group = await groupRequiringSessionInstrument(); + const response = await updateGroup(group.id, { accessibleInstrumentIds: [otherFormId] }); + expect(response.statusCode).toBe(400); + expect(response.json<{ message: string }>().message).toContain('Session Instrument'); + }); + }); + + describe('POST /v1/groups', () => { + it('should create a group without a session instrument, even when one is sent', async () => { + const group = await createGroup({ defaultIdentificationMethod: 'CUSTOM_ID', sessionInstrumentId }); + expect(group.settings.sessionInstrumentId).toBeFalsy(); + }); + }); + + describe('a new edition of the session instrument', () => { + it('should become the session instrument of every group that required the previous edition', async () => { + const group = await groupRequiringSessionInstrument(); + const nextEdition = await this.app + .get(InstrumentsService) + .create({ bundle: scoreFormBundle('SESSION_INSTRUMENT', { edition: 2 }) }); + + const response = await this.app.inject({ headers: adminHeaders, method: 'GET', url: `/v1/groups/${group.id}` }); + expect(response.json().settings.sessionInstrumentId).toBe(nextEdition.id); + }); + }); +}); diff --git a/apps/web/src/components/SessionInstrumentStep/SessionInstrumentStep.tsx b/apps/web/src/components/SessionInstrumentStep/SessionInstrumentStep.tsx new file mode 100644 index 000000000..1dd71dd63 --- /dev/null +++ b/apps/web/src/components/SessionInstrumentStep/SessionInstrumentStep.tsx @@ -0,0 +1,40 @@ +import { Button, Spinner } from '@douglasneuroinformatics/libui/components'; +import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; +import { InstrumentRenderer } from '@opendatacapture/react-core'; +import type { InstrumentSubmitHandler } from '@opendatacapture/react-core'; +import { ArrowLeftIcon } from 'lucide-react'; + +import { NavigationBlocker } from '@/components/NavigationBlocker'; +import { useInstrumentBundle } from '@/hooks/useInstrumentBundle'; + +type SessionInstrumentStepProps = { + instrumentId: string; + onBack: () => void; + onSubmit: InstrumentSubmitHandler; +}; + +export const SessionInstrumentStep = ({ instrumentId, onBack, onSubmit }: SessionInstrumentStepProps) => { + const { t } = useTranslation(); + const instrumentBundleQuery = useInstrumentBundle(instrumentId); + + return ( +
+
+ +
+ {instrumentBundleQuery.data ? ( + + ) : ( + + )} +
+ ); +}; diff --git a/apps/web/src/components/SessionInstrumentStep/__tests__/SessionInstrumentStep.test.tsx b/apps/web/src/components/SessionInstrumentStep/__tests__/SessionInstrumentStep.test.tsx new file mode 100644 index 000000000..5ab6b4f91 --- /dev/null +++ b/apps/web/src/components/SessionInstrumentStep/__tests__/SessionInstrumentStep.test.tsx @@ -0,0 +1,58 @@ +import type { InstrumentRendererProps } from '@opendatacapture/react-core'; +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { SessionInstrumentStep } from '../SessionInstrumentStep'; + +import '@/services/i18n'; + +const mocks = vi.hoisted(() => ({ + bundle: undefined as undefined | { bundle: string; id: string; kind: 'FORM' }, + InstrumentRenderer: vi.fn((_props: InstrumentRendererProps) =>
), + useInstrumentBundle: vi.fn() +})); + +vi.mock('@opendatacapture/react-core', () => ({ InstrumentRenderer: mocks.InstrumentRenderer })); +vi.mock('@/hooks/useInstrumentBundle', () => ({ + useInstrumentBundle: (id: string) => { + mocks.useInstrumentBundle(id); + return { data: mocks.bundle }; + } +})); +vi.mock('@/components/NavigationBlocker', () => ({ NavigationBlocker: () => null })); + +describe('SessionInstrumentStep', () => { + afterEach(() => { + cleanup(); + vi.clearAllMocks(); + mocks.bundle = undefined; + }); + + it('should load the bundle of the session instrument', () => { + render(); + expect(mocks.useInstrumentBundle).toHaveBeenCalledWith('form-1'); + }); + + it('should wait for the bundle before rendering the instrument', () => { + render(); + expect(screen.queryByTestId('instrument-renderer')).toBeNull(); + }); + + it('should render the instrument, submitting its answers to the page and blocking navigation away from them', () => { + mocks.bundle = { bundle: '__BUNDLE__', id: 'form-1', kind: 'FORM' }; + const onSubmit = vi.fn(); + render(); + expect(mocks.InstrumentRenderer.mock.lastCall?.[0]).toMatchObject({ + NavigationBlocker: expect.any(Function), + onSubmit, + target: mocks.bundle + }); + }); + + it('should return to the session details when the clinician goes back', () => { + const onBack = vi.fn(); + render(); + fireEvent.click(screen.getByTestId('session-instrument-back')); + expect(onBack).toHaveBeenCalledOnce(); + }); +}); diff --git a/apps/web/src/components/SessionInstrumentStep/index.ts b/apps/web/src/components/SessionInstrumentStep/index.ts new file mode 100644 index 000000000..adf37fd56 --- /dev/null +++ b/apps/web/src/components/SessionInstrumentStep/index.ts @@ -0,0 +1 @@ +export * from './SessionInstrumentStep'; diff --git a/apps/web/src/hooks/__tests__/useUpdateGroupMutation.test.ts b/apps/web/src/hooks/__tests__/useUpdateGroupMutation.test.ts index 0fde8f732..2966f60eb 100644 --- a/apps/web/src/hooks/__tests__/useUpdateGroupMutation.test.ts +++ b/apps/web/src/hooks/__tests__/useUpdateGroupMutation.test.ts @@ -39,7 +39,7 @@ function renderUpdateMutation(options?: Parameters { return createElement(QueryClientProvider, { children, client: queryClient }); }; - return renderHook(() => useUpdateGroupMutation(options), { wrapper }); + return { ...renderHook(() => useUpdateGroupMutation(options), { wrapper }), queryClient }; } describe('useUpdateGroupMutation', () => { @@ -49,6 +49,12 @@ describe('useUpdateGroupMutation', () => { store.currentGroup = { id: 'group-1' }; }); + it('should seed the group query with the saved group, so a page reading it fresh shows the save', async () => { + const { queryClient, result } = renderUpdateMutation(); + await result.current.mutateAsync({ name: 'Renamed' }); + expect(queryClient.getQueryData(['group', 'group-1'])).toMatchObject({ id: 'group-1', name: 'Group One' }); + }); + it('patches the currently selected group and keeps the default error toast', async () => { const { result } = renderUpdateMutation(); await result.current.mutateAsync({ name: 'Renamed' }); diff --git a/apps/web/src/hooks/useCreateSessionMutation.ts b/apps/web/src/hooks/useCreateSessionMutation.ts index e53bb8fbd..69e220e23 100644 --- a/apps/web/src/hooks/useCreateSessionMutation.ts +++ b/apps/web/src/hooks/useCreateSessionMutation.ts @@ -1,13 +1,13 @@ import { useNotificationsStore } from '@douglasneuroinformatics/libui/hooks'; import { $Session } from '@opendatacapture/schemas/session'; -import type { $CreateSessionData } from '@opendatacapture/schemas/session'; +import type { $StartSessionData } from '@opendatacapture/schemas/session'; import { useMutation } from '@tanstack/react-query'; import axios from 'axios'; export function useCreateSessionMutation() { const addNotification = useNotificationsStore((store) => store.addNotification); return useMutation({ - mutationFn: async (data: $CreateSessionData) => { + mutationFn: async (data: $StartSessionData) => { const response = await axios.post('/v1/sessions', data); return $Session.parseAsync(response.data); }, diff --git a/apps/web/src/hooks/useUpdateGroupMutation.ts b/apps/web/src/hooks/useUpdateGroupMutation.ts index cdb08274b..6aa048e53 100644 --- a/apps/web/src/hooks/useUpdateGroupMutation.ts +++ b/apps/web/src/hooks/useUpdateGroupMutation.ts @@ -1,11 +1,13 @@ import { useNotificationsStore } from '@douglasneuroinformatics/libui/hooks'; import { $Group } from '@opendatacapture/schemas/group'; import type { $UpdateGroupData } from '@opendatacapture/schemas/group'; -import { useMutation } from '@tanstack/react-query'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; import axios from 'axios'; import { useAppStore } from '@/store'; +import { groupQueryOptions } from './useGroupQuery'; + type UpdateGroupMutationOptions = { /** Whether a success toast is raised. Opt out where the caller renders its own save feedback. */ successNotification?: boolean; @@ -22,6 +24,7 @@ export function useUpdateGroupMutation({ }: UpdateGroupMutationOptions = {}) { const addNotification = useNotificationsStore((store) => store.addNotification); const currentGroup = useAppStore((store) => store.currentGroup); + const queryClient = useQueryClient(); return useMutation({ mutationFn: async (data: $UpdateGroupData) => { // A caller that opts out of throwing is declaring it renders its own failure feedback, so @@ -31,7 +34,9 @@ export function useUpdateGroupMutation({ }); return $Group.parseAsync(response.data); }, - onSuccess() { + onSuccess(group) { + // Pages that read the group fresh rather than from the store must see what was just saved. + queryClient.setQueryData(groupQueryOptions(group.id).queryKey, group); if (successNotification) { addNotification({ type: 'success' }); } diff --git a/apps/web/src/routes/_app/group/__tests__/manage.test.tsx b/apps/web/src/routes/_app/group/__tests__/manage.test.tsx index 98d295254..9e7650eee 100644 --- a/apps/web/src/routes/_app/group/__tests__/manage.test.tsx +++ b/apps/web/src/routes/_app/group/__tests__/manage.test.tsx @@ -12,16 +12,26 @@ import '@/services/i18n'; type DeleteCallbacks = { onSettled: () => void; onSuccess: () => void }; +type Loader = (ctx: { + context: { queryClient: { fetchQuery: (options: object) => Promise } }; +}) => Promise; + const mocks = vi.hoisted(() => ({ changeGroup: vi.fn(), createMutateAsync: vi.fn(), deleteMutate: vi.fn(), + /** The group as `GET /v1/groups/:id` returns it; the store's copy dates from sign-in. */ + fetchedGroup: undefined as Group | undefined, instruments: undefined as TranslatedInstrumentInfo[] | undefined, isDemo: false, store: { currentGroup: null as Group | null }, updateMutateAsync: vi.fn<(data: Partial<$UpdateGroupData>) => Promise>() })); +vi.mock('@/hooks/useGroupQuery', async (importOriginal) => ({ + ...(await importOriginal()), + useGroupQuery: (groupId: null | string | undefined) => ({ data: groupId ? mocks.fetchedGroup : undefined }) +})); vi.mock('@/hooks/useInstrumentInfoQuery', () => ({ useInstrumentInfoQuery: () => ({ data: mocks.instruments }) })); @@ -38,11 +48,12 @@ vi.mock('@/hooks/useUpdateGroupMutation', () => ({ useUpdateGroupMutation: () => ({ mutateAsync: mocks.updateMutateAsync }) })); vi.mock('@/store', () => ({ - useAppStore: ( - selector: (store: { changeGroup: typeof mocks.changeGroup; currentGroup: Group | null }) => unknown - ) => { - return selector({ changeGroup: mocks.changeGroup, currentGroup: mocks.store.currentGroup }); - } + useAppStore: Object.assign( + (selector: (store: { changeGroup: typeof mocks.changeGroup; currentGroup: Group | null }) => unknown) => { + return selector({ changeGroup: mocks.changeGroup, currentGroup: mocks.store.currentGroup }); + }, + { getState: () => ({ currentGroup: mocks.store.currentGroup }) } + ) })); vi.mock('@/components/LoadingFallback', () => ({ LoadingFallback: () =>
@@ -65,14 +76,18 @@ vi.mock('@/components/InstrumentPreviewDialog', () => ({ const scalar = ({ createdAt = null, + edition = 1, id, kind = 'FORM', + name = id, sourceRepo = null, title }: { createdAt?: Date | null; + edition?: number; id: string; kind?: 'FILE' | 'FORM' | 'INTERACTIVE'; + name?: string; sourceRepo?: null | { id: string; name: null | string }; title: string; }): TranslatedInstrumentInfo => ({ @@ -80,7 +95,7 @@ const scalar = ({ createdAt, details: { authors: null, description: `${title} description`, license: 'MIT', title }, id, - internal: { edition: 1, name: id }, + internal: { edition, name }, kind, language: 'en', sourceRepo, @@ -139,7 +154,13 @@ const defaultInstruments = () => [ const RouteComponent = Route.options.component!; -const renderPage = () => render(); +const loader = Route.options.loader as Loader; + +/** Renders with the server holding the same group as the store, unless a test says otherwise. */ +const renderPage = () => { + mocks.fetchedGroup ??= mocks.store.currentGroup ?? undefined; + return render(); +}; const rerenderPage = (rerender: (ui: ReactNode) => void) => rerender(); @@ -175,6 +196,7 @@ const resolveCreate = (result: CreateSeriesInstrumentResult) => mocks.createMuta describe('Route', () => { beforeEach(() => { vi.clearAllMocks(); + mocks.fetchedGroup = undefined; mocks.instruments = defaultInstruments(); mocks.isDemo = false; mocks.store.currentGroup = makeGroup(); @@ -198,6 +220,13 @@ describe('Route', () => { expect(screen.queryByText('Accessible Instruments')).toBeNull(); }); + it('should show a loading fallback until the group has been read from the server', () => { + mocks.fetchedGroup = undefined; + render(); + expect(screen.getByTestId('loading-fallback')).toBeTruthy(); + expect(screen.queryByText('Accessible Instruments')).toBeNull(); + }); + it('should show a loading fallback when no group is selected, since there is nothing to manage', () => { mocks.store.currentGroup = null; renderPage(); @@ -640,6 +669,7 @@ describe('Route', () => { idValidationRegex: '^[0-9]+$', idValidationRegexErrorMessage: { en: 'Digits only', fr: 'Chiffres seulement' }, minimumAge: 18, + sessionInstrumentId: null, subjectIdDisplayLength: 6 } }) @@ -677,4 +707,94 @@ describe('Route', () => { expect(screen.queryByText('Custom ID Validation Message (English)')).toBeNull(); }); }); + + describe('session instrument', () => { + const requiring = (sessionInstrumentId: string) => { + return makeGroup({ settings: { defaultIdentificationMethod: 'CUSTOM_ID', sessionInstrumentId } }); + }; + + const sessionInstrumentOptions = () => { + const select = document.querySelector('select[name="sessionInstrumentId"]')!; + return Array.from(select.options, (option) => option.textContent).filter(Boolean); + }; + + const savedSessionInstrumentId = () => mocks.updateMutateAsync.mock.lastCall?.[0].settings?.sessionInstrumentId; + + it('should save no session instrument for a group that requires none', async () => { + renderPage(); + submitSettings(); + await waitFor(() => expect(mocks.updateMutateAsync).toHaveBeenCalled()); + expect(savedSessionInstrumentId()).toBeNull(); + }); + + it('should keep the session instrument the group requires', async () => { + mocks.store.currentGroup = requiring('form-1'); + renderPage(); + submitSettings(); + await waitFor(() => expect(mocks.updateMutateAsync).toHaveBeenCalled()); + expect(savedSessionInstrumentId()).toBe('form-1'); + }); + + it('should offer only the forms the group has selected, since only those can be required', () => { + renderPage(); + expect(sessionInstrumentOptions()).toEqual(['None', 'Happiness Questionnaire']); + fireEvent.click(checkbox('Breakfast Survey')); + expect(sessionInstrumentOptions()).toEqual(['None', 'Happiness Questionnaire', 'Breakfast Survey']); + }); + + it('should tell two forms with the same title apart by their names', () => { + mocks.instruments = [ + ...defaultInstruments(), + scalar({ id: 'form-3', name: 'HAPPINESS_SHORT', title: 'Happiness Questionnaire' }) + ]; + mocks.store.currentGroup = makeGroup({ accessibleInstrumentIds: ['form-1', 'form-3'] }); + renderPage(); + expect(sessionInstrumentOptions()).toEqual([ + 'None', + 'Happiness Questionnaire (form-1)', + 'Happiness Questionnaire (HAPPINESS_SHORT)' + ]); + }); + + it('should seed the setting from the group the server holds, so a save cannot undo a change made since sign-in', async () => { + mocks.store.currentGroup = makeGroup(); + mocks.fetchedGroup = requiring('form-1'); + renderPage(); + submitSettings(); + await waitFor(() => expect(mocks.updateMutateAsync).toHaveBeenCalled()); + expect(savedSessionInstrumentId()).toBe('form-1'); + }); + + it('should refuse to save once the session instrument is no longer selected, rather than lose the group access to it', async () => { + mocks.store.currentGroup = requiring('form-1'); + renderPage(); + fireEvent.click(checkbox('Happiness Questionnaire')); + submitSettings(); + expect(await screen.findByText(/The session instrument must be one of the group's instruments/)).toBeTruthy(); + expect(mocks.updateMutateAsync).not.toHaveBeenCalled(); + }); + + it('should accept a session instrument the list does not display but the group can still access', async () => { + mocks.store.currentGroup = requiring('missing-1'); + renderPage(); + submitSettings(); + await waitFor(() => expect(mocks.updateMutateAsync).toHaveBeenCalled()); + expect(savedSessionInstrumentId()).toBe('missing-1'); + }); + }); + + describe('loader', () => { + it('should fetch the current group even when it is cached, since the form saves every setting it is seeded with', async () => { + const fetchQuery = vi.fn(() => Promise.resolve()); + await loader({ context: { queryClient: { fetchQuery } } }); + expect(fetchQuery).toHaveBeenCalledWith(expect.objectContaining({ queryKey: ['group', 'group-1'] })); + }); + + it('should fetch nothing when no group is selected', async () => { + mocks.store.currentGroup = null; + const fetchQuery = vi.fn(() => Promise.resolve()); + await loader({ context: { queryClient: { fetchQuery } } }); + expect(fetchQuery).not.toHaveBeenCalled(); + }); + }); }); diff --git a/apps/web/src/routes/_app/group/manage.tsx b/apps/web/src/routes/_app/group/manage.tsx index e5cc5c3e3..a463472d6 100644 --- a/apps/web/src/routes/_app/group/manage.tsx +++ b/apps/web/src/routes/_app/group/manage.tsx @@ -30,6 +30,7 @@ import { PageHeader } from '@/components/PageHeader'; import { WithFallback } from '@/components/WithFallback'; import { useCreateSeriesInstrumentMutation } from '@/hooks/useCreateSeriesInstrumentMutation'; import { useDeleteSeriesInstrumentMutation } from '@/hooks/useDeleteSeriesInstrumentMutation'; +import { groupQueryOptions, useGroupQuery } from '@/hooks/useGroupQuery'; import { useInstrumentInfoQuery } from '@/hooks/useInstrumentInfoQuery'; import { useSetupStateQuery } from '@/hooks/useSetupStateQuery'; import { useUpdateGroupMutation } from '@/hooks/useUpdateGroupMutation'; @@ -80,6 +81,9 @@ const expandSelectedSeriesIds = ({ return expandedIds; }; +/** The select's value for a group requiring no session instrument; instrument ids are hashes, so none is this. */ +const NO_SESSION_INSTRUMENT = 'NONE'; + type SettingsValues = { defaultIdentificationMethod?: SubjectIdentificationMethod; idValidationRegex?: null | string; @@ -87,6 +91,7 @@ type SettingsValues = { idValidationRegexErrorMessageFr?: null | string; minimumAge?: null | number; minimumAgeApplied?: boolean | null; + sessionInstrumentId?: string; subjectIdDisplayLength?: null | number; }; @@ -594,6 +599,17 @@ const ManageGroupForm = ({ data, onSubmit, readOnly }: ManageGroupFormProps) => [instruments] ); + // Only a form the group will be able to access may be required, so the options follow the selection. + // The list holds the latest edition of each form, so a shared title is two forms, told apart by name. + const selectedForms = instruments.form.filter((item) => selectedIds.has(item.id)); + const sessionInstrumentOptions = Object.fromEntries( + selectedForms.map((item) => { + const isTitleShared = selectedForms.some((other) => other !== item && other.title === item.title); + const label = isTitleShared && item.internal ? `${item.title} (${item.internal.name})` : item.title; + return [item.id, label]; + }) + ); + return (
{previewItem && ( @@ -795,6 +811,25 @@ const ManageGroupForm = ({ data, onSubmit, readOnly }: ManageGroupFormProps) => } }, title: t('group.manage.groupSettings') + }, + { + fields: { + sessionInstrumentId: { + description: t({ + en: 'A form completed as part of starting every session in this group. The session is created only once the form is submitted.', + es: 'Un formulario que se completa al iniciar cada sesión en este grupo. La sesión se crea solo cuando se envía el formulario.', + fr: "Un formulaire rempli au démarrage de chaque session dans ce groupe. La session n'est créée qu'une fois le formulaire soumis." + }), + kind: 'string', + label: t({ en: 'Session Instrument', es: 'Instrumento de sesión', fr: 'Instrument de session' }), + options: { + [NO_SESSION_INSTRUMENT]: t({ en: 'None', es: 'Ninguno', fr: 'Aucun' }), + ...sessionInstrumentOptions + }, + variant: 'select' + } + }, + title: t({ en: 'Starting a Session', es: 'Inicio de una sesión', fr: "Démarrage d'une session" }) } ]} initialValues={settingsInitialValues} @@ -807,9 +842,27 @@ const ManageGroupForm = ({ data, onSubmit, readOnly }: ManageGroupFormProps) => idValidationRegexErrorMessageFr: z.string().optional(), minimumAge: z.number().int().positive().optional(), minimumAgeApplied: z.boolean().optional(), + sessionInstrumentId: z.string().optional(), subjectIdDisplayLength: z.number().int().min(1).optional() }) .check((ctx) => { + const { sessionInstrumentId } = ctx.value; + if ( + sessionInstrumentId && + sessionInstrumentId !== NO_SESSION_INSTRUMENT && + !(selectedIds.has(sessionInstrumentId) || hiddenAccessibleIds.includes(sessionInstrumentId)) + ) { + ctx.issues.push({ + code: 'custom', + input: sessionInstrumentId, + message: t({ + en: "The session instrument must be one of the group's instruments. Select it above, or choose another session instrument.", + es: 'El instrumento de sesión debe ser uno de los instrumentos del grupo. Selecciónelo arriba o elija otro instrumento de sesión.', + fr: "L'instrument de session doit faire partie des instruments du groupe. Sélectionnez-le ci-dessus ou choisissez un autre instrument de session." + }), + path: ['sessionInstrumentId'] + }); + } if (ctx.value.minimumAgeApplied && !ctx.value.minimumAge) { ctx.issues.push({ code: 'custom', @@ -841,6 +894,8 @@ const ManageGroupForm = ({ data, onSubmit, readOnly }: ManageGroupFormProps) => fr: formData.idValidationRegexErrorMessageFr }, minimumAge: formData.minimumAgeApplied ? formData.minimumAge : null, + sessionInstrumentId: + formData.sessionInstrumentId === NO_SESSION_INSTRUMENT ? null : formData.sessionInstrumentId, subjectIdDisplayLength: formData.subjectIdDisplayLength } }); @@ -857,20 +912,20 @@ const RouteComponent = () => { const currentGroup = useAppStore((store) => store.currentGroup); const changeGroup = useAppStore((store) => store.changeGroup); const setupState = useSetupStateQuery(); + // The store holds the group as it was at sign-in, and a save sends back every setting the form was + // seeded with, so seeding it from that copy would undo any change made since. + const groupQuery = useGroupQuery(currentGroup?.id); + const group = groupQuery.data; const availableInstruments = instrumentInfoQuery.data; - const accessibleInstrumentIds = currentGroup?.accessibleInstrumentIds; - const instrumentRepoIds = currentGroup?.instrumentRepoIds; - const defaultIdentificationMethod = currentGroup?.settings.defaultIdentificationMethod; - const data = useMemo(() => { - if (!availableInstruments) { + if (!availableInstruments || !group) { return null; } - const accessibleSet = new Set(accessibleInstrumentIds ?? []); - const assignedRepos = new Set(instrumentRepoIds ?? []); + const accessibleSet = new Set(group.accessibleInstrumentIds); + const assignedRepos = new Set(group.instrumentRepoIds); const instruments: CategorizedInstruments = { form: [], interactive: [], series: [] }; const visibleIds = new Set(); @@ -903,12 +958,12 @@ const RouteComponent = () => { const seriesGroupId = instrument.kind === 'SERIES' ? (instrument.seriesGroupId ?? null) : null; const item: InstrumentItem = { authors: instrument.details.authors, - availability: buildSeriesAvailability({ currentGroup, instrumentKind: instrument.kind, seriesGroupId }), + availability: buildSeriesAvailability({ currentGroup: group, instrumentKind: instrument.kind, seriesGroupId }), createdAt: instrument.createdAt ?? null, description: instrument.details.description, id: instrument.id, internal: instrument.kind === 'SERIES' ? null : instrument.internal, - isDeletable: instrument.kind === 'SERIES' && seriesGroupId === currentGroup?.id, + isDeletable: instrument.kind === 'SERIES' && seriesGroupId === group.id, kind: instrument.kind, seriesItems: instrument.kind === 'SERIES' ? instrument.seriesItems : undefined, source, @@ -927,42 +982,31 @@ const RouteComponent = () => { // Preserve any accessible ids we are not displaying (defensive: e.g. instruments that failed to load). const hiddenAccessibleIds = [...accessibleSet].filter((id) => !visibleIds.has(id)); - const settings = currentGroup?.settings; + const settings = group.settings; const settingsInitialValues: SettingsValues = { - defaultIdentificationMethod, - idValidationRegex: settings?.idValidationRegex, - idValidationRegexErrorMessageEn: settings?.idValidationRegexErrorMessage?.en, - idValidationRegexErrorMessageFr: settings?.idValidationRegexErrorMessage?.fr, - minimumAge: settings?.minimumAge, - minimumAgeApplied: typeof settings?.minimumAge === 'number', - subjectIdDisplayLength: settings?.subjectIdDisplayLength + defaultIdentificationMethod: settings.defaultIdentificationMethod, + idValidationRegex: settings.idValidationRegex, + idValidationRegexErrorMessageEn: settings.idValidationRegexErrorMessage?.en, + idValidationRegexErrorMessageFr: settings.idValidationRegexErrorMessage?.fr, + minimumAge: settings.minimumAge, + minimumAgeApplied: typeof settings.minimumAge === 'number', + sessionInstrumentId: settings.sessionInstrumentId ?? NO_SESSION_INSTRUMENT, + subjectIdDisplayLength: settings.subjectIdDisplayLength }; const existingTitles = [...instruments.form, ...instruments.interactive, ...instruments.series].map( (item) => item.title ); - return currentGroup - ? { - existingTitles, - groupId: currentGroup.id, - hiddenAccessibleIds, - initialSelectedIds, - instruments, - settingsInitialValues - } - : null; - }, [ - accessibleInstrumentIds, - availableInstruments, - currentGroup?.id, - currentGroup?.name, - defaultIdentificationMethod, - instrumentRepoIds, - resolvedLanguage, - t, - currentGroup?.settings - ]); + return { + existingTitles, + groupId: group.id, + hiddenAccessibleIds, + initialSelectedIds, + instruments, + settingsInitialValues + }; + }, [availableInstruments, group, resolvedLanguage, t]); return ( @@ -990,5 +1034,12 @@ const RouteComponent = () => { }; export const Route = createFileRoute('/_app/group/manage')({ - component: RouteComponent + component: RouteComponent, + // Fetched even when cached, since the form is seeded once and saves every setting it was seeded with. + loader: async ({ context }) => { + const { currentGroup } = useAppStore.getState(); + if (currentGroup) { + await context.queryClient.fetchQuery(groupQueryOptions(currentGroup.id)); + } + } }); diff --git a/apps/web/src/routes/_app/session/__tests__/start-session.test.tsx b/apps/web/src/routes/_app/session/__tests__/start-session.test.tsx index f02d046e9..254aa1fff 100644 --- a/apps/web/src/routes/_app/session/__tests__/start-session.test.tsx +++ b/apps/web/src/routes/_app/session/__tests__/start-session.test.tsx @@ -1,5 +1,6 @@ import type { FC } from 'react'; +import type { InstrumentSubmitHandler } from '@opendatacapture/react-core'; import type { Group } from '@opendatacapture/schemas/group'; import type { $CreateSessionData, Session } from '@opendatacapture/schemas/session'; import { act, cleanup, render, screen } from '@testing-library/react'; @@ -18,11 +19,18 @@ type StartSessionFormProps = { username?: string; }; +type SessionInstrumentStepProps = { + instrumentId: string; + onBack: () => void; + onSubmit: (result: Parameters[0]) => Promise; +}; + type Loader = (ctx: { context: { queryClient: { ensureQueryData: (options: object) => Promise } }; }) => Promise; type MockState = { + fetchedGroup: Group | null; isPending: boolean; locationState: undefined | { initialValues?: { [key: string]: unknown } }; store: { @@ -35,6 +43,7 @@ type MockState = { const mocks = vi.hoisted(() => { const state: MockState = { + fetchedGroup: null, isPending: false, locationState: undefined, store: { currentGroup: null, currentSession: null, currentUser: null, startSession: vi.fn() } @@ -42,6 +51,7 @@ const mocks = vi.hoisted(() => { return { ...state, mutateAsync: vi.fn(), + SessionInstrumentStep: vi.fn((_props: SessionInstrumentStepProps) =>
), StartSessionForm: vi.fn((_props: StartSessionFormProps) =>
) }; }); @@ -52,9 +62,14 @@ vi.mock('@tanstack/react-router', async (importOriginal) => ({ useLocation: () => ({ state: mocks.locationState }) })); vi.mock('@/components/StartSessionForm', () => ({ StartSessionForm: mocks.StartSessionForm })); +vi.mock('@/components/SessionInstrumentStep', () => ({ SessionInstrumentStep: mocks.SessionInstrumentStep })); vi.mock('@/hooks/useCreateSessionMutation', () => ({ useCreateSessionMutation: () => ({ isPending: mocks.isPending, mutateAsync: mocks.mutateAsync }) })); +vi.mock('@/hooks/useGroupQuery', async (importOriginal) => ({ + ...(await importOriginal()), + useGroupQuery: (groupId: string | undefined) => ({ data: groupId ? mocks.fetchedGroup : undefined }) +})); vi.mock('@/hooks/useSubjectCustomIdsQuery', async (importOriginal) => ({ ...(await importOriginal()), useSubjectCustomIdsQuery: () => ({ data: ['group-1$CUSTOM-1', 'CUSTOM-2'] }) @@ -99,6 +114,7 @@ const formProps = () => mocks.StartSessionForm.mock.lastCall![0]; describe('Route', () => { beforeEach(() => { + mocks.fetchedGroup = group; mocks.isPending = false; mocks.locationState = undefined; mocks.store.currentGroup = group; @@ -201,6 +217,115 @@ describe('Route', () => { }); }); + describe('with a session instrument', () => { + const details: $CreateSessionData = { + date: NOW, + groupId: 'group-1', + subjectData: { id: 'subject-1' }, + type: 'IN_PERSON' + }; + + const answers = { + data: { score: 1 }, + instrumentId: 'form-1', + kind: 'FORM' + } as Parameters[0]; + + const stepProps = () => mocks.SessionInstrumentStep.mock.lastCall![0]; + + const isDetailsFormHidden = () => screen.getByTestId('start-session-form').parentElement!.className === 'hidden'; + + const submitDetails = async (data = details) => { + await act(() => formProps().onSubmit(data)); + }; + + beforeEach(() => { + mocks.fetchedGroup = { ...group, settings: { ...group.settings, sessionInstrumentId: 'form-1' } }; + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("should show the group's session instrument once the details are submitted, without starting the session", async () => { + render(); + await submitDetails(); + expect(stepProps().instrumentId).toBe('form-1'); + expect(isDetailsFormHidden()).toBe(true); + expect(mocks.mutateAsync).not.toHaveBeenCalled(); + }); + + it('should return to the details as they were entered when the clinician goes back, starting nothing', async () => { + render(); + const detailsForm = screen.getByTestId('start-session-form'); + await submitDetails(); + act(() => stepProps().onBack()); + expect(screen.queryByTestId('session-instrument-step')).toBeNull(); + expect(isDetailsFormHidden()).toBe(false); + // The same element, so the form was never remounted and kept what had been typed into it. + expect(screen.getByTestId('start-session-form')).toBe(detailsForm); + expect(mocks.mutateAsync).not.toHaveBeenCalled(); + }); + + it('should start the session with the answers once the instrument is submitted', async () => { + render(); + await submitDetails({ ...details, type: 'RETROSPECTIVE' }); + await act(() => stepProps().onSubmit(answers)); + expect(mocks.mutateAsync).toHaveBeenCalledWith({ + ...details, + sessionInstrumentAnswers: { data: { score: 1 }, instrumentId: 'form-1' }, + type: 'RETROSPECTIVE' + }); + expect(mocks.store.startSession).toHaveBeenCalledWith({ ...session, type: 'RETROSPECTIVE' }); + }); + + it('should date an in-person session when the instrument is submitted, since that is when it is created', async () => { + render(); + await submitDetails(); + const submittedAt = new Date(NOW.getTime() + 60 * 60 * 1000); + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(submittedAt); + await act(() => stepProps().onSubmit(answers)); + expect(mocks.mutateAsync.mock.lastCall?.[0].date).toStrictEqual(submittedAt); + }); + + it('should offer the details again, not the instrument, for the next session', async () => { + const { rerender } = render(); + await submitDetails(); + await act(() => stepProps().onSubmit(answers)); + mocks.store.currentSession = session; + rerender(); + mocks.store.currentSession = null; + rerender(); + expect(screen.queryByTestId('session-instrument-step')).toBeNull(); + expect(isDetailsFormHidden()).toBe(false); + }); + + // The store holds the group from the sign-in token, which predates a session instrument chosen since. + it('should require the session instrument the group has now, not the one it had at sign-in', async () => { + mocks.store.currentGroup = group; + render(); + await submitDetails(); + expect(stepProps().instrumentId).toBe('form-1'); + }); + + it('should start the session at once when the group requires no session instrument', async () => { + mocks.fetchedGroup = group; + render(); + await submitDetails(); + expect(screen.queryByTestId('session-instrument-step')).toBeNull(); + expect(mocks.mutateAsync).toHaveBeenCalledWith(details); + }); + + it('should drop the details entered for another group when the clinician switches group', async () => { + const { rerender } = render(); + await submitDetails(); + mocks.store.currentGroup = { ...mocks.store.currentGroup!, id: 'group-2' }; + rerender(); + expect(screen.queryByTestId('session-instrument-step')).toBeNull(); + }); + }); + describe('loader', () => { it('should prefetch the custom ids of the current group', async () => { const ensureQueryData = vi.fn(() => Promise.resolve()); @@ -218,5 +343,18 @@ describe('Route', () => { expect.objectContaining({ queryKey: ['subjects', 'custom-ids', undefined] }) ); }); + + it('should prefetch the current group, so its session instrument is known before the details are submitted', async () => { + const ensureQueryData = vi.fn(() => Promise.resolve()); + await loader({ context: { queryClient: { ensureQueryData } } }); + expect(ensureQueryData).toHaveBeenCalledWith(expect.objectContaining({ queryKey: ['group', 'group-1'] })); + }); + + it('should fetch no group when none is selected', async () => { + mocks.store.currentGroup = null; + const ensureQueryData = vi.fn(() => Promise.resolve()); + await loader({ context: { queryClient: { ensureQueryData } } }); + expect(ensureQueryData).toHaveBeenCalledOnce(); + }); }); }); diff --git a/apps/web/src/routes/_app/session/start-session.tsx b/apps/web/src/routes/_app/session/start-session.tsx index 284850028..fd0556ff9 100644 --- a/apps/web/src/routes/_app/session/start-session.tsx +++ b/apps/web/src/routes/_app/session/start-session.tsx @@ -3,17 +3,25 @@ import React, { useEffect, useState } from 'react'; import { Card, Heading } from '@douglasneuroinformatics/libui/components'; import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; import type { FormTypes } from '@opendatacapture/runtime-core'; +import type { $CreateSessionData, $StartSessionData } from '@opendatacapture/schemas/session'; import { removeSubjectIdScope } from '@opendatacapture/subject-utils'; import { createFileRoute, useLocation } from '@tanstack/react-router'; import { AnimatePresence, motion } from 'motion/react'; import { PageHeader } from '@/components/PageHeader'; +import { SessionInstrumentStep } from '@/components/SessionInstrumentStep'; import { StartSessionForm } from '@/components/StartSessionForm'; import type { StartSessionFormData } from '@/components/StartSessionForm'; import { useCreateSessionMutation } from '@/hooks/useCreateSessionMutation'; +import { groupQueryOptions, useGroupQuery } from '@/hooks/useGroupQuery'; import { subjectCustomIdsQueryOptions, useSubjectCustomIdsQuery } from '@/hooks/useSubjectCustomIdsQuery'; import { useAppStore } from '@/store'; +type PendingSession = { + details: $CreateSessionData; + sessionInstrumentId: string; +}; + const RouteComponent = () => { const currentGroup = useAppStore((store) => store.currentGroup); const currentSession = useAppStore((store) => store.currentSession); @@ -27,10 +35,13 @@ const RouteComponent = () => { const [initialValues, setInitialValues] = useState>( location.state?.initialValues ?? defaultInitialValues ); + const [pendingSession, setPendingSession] = useState(null); const { t } = useTranslation('session'); const createSessionMutation = useCreateSessionMutation(); const subjectCustomIdsQuery = useSubjectCustomIdsQuery({ params: { groupId: currentGroup?.id } }); + // The store holds the group as it was at sign-in, so a session instrument chosen since is read fresh. + const groupQuery = useGroupQuery(currentGroup?.id); const customSubjectIds = subjectCustomIdsQuery.data.map(removeSubjectIdScope); @@ -40,6 +51,17 @@ const RouteComponent = () => { } }, [currentSession]); + // The details name the group they were entered in, so they must not start a session after a switch. + useEffect(() => { + setPendingSession(null); + }, [currentGroup?.id]); + + const createSession = async (data: $StartSessionData) => { + const session = await createSessionMutation.mutateAsync(data); + setPendingSession(null); + startSession({ ...session, type: data.type }); + }; + return ( @@ -48,15 +70,37 @@ const RouteComponent = () => { {currentSession === null && ( - { - const session = await createSessionMutation.mutateAsync(formData); - startSession({ ...session, type: formData.type }); + // Kept mounted behind the session instrument, so going back finds the details as they were entered. +
+ { + const sessionInstrumentId = groupQuery.data?.settings.sessionInstrumentId; + if (sessionInstrumentId) { + setPendingSession({ details, sessionInstrumentId }); + return; + } + await createSession(details); + }} + /> +
+ )} + {currentSession === null && pendingSession && ( + setPendingSession(null)} + onSubmit={async (result) => { + const { details } = pendingSession; + await createSession({ + ...details, + // An in-person session is dated when it is created, which is now that its form is submitted. + date: details.type === 'IN_PERSON' ? new Date() : details.date, + sessionInstrumentAnswers: { data: result.data, instrumentId: result.instrumentId } + }); }} /> )} @@ -124,6 +168,9 @@ export const Route = createFileRoute('/_app/session/start-session')({ component: RouteComponent, loader: async ({ context }) => { const { currentGroup } = useAppStore.getState(); - await context.queryClient.ensureQueryData(subjectCustomIdsQueryOptions({ params: { groupId: currentGroup?.id } })); + await Promise.all([ + context.queryClient.ensureQueryData(subjectCustomIdsQueryOptions({ params: { groupId: currentGroup?.id } })), + currentGroup ? context.queryClient.ensureQueryData(groupQueryOptions(currentGroup.id)) : null + ]); } }); diff --git a/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx b/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx index 205aa86b0..fe452146c 100644 --- a/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx +++ b/docs/en/3-guides/3.4-how-to-get-started-with-odc.mdx @@ -80,6 +80,10 @@ The default Standard User role does not see Manage Group. Choose the default identification method and configure the ID validation pattern and validation messages. +6. **Choose a session instrument, if any** + + A group can require one form to be completed as part of starting every session. Set **Session Instrument** to that form, or to **None**. Only a form the group can access can be chosen, and it must stay accessible while it is the session instrument. When an administrator uploads a new edition of the form, the group requires the new edition. + ## Start a Session @@ -102,7 +106,11 @@ Use **Start Session** to begin work with a subject. Use an in-person session for new data collection; it is dated when it starts. Use a retrospective session when entering data that was collected earlier using another system, and enter the date and time the data was collected. -4. **Confirm the session is active** +4. **Complete the session instrument, if the group has one** + + When the group requires a session instrument, it opens once the session details are submitted. The session starts only when the form is submitted, and its answers are saved as a record of the session. **Back** returns to the session details; leaving saves nothing. + +5. **Confirm the session is active** After the session starts, ODC shows the active session in the sidebar. diff --git a/packages/schemas/src/group/__tests__/group.test.ts b/packages/schemas/src/group/__tests__/group.test.ts index 281ec11b7..94e7a3cee 100644 --- a/packages/schemas/src/group/__tests__/group.test.ts +++ b/packages/schemas/src/group/__tests__/group.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { $UpdateGroupData } from '../group.js'; +import { $CreateGroupData, $UpdateGroupData } from '../group.js'; describe('$UpdateGroupData', () => { it('should require expectedUpdatedAt when emailTemplates is included', () => { @@ -26,3 +26,14 @@ describe('$UpdateGroupData', () => { } ); }); + +describe('$CreateGroupData', () => { + it('should drop a session instrument, so a group is never created requiring one it cannot access', () => { + const data = $CreateGroupData.parse({ + name: 'New Group', + settings: { defaultIdentificationMethod: 'CUSTOM_ID', sessionInstrumentId: 'instrument-1' }, + type: 'RESEARCH' + }); + expect(data.settings).not.toHaveProperty('sessionInstrumentId'); + }); +}); diff --git a/packages/schemas/src/group/group.ts b/packages/schemas/src/group/group.ts index 10836001b..2de64395d 100644 --- a/packages/schemas/src/group/group.ts +++ b/packages/schemas/src/group/group.ts @@ -8,6 +8,7 @@ const $GroupSettings = z.object({ idValidationRegex: $RegexString.nullish(), idValidationRegexErrorMessage: $LocalizedString.nullish(), minimumAge: z.number().int().positive().nullish(), + sessionInstrumentId: z.string().nullish(), subjectIdDisplayLength: z.number().nullish() }); @@ -50,7 +51,9 @@ export const $Group = $BaseModel.extend({ export type $CreateGroupData = z.infer; export const $CreateGroupData = z.object({ name: z.string().min(1), - settings: $GroupSettings.optional(), + // The session instrument must be one the group can access, which is checked only when a group is + // updated, so a group is created without one. + settings: $GroupSettings.omit({ sessionInstrumentId: true }).optional(), type: $GroupType }); diff --git a/packages/schemas/src/session/session.ts b/packages/schemas/src/session/session.ts index 2c24851a2..e51c0e878 100644 --- a/packages/schemas/src/session/session.ts +++ b/packages/schemas/src/session/session.ts @@ -1,6 +1,6 @@ import { z } from 'zod/v4'; -import { $BaseModel, $DateLike } from '../core/core.js'; +import { $BaseModel, $DateLike, $Json } from '../core/core.js'; import { $CreateSubjectData, $Subject } from '../subject/subject.js'; export type SessionType = z.infer; @@ -25,6 +25,12 @@ export const $CreateSessionData = z.object({ username: z.string().nullish() }); +export type $StartSessionData = z.infer; +export const $StartSessionData = $CreateSessionData.extend({ + // Required exactly when the session's group has a session instrument. + sessionInstrumentAnswers: z.object({ data: $Json, instrumentId: z.string() }).optional() +}); + export type SessionWithUser = Session & { user: null | { username?: null | string; diff --git a/testing/src/pages/_app/session/start-session.page.ts b/testing/src/pages/_app/session/start-session.page.ts index 8a7054c9c..a772d0372 100644 --- a/testing/src/pages/_app/session/start-session.page.ts +++ b/testing/src/pages/_app/session/start-session.page.ts @@ -8,6 +8,10 @@ export class StartSessionPage extends AppPage { readonly pageHeader: Locator; readonly selectField: Locator; readonly sessionForm: Locator; + /** Returns from the group's session instrument to the session details. */ + readonly sessionInstrumentBackButton: Locator; + /** The form a group requires as part of starting a session, shown once the details are submitted. */ + readonly sessionInstrumentStep: Locator; /** The hidden native select that carries the value; `sexTrigger` is the control a user sees. */ readonly sexField: Locator; readonly sexTrigger: Locator; @@ -20,6 +24,8 @@ export class StartSessionPage extends AppPage { super(page); this.pageHeader = page.getByTestId('page-header'); this.sessionForm = page.getByTestId('start-session-form'); + this.sessionInstrumentBackButton = page.getByTestId('session-instrument-back'); + this.sessionInstrumentStep = page.getByTestId('session-instrument-step'); this.selectField = page.locator('[name="subjectIdentificationMethod"]'); this.successMessage = page.getByRole('heading', { name: 'Session Successfully Started' }); this.errorMessages = page.getByTestId('error-message-text'); diff --git a/testing/src/specs/start-session.spec.ts b/testing/src/specs/start-session.spec.ts index fdd515c71..3b0750038 100644 --- a/testing/src/specs/start-session.spec.ts +++ b/testing/src/specs/start-session.spec.ts @@ -1,3 +1,4 @@ +import { RenderInstrumentPage } from '../pages/_app/instruments/render/$id.page'; import { StartSessionPage } from '../pages/_app/session/start-session.page'; import { expect, test } from '../support/fixtures'; @@ -79,6 +80,56 @@ test.describe('start session', () => { }); }); +// A group can require one form to be completed as part of starting a session. The session is created +// only once that form is submitted, so going back to the details creates nothing. +test.describe('session instrument', () => { + test("should start a session only once the group's session instrument is submitted, recording its answers", async ({ + api, + authenticateAs, + page, + uniqueId + }) => { + const group = await api.createGroup({ settings: { defaultIdentificationMethod: 'CUSTOM_ID' } }); + const instrumentId = await api.findInstrumentIdByName('DNP_HAPPINESS_QUESTIONNAIRE'); + await api.updateGroup(group.id, { settings: { sessionInstrumentId: instrumentId } }); + const { credentials } = await api.createUser({ basePermissionLevel: 'STANDARD', groupIds: [group.id] }); + await authenticateAs(credentials); + + const sessionRequests: string[] = []; + page.on('request', (request) => { + if (request.url().endsWith('/v1/sessions') && request.method() === 'POST') { + sessionRequests.push(request.url()); + } + }); + + const startSessionPage = new StartSessionPage(page); + await startSessionPage.goto('/session/start-session'); + await startSessionPage.selectIdentificationMethod('CUSTOM_ID'); + await startSessionPage.typeSubjectId(`intake-${uniqueId}`); + await startSessionPage.dismissSubjectIdOptions(); + await startSessionPage.submitForm(); + await expect(startSessionPage.sessionInstrumentStep).toBeVisible(); + + await startSessionPage.sessionInstrumentBackButton.click(); + await expect(startSessionPage.subjectIdField).toHaveValue(`intake-${uniqueId}`); + expect(sessionRequests).toHaveLength(0); + await startSessionPage.submitForm(); + + const instrumentPage = new RenderInstrumentPage(page); + await instrumentPage.begin(); + await instrumentPage.completeHappinessQuestionnaire(); + const sessionCreated = page.waitForResponse( + (response) => response.url().endsWith('/v1/sessions') && response.request().method() === 'POST' + ); + await instrumentPage.submit(); + const session = (await (await sessionCreated).json()) as { id: string; subjectId: string }; + await expect(startSessionPage.successMessage).toBeVisible(); + + const records = await api.findRecordsBySubject(session.subjectId); + expect(records).toMatchObject([{ instrumentId, sessionId: session.id }]); + }); +}); + // The date picker opens on the browser's current month, so the clock is fixed to a known day; the // timezone makes the stored instant, which is what the API receives, the same wherever the suite runs. test.describe('retrospective session time', () => { diff --git a/testing/src/support/api-client.ts b/testing/src/support/api-client.ts index 047ed99d4..99bf3197e 100644 --- a/testing/src/support/api-client.ts +++ b/testing/src/support/api-client.ts @@ -3,7 +3,7 @@ import { AUDIT_LOGS_MAX_PAGE_SIZE } from '@opendatacapture/schemas/audit'; import type { $AuditLog, $AuditLogAction, $AuditLogsPage } from '@opendatacapture/schemas/audit'; import type { $LoginCredentials } from '@opendatacapture/schemas/auth'; import type { Permissions } from '@opendatacapture/schemas/core'; -import type { $CreateGroupData, Group } from '@opendatacapture/schemas/group'; +import type { $CreateGroupData, $UpdateGroupData, Group } from '@opendatacapture/schemas/group'; import type { InstrumentInfo } from '@opendatacapture/schemas/instrument'; import type { $CreateInstrumentRecordData, @@ -321,6 +321,15 @@ export class ApiClient { return this.putUserPermissions(id, { kind: 'custom', permissions }); } + /** Updates a group as admin, for settings a spec needs in place before a user signs in to it. */ + async updateGroup(id: string, data: $UpdateGroupData): Promise { + return this.expectJson( + this.request.patch(`${API}/groups/${id}`, { data, headers: this.authHeaders }), + 200, + `update group '${id}'` + ); + } + /** * Bulk-creates one record per entry, and with them the subjects and sessions they name. Returns * the records the api reports created, which the upload contract scopes to this request alone.