partial synch with ph2 updates

This commit is contained in:
2025-11-28 08:45:13 +00:00
parent 8f1aede2e3
commit 3f4bd8d52e
54 changed files with 4395 additions and 488 deletions
+48
View File
@@ -0,0 +1,48 @@
import { useState, useCallback } from "react";
export function useDownloadQueue(maxConcurrent = 3) {
const [queue, setQueue] = useState([]); // queued tasks
const [activeCount, setActiveCount] = useState(0);
const [statuses, setStatuses] = useState({}); // { id: "idle"|"queued"|"downloading"|"done"|"failed" }
const scheduleNext = useCallback(() => {
setQueue((queueCurr) => {
if (activeCount >= maxConcurrent || queueCurr.length === 0)
return queueCurr;
const [task, ...rest] = queueCurr;
setStatuses((s) => ({ ...s, [task.id]: "downloading" }));
setActiveCount((c) => c + 1);
// Run the download fully in async IIFE
(async () => {
try {
await task.downloadFn(); // triggers fetch + blob + <a> click
setStatuses((s) => ({ ...s, [task.id]: "done" }));
} catch (err) {
console.error(err);
setStatuses((s) => ({ ...s, [task.id]: "failed" }));
} finally {
setActiveCount((c) => c - 1);
scheduleNext(); // promote next in queue
}
})();
return rest;
});
}, [activeCount, maxConcurrent]);
const startDownload = useCallback(
(id, downloadFn) => {
setStatuses((s) => ({ ...s, [id]: "queued" }));
setQueue((curr) => [...curr, { id, downloadFn }]);
scheduleNext();
},
[scheduleNext]
);
const getStatus = useCallback((id) => statuses[id] || "idle", [statuses]);
return { startDownload, getStatus };
}
+325
View File
@@ -0,0 +1,325 @@
// // import { useState } from "react";
// // export default function DocumentLink({ detailsObj, caseReference }) {
// // const [downloadStatus, setDownloadStatus] = useState("");
// // const [progress, setProgress] = useState(null);
// // const handleDownload = async () => {
// // setDownloadStatus("Downloading");
// // setProgress(0);
// // try {
// // const res = await fetch(detailsObj.pinswg_hashlink);
// // if (!res.ok) throw new Error("Download failed");
// // const contentDisposition = res.headers.get("content-disposition");
// // const filename = contentDisposition
// // ? contentDisposition.split("filename=")[1]
// // : detailsObj.pinswg_name || "document";
// // const contentLength = res.headers.get("content-length");
// // const totalBytes = contentLength
// // ? parseInt(contentLength, 10)
// // : null;
// // const reader = res.body.getReader();
// // let receivedBytes = 0;
// // const chunks = [];
// // while (true) {
// // const { done, value } = await reader.read();
// // if (done) break;
// // chunks.push(value);
// // receivedBytes += value.length;
// // if (totalBytes) {
// // const percent = Math.round(
// // (receivedBytes / totalBytes) * 100
// // );
// // setProgress(percent);
// // }
// // }
// // // Combine chunks into one blob
// // const blob = new Blob(chunks);
// // const url = window.URL.createObjectURL(blob);
// // const link = document.createElement("a");
// // link.href = url;
// // link.download = filename;
// // document.body.appendChild(link);
// // link.click();
// // document.body.removeChild(link);
// // setDownloadStatus("Download complete!");
// // setProgress(100);
// // // Fire GA event
// // window.gtag?.("event", "DownloadedFile", {
// // caseReference,
// // filename,
// // });
// // } catch (err) {
// // console.error(err);
// // setDownloadStatus("Download failed");
// // setProgress(null);
// // }
// // };
// // return (
// // <>
// // {detailsObj.pinswg_publishtoweb ? (
// // <button className="documentLink" onClick={handleDownload}>
// // <span className="results-visually-hidden">
// // Document name:
// // </span>
// // {detailsObj.pinswg_name || ""}
// // </button>
// // ) : (
// // <>
// // <span className="results-visually-hidden">
// // Document name:
// // </span>
// // {detailsObj.pinswg_name || ""}
// // </>
// // )}
// // {downloadStatus && (
// // <p
// // className={
// // downloadStatus == "Downloading"
// // ? "govuk-!-font-size-14 govuk-!-margin-left-0 textloading"
// // : "govuk-!-font-size-14 govuk-!-margin-left-0 "
// // }
// // >
// // {downloadStatus}
// // {/* {progress !== null && ` (${progress}%)`} */}
// // </p>
// // )}
// // </>
// // );
// // }
// import { useState } from "react";
// export default function DocumentLink({
// id,
// detailsObj,
// caseReference,
// startDownload,
// getStatus,
// }) {
// const [downloadStatus, setDownloadStatus] = useState("");
// const [progress, setProgress] = useState(null);
// const downloadFile = async () => {
// setDownloadStatus("Downloading");
// setProgress(0);
// try {
// const res = await fetch(detailsObj.pinswg_hashlink);
// if (!res.ok) throw new Error("Download failed");
// const contentDisposition = res.headers.get("content-disposition");
// const filename = contentDisposition
// ? contentDisposition.split("filename=")[1]
// : detailsObj.pinswg_name || "document";
// const contentLength = res.headers.get("content-length");
// const totalBytes = contentLength
// ? parseInt(contentLength, 10)
// : null;
// const reader = res.body.getReader();
// let receivedBytes = 0;
// const chunks = [];
// while (true) {
// const { done, value } = await reader.read();
// if (done) break;
// chunks.push(value);
// receivedBytes += value.length;
// if (totalBytes) {
// const percent = Math.round(
// (receivedBytes / totalBytes) * 100
// );
// setProgress(percent);
// }
// }
// const blob = new Blob(chunks);
// const url = window.URL.createObjectURL(blob);
// const link = document.createElement("a");
// link.href = url;
// link.download = filename;
// document.body.appendChild(link);
// link.click();
// document.body.removeChild(link);
// setDownloadStatus("Download complete!");
// setProgress(100);
// window.gtag?.("event", "DownloadedFile", {
// caseReference,
// filename,
// });
// } catch (err) {
// console.error(err);
// setDownloadStatus("Download failed");
// setProgress(null);
// }
// };
// const handleClick = () => {
// if (getStatus(id) !== "idle") return; // don't double enqueue
// startDownload(id, downloadFile);
// };
// const status = getStatus(id);
// return (
// <>
// {detailsObj.pinswg_publishtoweb ? (
// <button className="documentLink" onClick={handleClick}>
// <span className="results-visually-hidden">
// Document name:
// </span>
// {detailsObj.pinswg_name || ""}
// </button>
// ) : (
// <>
// <span className="results-visually-hidden">
// Document name:
// </span>
// {detailsObj.pinswg_name || ""}
// </>
// )}
// {status !== "idle" && (
// <p
// className={
// status === "downloading"
// ? "govuk-!-font-size-14 govuk-!-margin-left-0 textloading"
// : "govuk-!-font-size-14 govuk-!-margin-left-0"
// }
// >
// {status === "downloading" && progress !== null
// ? `Downloading (${progress}%)`
// : status === "queued"
// ? "Queued"
// : status === "done"
// ? "Download complete!"
// : status === "failed"
// ? "Download failed"
// : ""}
// </p>
// )}
// </>
// );
// }
import { useState } from "react";
import useTranslation from "next-translate/useTranslation";
export default function DocumentLink({
id,
detailsObj,
caseReference,
startDownload,
getStatus,
}) {
const [progress, setProgress] = useState(null);
let { t } = useTranslation();
const downloadFile = async () => {
setProgress(0);
const res = await fetch(detailsObj.pinswg_hashlink);
if (!res.ok) throw new Error("Download failed");
const contentDisposition = res.headers.get("content-disposition");
const filename = contentDisposition
? contentDisposition.split("filename=")[1]
: detailsObj.pinswg_name || "document";
const contentLength = res.headers.get("content-length");
const totalBytes = contentLength ? parseInt(contentLength, 10) : null;
const reader = res.body.getReader();
let receivedBytes = 0;
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
receivedBytes += value.length;
if (totalBytes) {
const percent = Math.round((receivedBytes / totalBytes) * 100);
setProgress(percent);
}
}
const blob = new Blob(chunks);
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
setProgress(100);
window.gtag?.("event", "DownloadedFile", { caseReference, filename });
};
const handleClick = () => {
if (getStatus(id) !== "idle") return; // avoid double enqueue
startDownload(id, downloadFile);
};
const status = getStatus(id);
return (
<div>
{detailsObj.pinswg_publishtoweb ? (
<button className="documentLink" onClick={handleClick}>
<span className="results-visually-hidden">
Document name:
</span>
{detailsObj.pinswg_name || ""}
</button>
) : (
<span className="results-visually-hidden">
{detailsObj.pinswg_name || ""}
</span>
)}
{status !== "idle" && (
<p
className={
status === "downloading"
? "govuk-!-font-size-14 govuk-!-margin-left-0 textloading"
: "govuk-!-font-size-14 govuk-!-margin-left-0"
}
>
{status === "downloading" && progress !== null
? t("case:downloading-label")
: status === "queued"
? t("case:download-queued-label")
: status === "done"
? t("case:download-complete-label")
: status === "failed"
? t("case:download-failed-label")
: ""}
</p>
)}
</div>
);
}
+59 -21
View File
@@ -34,6 +34,15 @@ export const getFormCollectionByID = (appealTypeID) => {
return collectionName[0];
};
export const getNavigationPropertyByPrimaryAttribute = (primaryAttribute) => {
const collectionName = jsonpath({
path: "$..[?(@ && @.PrimaryIdAttribute =='" + primaryAttribute + "')]",
json: data,
eval: true,
});
return collectionName[0];
};
export const getFormIDByLogicalName = (appealTypeLogicalName) => {
const collectionName = jsonpath({
path: "$..[?(@ && @.LogicalName =='" + appealTypeLogicalName + "')]",
@@ -170,29 +179,58 @@ export const getPartSavedDetails = (searchResultsObj) => {
* Get the details of a case from the appeal type
* @param object searchResultsObj
*/
export const getSearchDetailsPaged = (searchResultsObj) => {
let detailsArr = [];
export const getSearchDetailsPaged = async (searchResultsObj) => {
searchResultsObj = searchResultsObj.value;
const detailsObj = searchResultsObj.map((searchDetail, index) => {
if (searchDetail.pinswg_appealcasetype == null) {
console.log(searchDetail.title);
} else {
let formMeta = getFormCollectionByID(
searchDetail.pinswg_appealcasetype
);
// formMeta?.LogicalCollectionName &&
// formMeta?.LogicalCollectionName != "pinswg_sipses" &&
detailsArr.push(
getBasicSearchDetailsPaged(
formMeta.LogicalCollectionName,
searchDetail.title,
formMeta.PrimaryIdAttribute,
searchDetail.incidentid
)
);
// Group incidents by appeal type
const groupedByAppealType = searchResultsObj.reduce((acc, detail) => {
const appealType = detail.pinswg_appealcasetype;
if (!appealType) {
console.log("No appeal type for:", detail.title);
return acc;
}
});
return Promise.all(detailsArr);
if (!acc[appealType]) acc[appealType] = [];
acc[appealType].push({
incidentID: detail.incidentid,
title: detail.title,
});
return acc;
}, {});
const allDetails = [];
// For each appeal type, call getBasicSearchDetailsPaged once with all incident IDs
for (const [appealType, incidents] of Object.entries(groupedByAppealType)) {
const incidentIDs = incidents.map((i) => i.incidentID);
// Get the form meta for this appeal type to access primaryIdAttribute
const formMeta = getFormCollectionByID(appealType);
if (!formMeta || !formMeta.PrimaryIdAttribute) {
console.log(`Missing form metadata for appeal type: ${appealType}`);
continue;
}
// console.log(
// `Fetching ${incidentIDs.length} incidents for appeal type: ${appealType} with primaryIdAttribute: ${formMeta.PrimaryIdAttribute}`
// );
try {
const details = await getBasicSearchDetailsPaged(
formMeta.LogicalCollectionName, // appealTypeName
null, // caseReference is no longer used in batch
formMeta.PrimaryIdAttribute, // primaryIdAttribute
incidentIDs // pass array of incidentIDs
);
allDetails.push(...details);
} catch (err) {
consoleLogger(err);
}
}
return allDetails;
};
// export const absoluteUrl = (req, setLocalhost) => {