import axios from "axios"; import CryptoJS from "crypto-js"; import { azureHeadersPaged } from "../../../actions/core/headers"; import { consoleLogger } from "../../../actions/core/logger"; import { getToken } from "../../../actions/core/token"; import { hashAPIPath } from "../../../actions/core/hash"; import { respondError, respondSuccess } from "../middleware/apiResponse"; const WORDKEY = process.env.HASHKEY; const WEBAPI_URL = process.env.RELAY_ROOT || "https://dev-pedw-ns.servicebus.windows.net/dev-pedw-hc/"; /** * Encrypts a document reference into a secure hash link. */ const encryptDocReference = (documentRef) => { const hash = CryptoJS.HmacSHA256( `documents/download/${documentRef}`, CryptoJS.enc.Hex.parse(WORDKEY) ).toString(CryptoJS.enc.Hex); return `/api/documents/download/${documentRef}?hash=${hash}`; }; export default async function ApiProxy(req, res) { const incidentID = req.query.incidentid; if (!incidentID) { return respondError(res, { status: 400, code: "INCIDENT_ID_REQUIRED", message: "incidentid query parameter is required." }); } try { const token = await getToken(); // Date range: today and 7 days ago const now = new Date(); const twoWeeksAgo = new Date(); twoWeeksAgo.setDate(now.getDate() - 7); const nowStr = now.toISOString(); const twoWeeksAgoStr = twoWeeksAgo.toISOString(); // Build query const query = `pinswg_documents?$count=true` + `&$filter=pinswg_publishtoweb eq true and _pinswg_documentids_value eq ${incidentID}` + ` and pinswg_documentpublisheddate ne null` + ` and pinswg_documentpublisheddate ge ${twoWeeksAgoStr}` + ` and pinswg_documentpublisheddate le ${nowStr}` + `&$select=pinswg_isharedocumentlocations,` + `_pinswg_documentids_value,` + `pinswg_isharelabelcasetype,` + `pinswg_isharelabellpaname,` + `pinswg_publishtoweb,` + `pinswg_uploadstatus,` + `pinswg_isharedocumentclassification,` + `pinswg_isharedocumentreference,` + `pinswg_name,` + `pinswg_latestpublishedversion,` + `pinswg_latestpublisheddate,` + `pinswg_documentpublisheddate`; const fullUrl = `${WEBAPI_URL}${query}${hashAPIPath(query)}`; const { data } = await axios.get( fullUrl, azureHeadersPaged(token.access_token) ); // Add hash download links to each result const resultsWithLinks = data.value.map((doc) => ({ ...doc, pinswg_hashlink: encryptDocReference( doc.pinswg_isharedocumentreference ) })); return respondSuccess(res, { ...data, value: resultsWithLinks }); } catch (error) { consoleLogger(error); return respondError(res, { status: 500, code: "DOCUMENTS_FETCH_FAILED", message: "Failed to fetch document details.", details: error.message || error.toString() }); } }