From c96c5d351fcd542f775af922226acebe4cf5a0dc Mon Sep 17 00:00:00 2001 From: KianKwa Date: Mon, 13 Jul 2026 13:15:23 +0100 Subject: [PATCH 1/9] Add PHT Weekly hearing List style guide and PDF --- apps/web/package.json | 1 + apps/web/src/app.ts | 4 +- .../(admin)/non-strategic-upload/index.ts | 6 +- .../pht-weekly-hearing-list/index.test.ts | 261 ++++++++++++++++++ .../pht-weekly-hearing-list/index.ts | 26 ++ .../pht-weekly-hearing-list.njk | 75 +++++ docs/tickets/645/plan.md | 170 ++++++++++++ docs/tickets/645/tasks.md | 37 +++ docs/tickets/645/ticket.md | 97 +++++++ libs/list-types/common/src/list-type-data.ts | 11 + .../pht-weekly-hearing-list/package.json | 42 +++ .../pht-weekly-hearing-list/src/config.ts | 9 + .../src/conversion/pht-config.ts | 53 ++++ .../src/email-summary/summary-builder.ts | 11 + .../pht-weekly-hearing-list/src/index.ts | 8 + .../pht-weekly-hearing-list/src/locales/cy.ts | 33 +++ .../pht-weekly-hearing-list/src/locales/en.ts | 32 +++ .../src/models/types.ts | 10 + .../src/pdf/pdf-generator.test.ts | 54 ++++ .../src/pdf/pdf-generator.ts | 64 +++++ .../src/pdf/pdf-template.njk | 64 +++++ .../src/rendering/renderer.test.ts | 197 +++++++++++++ .../src/rendering/renderer.ts | 70 +++++ .../src/schemas/pht-weekly-hearing-list.json | 54 ++++ .../pht-weekly-hearing-list/tsconfig.json | 12 + libs/location/src/location-data.ts | 8 + libs/notifications/package.json | 1 + .../src/notification/notification-service.ts | 5 + libs/publication/package.json | 1 + libs/publication/src/processing/service.ts | 8 +- tsconfig.json | 4 +- yarn.lock | 21 ++ 32 files changed, 1444 insertions(+), 5 deletions(-) create mode 100644 apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.test.ts create mode 100644 apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.ts create mode 100644 apps/web/src/pages/(list-types)/pht-weekly-hearing-list/pht-weekly-hearing-list.njk create mode 100644 docs/tickets/645/plan.md create mode 100644 docs/tickets/645/tasks.md create mode 100644 docs/tickets/645/ticket.md create mode 100644 libs/list-types/pht-weekly-hearing-list/package.json create mode 100644 libs/list-types/pht-weekly-hearing-list/src/config.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/conversion/pht-config.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/index.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/locales/cy.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/locales/en.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/models/types.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-template.njk create mode 100644 libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/schemas/pht-weekly-hearing-list.json create mode 100644 libs/list-types/pht-weekly-hearing-list/tsconfig.json diff --git a/apps/web/package.json b/apps/web/package.json index 4a4505d31..49b105d51 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -38,6 +38,7 @@ "@hmcts/london-administrative-court-daily-cause-list": "workspace:*", "@hmcts/magistrates-public-list": "workspace:*", "@hmcts/magistrates-standard-list": "workspace:*", + "@hmcts/pht-weekly-hearing-list": "workspace:*", "@hmcts/public-pages": "workspace:*", "@hmcts/rcj-standard-daily-cause-list": "workspace:*", "@hmcts/send-daily-hearing-list": "workspace:*", diff --git a/apps/web/src/app.ts b/apps/web/src/app.ts index eb5311e1a..9eeacdee4 100644 --- a/apps/web/src/app.ts +++ b/apps/web/src/app.ts @@ -22,6 +22,7 @@ import { apiRoutes as locationApiRoutes } from "@hmcts/location/config"; import { moduleRoot as londonAdminModuleRoot } from "@hmcts/london-administrative-court-daily-cause-list/config"; import { moduleRoot as magistratesPublicListModuleRoot } from "@hmcts/magistrates-public-list/config"; import { moduleRoot as magistratesStandardListModuleRoot } from "@hmcts/magistrates-standard-list/config"; +import { moduleRoot as phtWeeklyHearingListModuleRoot } from "@hmcts/pht-weekly-hearing-list/config"; import { apiRoutes as publicPagesApiRoutes, fileUploadRoutes as publicPagesFileUploadRoutes, @@ -140,7 +141,8 @@ export async function createApp(): Promise { grcWeeklyHearingListModuleRoot, wpafccWeeklyHearingListModuleRoot, utiacStatutoryAppealModuleRoot, - utiacJrModuleRoot + utiacJrModuleRoot, + phtWeeklyHearingListModuleRoot ]; await configureGovuk(app, modulePaths, { diff --git a/apps/web/src/pages/(admin)/non-strategic-upload/index.ts b/apps/web/src/pages/(admin)/non-strategic-upload/index.ts index 3892bb4f7..c36ae6657 100644 --- a/apps/web/src/pages/(admin)/non-strategic-upload/index.ts +++ b/apps/web/src/pages/(admin)/non-strategic-upload/index.ts @@ -9,7 +9,7 @@ import "@hmcts/upper-tribunal-administrative-appeals-chamber-daily-hearing-list" import { LANGUAGE_LABELS, SENSITIVITY_LABELS, storeNonStrategicUpload, type UploadFormData, validateNonStrategicUploadForm } from "@hmcts/admin-pages"; import { requireRole, USER_ROLES } from "@hmcts/auth"; import { getAllLocations, getLocationById } from "@hmcts/location"; -import { Language, Sensitivity } from "@hmcts/publication"; +import { Language } from "@hmcts/publication"; import { findListTypeById, findNonStrategicListTypes } from "@hmcts/system-admin-pages"; import { saveSession } from "@hmcts/web-core"; import type { Request, RequestHandler, Response } from "express"; @@ -25,7 +25,9 @@ async function getListTypesData() { text: listType.shortenedFriendlyName || listType.friendlyName || listType.name })) ]; - const sensitivityMap = Object.fromEntries(nonStrategicListTypes.map((listType) => [listType.id.toString(), Sensitivity.PUBLIC])); + const sensitivityMap = Object.fromEntries( + nonStrategicListTypes.map((listType) => [listType.id.toString(), listType.defaultSensitivity?.toUpperCase() ?? ""]) + ); return { options, sensitivityMap }; } diff --git a/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.test.ts b/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.test.ts new file mode 100644 index 000000000..f9f0f331c --- /dev/null +++ b/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.test.ts @@ -0,0 +1,261 @@ +import type { Request, Response } from "express"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mockValidate = vi.hoisted(() => vi.fn()); + +vi.mock("@hmcts/list-types-common", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + createJsonValidator: () => mockValidate, + provenanceLabelsEn: { MANUAL_UPLOAD: "Manual Upload", SNL: "ListAssist", COMMON_PLATFORM: "Common Platform", CP_CATH: "Libra", PDDA: "PDDA" }, + provenanceLabelsCy: { MANUAL_UPLOAD: "Lanlwytho â Llaw", SNL: "ListAssist", COMMON_PLATFORM: "Common Platform", CP_CATH: "Libra", PDDA: "PDDA" } + }; +}); + +vi.mock("@hmcts/publication", () => ({ + getArtefactById: vi.fn(), + getPublicationJson: vi.fn(), + PROVENANCE_LABELS: { + MANUAL_UPLOAD: "Manual Upload", + LIST_ASSIST: "List Assist" + } +})); + +vi.mock("@hmcts/pht-weekly-hearing-list", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + renderPhtData: vi.fn() + }; +}); + +import { renderPhtData } from "@hmcts/pht-weekly-hearing-list"; +import { getArtefactById, getPublicationJson } from "@hmcts/publication"; +import { GET } from "./index.js"; + +describe("PHT Weekly Hearing List page controller", () => { + let req: Partial; + let res: Partial; + + beforeEach(() => { + vi.clearAllMocks(); + + req = { + query: {} + }; + + res = { + status: vi.fn().mockReturnThis(), + render: vi.fn(), + locals: { locale: "en" } + }; + }); + + describe("GET handler", () => { + it("should render the list successfully with valid data", async () => { + const mockArtefact = { + artefactId: "test-artefact-123", + locationId: "9001", + listTypeId: 999, + contentDate: new Date("2026-01-01"), + displayFrom: new Date("2026-01-01"), + displayTo: new Date("2026-01-07"), + lastReceivedDate: new Date("2026-01-01T12:00:00Z"), + provenance: "MANUAL_UPLOAD" + }; + + const mockJsonData = [ + { + date: "01/01/2026", + caseName: "Test Case A vs B", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + } + ]; + + const mockRenderedData = { + header: { + listTitle: "Primary Health Tribunal Weekly Hearing List", + weekCommencingDate: "01 January 2026", + lastUpdatedDate: "01 January 2026", + lastUpdatedTime: "12pm" + }, + hearings: [ + { + date: "01 January 2026", + caseName: "Test Case A vs B", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + } + ] + }; + + req.query = { artefactId: "test-artefact-123" }; + + vi.mocked(getArtefactById).mockResolvedValue(mockArtefact as any); + vi.mocked(getPublicationJson).mockResolvedValue(mockJsonData); + mockValidate.mockReturnValue({ isValid: true, errors: [] }); + vi.mocked(renderPhtData).mockReturnValue(mockRenderedData as any); + + await GET(req as Request, res as Response); + + expect(getArtefactById).toHaveBeenCalledWith("test-artefact-123"); + expect(getPublicationJson).toHaveBeenCalled(); + expect(mockValidate).toHaveBeenCalledWith(mockJsonData); + expect(renderPhtData).toHaveBeenCalledWith(mockJsonData, { + locale: "en", + courtName: "Primary Health Tribunal", + contentDate: mockArtefact.contentDate, + lastReceivedDate: mockArtefact.lastReceivedDate.toISOString(), + listTitle: "Primary Health Tribunal Weekly Hearing List" + }); + const renderCall = vi.mocked(res.render!).mock.calls[0]!; + expect(renderCall[0]).toBe("pht-weekly-hearing-list"); + expect(renderCall[1]).toMatchObject({ + header: mockRenderedData.header, + hearings: mockRenderedData.hearings, + dataSource: "Manual Upload" + }); + }); + + it("should return 400 when artefactId is missing", async () => { + req.query = {}; + + await GET(req as Request, res as Response); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.render).toHaveBeenCalledWith( + "errors/common", + expect.objectContaining({ + errorTitle: "Bad Request", + errorMessage: "Missing artefactId parameter" + }) + ); + }); + + it("should return 404 when artefact is not found", async () => { + req.query = { artefactId: "non-existent-artefact" }; + + vi.mocked(getArtefactById).mockResolvedValue(null); + + await GET(req as Request, res as Response); + + expect(res.status).toHaveBeenCalledWith(404); + expect(res.render).toHaveBeenCalledWith( + "errors/common", + expect.objectContaining({ + errorTitle: "Not Found", + errorMessage: "The requested list could not be found" + }) + ); + }); + + it("should return 400 when JSON validation fails", async () => { + const mockArtefact = { + artefactId: "test-artefact-123", + listTypeId: 999, + contentDate: new Date("2026-01-01"), + lastReceivedDate: new Date("2026-01-01T12:00:00Z"), + provenance: "MANUAL_UPLOAD" + }; + + const mockJsonData = [ + { + date: "invalid-date", + caseName: "Test Case", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + } + ]; + + req.query = { artefactId: "test-artefact-123" }; + + vi.mocked(getArtefactById).mockResolvedValue(mockArtefact as any); + vi.mocked(getPublicationJson).mockResolvedValue(mockJsonData); + mockValidate.mockReturnValue({ isValid: false, errors: ["Invalid date format"] }); + + await GET(req as Request, res as Response); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.render).toHaveBeenCalledWith( + "errors/common", + expect.objectContaining({ + errorTitle: "Invalid Data", + errorMessage: "The list data is invalid" + }) + ); + }); + + it("should return 500 on server error", async () => { + req.query = { artefactId: "test-artefact-123" }; + + vi.mocked(getArtefactById).mockRejectedValue(new Error("Database connection failed")); + + await GET(req as Request, res as Response); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.render).toHaveBeenCalledWith( + "errors/common", + expect.objectContaining({ + errorTitle: "Server Error", + errorMessage: "An error occurred while loading the list" + }) + ); + }); + + it("should use Welsh locale when specified", async () => { + const mockArtefact = { + artefactId: "test-artefact-123", + listTypeId: 999, + contentDate: new Date("2026-01-01"), + lastReceivedDate: new Date("2026-01-01T12:00:00Z"), + provenance: "MANUAL_UPLOAD" + }; + + const mockJsonData = [ + { + date: "01/01/2026", + caseName: "Test Case", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + } + ]; + + const mockRenderedData = { + header: { + listTitle: "Rhestr Gwrandawiadau Wythnosol y Tribiwnlys Iechyd Sylfaenol", + weekCommencingDate: "01 Ionawr 2026", + lastUpdatedDate: "01 Ionawr 2026", + lastUpdatedTime: "12pm" + }, + hearings: [] + }; + + req.query = { artefactId: "test-artefact-123" }; + res.locals = { locale: "cy" }; + + vi.mocked(getArtefactById).mockResolvedValue(mockArtefact as any); + vi.mocked(getPublicationJson).mockResolvedValue(mockJsonData); + mockValidate.mockReturnValue({ isValid: true, errors: [] }); + vi.mocked(renderPhtData).mockReturnValue(mockRenderedData as any); + + await GET(req as Request, res as Response); + + expect(renderPhtData).toHaveBeenCalledWith( + mockJsonData, + expect.objectContaining({ + locale: "cy" + }) + ); + }); + }); +}); diff --git a/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.ts b/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.ts new file mode 100644 index 000000000..8036f3025 --- /dev/null +++ b/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.ts @@ -0,0 +1,26 @@ +import { createJsonValidator } from "@hmcts/list-types-common"; +import { phtWeeklyHearingListCy as cy, phtWeeklyHearingListEn as en, type PhtHearingList, renderPhtData } from "@hmcts/pht-weekly-hearing-list"; +import { schemaPath } from "@hmcts/pht-weekly-hearing-list/config"; +import { createSimpleListTypeHandler, resolveDataSource } from "../list-type-handler.js"; + +const validate = createJsonValidator(schemaPath); + +export const GET = createSimpleListTypeHandler({ + en, + cy, + validate, + logPrefix: "pht-weekly-hearing-list", + serverError: { errorTitle: "Server Error", errorMessage: "An error occurred while loading the list" }, + render: ({ artefact, jsonData, locale, res }) => { + const t = locale === "cy" ? cy : en; + const { header, hearings } = renderPhtData(jsonData, { + locale, + courtName: "Primary Health Tribunal", + contentDate: artefact.contentDate, + lastReceivedDate: artefact.lastReceivedDate.toISOString(), + listTitle: t.pageTitle + }); + const dataSource = resolveDataSource(artefact.provenance, t as { provenanceLabels?: Record }); + res.render("pht-weekly-hearing-list", { en, cy, t, title: header.listTitle, header, hearings, dataSource }); + } +}); diff --git a/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/pht-weekly-hearing-list.njk b/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/pht-weekly-hearing-list.njk new file mode 100644 index 000000000..7184680b9 --- /dev/null +++ b/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/pht-weekly-hearing-list.njk @@ -0,0 +1,75 @@ +{% extends "layouts/base-template.njk" %} + +{% block page_content %} +
+
+ +

{{ header.listTitle }}

+ +

+ {{ t.factLinkText }} {{ t.factAdditionalText }} +

+ +

{{ t.listForWeekCommencing }} {{ header.weekCommencingDate }}

+

{{ t.lastUpdated }} {{ header.lastUpdatedDate }} {{ t.at }} {{ header.lastUpdatedTime }}

+ +
+ + + {{ t.importantInformationTitle }} + + +
+

{{ t.importantInformationText }}

+

+ + {{ t.importantInformationLinkText }} + +

+
+
+ +
+

{{ t.searchCasesTitle }}

+ + +
+ +
+ + + + + + + + + + + + + {% for hearing in hearings %} + + + + + + + + + {% endfor %} + +
{{ t.tableHeaders.date }}{{ t.tableHeaders.caseName }}{{ t.tableHeaders.hearingLength }}{{ t.tableHeaders.hearingType }}{{ t.tableHeaders.venue }}{{ t.tableHeaders.additionalInformation }}
{{ hearing.date }}{{ hearing.caseName }}{{ hearing.hearingLength }}{{ hearing.hearingType }}{{ hearing.venue }}{{ hearing.additionalInformation }}
+
+ +

{{ t.dataSource }}: {{ dataSource }}

+ + + +
+
+{% endblock %} diff --git a/docs/tickets/645/plan.md b/docs/tickets/645/plan.md new file mode 100644 index 000000000..fcb5cf9ae --- /dev/null +++ b/docs/tickets/645/plan.md @@ -0,0 +1,170 @@ +# Technical Plan: #645 - Style Guide: Implement PHT Weekly Hearing List + +## Technical Approach + +Implement the `pht-weekly-hearing-list` module following the `ftt-tax-chamber-weekly-hearing-list` pattern exactly. This is a non-strategic list type with list type name `PHT_WEEKLY_HEARING_LIST`. + +The implementation is a straight adaptation of the FTT Tax reference — same structure, different columns (Date, Case Name, Hearing Length, Hearing Type, Venue, Additional Information), different introductory text (PHT contact details + observe-a-court link), and different locale strings. + +## Implementation Details + +### File Structure + +``` +libs/list-types/pht-weekly-hearing-list/ +├── package.json +├── tsconfig.json +└── src/ + ├── index.ts + ├── config.ts + ├── models/ + │ └── types.ts # PhtHearing, PhtHearingList + ├── schemas/ + │ └── pht-weekly-hearing-list.json # JSON schema + ├── locales/ + │ ├── en.ts + │ └── cy.ts + ├── rendering/ + │ └── renderer.ts + │ └── renderer.test.ts + ├── validation/ + │ └── json-validator.ts + ├── conversion/ + │ └── pht-config.ts # Excel converter, auto-registers on load + ├── pdf/ + │ ├── pdf-generator.ts + │ ├── pdf-template.njk + │ └── pdf-generator.test.ts + └── email-summary/ + └── summary-builder.ts # Deferred until requirements confirmed + +apps/web/src/pages/(list-types)/pht-weekly-hearing-list/ +├── index.ts # Page controller +├── index.test.ts +└── pht-weekly-hearing-list.njk # Nunjucks template +``` + +### Data Model + +PHT columns per acceptance criteria: + +```typescript +// src/models/types.ts +export interface PhtHearing { + date: string; // dd/MM/yyyy + caseName: string; + hearingLength: string; + hearingType: string; + venue: string; + additionalInformation: string; +} + +export type PhtHearingList = PhtHearing[]; +``` + +### JSON Schema + +Array of hearing objects with fields: `date` (pattern `^\d{2}/\d{2}/\d{4}$`), `caseName`, `hearingLength`, `hearingType`, `venue`, `additionalInformation`. All fields required, string type, no HTML tags pattern for non-date fields. + +### Locale Content + +**EN key strings:** +- `pageTitle`: `"Primary Health Tribunal Weekly Hearing List"` +- `listForWeekCommencing`: `"List for week commencing"` +- `contactParagraph`: `"Please contact the Primary Health Lists at primaryhealthlists@justice.gov.uk for details of how to access video hearings."` +- `observeLinkText`: `"Observe a court or tribunal hearing as a journalist, researcher or member of the public"` +- `observeLinkUrl`: `"https://www.gov.uk/guidance/observe-a-court-or-tribunal-hearing"` +- `tableHeaders`: `{ date, caseName, hearingLength, hearingType, venue, additionalInformation }` +- `dataSource`, `lastUpdated`, `at`, `backToTop`, `factLinkText`, `factLinkUrl`, `factAdditionalText` + +**CY key strings:** +- `pageTitle`: `"Rhestr Wrandawiadau Wythnosol y Tribiwnlys Iechyd Sylfaenol"` +- All other CY strings: translations required — use `[WELSH TRANSLATION REQUIRED: '...']` format for unconfirmed strings + +### Introductory Section + +The first section replaces the FTT Tax "important information" details box with: +1. A paragraph: "Please contact the Primary Health Lists at **primaryhealthlists@justice.gov.uk** for details of how to access video hearings." +2. A linked paragraph: "[Observe a court or tribunal hearing...](https://www.gov.uk/guidance/observe-a-court-or-tribunal-hearing)" + +This differs from FTT Tax which uses a `
` collapsible — PHT uses a plain section (no collapsible required per spec). + +### PDF Generator + +Uses `generateFttSiacWeeklyHearingListPdf` from `@hmcts/list-types-common` (same as FTT Tax pattern): + +```typescript +export async function generatePhtWeeklyHearingListPdf(options: PdfGenerationOptions) { + return generateFttSiacWeeklyHearingListPdf({ + ...options, + courtName: "Primary Health Tribunal", + listTitle: "Primary Health Tribunal Weekly Hearing List", + moduleDir: __dirname, + provenanceLabel: ..., + importEn: () => import("../locales/en.js"), + importCy: () => import("../locales/cy.js"), + generatePdf: generatePdfFromHtml, + renderData: renderPhtData + }); +} +``` + +### Excel Converter + +Fields: Date, Case Name, Hearing Length, Hearing Type, Venue, Additional Information. +Registers under `"PHT_WEEKLY_HEARING_LIST"`. + +### List Type Data Registration + +Add to `libs/location/src/list-type-data.ts` (next available ID, currently 62): + +```typescript +{ + id: 62, + name: "PHT_WEEKLY_HEARING_LIST", + englishFriendlyName: "Primary Health Tribunal Weekly Hearing List", + welshFriendlyName: "Rhestr Wrandawiadau Wythnosol y Tribiwnlys Iechyd Sylfaenol", + provenance: "MANUAL_UPLOAD", + urlPath: "pht-weekly-hearing-list", + isNonStrategic: true, + defaultSensitivity: "Public", + subJurisdictionIds: [] +} +``` + +### Registration Points + +| Location | Change | +|----------|--------| +| `libs/publication/src/processing/service.ts` | Import + add `PHT_WEEKLY_HEARING_LIST` to `PDF_GENERATOR_REGISTRY` | +| `apps/web/src/app.ts` | Import `moduleRoot as phtWeeklyHearingListModuleRoot` + add to `modulePaths` | +| `apps/web/package.json` | Add `"@hmcts/pht-weekly-hearing-list": "workspace:*"` | +| `libs/publication/package.json` | Add `"@hmcts/pht-weekly-hearing-list": "workspace:*"` | +| `tsconfig.json` (root) | Add path aliases for `@hmcts/pht-weekly-hearing-list` and `/config` | + +## Error Handling & Edge Cases + +- Missing `artefactId` → 400 (handled by `createSimpleListTypeHandler`) +- Artefact not found → 404 (handled by `createSimpleListTypeHandler`) +- Access denied → 403 (handled by `createSimpleListTypeHandler`) +- JSON fails schema validation → 400 (handled by `createSimpleListTypeHandler`) +- `additionalInformation` may be empty — template should handle blank values gracefully + +## Acceptance Criteria Mapping + +| Criterion | Implementation | +|-----------|---------------| +| Columns: Date, Case Name, Hearing Length, Hearing Type, Venue, Additional Information | `PhtHearing` type + table headers in locales + template columns | +| List title: "Primary Health Tribunal Weekly Hearing List - [date]" | `pageTitle` in `en.ts`, date appended in renderer `header.listTitle` | +| Contact paragraph with email | `contactParagraph` in locales, rendered in template first section | +| Observe-a-court link | `observeLinkText` + `observeLinkUrl` in locales | +| Page at `GET /pht-weekly-hearing-list?artefactId=` | Page controller at `apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.ts` | +| Welsh content via `?lng=cy` | `cy.ts` locale + controller passes both `en` and `cy` | +| PDF generation | `pdf-generator.ts` + `pdf-template.njk` | + +## Open Questions / Clarifications Needed + +- **Welsh translations**: All Welsh strings other than `pageTitle` and column headers need confirmed translations. Currently the reference FTT Tax `cy.ts` has the same English text as a placeholder. +- **`additionalInformation` optional?**: The spec lists it as a column but doesn't say if it's required in the schema. Treat as optional (not in `required` array) to match likely real-world data. +- **Email summary**: Explicitly deferred per ticket TODO — do not implement until requirements confirmed. +- **Sub-jurisdiction ID**: Left as `[]` — needs to be confirmed if PHT belongs to a jurisdiction subtree. diff --git a/docs/tickets/645/tasks.md b/docs/tickets/645/tasks.md new file mode 100644 index 000000000..f78a50f67 --- /dev/null +++ b/docs/tickets/645/tasks.md @@ -0,0 +1,37 @@ +# Implementation Tasks: #645 - PHT Weekly Hearing List + +## Implementation Tasks + +### Lib module +- [ ] Create `libs/list-types/pht-weekly-hearing-list/package.json` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/tsconfig.json` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/models/types.ts` — `PhtHearing`, `PhtHearingList` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/schemas/pht-weekly-hearing-list.json` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/locales/en.ts` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/locales/cy.ts` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/validation/json-validator.ts` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/conversion/pht-config.ts` (Excel converter, registers `PHT_WEEKLY_HEARING_LIST`) +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-template.njk` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/config.ts` +- [ ] Create `libs/list-types/pht-weekly-hearing-list/src/index.ts` + +### Page (web app) +- [ ] Create `apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.ts` (page controller) +- [ ] Create `apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.test.ts` +- [ ] Create `apps/web/src/pages/(list-types)/pht-weekly-hearing-list/pht-weekly-hearing-list.njk` + +### Registration +- [ ] Add `PHT_WEEKLY_HEARING_LIST` entry to `libs/location/src/list-type-data.ts` +- [ ] Add import + PDF generator entry to `libs/publication/src/processing/service.ts` +- [ ] Add `moduleRoot` import + path to `modulePaths` in `apps/web/src/app.ts` +- [ ] Add `"@hmcts/pht-weekly-hearing-list": "workspace:*"` to `apps/web/package.json` +- [ ] Add `"@hmcts/pht-weekly-hearing-list": "workspace:*"` to `libs/publication/package.json` +- [ ] Add path aliases to root `tsconfig.json` + +### Verification +- [ ] Run `yarn test` — all tests pass +- [ ] Run `yarn lint:fix` — no lint errors diff --git a/docs/tickets/645/ticket.md b/docs/tickets/645/ticket.md new file mode 100644 index 000000000..3f9c5bc72 --- /dev/null +++ b/docs/tickets/645/ticket.md @@ -0,0 +1,97 @@ +# #645: Style Guide: Implement PHT Weekly Hearing List + +**State:** OPEN +**Assignees:** KianKwa +**Author:** junaidiqbalmoj +**Labels:** (none) +**Created:** 2026-05-19T15:07:35Z +**Updated:** 2026-07-13T07:50:18Z + +## Description + +## User Story + +As a user, I want to view Primary Health Tribunal Weekly Hearing List in an accessible and well-formatted style, so that I can see scheduled hearings with all relevant case details. + +## Background + +One weekly hearing list type is implemented: +- `pht-weekly-hearing-list` — `PHT_WEEKLY_HEARING_LIST` (Primary Health Tribunal) + +This is a non-strategic list type with its own separate JSON schema. It follows the same module pattern as the existing weekly hearing list implementations (e.g. `ftt-tax-weekly-hearing-list` in #612). + +## Acceptance Criteria + +**Data fields for PHT Weekly Hearing List:** +Date, Case Name, Hearing Length, Hearing Type, Venue and Additional Information + +**List title:** +Primary Health Tribunal Weekly Hearing List - [date] + +**Wording in first section:** +Please contact the Primary Health Lists at primaryhealthlists@justice.gov.uk for details of how to access video hearings. +Link https://www.gov.uk/guidance/observe-a-court-or-tribunal-hearing is to be embedded in the text 'Observe a court or tribunal hearing as a journalist, researcher or member of the public.' + +**Columns:** +Date | Case Name | Hearing length | Hearing type | Venue | Additional information + +### Module structure +- [ ] New lib created: `libs/list-types/pht-weekly-hearing-list/` +- [ ] Lib contains: + - `src/validation/json-validator.ts`, `src/schemas/pht-weekly-hearing-list.json` + - `src/rendering/renderer.ts`, `renderer.test.ts` + - `src/pages/index.ts`, `index.test.ts`, `en.ts`, `cy.ts`, `pht-weekly-hearing-list.njk` + - `src/pdf/pdf-generator.ts`, `pdf-template.njk`, `pdf-generator.test.ts` + - `src/index.ts`, `src/config.ts`, `package.json`, `tsconfig.json` + +### List type data registration +- [ ] List type key added to `libs/location/src/list-type-data.ts` with correct `urlPath`, `provenance`, `isNonStrategic: true`, and `defaultSensitivity` + +### Page titles + +| List | EN title | CY title | +|------|----------|----------| +| pht-weekly-hearing-list | Primary Health Tribunal Weekly Hearing List | Rhestr Wrandawiadau Wythnosol y Tribiwnlys Iechyd Sylfaenol | + +### Pages +- [ ] Page accessible at `GET /pht-weekly-hearing-list?artefactId=` +- [ ] Displays venue name, address, content date, last updated timestamp +- [ ] Hearings table displays relevant columns per schema +- [ ] Open Justice collapsible section present +- [ ] Data source attribution shown at bottom + +### Validation and access control +- [ ] Returns 400 if `artefactId` is missing +- [ ] Returns 404 if artefact not found +- [ ] Returns 403 if user does not have access +- [ ] Returns 400 if JSON fails schema validation + +### PDF generation +- [ ] PDF generated matching the HTML view structure +- [ ] PDF saved to storage correctly + +### Welsh language +- [ ] All page content available in Welsh via `?lng=cy` +- [ ] PDF generated in correct language based on locale + +### Registration +- [ ] Module registered in `apps/web/src/app.ts` +- [ ] Path alias added to root `tsconfig.json` +- [ ] Package added as dependency in `apps/web/package.json` + +### Tests +- [ ] Unit tests pass +- [ ] `yarn test` passes across the workspace + +## TODO + +- [ ] Add email summary (`src/email-summary/summary-builder.ts`) once email summary requirements are confirmed + +## Technical Notes + +- Schema sources from pip-data-management `src/main/resources/schemas/non-strategic/` +- Follow the `ftt-tax-weekly-hearing-list` module as the reference implementation + +## Comments + +No comments on this issue. diff --git a/libs/list-types/common/src/list-type-data.ts b/libs/list-types/common/src/list-type-data.ts index 8c93ebbbd..7d9d47555 100644 --- a/libs/list-types/common/src/list-type-data.ts +++ b/libs/list-types/common/src/list-type-data.ts @@ -630,5 +630,16 @@ export const listTypeData: ListTypeData[] = [ defaultSensitivity: "Public", shortenedFriendlyName: "UT (AAC) Daily Hearing List", subJurisdictionIds: [26] + }, + { + name: "PHT_WEEKLY_HEARING_LIST", + englishFriendlyName: "Primary Health Tribunal Weekly Hearing List", + welshFriendlyName: "Rhestr Gwrandawiadau Wythnosol y Tribiwnlys Iechyd Sylfaenol", + provenance: "MANUAL_UPLOAD", + urlPath: "pht-weekly-hearing-list", + isNonStrategic: true, + defaultSensitivity: null, + shortenedFriendlyName: "PHT Weekly Hearing List", + subJurisdictionIds: [22] } ]; diff --git a/libs/list-types/pht-weekly-hearing-list/package.json b/libs/list-types/pht-weekly-hearing-list/package.json new file mode 100644 index 000000000..aa4337dd3 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/package.json @@ -0,0 +1,42 @@ +{ + "name": "@hmcts/pht-weekly-hearing-list", + "version": "1.0.0", + "type": "module", + "exports": { + ".": { + "production": "./dist/index.js", + "default": "./src/index.ts" + }, + "./config": { + "production": "./dist/config.js", + "default": "./src/config.ts" + } + }, + "scripts": { + "build": "tsc && yarn build:nunjucks && yarn build:schemas", + "build:nunjucks": "mkdir -p dist/pdf && cd src/pdf && find . -name '*.njk' -exec sh -c 'mkdir -p ../../dist/pdf/$(dirname {}) && cp {} ../../dist/pdf/{}' \\;", + "build:schemas": "mkdir -p dist/schemas && cp src/schemas/*.json dist/schemas/", + "dev": "tsc --watch", + "test": "vitest run", + "test:watch": "vitest watch", + "format": "biome format --write .", + "lint": "biome check .", + "lint:fix": "biome check --write --unsafe ." + }, + "dependencies": { + "@hmcts/list-types-common": "workspace:*", + "@hmcts/pdf-generation": "workspace:*", + "@hmcts/postgres-prisma": "workspace:*", + "luxon": "3.7.2", + "nunjucks": "3.2.4" + }, + "devDependencies": { + "@types/luxon": "3.7.2", + "@types/node": "24.10.4", + "typescript": "6.0.3", + "vitest": "4.1.10" + }, + "peerDependencies": { + "express": "^5.1.0" + } +} diff --git a/libs/list-types/pht-weekly-hearing-list/src/config.ts b/libs/list-types/pht-weekly-hearing-list/src/config.ts new file mode 100644 index 000000000..21c782928 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/config.ts @@ -0,0 +1,9 @@ +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +export const moduleRoot = __dirname; +export const assets = path.join(__dirname, "assets/"); +export const schemaPath = path.join(__dirname, "schemas/pht-weekly-hearing-list.json"); diff --git a/libs/list-types/pht-weekly-hearing-list/src/conversion/pht-config.ts b/libs/list-types/pht-weekly-hearing-list/src/conversion/pht-config.ts new file mode 100644 index 000000000..7ec4846e5 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/conversion/pht-config.ts @@ -0,0 +1,53 @@ +import { + createConverter, + DD_MM_YYYY_PATTERN, + type ExcelConverterConfig, + registerConverterByName, + validateDateFormat, + validateNoHtmlTags +} from "@hmcts/list-types-common"; + +export const PHT_EXCEL_CONFIG: ExcelConverterConfig = { + fields: [ + { + header: "Date", + fieldName: "date", + required: true, + validators: [validateDateFormat(DD_MM_YYYY_PATTERN, "dd/MM/yyyy (e.g., 02/01/2025)")] + }, + { + header: "Case name", + fieldName: "caseName", + required: true, + validators: [(value, rowNumber) => validateNoHtmlTags(value, "Case name", rowNumber)] + }, + { + header: "Hearing length", + fieldName: "hearingLength", + required: true, + validators: [(value, rowNumber) => validateNoHtmlTags(value, "Hearing length", rowNumber)] + }, + { + header: "Hearing type", + fieldName: "hearingType", + required: true, + validators: [(value, rowNumber) => validateNoHtmlTags(value, "Hearing type", rowNumber)] + }, + { + header: "Venue", + fieldName: "venue", + required: true, + validators: [(value, rowNumber) => validateNoHtmlTags(value, "Venue", rowNumber)] + }, + { + header: "Additional information", + fieldName: "additionalInformation", + required: true, + validators: [(value, rowNumber) => validateNoHtmlTags(value, "Additional information", rowNumber)] + } + ], + minRows: 1 +}; + +const phtConverter = createConverter(PHT_EXCEL_CONFIG); +registerConverterByName("PHT_WEEKLY_HEARING_LIST", phtConverter); diff --git a/libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.ts b/libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.ts new file mode 100644 index 000000000..27724ca7c --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.ts @@ -0,0 +1,11 @@ +import { type CaseSummary, formatCaseSummaryForEmail, SPECIAL_CATEGORY_DATA_WARNING } from "@hmcts/list-types-common"; +import type { PhtHearingList } from "../models/types.js"; + +export { formatCaseSummaryForEmail, SPECIAL_CATEGORY_DATA_WARNING }; + +export function extractCaseSummary(jsonData: PhtHearingList): CaseSummary[] { + return jsonData.map((hearing) => [ + { label: "Date", value: hearing.date || "" }, + { label: "Case name", value: hearing.caseName || "" } + ]); +} diff --git a/libs/list-types/pht-weekly-hearing-list/src/index.ts b/libs/list-types/pht-weekly-hearing-list/src/index.ts new file mode 100644 index 000000000..99f04e1ba --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/index.ts @@ -0,0 +1,8 @@ +import "./conversion/pht-config.js"; // Register converter on module load + +export * from "./email-summary/summary-builder.js"; +export { cy as phtWeeklyHearingListCy } from "./locales/cy.js"; +export { en as phtWeeklyHearingListEn } from "./locales/en.js"; +export * from "./models/types.js"; +export * from "./pdf/pdf-generator.js"; +export * from "./rendering/renderer.js"; diff --git a/libs/list-types/pht-weekly-hearing-list/src/locales/cy.ts b/libs/list-types/pht-weekly-hearing-list/src/locales/cy.ts new file mode 100644 index 000000000..20ab85248 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/locales/cy.ts @@ -0,0 +1,33 @@ +import { provenanceLabelsCy as provenanceLabels } from "@hmcts/list-types-common"; + +export const cy = { + pageTitle: "Rhestr Gwrandawiadau Wythnosol y Tribiwnlys Iechyd Sylfaenol", + listForWeekCommencing: "Rhestr ar gyfer yr wythnos yn dechrau ar", + lastUpdated: "Diweddarwyd ddiwethaf", + at: "am", + factLinkText: "Dod o hyd i fanylion cyswllt a gwybodaeth arall am lysoedd a thribiwnlysoedd yng Nghymru a Lloegr", + factLinkUrl: "https://www.find-court-tribunal.service.gov.uk/", + factAdditionalText: "a rhai tribiwnlysoedd heb eu datganoli yn yr Alban.", + importantInformationTitle: "Gwybodaeth bwysig", + importantInformationText: + "Cysylltwch â'r Rhestrau Iechyd Sylfaenol yn primaryhealthlists@justice.gov.uk i gael manylion am sut i gael mynediad at wrandawiadau fideo.", + importantInformationLinkText: "Arsylwi gwrandawiad llys neu dribiwnlys fel newyddiadurwr, ymchwilydd neu aelod o'r cyhoedd", + importantInformationLinkUrl: "https://www.gov.uk/guidance/observe-a-court-or-tribunal-hearing", + searchCasesTitle: "Chwilio Achosion", + searchCasesLabel: "Chwilio yn ôl rhif achos, manylion, lleoliad, barnwr, neu wybodaeth arall", + tableHeaders: { + date: "Dyddiad", + caseName: "Enw'r achos", + hearingLength: "Hyd y gwrandawiad", + hearingType: "Math o wrandawiad", + venue: "Lleoliad", + additionalInformation: "Gwybodaeth ychwanegol" + }, + dataSource: "Ffynhonnell data", + backToTop: "Yn ôl i frig y dudalen", + cautionNote: + "Noder bod y ddogfen hon yn cynnwys Data Categori Arbennig fel y'i diffinnir yn Neddf Gwarchod Data 2018, a elwid gynt yn Ddata Personol Sensitif, a dylid ei drin yn y ffordd briodol.", + cautionReporting: + "Mae'r ddogfen hon yn cynnwys gwybodaeth a fwriedir i gynorthwyo i roi adroddiad manwl-gywir am achosion llys. Mae'n hanfodol eich bod yn sicrhau eich bod yn gwarchod y Data Categori Arbennig sydd ynddi ac yn cadw at gyfyngiadau adrodd (er enghraifft yn achos dioddefwyr a phlant). Bydd GLlTEF yn rhoi'r gorau i anfon y data os cyfyd pryder ynghylch sut y'i defnyddir.", + provenanceLabels +}; diff --git a/libs/list-types/pht-weekly-hearing-list/src/locales/en.ts b/libs/list-types/pht-weekly-hearing-list/src/locales/en.ts new file mode 100644 index 000000000..88046549b --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/locales/en.ts @@ -0,0 +1,32 @@ +import { provenanceLabelsEn as provenanceLabels } from "@hmcts/list-types-common"; + +export const en = { + pageTitle: "Primary Health Tribunal Weekly Hearing List", + listForWeekCommencing: "List for week commencing", + lastUpdated: "Last updated", + at: "at", + factLinkText: "Find contact details and other information about courts and tribunals", + factLinkUrl: "https://www.find-court-tribunal.service.gov.uk/", + factAdditionalText: "in England and Wales, and some non-devolved tribunals in Scotland.", + importantInformationTitle: "Important information", + importantInformationText: "Please contact the Primary Health Lists at primaryhealthlists@justice.gov.uk for details of how to access video hearings.", + importantInformationLinkText: "Observe a court or tribunal hearing as a journalist, researcher or member of the public", + importantInformationLinkUrl: "https://www.gov.uk/guidance/observe-a-court-or-tribunal-hearing", + searchCasesTitle: "Search Cases", + searchCasesLabel: "Search by case name, date, venue, or other details", + tableHeaders: { + date: "Date", + caseName: "Case name", + hearingLength: "Hearing length", + hearingType: "Hearing type", + venue: "Venue", + additionalInformation: "Additional information" + }, + dataSource: "Data source", + backToTop: "Back to top", + cautionNote: + "Note this document contains Special Category Data as defined by Data Protection Act 2018, formally known as Sensitive Personal Data, and should be handled appropriately.", + cautionReporting: + "This document contains information intended to assist the accurate reporting of court proceedings. It is vital you ensure that you safeguard the Special Category Data included and abide by reporting restrictions (for example on victims and children). HMCTS will stop sending the data if there is concern about how it will be used.", + provenanceLabels +}; diff --git a/libs/list-types/pht-weekly-hearing-list/src/models/types.ts b/libs/list-types/pht-weekly-hearing-list/src/models/types.ts new file mode 100644 index 000000000..5291917d2 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/models/types.ts @@ -0,0 +1,10 @@ +export interface PhtHearing { + date: string; + caseName: string; + hearingLength: string; + hearingType: string; + venue: string; + additionalInformation: string; +} + +export type PhtHearingList = PhtHearing[]; diff --git a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts new file mode 100644 index 000000000..f746abd43 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts @@ -0,0 +1,54 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@hmcts/list-types-common", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + configureNunjucks: vi.fn().mockReturnValue({ + render: vi.fn().mockReturnValue("mock pdf html") + }), + loadTranslations: vi.fn().mockResolvedValue({ pageTitle: "Primary Health Tribunal Weekly Hearing List" }), + savePdfToStorage: vi.fn().mockResolvedValue({ success: true }), + createPdfErrorResult: vi.fn().mockReturnValue({ success: false, error: "error" }) + }; +}); + +vi.mock("@hmcts/pdf-generation", () => ({ + generatePdfFromHtml: vi.fn().mockResolvedValue({ success: true, pdfBuffer: Buffer.from("pdf"), sizeBytes: 3 }) +})); + +vi.mock("@hmcts/publication", () => ({ + PROVENANCE_LABELS: { MANUAL_UPLOAD: "Manual Upload" } +})); + +import { generatePhtWeeklyHearingListPdf } from "./pdf-generator.js"; + +describe("generatePhtWeeklyHearingListPdf", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("should generate PDF successfully", async () => { + const { savePdfToStorage } = await import("@hmcts/list-types-common"); + vi.mocked(savePdfToStorage).mockResolvedValue({ success: true }); + + const result = await generatePhtWeeklyHearingListPdf({ + artefactId: "test-artefact-id", + jsonData: [ + { + date: "02/01/2025", + caseName: "A Vs B", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + } + ], + locale: "en", + provenance: "MANUAL_UPLOAD", + contentDate: new Date(2025, 0, 2) + }); + + expect(result.success).toBe(true); + }); +}); diff --git a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts new file mode 100644 index 000000000..a0bc181fd --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts @@ -0,0 +1,64 @@ +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { + type BasePdfGenerationOptions, + configureNunjucks, + createPdfErrorResult, + loadTranslations, + PDF_BASE_STYLES, + type PdfGenerationResult, + savePdfToStorage +} from "@hmcts/list-types-common"; +import { generatePdfFromHtml } from "@hmcts/pdf-generation"; +import { PROVENANCE_LABELS } from "@hmcts/publication"; +import type { PhtHearingList } from "../models/types.js"; +import { renderPhtData } from "../rendering/renderer.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +interface PdfGenerationOptions extends BasePdfGenerationOptions { + contentDate: Date; +} + +export async function generatePhtWeeklyHearingListPdf(options: PdfGenerationOptions): Promise { + try { + const renderedData = renderPhtData(options.jsonData, { + locale: options.locale, + courtName: "Primary Health Tribunal", + contentDate: options.contentDate, + lastReceivedDate: new Date().toISOString(), + listTitle: "Primary Health Tribunal Weekly Hearing List" + }); + + const translations = await loadTranslations( + options.locale, + () => import("../locales/en.js"), + () => import("../locales/cy.js") + ); + + const provenanceLabel = options.provenance ? PROVENANCE_LABELS[options.provenance as keyof typeof PROVENANCE_LABELS] || options.provenance : ""; + + const env = configureNunjucks(__dirname); + const html = env.render("pdf-template.njk", { + header: renderedData.header, + hearings: renderedData.hearings, + dataSource: provenanceLabel, + t: translations, + pdfStyles: PDF_BASE_STYLES + }); + + const pdfResult = await generatePdfFromHtml(html); + + if (!pdfResult.success || !pdfResult.pdfBuffer) { + return { + success: false, + error: pdfResult.error || "PDF generation failed" + }; + } + + return await savePdfToStorage(options.artefactId, pdfResult.pdfBuffer, pdfResult.sizeBytes!); + } catch (error) { + return createPdfErrorResult(error); + } +} diff --git a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-template.njk b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-template.njk new file mode 100644 index 000000000..666b64dae --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-template.njk @@ -0,0 +1,64 @@ + + + + + + {{ header.listTitle }} + + + +
+

{{ header.listTitle }}

+ +

{{ t.factLinkText }} {{ t.factAdditionalText }}

+ +

{{ t.listForWeekCommencing }} {{ header.weekCommencingDate }}

+

{{ t.lastUpdated }} {{ header.lastUpdatedDate }} {{ t.at }} {{ header.lastUpdatedTime }}

+
+ +
+

{{ t.importantInformationTitle }}

+

{{ t.importantInformationText }}

+

{{ t.importantInformationLinkText }}

+
+ + {% if hearings.length > 0 %} + + + + + + + + + + + + + {% for hearing in hearings %} + + + + + + + + + {% endfor %} + +
{{ t.tableHeaders.date }}{{ t.tableHeaders.caseName }}{{ t.tableHeaders.hearingLength }}{{ t.tableHeaders.hearingType }}{{ t.tableHeaders.venue }}{{ t.tableHeaders.additionalInformation }}
{{ hearing.date }}{{ hearing.caseName }}{{ hearing.hearingLength }}{{ hearing.hearingType }}{{ hearing.venue }}{{ hearing.additionalInformation }}
+ {% else %} +

No hearings scheduled.

+ {% endif %} + + + + diff --git a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts new file mode 100644 index 000000000..57d10b8c6 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts @@ -0,0 +1,197 @@ +import { describe, expect, it } from "vitest"; +import type { PhtHearingList } from "../models/types.js"; +import { renderPhtData } from "./renderer.js"; + +describe("renderPhtData", () => { + it("should render hearing list with formatted dates", () => { + const hearingList: PhtHearingList = [ + { + date: "02/01/2025", + caseName: "A Vs B", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + } + ]; + + const options = { + locale: "en", + courtName: "Primary Health Tribunal", + contentDate: new Date(2025, 0, 2), + lastReceivedDate: "2025-01-01T09:55:00Z", + listTitle: "Primary Health Tribunal Weekly Hearing List" + }; + + const result = renderPhtData(hearingList, options); + + expect(result.header.listTitle).toBe("Primary Health Tribunal Weekly Hearing List"); + expect(result.header.weekCommencingDate).toBe("02 January 2025"); + expect(result.header.lastUpdatedDate).toBe("01 January 2025"); + expect(result.header.lastUpdatedTime).toContain("am"); + + expect(result.hearings).toHaveLength(1); + expect(result.hearings[0].date).toBe("02 January 2025"); + expect(result.hearings[0].caseName).toBe("A Vs B"); + expect(result.hearings[0].hearingLength).toBe("1 hour"); + expect(result.hearings[0].hearingType).toBe("Substantive hearing"); + expect(result.hearings[0].venue).toBe("Primary Health Tribunal"); + expect(result.hearings[0].additionalInformation).toBe("Remote hearing"); + }); + + it("should render multiple hearings", () => { + const hearingList: PhtHearingList = [ + { + date: "02/01/2025", + caseName: "A Vs B", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + }, + { + date: "03/01/2025", + caseName: "C Vs D", + hearingLength: "Half day", + hearingType: "Preliminary hearing", + venue: "Health Tribunal Office", + additionalInformation: "In person" + } + ]; + + const options = { + locale: "en", + courtName: "Primary Health Tribunal", + contentDate: new Date(2025, 0, 2), + lastReceivedDate: "2025-01-01T09:55:00Z", + listTitle: "Primary Health Tribunal Weekly Hearing List" + }; + + const result = renderPhtData(hearingList, options); + + expect(result.hearings).toHaveLength(2); + expect(result.hearings[0].date).toBe("02 January 2025"); + expect(result.hearings[1].date).toBe("03 January 2025"); + }); + + it("should format lastUpdated with time", () => { + const hearingList: PhtHearingList = [ + { + date: "02/01/2025", + caseName: "A Vs B", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + } + ]; + + const options = { + locale: "en", + courtName: "Primary Health Tribunal", + contentDate: new Date(2025, 0, 2), + lastReceivedDate: "2025-01-01T09:55:00Z", + listTitle: "Primary Health Tribunal Weekly Hearing List" + }; + + const result = renderPhtData(hearingList, options); + + expect(result.header.lastUpdatedTime).toBe("9:55am"); + }); + + it("should format PM times correctly", () => { + const hearingList: PhtHearingList = [ + { + date: "02/01/2025", + caseName: "A Vs B", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + } + ]; + + const options = { + locale: "en", + courtName: "Primary Health Tribunal", + contentDate: new Date(2025, 0, 2), + lastReceivedDate: "2025-01-01T14:30:00Z", + listTitle: "Primary Health Tribunal Weekly Hearing List" + }; + + const result = renderPhtData(hearingList, options); + + expect(result.header.lastUpdatedTime).toBe("2:30pm"); + }); + + it("should handle empty hearing list", () => { + const hearingList: PhtHearingList = []; + + const options = { + locale: "en", + courtName: "Primary Health Tribunal", + contentDate: new Date(2025, 0, 2), + lastReceivedDate: "2025-01-01T09:55:00Z", + listTitle: "Primary Health Tribunal Weekly Hearing List" + }; + + const result = renderPhtData(hearingList, options); + + expect(result.hearings).toHaveLength(0); + expect(result.header.listTitle).toBe("Primary Health Tribunal Weekly Hearing List"); + }); + + it("should use the provided Welsh listTitle", () => { + const hearingList: PhtHearingList = [ + { + date: "02/01/2025", + caseName: "A Vs B", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + } + ]; + + const options = { + locale: "cy", + courtName: "Primary Health Tribunal", + contentDate: new Date(2025, 0, 2), + lastReceivedDate: "2025-01-01T09:55:00Z", + listTitle: "Rhestr Gwrandawiadau Wythnosol y Tribiwnlys Iechyd Sylfaenol" + }; + + const result = renderPhtData(hearingList, options); + + expect(result.header.listTitle).toBe("Rhestr Gwrandawiadau Wythnosol y Tribiwnlys Iechyd Sylfaenol"); + }); + + it("should preserve all hearing fields without modification", () => { + const hearingList: PhtHearingList = [ + { + date: "02/01/2025", + caseName: "Case With Special Characters: A vs B & C", + hearingLength: "2 hours 30 minutes", + hearingType: "Final hearing - substantive", + venue: "Primary Health Tribunal - London Office", + additionalInformation: "Remote hearing via video link; contact primaryhealthlists@justice.gov.uk" + } + ]; + + const options = { + locale: "en", + courtName: "Primary Health Tribunal", + contentDate: new Date(2025, 0, 2), + lastReceivedDate: "2025-01-01T09:55:00Z", + listTitle: "Primary Health Tribunal Weekly Hearing List" + }; + + const result = renderPhtData(hearingList, options); + + expect(result.hearings[0].caseName).toBe("Case With Special Characters: A vs B & C"); + expect(result.hearings[0].hearingLength).toBe("2 hours 30 minutes"); + expect(result.hearings[0].hearingType).toBe("Final hearing - substantive"); + expect(result.hearings[0].venue).toBe("Primary Health Tribunal - London Office"); + expect(result.hearings[0].additionalInformation).toBe("Remote hearing via video link; contact primaryhealthlists@justice.gov.uk"); + }); +}); diff --git a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts new file mode 100644 index 000000000..2d63b44e0 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts @@ -0,0 +1,70 @@ +import { formatDdMmYyyyDate } from "@hmcts/list-types-common"; +import { DateTime } from "luxon"; +import type { PhtHearing, PhtHearingList } from "../models/types.js"; + +export interface RenderOptions { + locale: string; + courtName: string; + contentDate: Date; + lastReceivedDate: string; + listTitle: string; +} + +export interface RenderedData { + header: { + listTitle: string; + weekCommencingDate: string; + lastUpdatedDate: string; + lastUpdatedTime: string; + }; + hearings: PhtHearing[]; +} + +function formatDate(date: Date, locale: string): string { + const localeCode = locale === "cy" ? "cy-GB" : "en-GB"; + return date.toLocaleDateString(localeCode, { + day: "numeric", + month: "long", + year: "numeric" + }); +} + +function formatLastUpdatedDateTime(isoDateTime: string, locale: string): { date: string; time: string } { + const dt = DateTime.fromISO(isoDateTime).setZone("Europe/London").setLocale(locale); + + const date = dt.toFormat("d MMMM yyyy"); + + const hours = dt.hour; + const minutes = dt.minute; + const period = hours >= 12 ? "pm" : "am"; + const hour12 = hours % 12 || 12; + + const minuteStr = minutes > 0 ? `:${minutes.toString().padStart(2, "0")}` : ""; + const time = `${hour12}${minuteStr}${period}`; + + return { date, time }; +} + +export function renderPhtData(hearingList: PhtHearingList, options: RenderOptions): RenderedData { + const weekCommencingDate = formatDate(options.contentDate, options.locale); + const { date: lastUpdatedDate, time: lastUpdatedTime } = formatLastUpdatedDateTime(options.lastReceivedDate, options.locale); + + const renderedHearings = hearingList.map((hearing) => ({ + date: formatDdMmYyyyDate(hearing.date, options.locale), + caseName: hearing.caseName, + hearingLength: hearing.hearingLength, + hearingType: hearing.hearingType, + venue: hearing.venue, + additionalInformation: hearing.additionalInformation + })); + + return { + header: { + listTitle: options.listTitle, + weekCommencingDate, + lastUpdatedDate, + lastUpdatedTime + }, + hearings: renderedHearings + }; +} diff --git a/libs/list-types/pht-weekly-hearing-list/src/schemas/pht-weekly-hearing-list.json b/libs/list-types/pht-weekly-hearing-list/src/schemas/pht-weekly-hearing-list.json new file mode 100644 index 000000000..7b73bd625 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/schemas/pht-weekly-hearing-list.json @@ -0,0 +1,54 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Root", + "type": "array", + "items": { + "title": "Hearing list", + "type": "object", + "required": ["date", "caseName", "hearingLength", "hearingType", "venue", "additionalInformation"], + "properties": { + "date": { + "title": "Date", + "type": "string", + "default": "", + "examples": ["02/01/2025"], + "pattern": "^\\d{2}/\\d{2}/\\d{4}$" + }, + "caseName": { + "title": "Case name", + "type": "string", + "default": "", + "examples": ["A Vs B"], + "pattern": "^(?!(.|\\r|\\n)*<[^>]+>)(.|\\r|\\n)*$" + }, + "hearingLength": { + "title": "Length of hearing", + "type": "string", + "default": "", + "examples": ["1 hour"], + "pattern": "^(?!(.|\\r|\\n)*<[^>]+>)(.|\\r|\\n)*$" + }, + "hearingType": { + "title": "Type of hearing being presented", + "type": "string", + "default": "", + "examples": ["mda"], + "pattern": "^(?!(.|\\r|\\n)*<[^>]+>)(.|\\r|\\n)*$" + }, + "venue": { + "title": "Venue name of the hearing", + "type": "string", + "default": "", + "examples": ["This is the venue of the hearing"], + "pattern": "^(?!(.|\\r|\\n)*<[^>]+>)(.|\\r|\\n)*$" + }, + "additionalInformation": { + "title": "Additional information", + "type": "string", + "default": "", + "examples": ["This is additional information"], + "pattern": "^(?!(.|\\r|\\n)*<[^>]+>)(.|\\r|\\n)*$" + } + } + } +} diff --git a/libs/list-types/pht-weekly-hearing-list/tsconfig.json b/libs/list-types/pht-weekly-hearing-list/tsconfig.json new file mode 100644 index 000000000..a029ee937 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src", + "declaration": true, + "declarationMap": true, + "resolveJsonModule": true + }, + "include": ["src/**/*"], + "exclude": ["**/*.test.ts", "**/*.spec.ts", "dist", "node_modules", "src/assets/"] +} diff --git a/libs/location/src/location-data.ts b/libs/location/src/location-data.ts index 926b75a80..d8f906be9 100644 --- a/libs/location/src/location-data.ts +++ b/libs/location/src/location-data.ts @@ -175,6 +175,14 @@ export const locationData: { welshName: "Tribiwnlys Nawdd Cymdeithasol a Chynhaliaeth Plant Lerpwl", regions: [4], subJurisdictions: [8] + }, + { + locationId: 25, + name: "Primary Health Tribunal", + welshName: "Tribiwnlys Iechyd Sylfaenol", + regions: [8], + subJurisdictions: [22], + provenanceLocationType: "NATIONAL" } ], regions: [ diff --git a/libs/notifications/package.json b/libs/notifications/package.json index 4c11b404b..a88eda14c 100644 --- a/libs/notifications/package.json +++ b/libs/notifications/package.json @@ -37,6 +37,7 @@ "@hmcts/list-types-common": "workspace:*", "@hmcts/london-administrative-court-daily-cause-list": "workspace:*", "@hmcts/magistrates-public-list": "workspace:*", + "@hmcts/pht-weekly-hearing-list": "workspace:*", "@hmcts/postgres-prisma": "workspace:*", "@hmcts/rcj-standard-daily-cause-list": "workspace:*", "@hmcts/send-daily-hearing-list": "workspace:*", diff --git a/libs/notifications/src/notification/notification-service.ts b/libs/notifications/src/notification/notification-service.ts index 020c2e1d9..17edfeebe 100644 --- a/libs/notifications/src/notification/notification-service.ts +++ b/libs/notifications/src/notification/notification-service.ts @@ -45,6 +45,7 @@ import { extractCaseSummary as extractMagistratesStandardSummary, formatCaseSummaryForEmail as formatMagistratesStandardSummaryForEmail } from "@hmcts/magistrates-standard-list"; +import { extractCaseSummary as extractPhtSummary, formatCaseSummaryForEmail as formatPhtSummaryForEmail } from "@hmcts/pht-weekly-hearing-list"; import { prisma } from "@hmcts/postgres-prisma"; import { extractCaseSummary as extractRcjSummary, formatCaseSummaryForEmail as formatRcjSummaryForEmail } from "@hmcts/rcj-standard-daily-cause-list"; import { extractCaseSummary as extractSendSummary, formatCaseSummaryForEmail as formatSendSummaryForEmail } from "@hmcts/send-daily-hearing-list"; @@ -138,6 +139,10 @@ const EMAIL_BUILDER_REGISTRY: Partial> = { extract: extractAstSummary as SummaryExtractor, format: formatAstSummaryForEmail }, + PHT_WEEKLY_HEARING_LIST: { + extract: extractPhtSummary as SummaryExtractor, + format: formatPhtSummaryForEmail + }, CIVIL_COURTS_RCJ_DAILY_CAUSE_LIST: rcjStandardConfig, COUNTY_COURT_LONDON_CIVIL_DAILY_CAUSE_LIST: rcjStandardConfig, COURT_OF_APPEAL_CRIMINAL_DAILY_CAUSE_LIST: rcjStandardConfig, diff --git a/libs/publication/package.json b/libs/publication/package.json index d9cdcbc63..82764b483 100644 --- a/libs/publication/package.json +++ b/libs/publication/package.json @@ -44,6 +44,7 @@ "@hmcts/magistrates-public-list": "workspace:*", "@hmcts/magistrates-standard-list": "workspace:*", "@hmcts/notifications": "workspace:*", + "@hmcts/pht-weekly-hearing-list": "workspace:*", "@hmcts/postgres-prisma": "workspace:*", "@hmcts/rcj-standard-daily-cause-list": "workspace:*", "@hmcts/send-daily-hearing-list": "workspace:*", diff --git a/libs/publication/src/processing/service.ts b/libs/publication/src/processing/service.ts index 75ff72c18..ca90452a6 100644 --- a/libs/publication/src/processing/service.ts +++ b/libs/publication/src/processing/service.ts @@ -19,6 +19,7 @@ import { generateLondonAdministrativeCourtDailyCauseListPdf, type LondonAdminCou import { generateMagistratesPublicListPdf, type MagistratesPublicListData } from "@hmcts/magistrates-public-list"; import { generateMagistratesStandardListPdf, type MagistratesStandardList } from "@hmcts/magistrates-standard-list"; import { sendListTypePublicationNotifications, sendLocationAndCaseSubscriptionNotifications } from "@hmcts/notifications"; +import { generatePhtWeeklyHearingListPdf, type PhtHearingList } from "@hmcts/pht-weekly-hearing-list"; import { prisma } from "@hmcts/postgres-prisma"; import { generateRcjStandardDailyCauseListPdf, type StandardHearingList } from "@hmcts/rcj-standard-daily-cause-list"; import { generateSendDailyHearingListPdf, type SendDailyHearingList } from "@hmcts/send-daily-hearing-list"; @@ -276,7 +277,12 @@ const PDF_GENERATOR_REGISTRY: Partial> = { UT_LANDS_CHAMBER_DAILY_HEARING_LIST: (p) => generateUtlcDailyHearingListPdf({ ...p, jsonData: p.jsonData as UtlcHearingList }), UT_ADMINISTRATIVE_APPEALS_CHAMBER_DAILY_HEARING_LIST: (p) => generateUtaacDailyHearingListPdf({ ...p, jsonData: p.jsonData as UtaacHearingList }), MAGISTRATES_STANDARD_LIST: (p) => generateMagistratesStandardListPdf({ ...p, jsonData: p.jsonData as MagistratesStandardList }), - MAGISTRATES_PUBLIC_LIST: (p) => generateMagistratesPublicListPdf({ ...p, jsonData: p.jsonData as MagistratesPublicListData }) + MAGISTRATES_PUBLIC_LIST: (p) => generateMagistratesPublicListPdf({ ...p, jsonData: p.jsonData as MagistratesPublicListData }), + PHT_WEEKLY_HEARING_LIST: (p) => + generatePhtWeeklyHearingListPdf({ + ...p, + jsonData: p.jsonData as PhtHearingList + }) }; export async function generatePublicationPdf(params: GeneratePdfParams): Promise { diff --git a/tsconfig.json b/tsconfig.json index 8d376f220..f0b35e24b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -95,7 +95,9 @@ "@hmcts/sscs-daily-hearing-list/config": ["libs/list-types/sscs-daily-hearing-list/src/config"], "@hmcts/azure-blob": ["libs/azure-blob/src"], "@hmcts/magistrates-standard-list": ["libs/list-types/magistrates-standard-list/src"], - "@hmcts/magistrates-standard-list/config": ["libs/list-types/magistrates-standard-list/src/config"] + "@hmcts/magistrates-standard-list/config": ["libs/list-types/magistrates-standard-list/src/config"], + "@hmcts/pht-weekly-hearing-list": ["libs/list-types/pht-weekly-hearing-list/src"], + "@hmcts/pht-weekly-hearing-list/config": ["libs/list-types/pht-weekly-hearing-list/src/config"] }, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, diff --git a/yarn.lock b/yarn.lock index cfbd52e33..0827ff74b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1869,6 +1869,7 @@ __metadata: "@hmcts/list-types-common": "workspace:*" "@hmcts/london-administrative-court-daily-cause-list": "workspace:*" "@hmcts/magistrates-public-list": "workspace:*" + "@hmcts/pht-weekly-hearing-list": "workspace:*" "@hmcts/postgres-prisma": "workspace:*" "@hmcts/rcj-standard-daily-cause-list": "workspace:*" "@hmcts/send-daily-hearing-list": "workspace:*" @@ -1914,6 +1915,24 @@ __metadata: languageName: unknown linkType: soft +"@hmcts/pht-weekly-hearing-list@workspace:*, @hmcts/pht-weekly-hearing-list@workspace:libs/list-types/pht-weekly-hearing-list": + version: 0.0.0-use.local + resolution: "@hmcts/pht-weekly-hearing-list@workspace:libs/list-types/pht-weekly-hearing-list" + dependencies: + "@hmcts/list-types-common": "workspace:*" + "@hmcts/pdf-generation": "workspace:*" + "@hmcts/postgres-prisma": "workspace:*" + "@types/luxon": "npm:3.7.2" + "@types/node": "npm:24.10.4" + luxon: "npm:3.7.2" + nunjucks: "npm:3.2.4" + typescript: "npm:6.0.3" + vitest: "npm:4.1.10" + peerDependencies: + express: ^5.1.0 + languageName: unknown + linkType: soft + "@hmcts/postgres-prisma@workspace:*, @hmcts/postgres-prisma@workspace:libs/postgres-prisma": version: 0.0.0-use.local resolution: "@hmcts/postgres-prisma@workspace:libs/postgres-prisma" @@ -1986,6 +2005,7 @@ __metadata: "@hmcts/magistrates-public-list": "workspace:*" "@hmcts/magistrates-standard-list": "workspace:*" "@hmcts/notifications": "workspace:*" + "@hmcts/pht-weekly-hearing-list": "workspace:*" "@hmcts/postgres-prisma": "workspace:*" "@hmcts/rcj-standard-daily-cause-list": "workspace:*" "@hmcts/send-daily-hearing-list": "workspace:*" @@ -2341,6 +2361,7 @@ __metadata: "@hmcts/london-administrative-court-daily-cause-list": "workspace:*" "@hmcts/magistrates-public-list": "workspace:*" "@hmcts/magistrates-standard-list": "workspace:*" + "@hmcts/pht-weekly-hearing-list": "workspace:*" "@hmcts/public-pages": "workspace:*" "@hmcts/rcj-standard-daily-cause-list": "workspace:*" "@hmcts/send-daily-hearing-list": "workspace:*" From c3f891b54b0b37dfcaed6159426b859e2b853703 Mon Sep 17 00:00:00 2001 From: KianKwa Date: Mon, 13 Jul 2026 13:51:12 +0100 Subject: [PATCH 2/9] Add validator --- .../pht-weekly-hearing-list/src/index.ts | 1 + .../src/rendering/renderer.test.ts | 4 +- .../src/schemas/pht-weekly-hearing-list.json | 2 +- .../src/validation/json-validator.test.ts | 130 ++++++++++++++++++ .../src/validation/json-validator.ts | 6 + 5 files changed, 140 insertions(+), 3 deletions(-) create mode 100644 libs/list-types/pht-weekly-hearing-list/src/validation/json-validator.test.ts create mode 100644 libs/list-types/pht-weekly-hearing-list/src/validation/json-validator.ts diff --git a/libs/list-types/pht-weekly-hearing-list/src/index.ts b/libs/list-types/pht-weekly-hearing-list/src/index.ts index 99f04e1ba..d6191ba15 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/index.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/index.ts @@ -6,3 +6,4 @@ export { en as phtWeeklyHearingListEn } from "./locales/en.js"; export * from "./models/types.js"; export * from "./pdf/pdf-generator.js"; export * from "./rendering/renderer.js"; +export * from "./validation/json-validator.js"; diff --git a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts index 57d10b8c6..0b22a2141 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts @@ -26,8 +26,8 @@ describe("renderPhtData", () => { const result = renderPhtData(hearingList, options); expect(result.header.listTitle).toBe("Primary Health Tribunal Weekly Hearing List"); - expect(result.header.weekCommencingDate).toBe("02 January 2025"); - expect(result.header.lastUpdatedDate).toBe("01 January 2025"); + expect(result.header.weekCommencingDate).toBe("2 January 2025"); + expect(result.header.lastUpdatedDate).toBe("1 January 2025"); expect(result.header.lastUpdatedTime).toContain("am"); expect(result.hearings).toHaveLength(1); diff --git a/libs/list-types/pht-weekly-hearing-list/src/schemas/pht-weekly-hearing-list.json b/libs/list-types/pht-weekly-hearing-list/src/schemas/pht-weekly-hearing-list.json index 7b73bd625..2fdfaf57e 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/schemas/pht-weekly-hearing-list.json +++ b/libs/list-types/pht-weekly-hearing-list/src/schemas/pht-weekly-hearing-list.json @@ -1,5 +1,5 @@ { - "$schema": "http://json-schema.org/draft-07/schema#", + "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Root", "type": "array", "items": { diff --git a/libs/list-types/pht-weekly-hearing-list/src/validation/json-validator.test.ts b/libs/list-types/pht-weekly-hearing-list/src/validation/json-validator.test.ts new file mode 100644 index 000000000..dd1a2bfb1 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/validation/json-validator.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from "vitest"; +import { validatePhtWeeklyHearingList } from "./json-validator.js"; + +const validHearing = { + date: "02/01/2025", + caseName: "A Vs B", + hearingLength: "1 hour", + hearingType: "mda", + venue: "Primary Health Tribunal", + additionalInformation: "None" +}; + +describe("validatePhtWeeklyHearingList", () => { + describe("valid data", () => { + it("should accept a valid hearing list", () => { + const result = validatePhtWeeklyHearingList([validHearing]); + expect(result.isValid).toBe(true); + expect(result.errors).toHaveLength(0); + }); + + it("should accept an empty array", () => { + const result = validatePhtWeeklyHearingList([]); + expect(result.isValid).toBe(true); + }); + + it("should accept multiple valid hearings", () => { + const result = validatePhtWeeklyHearingList([validHearing, { ...validHearing, date: "15/06/2025" }]); + expect(result.isValid).toBe(true); + }); + }); + + describe("required fields", () => { + it("should reject missing date", () => { + const { date: _, ...noDate } = validHearing; + const result = validatePhtWeeklyHearingList([noDate]); + expect(result.isValid).toBe(false); + }); + + it("should reject missing caseName", () => { + const { caseName: _, ...noCaseName } = validHearing; + const result = validatePhtWeeklyHearingList([noCaseName]); + expect(result.isValid).toBe(false); + }); + + it("should reject missing hearingLength", () => { + const { hearingLength: _, ...noHearingLength } = validHearing; + const result = validatePhtWeeklyHearingList([noHearingLength]); + expect(result.isValid).toBe(false); + }); + + it("should reject missing hearingType", () => { + const { hearingType: _, ...noHearingType } = validHearing; + const result = validatePhtWeeklyHearingList([noHearingType]); + expect(result.isValid).toBe(false); + }); + + it("should reject missing venue", () => { + const { venue: _, ...noVenue } = validHearing; + const result = validatePhtWeeklyHearingList([noVenue]); + expect(result.isValid).toBe(false); + }); + + it("should reject missing additionalInformation", () => { + const { additionalInformation: _, ...noAdditionalInfo } = validHearing; + const result = validatePhtWeeklyHearingList([noAdditionalInfo]); + expect(result.isValid).toBe(false); + }); + }); + + describe("date format", () => { + it("should accept a valid dd/MM/yyyy date", () => { + const result = validatePhtWeeklyHearingList([{ ...validHearing, date: "31/12/2025" }]); + expect(result.isValid).toBe(true); + }); + + it("should reject ISO date format", () => { + const result = validatePhtWeeklyHearingList([{ ...validHearing, date: "2025-01-02" }]); + expect(result.isValid).toBe(false); + }); + + it("should reject date without leading zeros", () => { + const result = validatePhtWeeklyHearingList([{ ...validHearing, date: "2/1/2025" }]); + expect(result.isValid).toBe(false); + }); + + it("should reject date with slashes in wrong positions", () => { + const result = validatePhtWeeklyHearingList([{ ...validHearing, date: "2025/01/02" }]); + expect(result.isValid).toBe(false); + }); + }); + + describe("HTML injection protection", () => { + it("should reject HTML tags in caseName", () => { + const result = validatePhtWeeklyHearingList([{ ...validHearing, caseName: "" }]); + expect(result.isValid).toBe(false); + }); + + it("should reject HTML tags in hearingLength", () => { + const result = validatePhtWeeklyHearingList([{ ...validHearing, hearingLength: "1 hour" }]); + expect(result.isValid).toBe(false); + }); + + it("should reject HTML tags in hearingType", () => { + const result = validatePhtWeeklyHearingList([{ ...validHearing, hearingType: "" }]); + expect(result.isValid).toBe(false); + }); + + it("should reject HTML tags in venue", () => { + const result = validatePhtWeeklyHearingList([{ ...validHearing, venue: "" }]); + expect(result.isValid).toBe(false); + }); + + it("should reject HTML tags in additionalInformation", () => { + const result = validatePhtWeeklyHearingList([{ ...validHearing, additionalInformation: "

info

" }]); + expect(result.isValid).toBe(false); + }); + }); + + describe("invalid input types", () => { + it("should reject a non-array input", () => { + const result = validatePhtWeeklyHearingList(validHearing); + expect(result.isValid).toBe(false); + }); + + it("should reject null", () => { + const result = validatePhtWeeklyHearingList(null); + expect(result.isValid).toBe(false); + }); + }); +}); diff --git a/libs/list-types/pht-weekly-hearing-list/src/validation/json-validator.ts b/libs/list-types/pht-weekly-hearing-list/src/validation/json-validator.ts new file mode 100644 index 000000000..558aabe16 --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/validation/json-validator.ts @@ -0,0 +1,6 @@ +import { type ValidationResult, validateJson } from "@hmcts/publication"; +import schema from "../schemas/pht-weekly-hearing-list.json" with { type: "json" }; + +export function validatePhtWeeklyHearingList(jsonData: unknown): ValidationResult { + return validateJson(jsonData, schema, "1.0"); +} From 7a36f06159e2f41c4d4e3f1b630a02d474ead0d6 Mon Sep 17 00:00:00 2001 From: KianKwa Date: Mon, 13 Jul 2026 14:19:25 +0100 Subject: [PATCH 3/9] Update validator --- .../pht-weekly-hearing-list/index.test.ts | 16 +++++----------- .../pht-weekly-hearing-list/index.ts | 14 ++++++++------ 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.test.ts b/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.test.ts index f9f0f331c..52521708b 100644 --- a/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.test.ts +++ b/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.test.ts @@ -3,19 +3,12 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const mockValidate = vi.hoisted(() => vi.fn()); -vi.mock("@hmcts/list-types-common", async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - createJsonValidator: () => mockValidate, - provenanceLabelsEn: { MANUAL_UPLOAD: "Manual Upload", SNL: "ListAssist", COMMON_PLATFORM: "Common Platform", CP_CATH: "Libra", PDDA: "PDDA" }, - provenanceLabelsCy: { MANUAL_UPLOAD: "Lanlwytho â Llaw", SNL: "ListAssist", COMMON_PLATFORM: "Common Platform", CP_CATH: "Libra", PDDA: "PDDA" } - }; -}); - vi.mock("@hmcts/publication", () => ({ getArtefactById: vi.fn(), getPublicationJson: vi.fn(), + canAccessPublicationData: vi.fn().mockReturnValue(true), + resolveListType: vi.fn().mockResolvedValue({}), + validateJson: vi.fn().mockReturnValue({ isValid: true, errors: [] }), PROVENANCE_LABELS: { MANUAL_UPLOAD: "Manual Upload", LIST_ASSIST: "List Assist" @@ -26,7 +19,8 @@ vi.mock("@hmcts/pht-weekly-hearing-list", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - renderPhtData: vi.fn() + renderPhtData: vi.fn(), + validatePhtWeeklyHearingList: mockValidate }; }); diff --git a/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.ts b/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.ts index 8036f3025..f157627d3 100644 --- a/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.ts +++ b/apps/web/src/pages/(list-types)/pht-weekly-hearing-list/index.ts @@ -1,14 +1,16 @@ -import { createJsonValidator } from "@hmcts/list-types-common"; -import { phtWeeklyHearingListCy as cy, phtWeeklyHearingListEn as en, type PhtHearingList, renderPhtData } from "@hmcts/pht-weekly-hearing-list"; -import { schemaPath } from "@hmcts/pht-weekly-hearing-list/config"; +import { + phtWeeklyHearingListCy as cy, + phtWeeklyHearingListEn as en, + type PhtHearingList, + renderPhtData, + validatePhtWeeklyHearingList +} from "@hmcts/pht-weekly-hearing-list"; import { createSimpleListTypeHandler, resolveDataSource } from "../list-type-handler.js"; -const validate = createJsonValidator(schemaPath); - export const GET = createSimpleListTypeHandler({ en, cy, - validate, + validate: validatePhtWeeklyHearingList, logPrefix: "pht-weekly-hearing-list", serverError: { errorTitle: "Server Error", errorMessage: "An error occurred while loading the list" }, render: ({ artefact, jsonData, locale, res }) => { From 464cfe5312a67a892d211067f8e83e56eaa90041 Mon Sep 17 00:00:00 2001 From: KianKwa Date: Mon, 13 Jul 2026 16:37:25 +0100 Subject: [PATCH 4/9] fix sonar issues --- .../src/email-summary/summary-builder.test.ts | 115 ++++++++++ .../src/email-summary/summary-builder.ts | 6 +- .../src/pdf/pdf-generator.test.ts | 208 ++++++++++++++++-- .../src/pdf/pdf-generator.ts | 6 +- .../src/rendering/renderer.ts | 3 + .../src/processing/service.test.ts | 15 ++ 6 files changed, 328 insertions(+), 25 deletions(-) create mode 100644 libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.test.ts diff --git a/libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.test.ts b/libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.test.ts new file mode 100644 index 000000000..055816e5e --- /dev/null +++ b/libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("@hmcts/list-types-common", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual }; +}); + +vi.mock("@hmcts/publication", () => ({ + PROVENANCE_LABELS: {} +})); + +import type { PhtHearingList } from "../models/types.js"; +import { extractCaseSummary, formatCaseSummaryForEmail, SPECIAL_CATEGORY_DATA_WARNING } from "./summary-builder.js"; + +const HEARING: PhtHearingList[number] = { + date: "02/01/2025", + caseName: "A Vs B", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" +}; + +describe("extractCaseSummary", () => { + it("should return one summary entry per hearing with Date and Case name fields", () => { + const result = extractCaseSummary([HEARING]); + + expect(result).toHaveLength(1); + expect(result[0]).toEqual([ + { label: "Date", value: "02/01/2025" }, + { label: "Case name", value: "A Vs B" } + ]); + }); + + it("should return an empty array for an empty hearing list", () => { + expect(extractCaseSummary([])).toEqual([]); + }); + + it("should return one entry per hearing for multiple hearings", () => { + const hearings: PhtHearingList = [HEARING, { ...HEARING, date: "03/01/2025", caseName: "C Vs D" }]; + + const result = extractCaseSummary(hearings); + + expect(result).toHaveLength(2); + expect(result[1]).toEqual([ + { label: "Date", value: "03/01/2025" }, + { label: "Case name", value: "C Vs D" } + ]); + }); + + it("should use empty string when date is falsy", () => { + const hearingWithEmptyDate = { ...HEARING, date: "" }; + + const result = extractCaseSummary([hearingWithEmptyDate]); + + expect(result[0][0]).toEqual({ label: "Date", value: "" }); + }); + + it("should use empty string when caseName is falsy", () => { + const hearingWithEmptyCaseName = { ...HEARING, caseName: "" }; + + const result = extractCaseSummary([hearingWithEmptyCaseName]); + + expect(result[0][1]).toEqual({ label: "Case name", value: "" }); + }); + + it("should only include Date and Case name fields, ignoring other hearing fields", () => { + const result = extractCaseSummary([HEARING]); + + expect(result[0]).toHaveLength(2); + const labels = result[0].map((f) => f.label); + expect(labels).toEqual(["Date", "Case name"]); + }); +}); + +describe("formatCaseSummaryForEmail (re-export)", () => { + it("should be a function", () => { + expect(typeof formatCaseSummaryForEmail).toBe("function"); + }); + + it("should return 'No cases scheduled.' for an empty list", () => { + expect(formatCaseSummaryForEmail([])).toBe("No cases scheduled."); + }); + + it("should format a single case summary correctly", () => { + const summary = extractCaseSummary([HEARING]); + + const result = formatCaseSummaryForEmail(summary); + + expect(result).toContain("Date - 02/01/2025"); + expect(result).toContain("Case name - A Vs B"); + }); + + it("should separate multiple cases with dividers", () => { + const hearings: PhtHearingList = [HEARING, { ...HEARING, date: "03/01/2025", caseName: "C Vs D" }]; + const summary = extractCaseSummary(hearings); + + const result = formatCaseSummaryForEmail(summary); + + expect(result).toContain("Date - 02/01/2025"); + expect(result).toContain("Date - 03/01/2025"); + expect(result).toContain("---"); + }); +}); + +describe("SPECIAL_CATEGORY_DATA_WARNING (re-export)", () => { + it("should be a non-empty string", () => { + expect(typeof SPECIAL_CATEGORY_DATA_WARNING).toBe("string"); + expect(SPECIAL_CATEGORY_DATA_WARNING.length).toBeGreaterThan(0); + }); + + it("should mention Special Category Data", () => { + expect(SPECIAL_CATEGORY_DATA_WARNING).toContain("Special Category Data"); + }); +}); diff --git a/libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.ts b/libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.ts index 27724ca7c..77101c3a1 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/email-summary/summary-builder.ts @@ -1,7 +1,7 @@ -import { type CaseSummary, formatCaseSummaryForEmail, SPECIAL_CATEGORY_DATA_WARNING } from "@hmcts/list-types-common"; -import type { PhtHearingList } from "../models/types.js"; +export { formatCaseSummaryForEmail, SPECIAL_CATEGORY_DATA_WARNING } from "@hmcts/list-types-common"; -export { formatCaseSummaryForEmail, SPECIAL_CATEGORY_DATA_WARNING }; +import type { CaseSummary } from "@hmcts/list-types-common"; +import type { PhtHearingList } from "../models/types.js"; export function extractCaseSummary(jsonData: PhtHearingList): CaseSummary[] { return jsonData.map((hearing) => [ diff --git a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts index f746abd43..e318dcbae 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts @@ -8,7 +8,7 @@ vi.mock("@hmcts/list-types-common", async (importOriginal) => { render: vi.fn().mockReturnValue("mock pdf html") }), loadTranslations: vi.fn().mockResolvedValue({ pageTitle: "Primary Health Tribunal Weekly Hearing List" }), - savePdfToStorage: vi.fn().mockResolvedValue({ success: true }), + savePdfToStorage: vi.fn().mockResolvedValue({ success: true, pdfPath: "/stored/path.pdf", sizeBytes: 3 }), createPdfErrorResult: vi.fn().mockReturnValue({ success: false, error: "error" }) }; }); @@ -21,8 +21,41 @@ vi.mock("@hmcts/publication", () => ({ PROVENANCE_LABELS: { MANUAL_UPLOAD: "Manual Upload" } })); +vi.mock("../rendering/renderer.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + renderPhtData: vi.fn().mockReturnValue({ + header: { + listTitle: "Primary Health Tribunal Weekly Hearing List", + weekCommencingDate: "2 January 2025", + lastUpdatedDate: "1 January 2025", + lastUpdatedTime: "9am" + }, + hearings: [] + }) + }; +}); + import { generatePhtWeeklyHearingListPdf } from "./pdf-generator.js"; +const BASE_OPTIONS = { + artefactId: "test-artefact-id", + jsonData: [ + { + date: "02/01/2025", + caseName: "A Vs B", + hearingLength: "1 hour", + hearingType: "Substantive hearing", + venue: "Primary Health Tribunal", + additionalInformation: "Remote hearing" + } + ], + locale: "en", + provenance: "MANUAL_UPLOAD", + contentDate: new Date(2025, 0, 2) +}; + describe("generatePhtWeeklyHearingListPdf", () => { beforeEach(() => { vi.clearAllMocks(); @@ -30,25 +63,162 @@ describe("generatePhtWeeklyHearingListPdf", () => { it("should generate PDF successfully", async () => { const { savePdfToStorage } = await import("@hmcts/list-types-common"); - vi.mocked(savePdfToStorage).mockResolvedValue({ success: true }); - - const result = await generatePhtWeeklyHearingListPdf({ - artefactId: "test-artefact-id", - jsonData: [ - { - date: "02/01/2025", - caseName: "A Vs B", - hearingLength: "1 hour", - hearingType: "Substantive hearing", - venue: "Primary Health Tribunal", - additionalInformation: "Remote hearing" - } - ], - locale: "en", - provenance: "MANUAL_UPLOAD", - contentDate: new Date(2025, 0, 2) - }); + vi.mocked(savePdfToStorage).mockResolvedValue({ success: true, pdfPath: "/stored/path.pdf", sizeBytes: 3 }); + + const result = await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); expect(result.success).toBe(true); }); + + it("should call renderPhtData with PHT_COURT_NAME and PHT_LIST_TITLE constants", async () => { + const { renderPhtData } = await import("../rendering/renderer.js"); + + await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); + + expect(renderPhtData).toHaveBeenCalledWith( + BASE_OPTIONS.jsonData, + expect.objectContaining({ + courtName: "Primary Health Tribunal", + listTitle: "Primary Health Tribunal Weekly Hearing List", + locale: "en", + contentDate: BASE_OPTIONS.contentDate + }) + ); + }); + + it("should pass Welsh locale to renderPhtData when locale is cy", async () => { + const { renderPhtData } = await import("../rendering/renderer.js"); + + await generatePhtWeeklyHearingListPdf({ ...BASE_OPTIONS, locale: "cy" }); + + expect(renderPhtData).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ locale: "cy" })); + }); + + it("should load translations for the given locale", async () => { + const { loadTranslations } = await import("@hmcts/list-types-common"); + + await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); + + expect(loadTranslations).toHaveBeenCalledWith("en", expect.any(Function), expect.any(Function)); + }); + + it("should load Welsh translations when locale is cy", async () => { + const { loadTranslations } = await import("@hmcts/list-types-common"); + + await generatePhtWeeklyHearingListPdf({ ...BASE_OPTIONS, locale: "cy" }); + + expect(loadTranslations).toHaveBeenCalledWith("cy", expect.any(Function), expect.any(Function)); + }); + + it("should use provenance label from PROVENANCE_LABELS when provenance matches", async () => { + const { configureNunjucks } = await import("@hmcts/list-types-common"); + const mockRender = vi.fn().mockReturnValue(""); + vi.mocked(configureNunjucks).mockReturnValue({ render: mockRender } as any); + + await generatePhtWeeklyHearingListPdf({ ...BASE_OPTIONS, provenance: "MANUAL_UPLOAD" }); + + expect(mockRender).toHaveBeenCalledWith("pdf-template.njk", expect.objectContaining({ dataSource: "Manual Upload" })); + }); + + it("should use raw provenance string when not in PROVENANCE_LABELS", async () => { + const { configureNunjucks } = await import("@hmcts/list-types-common"); + const mockRender = vi.fn().mockReturnValue(""); + vi.mocked(configureNunjucks).mockReturnValue({ render: mockRender } as any); + + await generatePhtWeeklyHearingListPdf({ ...BASE_OPTIONS, provenance: "SOME_UNKNOWN_SOURCE" }); + + expect(mockRender).toHaveBeenCalledWith("pdf-template.njk", expect.objectContaining({ dataSource: "SOME_UNKNOWN_SOURCE" })); + }); + + it("should use empty string for dataSource when provenance is not provided", async () => { + const { configureNunjucks } = await import("@hmcts/list-types-common"); + const mockRender = vi.fn().mockReturnValue(""); + vi.mocked(configureNunjucks).mockReturnValue({ render: mockRender } as any); + + const { provenance: _, ...optionsWithoutProvenance } = BASE_OPTIONS; + await generatePhtWeeklyHearingListPdf(optionsWithoutProvenance as any); + + expect(mockRender).toHaveBeenCalledWith("pdf-template.njk", expect.objectContaining({ dataSource: "" })); + }); + + it("should pass rendered header and hearings to the template", async () => { + const { configureNunjucks, loadTranslations } = await import("@hmcts/list-types-common"); + const { renderPhtData } = await import("../rendering/renderer.js"); + const mockRender = vi.fn().mockReturnValue(""); + vi.mocked(configureNunjucks).mockReturnValue({ render: mockRender } as any); + const mockTranslations = { title: "PHT" }; + vi.mocked(loadTranslations).mockResolvedValue(mockTranslations as any); + const mockRenderedData = { + header: { listTitle: "PHT List", weekCommencingDate: "2 January 2025", lastUpdatedDate: "1 January 2025", lastUpdatedTime: "9am" }, + hearings: [ + { date: "02 January 2025", caseName: "A Vs B", hearingLength: "1 hour", hearingType: "Substantive hearing", venue: "PHT", additionalInformation: "" } + ] + }; + vi.mocked(renderPhtData).mockReturnValue(mockRenderedData); + + await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); + + expect(mockRender).toHaveBeenCalledWith( + "pdf-template.njk", + expect.objectContaining({ + header: mockRenderedData.header, + hearings: mockRenderedData.hearings, + t: mockTranslations + }) + ); + }); + + it("should return failure when generatePdfFromHtml returns success: false", async () => { + const { generatePdfFromHtml } = await import("@hmcts/pdf-generation"); + vi.mocked(generatePdfFromHtml).mockResolvedValue({ success: false, error: "PDF engine error" }); + + const result = await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); + + expect(result.success).toBe(false); + expect(result.error).toBe("PDF engine error"); + }); + + it("should return 'PDF generation failed' when generatePdfFromHtml returns no error message", async () => { + const { generatePdfFromHtml } = await import("@hmcts/pdf-generation"); + vi.mocked(generatePdfFromHtml).mockResolvedValue({ success: false }); + + const result = await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); + + expect(result.success).toBe(false); + expect(result.error).toBe("PDF generation failed"); + }); + + it("should return failure when generatePdfFromHtml returns no pdfBuffer", async () => { + const { generatePdfFromHtml } = await import("@hmcts/pdf-generation"); + vi.mocked(generatePdfFromHtml).mockResolvedValue({ success: true, pdfBuffer: undefined }); + + const result = await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); + + expect(result.success).toBe(false); + }); + + it("should call savePdfToStorage with artefactId and pdfBuffer", async () => { + const { savePdfToStorage } = await import("@hmcts/list-types-common"); + const { generatePdfFromHtml } = await import("@hmcts/pdf-generation"); + const pdfBuffer = Buffer.from("test-pdf-content"); + vi.mocked(generatePdfFromHtml).mockResolvedValue({ success: true, pdfBuffer, sizeBytes: 42 }); + + await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); + + expect(savePdfToStorage).toHaveBeenCalledWith("test-artefact-id", pdfBuffer, 42); + }); + + it("should return createPdfErrorResult when an unexpected error is thrown", async () => { + const { renderPhtData } = await import("../rendering/renderer.js"); + const { createPdfErrorResult } = await import("@hmcts/list-types-common"); + vi.mocked(renderPhtData).mockImplementation(() => { + throw new Error("Unexpected render error"); + }); + vi.mocked(createPdfErrorResult).mockReturnValue({ success: false, error: "Unexpected render error" }); + + const result = await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); + + expect(result.success).toBe(false); + expect(createPdfErrorResult).toHaveBeenCalled(); + }); }); diff --git a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts index a0bc181fd..0566c85cb 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts @@ -12,7 +12,7 @@ import { import { generatePdfFromHtml } from "@hmcts/pdf-generation"; import { PROVENANCE_LABELS } from "@hmcts/publication"; import type { PhtHearingList } from "../models/types.js"; -import { renderPhtData } from "../rendering/renderer.js"; +import { PHT_COURT_NAME, PHT_LIST_TITLE, renderPhtData } from "../rendering/renderer.js"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -25,10 +25,10 @@ export async function generatePhtWeeklyHearingListPdf(options: PdfGenerationOpti try { const renderedData = renderPhtData(options.jsonData, { locale: options.locale, - courtName: "Primary Health Tribunal", + courtName: PHT_COURT_NAME, contentDate: options.contentDate, lastReceivedDate: new Date().toISOString(), - listTitle: "Primary Health Tribunal Weekly Hearing List" + listTitle: PHT_LIST_TITLE }); const translations = await loadTranslations( diff --git a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts index 2d63b44e0..a0d3e28a5 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts @@ -2,6 +2,9 @@ import { formatDdMmYyyyDate } from "@hmcts/list-types-common"; import { DateTime } from "luxon"; import type { PhtHearing, PhtHearingList } from "../models/types.js"; +export const PHT_COURT_NAME = "Primary Health Tribunal"; +export const PHT_LIST_TITLE = "Primary Health Tribunal Weekly Hearing List"; + export interface RenderOptions { locale: string; courtName: string; diff --git a/libs/publication/src/processing/service.test.ts b/libs/publication/src/processing/service.test.ts index 9054f7621..30168c2e0 100644 --- a/libs/publication/src/processing/service.test.ts +++ b/libs/publication/src/processing/service.test.ts @@ -7,6 +7,10 @@ vi.mock("@hmcts/care-standards-tribunal-weekly-hearing-list", () => ({ generateCareStandardsTribunalWeeklyHearingListPdf: vi.fn() })); +vi.mock("@hmcts/pht-weekly-hearing-list", () => ({ + generatePhtWeeklyHearingListPdf: vi.fn() +})); + vi.mock("@hmcts/sscs-daily-hearing-list", () => ({ generateSscsDailyHearingListPdf: vi.fn(), importantInformationByListType: { @@ -137,6 +141,7 @@ describe("publication-processor", async () => { const { generateUtiacJrLondonDailyHearingListPdf, generateUtiacJrLeedsDailyHearingListPdf } = await import("@hmcts/utiac-jr-daily-hearing-list"); const { generateRcjStandardDailyCauseListPdf } = await import("@hmcts/rcj-standard-daily-cause-list"); const { generateAdministrativeCourtDailyCauseListPdf } = await import("@hmcts/administrative-court-daily-cause-list"); + const { generatePhtWeeklyHearingListPdf } = await import("@hmcts/pht-weekly-hearing-list"); const { getLocationById } = await import("@hmcts/location"); const { sendLocationAndCaseSubscriptionNotifications, sendListTypePublicationNotifications } = await import("@hmcts/notifications"); const { prisma } = await import("@hmcts/postgres-prisma"); @@ -684,6 +689,16 @@ describe("publication-processor", async () => { expect(result).toEqual({}); }); + + it("should generate PDF for PHT Weekly Hearing List", async () => { + vi.mocked(prisma.listType.findUnique).mockResolvedValue({ name: "PHT_WEEKLY_HEARING_LIST", friendlyName: "PHT Weekly Hearing List" } as any); + vi.mocked(generatePhtWeeklyHearingListPdf).mockResolvedValue({ success: true, pdfPath: "/path/pht.pdf", sizeBytes: 1024, exceedsMaxSize: false }); + + const result = await generatePublicationPdf({ ...baseParams, listTypeId: 60 }); + + expect(generatePhtWeeklyHearingListPdf).toHaveBeenCalledWith(expect.objectContaining({ artefactId: "test-artefact-id" })); + expect(result).toEqual({ pdfPath: "/path/pht.pdf", sizeBytes: 1024, exceedsMaxSize: false }); + }); }); describe("sendPublicationNotificationsForArtefact", () => { From c1ce2b1443948bcfb0065aa48c7c814d3fd72b74 Mon Sep 17 00:00:00 2001 From: KianKwa Date: Mon, 13 Jul 2026 17:16:44 +0100 Subject: [PATCH 5/9] fix sonar issues --- .../src/pdf/pdf-generator.test.ts | 176 +++--------------- .../src/pdf/pdf-generator.ts | 63 ++----- .../src/rendering/renderer.test.ts | 16 +- .../src/rendering/renderer.ts | 32 +--- 4 files changed, 55 insertions(+), 232 deletions(-) diff --git a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts index e318dcbae..215c8e711 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.test.ts @@ -4,39 +4,14 @@ vi.mock("@hmcts/list-types-common", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - configureNunjucks: vi.fn().mockReturnValue({ - render: vi.fn().mockReturnValue("mock pdf html") - }), - loadTranslations: vi.fn().mockResolvedValue({ pageTitle: "Primary Health Tribunal Weekly Hearing List" }), - savePdfToStorage: vi.fn().mockResolvedValue({ success: true, pdfPath: "/stored/path.pdf", sizeBytes: 3 }), - createPdfErrorResult: vi.fn().mockReturnValue({ success: false, error: "error" }) + generateListPdf: vi.fn().mockResolvedValue({ success: true, pdfPath: "/stored/path.pdf", sizeBytes: 1024, exceedsMaxSize: false }) }; }); -vi.mock("@hmcts/pdf-generation", () => ({ - generatePdfFromHtml: vi.fn().mockResolvedValue({ success: true, pdfBuffer: Buffer.from("pdf"), sizeBytes: 3 }) -})); - vi.mock("@hmcts/publication", () => ({ PROVENANCE_LABELS: { MANUAL_UPLOAD: "Manual Upload" } })); -vi.mock("../rendering/renderer.js", async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - renderPhtData: vi.fn().mockReturnValue({ - header: { - listTitle: "Primary Health Tribunal Weekly Hearing List", - weekCommencingDate: "2 January 2025", - lastUpdatedDate: "1 January 2025", - lastUpdatedTime: "9am" - }, - hearings: [] - }) - }; -}); - import { generatePhtWeeklyHearingListPdf } from "./pdf-generator.js"; const BASE_OPTIONS = { @@ -52,6 +27,7 @@ const BASE_OPTIONS = { } ], locale: "en", + locationId: "location-1", provenance: "MANUAL_UPLOAD", contentDate: new Date(2025, 0, 2) }; @@ -61,164 +37,66 @@ describe("generatePhtWeeklyHearingListPdf", () => { vi.clearAllMocks(); }); - it("should generate PDF successfully", async () => { - const { savePdfToStorage } = await import("@hmcts/list-types-common"); - vi.mocked(savePdfToStorage).mockResolvedValue({ success: true, pdfPath: "/stored/path.pdf", sizeBytes: 3 }); - + it("should return the result from generateListPdf", async () => { const result = await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); - expect(result.success).toBe(true); - }); - - it("should call renderPhtData with PHT_COURT_NAME and PHT_LIST_TITLE constants", async () => { - const { renderPhtData } = await import("../rendering/renderer.js"); - - await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); - - expect(renderPhtData).toHaveBeenCalledWith( - BASE_OPTIONS.jsonData, - expect.objectContaining({ - courtName: "Primary Health Tribunal", - listTitle: "Primary Health Tribunal Weekly Hearing List", - locale: "en", - contentDate: BASE_OPTIONS.contentDate - }) - ); - }); - - it("should pass Welsh locale to renderPhtData when locale is cy", async () => { - const { renderPhtData } = await import("../rendering/renderer.js"); - - await generatePhtWeeklyHearingListPdf({ ...BASE_OPTIONS, locale: "cy" }); - - expect(renderPhtData).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ locale: "cy" })); + expect(result).toEqual({ success: true, pdfPath: "/stored/path.pdf", sizeBytes: 1024, exceedsMaxSize: false }); }); - it("should load translations for the given locale", async () => { - const { loadTranslations } = await import("@hmcts/list-types-common"); + it("should call generateListPdf with PHT_LIST_TITLE", async () => { + const { generateListPdf } = await import("@hmcts/list-types-common"); await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); - expect(loadTranslations).toHaveBeenCalledWith("en", expect.any(Function), expect.any(Function)); + expect(generateListPdf).toHaveBeenCalledWith(expect.objectContaining({ listTitle: "Primary Health Tribunal Weekly Hearing List" })); }); - it("should load Welsh translations when locale is cy", async () => { - const { loadTranslations } = await import("@hmcts/list-types-common"); - - await generatePhtWeeklyHearingListPdf({ ...BASE_OPTIONS, locale: "cy" }); - - expect(loadTranslations).toHaveBeenCalledWith("cy", expect.any(Function), expect.any(Function)); - }); - - it("should use provenance label from PROVENANCE_LABELS when provenance matches", async () => { - const { configureNunjucks } = await import("@hmcts/list-types-common"); - const mockRender = vi.fn().mockReturnValue(""); - vi.mocked(configureNunjucks).mockReturnValue({ render: mockRender } as any); + it("should resolve provenance to its display label", async () => { + const { generateListPdf } = await import("@hmcts/list-types-common"); await generatePhtWeeklyHearingListPdf({ ...BASE_OPTIONS, provenance: "MANUAL_UPLOAD" }); - expect(mockRender).toHaveBeenCalledWith("pdf-template.njk", expect.objectContaining({ dataSource: "Manual Upload" })); + expect(generateListPdf).toHaveBeenCalledWith(expect.objectContaining({ provenanceLabel: "Manual Upload" })); }); it("should use raw provenance string when not in PROVENANCE_LABELS", async () => { - const { configureNunjucks } = await import("@hmcts/list-types-common"); - const mockRender = vi.fn().mockReturnValue(""); - vi.mocked(configureNunjucks).mockReturnValue({ render: mockRender } as any); + const { generateListPdf } = await import("@hmcts/list-types-common"); - await generatePhtWeeklyHearingListPdf({ ...BASE_OPTIONS, provenance: "SOME_UNKNOWN_SOURCE" }); + await generatePhtWeeklyHearingListPdf({ ...BASE_OPTIONS, provenance: "UNKNOWN_SOURCE" }); - expect(mockRender).toHaveBeenCalledWith("pdf-template.njk", expect.objectContaining({ dataSource: "SOME_UNKNOWN_SOURCE" })); + expect(generateListPdf).toHaveBeenCalledWith(expect.objectContaining({ provenanceLabel: "UNKNOWN_SOURCE" })); }); - it("should use empty string for dataSource when provenance is not provided", async () => { - const { configureNunjucks } = await import("@hmcts/list-types-common"); - const mockRender = vi.fn().mockReturnValue(""); - vi.mocked(configureNunjucks).mockReturnValue({ render: mockRender } as any); - + it("should use empty string for provenanceLabel when provenance is not provided", async () => { + const { generateListPdf } = await import("@hmcts/list-types-common"); const { provenance: _, ...optionsWithoutProvenance } = BASE_OPTIONS; + await generatePhtWeeklyHearingListPdf(optionsWithoutProvenance as any); - expect(mockRender).toHaveBeenCalledWith("pdf-template.njk", expect.objectContaining({ dataSource: "" })); + expect(generateListPdf).toHaveBeenCalledWith(expect.objectContaining({ provenanceLabel: "" })); }); - it("should pass rendered header and hearings to the template", async () => { - const { configureNunjucks, loadTranslations } = await import("@hmcts/list-types-common"); - const { renderPhtData } = await import("../rendering/renderer.js"); - const mockRender = vi.fn().mockReturnValue(""); - vi.mocked(configureNunjucks).mockReturnValue({ render: mockRender } as any); - const mockTranslations = { title: "PHT" }; - vi.mocked(loadTranslations).mockResolvedValue(mockTranslations as any); - const mockRenderedData = { - header: { listTitle: "PHT List", weekCommencingDate: "2 January 2025", lastUpdatedDate: "1 January 2025", lastUpdatedTime: "9am" }, - hearings: [ - { date: "02 January 2025", caseName: "A Vs B", hearingLength: "1 hour", hearingType: "Substantive hearing", venue: "PHT", additionalInformation: "" } - ] - }; - vi.mocked(renderPhtData).mockReturnValue(mockRenderedData); + it("should pass artefactId, locale and contentDate through to generateListPdf", async () => { + const { generateListPdf } = await import("@hmcts/list-types-common"); - await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); + await generatePhtWeeklyHearingListPdf({ ...BASE_OPTIONS, locale: "cy" }); - expect(mockRender).toHaveBeenCalledWith( - "pdf-template.njk", + expect(generateListPdf).toHaveBeenCalledWith( expect.objectContaining({ - header: mockRenderedData.header, - hearings: mockRenderedData.hearings, - t: mockTranslations + artefactId: "test-artefact-id", + locale: "cy", + contentDate: BASE_OPTIONS.contentDate }) ); }); - it("should return failure when generatePdfFromHtml returns success: false", async () => { - const { generatePdfFromHtml } = await import("@hmcts/pdf-generation"); - vi.mocked(generatePdfFromHtml).mockResolvedValue({ success: false, error: "PDF engine error" }); - - const result = await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); - - expect(result.success).toBe(false); - expect(result.error).toBe("PDF engine error"); - }); - - it("should return 'PDF generation failed' when generatePdfFromHtml returns no error message", async () => { - const { generatePdfFromHtml } = await import("@hmcts/pdf-generation"); - vi.mocked(generatePdfFromHtml).mockResolvedValue({ success: false }); + it("should return failure when generateListPdf returns failure", async () => { + const { generateListPdf } = await import("@hmcts/list-types-common"); + vi.mocked(generateListPdf).mockResolvedValue({ success: false, error: "PDF generation failed" }); const result = await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); expect(result.success).toBe(false); expect(result.error).toBe("PDF generation failed"); }); - - it("should return failure when generatePdfFromHtml returns no pdfBuffer", async () => { - const { generatePdfFromHtml } = await import("@hmcts/pdf-generation"); - vi.mocked(generatePdfFromHtml).mockResolvedValue({ success: true, pdfBuffer: undefined }); - - const result = await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); - - expect(result.success).toBe(false); - }); - - it("should call savePdfToStorage with artefactId and pdfBuffer", async () => { - const { savePdfToStorage } = await import("@hmcts/list-types-common"); - const { generatePdfFromHtml } = await import("@hmcts/pdf-generation"); - const pdfBuffer = Buffer.from("test-pdf-content"); - vi.mocked(generatePdfFromHtml).mockResolvedValue({ success: true, pdfBuffer, sizeBytes: 42 }); - - await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); - - expect(savePdfToStorage).toHaveBeenCalledWith("test-artefact-id", pdfBuffer, 42); - }); - - it("should return createPdfErrorResult when an unexpected error is thrown", async () => { - const { renderPhtData } = await import("../rendering/renderer.js"); - const { createPdfErrorResult } = await import("@hmcts/list-types-common"); - vi.mocked(renderPhtData).mockImplementation(() => { - throw new Error("Unexpected render error"); - }); - vi.mocked(createPdfErrorResult).mockReturnValue({ success: false, error: "Unexpected render error" }); - - const result = await generatePhtWeeklyHearingListPdf(BASE_OPTIONS); - - expect(result.success).toBe(false); - expect(createPdfErrorResult).toHaveBeenCalled(); - }); }); diff --git a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts index 0566c85cb..7b9c2b99e 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/pdf/pdf-generator.ts @@ -1,18 +1,9 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; -import { - type BasePdfGenerationOptions, - configureNunjucks, - createPdfErrorResult, - loadTranslations, - PDF_BASE_STYLES, - type PdfGenerationResult, - savePdfToStorage -} from "@hmcts/list-types-common"; -import { generatePdfFromHtml } from "@hmcts/pdf-generation"; +import { type BasePdfGenerationOptions, generateListPdf, type PdfGenerationResult } from "@hmcts/list-types-common"; import { PROVENANCE_LABELS } from "@hmcts/publication"; import type { PhtHearingList } from "../models/types.js"; -import { PHT_COURT_NAME, PHT_LIST_TITLE, renderPhtData } from "../rendering/renderer.js"; +import { PHT_LIST_TITLE, renderPhtData } from "../rendering/renderer.js"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -21,44 +12,14 @@ interface PdfGenerationOptions extends BasePdfGenerationOptions contentDate: Date; } -export async function generatePhtWeeklyHearingListPdf(options: PdfGenerationOptions): Promise { - try { - const renderedData = renderPhtData(options.jsonData, { - locale: options.locale, - courtName: PHT_COURT_NAME, - contentDate: options.contentDate, - lastReceivedDate: new Date().toISOString(), - listTitle: PHT_LIST_TITLE - }); - - const translations = await loadTranslations( - options.locale, - () => import("../locales/en.js"), - () => import("../locales/cy.js") - ); - - const provenanceLabel = options.provenance ? PROVENANCE_LABELS[options.provenance as keyof typeof PROVENANCE_LABELS] || options.provenance : ""; - - const env = configureNunjucks(__dirname); - const html = env.render("pdf-template.njk", { - header: renderedData.header, - hearings: renderedData.hearings, - dataSource: provenanceLabel, - t: translations, - pdfStyles: PDF_BASE_STYLES - }); - - const pdfResult = await generatePdfFromHtml(html); - - if (!pdfResult.success || !pdfResult.pdfBuffer) { - return { - success: false, - error: pdfResult.error || "PDF generation failed" - }; - } - - return await savePdfToStorage(options.artefactId, pdfResult.pdfBuffer, pdfResult.sizeBytes!); - } catch (error) { - return createPdfErrorResult(error); - } +export function generatePhtWeeklyHearingListPdf(options: PdfGenerationOptions): Promise { + return generateListPdf({ + ...options, + listTitle: PHT_LIST_TITLE, + provenanceLabel: options.provenance ? PROVENANCE_LABELS[options.provenance as keyof typeof PROVENANCE_LABELS] || options.provenance : "", + templateDir: __dirname, + renderData: (jsonData, opts) => renderPhtData(jsonData, opts), + importEn: () => import("../locales/en.js"), + importCy: () => import("../locales/cy.js") + }); } diff --git a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts index 0b22a2141..0e9eb35f3 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts @@ -1,4 +1,14 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; + +vi.mock("@hmcts/list-types-common", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual }; +}); + +vi.mock("@hmcts/publication", () => ({ + PROVENANCE_LABELS: {} +})); + import type { PhtHearingList } from "../models/types.js"; import { renderPhtData } from "./renderer.js"; @@ -26,8 +36,8 @@ describe("renderPhtData", () => { const result = renderPhtData(hearingList, options); expect(result.header.listTitle).toBe("Primary Health Tribunal Weekly Hearing List"); - expect(result.header.weekCommencingDate).toBe("2 January 2025"); - expect(result.header.lastUpdatedDate).toBe("1 January 2025"); + expect(result.header.weekCommencingDate).toBe("02 January 2025"); + expect(result.header.lastUpdatedDate).toBe("01 January 2025"); expect(result.header.lastUpdatedTime).toContain("am"); expect(result.hearings).toHaveLength(1); diff --git a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts index a0d3e28a5..8255a6b36 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.ts @@ -1,5 +1,4 @@ -import { formatDdMmYyyyDate } from "@hmcts/list-types-common"; -import { DateTime } from "luxon"; +import { formatDdMmYyyyDate, formatDisplayDate, formatLastUpdatedDateTime } from "@hmcts/list-types-common"; import type { PhtHearing, PhtHearingList } from "../models/types.js"; export const PHT_COURT_NAME = "Primary Health Tribunal"; @@ -7,7 +6,7 @@ export const PHT_LIST_TITLE = "Primary Health Tribunal Weekly Hearing List"; export interface RenderOptions { locale: string; - courtName: string; + courtName?: string; contentDate: Date; lastReceivedDate: string; listTitle: string; @@ -23,33 +22,8 @@ export interface RenderedData { hearings: PhtHearing[]; } -function formatDate(date: Date, locale: string): string { - const localeCode = locale === "cy" ? "cy-GB" : "en-GB"; - return date.toLocaleDateString(localeCode, { - day: "numeric", - month: "long", - year: "numeric" - }); -} - -function formatLastUpdatedDateTime(isoDateTime: string, locale: string): { date: string; time: string } { - const dt = DateTime.fromISO(isoDateTime).setZone("Europe/London").setLocale(locale); - - const date = dt.toFormat("d MMMM yyyy"); - - const hours = dt.hour; - const minutes = dt.minute; - const period = hours >= 12 ? "pm" : "am"; - const hour12 = hours % 12 || 12; - - const minuteStr = minutes > 0 ? `:${minutes.toString().padStart(2, "0")}` : ""; - const time = `${hour12}${minuteStr}${period}`; - - return { date, time }; -} - export function renderPhtData(hearingList: PhtHearingList, options: RenderOptions): RenderedData { - const weekCommencingDate = formatDate(options.contentDate, options.locale); + const weekCommencingDate = formatDisplayDate(options.contentDate, options.locale); const { date: lastUpdatedDate, time: lastUpdatedTime } = formatLastUpdatedDateTime(options.lastReceivedDate, options.locale); const renderedHearings = hearingList.map((hearing) => ({ From 4b63bd0780eecc1d52fa8016c354b878a53a264d Mon Sep 17 00:00:00 2001 From: junaidiqbalmoj <84805836+junaidiqbalmoj@users.noreply.github.com> Date: Tue, 14 Jul 2026 15:44:00 +0100 Subject: [PATCH 6/9] feat: expand schema validation tests for magistrates adult court list types Add pattern/format validation, HTML injection protection, string constraint, and invalid input type tests to magistrates-adult-court-list and magistrates-public-adult-court-list, consistent with the pattern established in PR #844. Co-Authored-By: Claude Sonnet 4.6 --- .../src/validation/json-validator.test.ts | 447 +++++++++++++++--- .../src/validation/json-validator.test.ts | 447 +++++++++++++++--- 2 files changed, 742 insertions(+), 152 deletions(-) diff --git a/libs/list-types/magistrates-adult-court-list/src/validation/json-validator.test.ts b/libs/list-types/magistrates-adult-court-list/src/validation/json-validator.test.ts index bf2a79fea..b0df8cabd 100644 --- a/libs/list-types/magistrates-adult-court-list/src/validation/json-validator.test.ts +++ b/libs/list-types/magistrates-adult-court-list/src/validation/json-validator.test.ts @@ -38,97 +38,392 @@ const VALID_DATA = { }; describe("validateMagistratesAdultCourtList", () => { - it("should return valid when all required fields are present", () => { - const result = validateMagistratesAdultCourtList(VALID_DATA); - expect(result.isValid).toBe(true); - expect(result.errors).toHaveLength(0); - }); + describe("valid data", () => { + it("should return valid when all required fields are present", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); - it("should return invalid when document is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + // Act + const result = validateMagistratesAdultCourtList(data); - it("should return invalid when document.data.job is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + // Assert + expect(result.isValid).toBe(true); + expect(result.errors).toHaveLength(0); + }); - it("should return invalid when job.printdate is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.printdate; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + it("should accept multiple sessions", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session.push({ + lja: "Another Area", + court: "Another Court", + room: 2, + sstart: "10:00", + blocks: { block: [{ bstart: "10:00", cases: { case: [{ caseno: "CD98765432", def_name: "Jones, Jane" }] } }] } + }); - it("should return invalid when job.sessions is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + // Act + const result = validateMagistratesAdultCourtList(data); - it("should return invalid when session[0].lja is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].lja; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + // Assert + expect(result.isValid).toBe(true); + }); }); - it("should return invalid when session[0].court is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].court; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + describe("required fields", () => { + it("should return invalid when document is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when document.data.job is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when job.printdate is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.printdate; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when job.sessions is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when session[0].lja is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].lja; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when session[0].court is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].court; - it("should return invalid when session[0].room is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].room; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when session[0].room is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].room; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when session[0].sstart is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].sstart; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when block[0].bstart is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].bstart; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when case[0].caseno is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when case[0].def_name is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); }); - it("should return invalid when session[0].sstart is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].sstart; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + describe("date format", () => { + it("should accept a valid DD/MM/YYYY printdate", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.printdate = "31/12/2025"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(true); + }); + + it("should reject ISO date format for printdate", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.printdate = "2020-09-13"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject printdate without leading zeros", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.printdate = "1/1/2020"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should accept a valid hh:mm sstart", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].sstart = "14:30"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(true); + }); + + it("should reject sstart without leading zero", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].sstart = "9:00"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should accept a valid hh:mm:ss start_time in info", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.info.start_time = "14:30:00"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(true); + }); + + it("should reject start_time without seconds", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.info.start_time = "09:00"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); }); - it("should return invalid when block[0].bstart is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].bstart; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + describe("string constraints", () => { + it("should reject lja exceeding 100 characters", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].lja = "A".repeat(101); + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject caseno shorter than 10 characters", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB123"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject caseno longer than 10 characters", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB1234567890"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject def_name exceeding 200 characters", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name = "A".repeat(201); + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); }); - it("should return invalid when case[0].caseno is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + describe("HTML injection protection", () => { + it("should reject HTML tags in lja", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].lja = ""; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject HTML tags in court", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].court = "North Shields"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject HTML tags in caseno", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB123456"; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject HTML tags in def_name", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name = ""; + + // Act + const result = validateMagistratesAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); }); - it("should return invalid when case[0].def_name is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name; - const result = validateMagistratesAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + describe("invalid input types", () => { + it("should reject a non-object input", () => { + // Act + const result = validateMagistratesAdultCourtList([]); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject null", () => { + // Act + const result = validateMagistratesAdultCourtList(null); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject a string", () => { + // Act + const result = validateMagistratesAdultCourtList("invalid"); + + // Assert + expect(result.isValid).toBe(false); + }); }); }); diff --git a/libs/list-types/magistrates-public-adult-court-list/src/validation/json-validator.test.ts b/libs/list-types/magistrates-public-adult-court-list/src/validation/json-validator.test.ts index 2ccab028c..853fab079 100644 --- a/libs/list-types/magistrates-public-adult-court-list/src/validation/json-validator.test.ts +++ b/libs/list-types/magistrates-public-adult-court-list/src/validation/json-validator.test.ts @@ -38,97 +38,392 @@ const VALID_DATA = { }; describe("validateMagistratesPublicAdultCourtList", () => { - it("should return valid when all required fields are present", () => { - const result = validateMagistratesPublicAdultCourtList(VALID_DATA); - expect(result.isValid).toBe(true); - expect(result.errors).toHaveLength(0); - }); + describe("valid data", () => { + it("should return valid when all required fields are present", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); - it("should return invalid when document is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + // Act + const result = validateMagistratesPublicAdultCourtList(data); - it("should return invalid when document.data.job is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + // Assert + expect(result.isValid).toBe(true); + expect(result.errors).toHaveLength(0); + }); - it("should return invalid when job.printdate is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.printdate; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + it("should accept multiple sessions", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session.push({ + lja: "Another Area", + court: "Another Court", + room: 2, + sstart: "10:00", + blocks: { block: [{ bstart: "10:00", cases: { case: [{ caseno: "CD98765432", def_name: "Jones, Jane" }] } }] } + }); - it("should return invalid when job.sessions is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + // Act + const result = validateMagistratesPublicAdultCourtList(data); - it("should return invalid when session[0].lja is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].lja; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + // Assert + expect(result.isValid).toBe(true); + }); }); - it("should return invalid when session[0].court is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].court; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + describe("required fields", () => { + it("should return invalid when document is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when document.data.job is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when job.printdate is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.printdate; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when job.sessions is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when session[0].lja is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].lja; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when session[0].court is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].court; - it("should return invalid when session[0].room is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].room; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when session[0].room is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].room; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when session[0].sstart is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].sstart; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when block[0].bstart is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].bstart; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when case[0].caseno is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); + + it("should return invalid when case[0].def_name is missing", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); }); - it("should return invalid when session[0].sstart is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].sstart; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + describe("date format", () => { + it("should accept a valid DD/MM/YYYY printdate", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.printdate = "31/12/2025"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(true); + }); + + it("should reject ISO date format for printdate", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.printdate = "2020-09-13"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject printdate without leading zeros", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.printdate = "1/1/2020"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should accept a valid hh:mm sstart", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].sstart = "14:30"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(true); + }); + + it("should reject sstart without leading zero", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].sstart = "9:00"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should accept a valid hh:mm:ss start_time in info", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.info.start_time = "14:30:00"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(true); + }); + + it("should reject start_time without seconds", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.info.start_time = "09:00"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); }); - it("should return invalid when block[0].bstart is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].bstart; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + describe("string constraints", () => { + it("should reject lja exceeding 100 characters", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].lja = "A".repeat(101); + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject caseno shorter than 10 characters", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB123"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject caseno longer than 10 characters", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB1234567890"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject def_name exceeding 200 characters", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name = "A".repeat(201); + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); }); - it("should return invalid when case[0].caseno is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + describe("HTML injection protection", () => { + it("should reject HTML tags in lja", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].lja = ""; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject HTML tags in court", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].court = "Manchester Court"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject HTML tags in caseno", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB123456"; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject HTML tags in def_name", () => { + // Arrange + const data = JSON.parse(JSON.stringify(VALID_DATA)); + data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name = ""; + + // Act + const result = validateMagistratesPublicAdultCourtList(data); + + // Assert + expect(result.isValid).toBe(false); + }); }); - it("should return invalid when case[0].def_name is missing", () => { - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name; - const result = validateMagistratesPublicAdultCourtList(data); - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); + describe("invalid input types", () => { + it("should reject a non-object input", () => { + // Act + const result = validateMagistratesPublicAdultCourtList([]); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject null", () => { + // Act + const result = validateMagistratesPublicAdultCourtList(null); + + // Assert + expect(result.isValid).toBe(false); + }); + + it("should reject a string", () => { + // Act + const result = validateMagistratesPublicAdultCourtList("invalid"); + + // Assert + expect(result.isValid).toBe(false); + }); }); }); From 33f139e437ba401cd6ddc8de741a86a2e66633fb Mon Sep 17 00:00:00 2001 From: junaidiqbalmoj <84805836+junaidiqbalmoj@users.noreply.github.com> Date: Tue, 14 Jul 2026 15:47:28 +0100 Subject: [PATCH 7/9] revert: restore magistrates adult court list validator tests to pre-change state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Undoes unnecessary expansion of these test files — they were not in scope. Co-Authored-By: Claude Sonnet 4.6 --- .../src/validation/json-validator.test.ts | 447 +++--------------- .../src/validation/json-validator.test.ts | 447 +++--------------- 2 files changed, 152 insertions(+), 742 deletions(-) diff --git a/libs/list-types/magistrates-adult-court-list/src/validation/json-validator.test.ts b/libs/list-types/magistrates-adult-court-list/src/validation/json-validator.test.ts index b0df8cabd..bf2a79fea 100644 --- a/libs/list-types/magistrates-adult-court-list/src/validation/json-validator.test.ts +++ b/libs/list-types/magistrates-adult-court-list/src/validation/json-validator.test.ts @@ -38,392 +38,97 @@ const VALID_DATA = { }; describe("validateMagistratesAdultCourtList", () => { - describe("valid data", () => { - it("should return valid when all required fields are present", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(true); - expect(result.errors).toHaveLength(0); - }); - - it("should accept multiple sessions", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session.push({ - lja: "Another Area", - court: "Another Court", - room: 2, - sstart: "10:00", - blocks: { block: [{ bstart: "10:00", cases: { case: [{ caseno: "CD98765432", def_name: "Jones, Jane" }] } }] } - }); - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(true); - }); + it("should return valid when all required fields are present", () => { + const result = validateMagistratesAdultCourtList(VALID_DATA); + expect(result.isValid).toBe(true); + expect(result.errors).toHaveLength(0); }); - describe("required fields", () => { - it("should return invalid when document is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when document.data.job is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when job.printdate is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.printdate; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when job.sessions is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when session[0].lja is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].lja; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when session[0].court is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].court; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when session[0].room is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].room; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when session[0].sstart is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].sstart; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when block[0].bstart is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].bstart; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when case[0].caseno is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when case[0].def_name is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + it("should return invalid when document is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); }); - describe("date format", () => { - it("should accept a valid DD/MM/YYYY printdate", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.printdate = "31/12/2025"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(true); - }); - - it("should reject ISO date format for printdate", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.printdate = "2020-09-13"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject printdate without leading zeros", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.printdate = "1/1/2020"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should accept a valid hh:mm sstart", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].sstart = "14:30"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(true); - }); - - it("should reject sstart without leading zero", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].sstart = "9:00"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should accept a valid hh:mm:ss start_time in info", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.info.start_time = "14:30:00"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(true); - }); - - it("should reject start_time without seconds", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.info.start_time = "09:00"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when document.data.job is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); }); - describe("string constraints", () => { - it("should reject lja exceeding 100 characters", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].lja = "A".repeat(101); - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject caseno shorter than 10 characters", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB123"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject caseno longer than 10 characters", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB1234567890"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject def_name exceeding 200 characters", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name = "A".repeat(201); - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when job.printdate is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.printdate; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); }); - describe("HTML injection protection", () => { - it("should reject HTML tags in lja", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].lja = ""; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject HTML tags in court", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].court = "North Shields"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject HTML tags in caseno", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB123456"; - - // Act - const result = validateMagistratesAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject HTML tags in def_name", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name = ""; - - // Act - const result = validateMagistratesAdultCourtList(data); + it("should return invalid when job.sessions is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when session[0].lja is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].lja; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); }); - describe("invalid input types", () => { - it("should reject a non-object input", () => { - // Act - const result = validateMagistratesAdultCourtList([]); + it("should return invalid when session[0].court is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].court; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when session[0].room is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].room; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - it("should reject null", () => { - // Act - const result = validateMagistratesAdultCourtList(null); + it("should return invalid when session[0].sstart is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].sstart; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when block[0].bstart is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].bstart; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - it("should reject a string", () => { - // Act - const result = validateMagistratesAdultCourtList("invalid"); + it("should return invalid when case[0].caseno is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when case[0].def_name is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name; + const result = validateMagistratesAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); }); }); diff --git a/libs/list-types/magistrates-public-adult-court-list/src/validation/json-validator.test.ts b/libs/list-types/magistrates-public-adult-court-list/src/validation/json-validator.test.ts index 853fab079..2ccab028c 100644 --- a/libs/list-types/magistrates-public-adult-court-list/src/validation/json-validator.test.ts +++ b/libs/list-types/magistrates-public-adult-court-list/src/validation/json-validator.test.ts @@ -38,392 +38,97 @@ const VALID_DATA = { }; describe("validateMagistratesPublicAdultCourtList", () => { - describe("valid data", () => { - it("should return valid when all required fields are present", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(true); - expect(result.errors).toHaveLength(0); - }); - - it("should accept multiple sessions", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session.push({ - lja: "Another Area", - court: "Another Court", - room: 2, - sstart: "10:00", - blocks: { block: [{ bstart: "10:00", cases: { case: [{ caseno: "CD98765432", def_name: "Jones, Jane" }] } }] } - }); - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(true); - }); + it("should return valid when all required fields are present", () => { + const result = validateMagistratesPublicAdultCourtList(VALID_DATA); + expect(result.isValid).toBe(true); + expect(result.errors).toHaveLength(0); }); - describe("required fields", () => { - it("should return invalid when document is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when document.data.job is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when job.printdate is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.printdate; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when job.sessions is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when session[0].lja is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].lja; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when session[0].court is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].court; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when session[0].room is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].room; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when session[0].sstart is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].sstart; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when block[0].bstart is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].bstart; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when case[0].caseno is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); - - it("should return invalid when case[0].def_name is missing", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - expect(result.errors.length).toBeGreaterThan(0); - }); + it("should return invalid when document is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); }); - describe("date format", () => { - it("should accept a valid DD/MM/YYYY printdate", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.printdate = "31/12/2025"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(true); - }); - - it("should reject ISO date format for printdate", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.printdate = "2020-09-13"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject printdate without leading zeros", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.printdate = "1/1/2020"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should accept a valid hh:mm sstart", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].sstart = "14:30"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(true); - }); - - it("should reject sstart without leading zero", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].sstart = "9:00"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should accept a valid hh:mm:ss start_time in info", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.info.start_time = "14:30:00"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(true); - }); - - it("should reject start_time without seconds", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.info.start_time = "09:00"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when document.data.job is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); }); - describe("string constraints", () => { - it("should reject lja exceeding 100 characters", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].lja = "A".repeat(101); - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject caseno shorter than 10 characters", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB123"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject caseno longer than 10 characters", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB1234567890"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject def_name exceeding 200 characters", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name = "A".repeat(201); - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when job.printdate is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.printdate; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); }); - describe("HTML injection protection", () => { - it("should reject HTML tags in lja", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].lja = ""; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject HTML tags in court", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].court = "Manchester Court"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject HTML tags in caseno", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno = "AB123456"; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); - - // Assert - expect(result.isValid).toBe(false); - }); - - it("should reject HTML tags in def_name", () => { - // Arrange - const data = JSON.parse(JSON.stringify(VALID_DATA)); - data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name = ""; - - // Act - const result = validateMagistratesPublicAdultCourtList(data); + it("should return invalid when job.sessions is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when session[0].lja is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].lja; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); }); - describe("invalid input types", () => { - it("should reject a non-object input", () => { - // Act - const result = validateMagistratesPublicAdultCourtList([]); + it("should return invalid when session[0].court is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].court; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when session[0].room is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].room; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - it("should reject null", () => { - // Act - const result = validateMagistratesPublicAdultCourtList(null); + it("should return invalid when session[0].sstart is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].sstart; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when block[0].bstart is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].bstart; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - it("should reject a string", () => { - // Act - const result = validateMagistratesPublicAdultCourtList("invalid"); + it("should return invalid when case[0].caseno is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].caseno; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + }); - // Assert - expect(result.isValid).toBe(false); - }); + it("should return invalid when case[0].def_name is missing", () => { + const data = JSON.parse(JSON.stringify(VALID_DATA)); + delete data.document.data.job.sessions.session[0].blocks.block[0].cases.case[0].def_name; + const result = validateMagistratesPublicAdultCourtList(data); + expect(result.isValid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); }); }); From aabd3071e7ec744c6f3d32dabb105ba20ed001e6 Mon Sep 17 00:00:00 2001 From: junaidiqbalmoj <84805836+junaidiqbalmoj@users.noreply.github.com> Date: Tue, 14 Jul 2026 16:27:52 +0100 Subject: [PATCH 8/9] fix: correct date assertions in PHT renderer tests formatDisplayDate and formatDdMmYyyyDate use day: "numeric" which produces "2 January 2025" not "02 January 2025". Tests had the wrong expected values. Co-Authored-By: Claude Sonnet 4.6 --- .../src/rendering/renderer.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts index 0e9eb35f3..04f1e3da6 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/rendering/renderer.test.ts @@ -36,12 +36,12 @@ describe("renderPhtData", () => { const result = renderPhtData(hearingList, options); expect(result.header.listTitle).toBe("Primary Health Tribunal Weekly Hearing List"); - expect(result.header.weekCommencingDate).toBe("02 January 2025"); - expect(result.header.lastUpdatedDate).toBe("01 January 2025"); + expect(result.header.weekCommencingDate).toBe("2 January 2025"); + expect(result.header.lastUpdatedDate).toBe("1 January 2025"); expect(result.header.lastUpdatedTime).toContain("am"); expect(result.hearings).toHaveLength(1); - expect(result.hearings[0].date).toBe("02 January 2025"); + expect(result.hearings[0].date).toBe("2 January 2025"); expect(result.hearings[0].caseName).toBe("A Vs B"); expect(result.hearings[0].hearingLength).toBe("1 hour"); expect(result.hearings[0].hearingType).toBe("Substantive hearing"); @@ -80,8 +80,8 @@ describe("renderPhtData", () => { const result = renderPhtData(hearingList, options); expect(result.hearings).toHaveLength(2); - expect(result.hearings[0].date).toBe("02 January 2025"); - expect(result.hearings[1].date).toBe("03 January 2025"); + expect(result.hearings[0].date).toBe("2 January 2025"); + expect(result.hearings[1].date).toBe("3 January 2025"); }); it("should format lastUpdated with time", () => { From 323d46590f688f61fc4f8c8a1454b3c04cb7047f Mon Sep 17 00:00:00 2001 From: junaidiqbalmoj <84805836+junaidiqbalmoj@users.noreply.github.com> Date: Tue, 14 Jul 2026 16:33:55 +0100 Subject: [PATCH 9/9] fix: use named export for validatePhtWeeklyHearingList in index.ts The CI guard in list-types/common checks for /export\s+.*validate[A-Z]/ in src/index.ts. A wildcard re-export doesn't satisfy that regex. Co-Authored-By: Claude Sonnet 4.6 --- libs/list-types/pht-weekly-hearing-list/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/list-types/pht-weekly-hearing-list/src/index.ts b/libs/list-types/pht-weekly-hearing-list/src/index.ts index d6191ba15..611aa9130 100644 --- a/libs/list-types/pht-weekly-hearing-list/src/index.ts +++ b/libs/list-types/pht-weekly-hearing-list/src/index.ts @@ -6,4 +6,4 @@ export { en as phtWeeklyHearingListEn } from "./locales/en.js"; export * from "./models/types.js"; export * from "./pdf/pdf-generator.js"; export * from "./rendering/renderer.js"; -export * from "./validation/json-validator.js"; +export { validatePhtWeeklyHearingList } from "./validation/json-validator.js";