Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions e2e-tests/tests/admin/manual-upload.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import fs from "node:fs";
import path from "node:path";
import AxeBuilder from "@axe-core/playwright";
import type { Page } from "@playwright/test";
import { expect, test } from "@playwright/test";
Expand All @@ -8,6 +10,7 @@ import {
cleanupTestUsers,
createTestSubscription,
createTestUser,
getLatestArtefactByLocationAndListType,
getNotificationsBySubscriptionId
} from "../../utils/notification-helpers.js";
import { loginWithSSO } from "../../utils/sso-helpers.js";
Expand Down Expand Up @@ -438,3 +441,102 @@ test.describe
}
});
});

test.describe("PDF Generation", () => {
let pdfTestLocationId: number;

test.beforeAll(async () => {
const testLocation = await createUniqueTestLocation({ namePrefix: "PDF Generation Court" });
pdfTestLocationId = testLocation.locationId;
});

const CIVIL_FAMILY_JSON = {
document: {
publicationDate: "2025-11-12T09:00:00.000Z",
documentName: "Civil and Family Daily Cause List",
version: "1.0"
},
venue: {
venueName: "Oxford Combined Court Centre",
venueAddress: {
line: ["St Aldate's"],
town: "Oxford",
postCode: "OX1 1TL"
},
venueContact: {
venueTelephone: "01865 264 200",
venueEmail: "enquiries.oxford.countycourt@justice.gov.uk"
}
},
courtLists: [
{
courtHouse: {
courtHouseName: "Oxford Combined Court Centre",
courtRoom: [
{
courtRoomName: "Courtroom 1",
session: [
{
sittings: [
{
sittingStart: "2025-11-12T10:00:00.000Z",
sittingEnd: "2025-11-12T11:00:00.000Z",
hearing: [
{
hearingType: "Family Hearing",
case: [{ caseName: "Brown v Brown", caseNumber: "CF-2025-001" }]
}
]
}
]
}
]
}
]
}
}
]
};

test.beforeEach(async ({ page }) => {
await authenticateSystemAdmin(page);
});

test("should generate a PDF after uploading a JSON publication @nightly", async ({ page }) => {
await page.goto(`/manual-upload?locationId=${pdfTestLocationId}`);
await page.waitForTimeout(1000);

await page.selectOption('select[name="listType"]', "8"); // CIVIL_AND_FAMILY_DAILY_CAUSE_LIST
await page.fill('input[name="hearingStartDate-day"]', "12");
await page.fill('input[name="hearingStartDate-month"]', "11");
await page.fill('input[name="hearingStartDate-year"]', "2025");
await page.selectOption('select[name="sensitivity"]', "PUBLIC");
await page.selectOption('select[name="language"]', "ENGLISH");
await page.fill('input[name="displayFrom-day"]', "12");
await page.fill('input[name="displayFrom-month"]', "11");
await page.fill('input[name="displayFrom-year"]', "2025");
await page.fill('input[name="displayTo-day"]', "13");
await page.fill('input[name="displayTo-month"]', "11");
await page.fill('input[name="displayTo-year"]', "2025");

const fileInput = page.locator('input[name="file"]');
await fileInput.setInputFiles({
name: "civil-and-family-daily-cause-list.json",
mimeType: "application/json",
buffer: Buffer.from(JSON.stringify(CIVIL_FAMILY_JSON))
});

await page.getByRole("button", { name: /continue/i }).click();
await page.waitForURL(/\/manual-upload-summary\?uploadId=/);

await page.getByRole("button", { name: "Confirm" }).click();
await page.waitForURL("/manual-upload-success", { timeout: 30000 });

const artefact = await getLatestArtefactByLocationAndListType(pdfTestLocationId, 8);
expect(artefact).toBeDefined();

const pdfPath = path.join(process.cwd(), "..", "storage", "temp", "uploads", `${artefact!.artefactId}.pdf`);
expect(fs.existsSync(pdfPath)).toBe(true);
expect(fs.statSync(pdfPath).size).toBeGreaterThan(0);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
});
10 changes: 10 additions & 0 deletions e2e-tests/utils/notification-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,16 @@ export async function cleanupTestSubscriptions(subscriptionIds: string[]) {
await deleteTestSubscriptions({ searchValues: subscriptionIds });
}

export async function getLatestArtefactByLocationAndListType(locationId: number, listTypeId: number) {
return await prisma.artefact.findFirst({
where: {
locationId: locationId.toString(),
listTypeId
},
orderBy: { lastReceivedDate: "desc" }
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Tighten this lookup to the current test run.

Filtering only by locationId and listTypeId is too broad for E2E assertions. A previous or concurrent upload for the same pair can be returned here, which makes the nightly PDF test flaky. Please add a discriminator from the current run, e.g. a createdAfter timestamp captured before submission.

}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

export async function cleanupTestUsers(userIds: string[]) {
if (userIds.length === 0) return;

Expand Down
2 changes: 1 addition & 1 deletion libs/admin-pages/src/pages/manual-upload-summary/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ const postHandler = async (req: Request, res: Response) => {
let jsonData: unknown;
if (!isFlatFile) {
try {
const jsonData = JSON.parse(uploadData.file.toString("utf-8"));
jsonData = JSON.parse(uploadData.file.toString("utf-8"));
await extractAndStoreArtefactSearch(artefactId, listTypeId, jsonData);
} catch (error) {
Comment on lines 130 to 135

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Do not swallow JSON parse failures here.

If JSON.parse() throws, jsonData stays undefined and processPublication() will skip PDF generation, but the request still carries on to the success page. Please fail the upload when the .json payload cannot be parsed, and only treat search extraction as non-fatal.

Suggested split between parse failure and search extraction failure
     let jsonData: unknown;
     if (!isFlatFile) {
       try {
         jsonData = JSON.parse(uploadData.file.toString("utf-8"));
-        await extractAndStoreArtefactSearch(artefactId, listTypeId, jsonData);
-      } catch (error) {
+      } catch {
+        throw new Error("Uploaded JSON could not be parsed");
+      }
+
+      try {
+        await extractAndStoreArtefactSearch(artefactId, listTypeId, jsonData);
+      } catch (error) {
         console.error("[Manual Upload] Failed to extract artefact search data", {
           artefactId,
           error: error instanceof Error ? error.message : String(error)
         });
       }

console.error("[Manual Upload] Failed to extract artefact search data", {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,14 +149,14 @@ const postHandler = async (req: Request, res: Response) => {
const canConvertByName = !canConvertById && listTypeName ? hasConverterForListTypeName(listTypeName) : false;

if (canConvertById || canConvertByName) {
const hearingsData = canConvertById
jsonData = canConvertById
? await convertExcelForListType(listTypeId, uploadData.file)
: await convertExcelForListTypeName(listTypeName!, uploadData.file);
await saveUploadedFile(artefactId, `${artefactId}.json`, Buffer.from(JSON.stringify(hearingsData)));
await saveUploadedFile(artefactId, `${artefactId}.json`, Buffer.from(JSON.stringify(jsonData)));

// Extract and store artefact search data from converted JSON
try {
await extractAndStoreArtefactSearch(artefactId, listTypeId, hearingsData);
await extractAndStoreArtefactSearch(artefactId, listTypeId, jsonData);
} catch (error) {
console.error("[Non-Strategic Upload] Failed to extract artefact search data from converted Excel", {
artefactId,
Expand Down
Loading