import { JSONPath as jsonpath } from "jsonpath-plus";
import useTranslation from "next-translate/useTranslation";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { connect } from "react-redux";
import { reduxForm } from "redux-form";
import { useSession } from "next-auth/react";
import {
generateRepPDF,
uploadRepFiles
} from "../../../actions/services/documentService";
import { sendEmail } from "../../../actions/services/notifyService";
import { formatDates, updateLinks } from "../../../components/utils";
import {
setRepresentationCapacity,
setRepresentationMessageSent,
setRepresentationReset,
setRepresentationSubmit,
setRepresentationSubmitConfirmation
} from "../../../store/currentView/action";
import ConsultationAgent from "./consultationAgent";
import ConsultationAppellant from "./consultationAppellant";
import ConsultationInterestedPartyPerson from "./consultationInterestedPartyPerson";
import RepAgent from "./representationAgent";
import RepAppellant from "./representationAppellant";
import RepCapacitySelection from "./representationCapacitySelection";
import RepCompleteSubmit from "./representationCompleteSubmit";
import RepInterestedPartyPerson from "./representationInterestedPartyPerson";
import RepLPA from "./representationLPA";
import RepLPACapacitySelection from "./representationLPACapacitySelection";
import RepLandOwner from "./representationLandowner";
import RepresentationProgress_enforcement from "./representationProgress/representationProgress_enforcement";
import RepresentationProgress_s78 from "./representationProgress/representationProgress_s78";
import RepresentationFlowFormStage from "./shell/RepresentationFlowFormStage";
import {
getQuestionnaireNextSection,
resolveJourneyStageFlags,
resolveRepresentationControlKey,
resolveSubmitTransition
} from "./utils/stepResolution";
import {
findDetailsObjForSubmit,
findDetailsObjForView,
findResultsObjForCurrentReference,
resolveInitialCaseDataSources,
resolveSubmitCaseDetailsSource
} from "./utils/dataResolution";
import {
buildRepresentationUpdateBody,
buildSubmitEnrichedValues,
runFinalisationSequence
} from "./utils/finalisationBoundary";
let MakeRepresentation = (props) => {
let { t } = useTranslation();
const [savingStatus, setSavingStatus] = useState(false);
const [finaliseAppealProcess, setFinaliseAppealProcess] = useState(false);
//const [questionnaireCount, setQuestionnaireCount] = useState(0);
const { data: session } = useSession();
const router = useRouter();
const { locale } = router;
const {
caseReference,
myCases,
myRepresentations,
watchedCases,
awaitingSubmission,
searchResultsObj,
representationSubmit,
currentType,
currentView,
setRepresentationCapacity,
setRepresentationSubmit,
setSubmitBack,
handleSubmit,
setRepresentationSubmitConfirmation,
setRepresentationMessageSent,
setShowQuestionnaireSection,
showQuestionnaireSection,
initialValues,
setCurrentReference,
ticketnumber,
docsOffline
} = props;
const formObj = props.props.form;
let setCaseQueryObj = props[currentType] || {};
var casesObj = {};
const appealType = currentView.caseReference.appealType;
const accountDetails = props.props.accountDetails.accountDetails;
const caseReferenceObj = props.props.currentView.caseReference;
const updateQuestionnaireCount = () => {
const countMap = {
846040000: 7,
846040001: 7,
846040025: 7,
846040004: 7,
846040018: 7,
846040003: 7,
846040009: 7,
846040008: 7,
846040005: 9,
846040006: 9,
846040007: 9
};
return countMap[appealType] || 7;
};
let questionnaireCount = updateQuestionnaireCount();
const isLPA =
accountDetails?.[
"pinswg_typeofinvolvement@OData.Community.Display.V1.FormattedValue"
] == "LPA"
? true
: false;
const isNRW = currentView.caseReference?.isNRW;
const { showCheckStage } = resolveJourneyStageFlags({
"representationSubmit": currentView.representationSubmit,
"representationSubmitConfirmation":
currentView.representationSubmitConfirmation
});
const setRepFileName = (values) => {
if (
!values.hasOwnProperty("representationCapacity") ||
!values.hasOwnProperty("representationType")
) {
return values;
}
const repCapMap = {
[t("myrepresentations:capacity-options-arr-appellant")]: "APP",
[t("myrepresentations:capacity-options-arr-agent")]: "APP", // agent treated as appellant proxy
[t("myrepresentations:capacity-options-arr-interested")]: "IP",
"Land Owner": "LO",
lpa: "LPA",
LPA: "LPA",
NRW: "NRW"
};
const repTypeMap = {
Statement: "Statement",
"Statement of common ground": "SCG",
"Written statement": "WS",
"Written statement of evidence": "WSE",
Questionnaire: "Questionnaire",
"Final comments": "Comments",
"Consultation Response": "Consultation_Response",
"Local Impact Report": "Local_Impact_Report",
"Marine Impact Report": "Marine_Impact_Report",
Other: "OTHER"
};
const now = new Date();
const pad = (num) => String(num).padStart(2, "0");
const dateStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(
now.getDate()
)}-${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(
now.getSeconds()
)}`;
const repCap = repCapMap[values.representationCapacity] || "";
const repType = repTypeMap[values.representationType] || "";
const sanitize = (str) =>
str.replace(/[\s~`!@#$%^&*(){}\[\];:"'<,.>?\/\\|_+=-]/g, "");
const namePart = isLPA
? sanitize(values.onBehalfOfLPA || "")
: `${sanitize(values.lastname || "")}_${sanitize(
values.firstname || ""
)}`;
values.repfile_name =
values.repfile_name ||
`${dateStr}_-_${repCap}_-_${repType}_-_${namePart}`;
return values;
};
useEffect(() => {
if (isLPA && !currentView?.representationCapacity) {
setRepresentationCapacity("LPA");
}
}, [isLPA, currentView?.representationCapacity, setRepresentationCapacity]);
const normalizeCapacity = (rawCapacity) => {
const normalized = (rawCapacity || "")
.toString()
.toLowerCase()
.replace(/(\band|[\s\-\+\(\)\,\&])/g, "");
const capacityMap = {
appellant: "appellant",
apelydd: "appellant",
agent: "agent",
asiant: "agent",
interestedparty: "interestedparty",
lpa: "lpa",
landowner: "landowner",
[t("myrepresentations:capacity-options-arr-appellant")
.toLowerCase()
.replace(/(\band|[\s\-\+\(\)\,\&])/g, "")]: "appellant",
[t("myrepresentations:capacity-options-arr-agent")
.toLowerCase()
.replace(/(\band|[\s\-\+\(\)\,\&])/g, "")]: "agent",
[t("myrepresentations:capacity-options-arr-interested")
.toLowerCase()
.replace(/(\band|[\s\-\+\(\)\,\&])/g, "")]: "interestedparty"
};
return capacityMap[normalized] || normalized || "false";
};
const getCasePath = () => {
switch (currentType) {
case "searchResultsObj":
return {
path: `$..[?(@ && @.title=="${caseReference}")]`,
json: setCaseQueryObj
};
case "watchedCases":
return {
path: `$..[?(@ && @.ticketnumber=="${caseReference}")]`,
json: watchedCases
};
default:
return {
path: `$..[?(@ && @.ticketnumber=="${ticketnumber}")]`,
json: setCaseQueryObj
};
}
};
const { path, json } = getCasePath();
casesObj = jsonpath({ path, json, eval: true });
casesObj = Object.assign({}, ...casesObj);
var detailsObj = {};
const isAppellant =
props.props.accountDetails.accountDetails.pinswg_typeofinvolvement ===
846040001;
const capacityOptionsArr = [];
isAppellant &&
capacityOptionsArr.push(
t("myrepresentations:capacity-options-arr-appellant")
);
const shouldIncludeInterested =
appealType !== 846040017 ||
caseReferenceObj.specialistProcess !== 846040000;
if (shouldIncludeInterested) {
capacityOptionsArr.push(
t("myrepresentations:capacity-options-arr-interested"),
t("myrepresentations:capacity-options-arr-agent")
);
}
const isEditState = router.query.state === "edit";
const hasState = router.query.hasOwnProperty("state");
const { caseDetailsSource, caseResultsSource } =
resolveInitialCaseDataSources({
hasState,
isEditState,
currentType: props.currentType,
myRepresentations: props.props.myRepresentations.myRepresentations,
searchDetailsObj: props.props.searchResultsObj.searchDetailsObj,
searchResultsObj: props.props.searchResultsObj.searchResultsObj,
watchedCasesDetails: props.props.watchedCases.watchedCasesDetails
});
let resultsObj = findResultsObjForCurrentReference({
"currentReference": currentView.caseReference.currentReference,
"caseResultsSource": caseResultsSource
});
// let detailsObj;
detailsObj = findDetailsObjForView({
hasState,
isEditState,
"queryCreated": router.query.created,
"ticketnumber": currentView.caseReference.ticketnumber,
"caseDetailsSource": caseDetailsSource
});
const safeDetailsObj = detailsObj || {};
const safeResultsObj = resultsObj || {};
// blocked out build reps arr for refactoring
// const buildRepsArr = (detailsObj) => {
// const buildArr = [];
// const todaysDate = new Date();
// const isDNS = appealType === 846040011;
// const isSIPS = appealType === 846040002;
// const isIP = true;
// const isAppellant =
// props.props.accountDetails.accountDetails
// .pinswg_typeofinvolvement === 846040001;
// // Determine key dates based on appeal type
// const startDate = new Date(
// isDNS
// ? detailsObj.pinswg_applicationacceptedasvalid
// : detailsObj.pinswg_startdate || detailsObj.pinswg_startdates
// );
// const questionnaireDate = new Date(
// isDNS
// ? detailsObj.pinswg_endofrepresentationperiod
// : detailsObj.pinswg_questionnaireduedate
// );
// questionnaireDate.setHours(23, 59, 59, 999);
// const finalCommentsDate = new Date(
// isDNS
// ? detailsObj.pinswg_endofrepresentationperiod
// : detailsObj.pinswg_finalcommentsduedate
// );
// finalCommentsDate.setHours(23, 59, 59, 999);
// const statementDueDate = new Date(
// isDNS
// ? detailsObj.pinswg_endofrepresentationperiod
// : detailsObj.pinswg_statementduedate ||
// detailsObj.pinswg_statementsduedate
// );
// statementDueDate.setHours(23, 59, 59, 999);
// // Shared condition
// const isWithin = (start, end) =>
// todaysDate >= start && todaysDate <= end;
// const notAppeal = (...types) => !types.includes(appealType);
// // Questionnaire
// if (
// isLPA &&
// notAppeal(846040019, 846040011, 846040015, 846040016) &&
// isWithin(startDate, finalCommentsDate)
// ) {
// buildArr.push("Questionnaire");
// }
// // DNS LPA Documents
// if (
// isLPA &&
// isDNS &&
// appealType !== 846040019 &&
// isWithin(startDate, finalCommentsDate)
// ) {
// buildArr.push("Local Impact Report", "Statement");
// }
// // Non-DNS Statement
// if (
// !isDNS &&
// appealType !== 846040004 &&
// isWithin(startDate, statementDueDate)
// ) {
// buildArr.push("Statement");
// }
// // DNS Non-LPA Statement
// if (isDNS && !isLPA && isWithin(startDate, statementDueDate)) {
// buildArr.push("Statement");
// }
// // Final Comments
// const isSpecialistNonHearing =
// currentView.caseReference.specialistProcess !== 846040001;
// if (
// (appealType !== 846040004 ||
// (appealType === 846040015 && isSpecialistNonHearing)) &&
// isWithin(statementDueDate, finalCommentsDate)
// ) {
// buildArr.push("Final comments");
// }
// if (
// appealType === 846040004 &&
// isSpecialistNonHearing &&
// isWithin(statementDueDate, finalCommentsDate)
// ) {
// buildArr.push("Final comments");
// }
// // Remove "Statement" for LPA Advert Part 3 (no statement)
// if (
// isLPA &&
// appealType === 846040018 &&
// currentView.caseReference.specialistProcess === 846040000
// ) {
// const index = buildArr.indexOf("Statement");
// if (index !== -1) buildArr.splice(index, 1);
// }
// // SIPS-related documents
// if (isSIPS) {
// const capacity = repCapacityType();
// if (capacity === "appellant") {
// buildArr.push("Consultation Response");
// } else {
// buildArr.push("Consultation Response", "Local Impact Report");
// }
// if (isNRW) {
// buildArr.push("Marine Impact Report");
// }
// }
// return buildArr;
// };
const buildRepsArr = (detailsObj) => {
const buildArr = [];
const todaysDate = new Date();
const isDNS = appealType === 846040011;
const isSIPS = appealType === 846040002;
const specialistProcess = currentView.caseReference.specialistProcess;
const isSpecialistNonHearing = specialistProcess !== 846040001;
const involvementType =
props.props?.accountDetails?.accountDetails
?.pinswg_typeofinvolvement;
const isAppellant = involvementType === 846040001;
const isAgent = involvementType === 846040000;
const isIP = involvementType === 846040061;
//const isLPA = involvementType === 846040000;
const startDate = new Date(
isDNS
? detailsObj.pinswg_applicationacceptedasvalid
: detailsObj.pinswg_startdate || detailsObj.pinswg_startdates
);
const finalCommentsDate = new Date(
isDNS
? detailsObj.pinswg_endofrepresentationperiod
: detailsObj.pinswg_finalcommentsduedate
);
finalCommentsDate.setHours(23, 59, 59, 999);
const statementDueDate = new Date(
isDNS
? detailsObj.pinswg_endofrepresentationperiod
: detailsObj.pinswg_statementduedate ||
detailsObj.pinswg_statementsduedate
);
statementDueDate.setHours(23, 59, 59, 999);
const isWithin = (start, end) =>
todaysDate >= start && todaysDate <= end;
const addRep = (value) => {
if (!buildArr.includes(value)) {
buildArr.push(value);
}
};
const canAddQuestionnaire =
isLPA &&
![846040019, 846040011, 846040015, 846040016].includes(
appealType
) &&
isWithin(startDate, finalCommentsDate);
if (canAddQuestionnaire) {
addRep("Questionnaire");
}
const isLpaAdvertPart3NoStatement =
isLPA &&
appealType === 846040018 &&
specialistProcess === 846040000;
const canAddDnsLpaDocs =
isLPA &&
isDNS &&
appealType !== 846040019 &&
!isAppellant &&
isWithin(startDate, finalCommentsDate);
if (canAddDnsLpaDocs) {
addRep("Local Impact Report");
addRep("Statement");
}
const canAddStatementForNonDns =
!isDNS &&
appealType !== 846040004 &&
!isLpaAdvertPart3NoStatement &&
!isAppellant &&
isWithin(startDate, statementDueDate);
if (canAddStatementForNonDns) {
addRep("Statement");
}
const canAddStatementForDnsNonLpa =
isDNS &&
!isLPA &&
!isAppellant &&
isWithin(startDate, statementDueDate);
if (canAddStatementForDnsNonLpa) {
addRep("Statement");
}
const canSubmitFinalComments = isAppellant || isAgent || isIP || isLPA;
const canAddFinalComments =
canSubmitFinalComments &&
isWithin(statementDueDate, finalCommentsDate) &&
(appealType !== 846040004 || isSpecialistNonHearing);
// IP and Agents and LPA can do final comments.
if (canAddFinalComments) {
addRep("Final comments");
}
if (isSIPS) {
const capacity = repCapacityType();
addRep("Consultation Response");
if (capacity !== "appellant") {
addRep("Local Impact Report");
}
if (isNRW) {
addRep("Marine Impact Report");
}
}
return buildArr;
};
const repCapacityType = () => {
const repForm = formObj["representationForm"];
if (
!repForm ||
!repForm.values ||
!repForm.values.representationCapacity
) {
return false;
}
return repForm.values.representationCapacity
.replace(/(\band|[\s\-\+\(\)\,\&])/g, "")
.toLowerCase();
};
const whichControl = () => {
const commonProps = {
formObj,
setRepresentationCapacity,
setRepresentationSubmit,
onHandleSubmit,
currentView,
setSubmitBack,
props,
setRepFileName,
updateRepresentation,
setSavingStatus,
savingStatus,
setCurrentReference
};
const { controlKey } = resolveRepresentationControlKey({
"isLPA": isLPA,
"representationCapacity": currentView.representationCapacity,
"repDetailsCapacity":
currentView.caseReference?.repDetails?.representationCapacity,
"appealType": appealType,
"normalizeCapacity": normalizeCapacity
});
if (controlKey === "lpa-capacity-selection") {
return (