diff --git a/components/elements/index.js b/components/elements/index.js index 931edf43..3fcdda03 100644 --- a/components/elements/index.js +++ b/components/elements/index.js @@ -748,7 +748,7 @@ const RenderDatePicker = ({ : value : null } //{parseISO(value) || null} - className="govuk-input govuk-input--width-10" + className="govuk-input govuk-input--width-12" minDate={minDate} maxDate={maxDate} autoComplete="off" @@ -2179,7 +2179,8 @@ const RenderFileUpload = (field) => { ).then((data) => { console.log(data); let buildAppealFilesArray = []; - let values = field.form.appealForm.values; + //let values = field.form.appealForm.values; + let values = field.props.form.appealForm.values; let filesUploadObj = renamedAcceptedFiles; for (let key in filesUploadObj) { @@ -2434,6 +2435,18 @@ const RenderSubFields = ({ fields, meta: { touched, error }, ...custom }) => { const required = (value) => value ? undefined : t("newappeal:is-required-label"); + const email = (value) => { + let errors; + + const emailRegex = + /(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/gi; + + if (!emailRegex.test(value)) { + errors = t("newappeal:invalid-email-address-errormsg"); + } + return errors; + }; + //fields.push({}); fields.length == 0 && fields.push({}); return ( @@ -2445,40 +2458,75 @@ const RenderSubFields = ({ fields, meta: { touched, error }, ...custom }) => {
- - - - + +
))} diff --git a/components/myportal/advancedsearch.js b/components/myportal/advancedsearch.js index 87d56566..1525acbf 100644 --- a/components/myportal/advancedsearch.js +++ b/components/myportal/advancedsearch.js @@ -24,25 +24,15 @@ let AdvancedSearch = (props) => { //console.log("props here:", props.props); - const appealOptionsObj = _.isEmpty(props) - ? [{}] - : _.isEmpty(props.appealType) - ? [{}] - : _.isEmpty(props.appealType.appealTypeOptions) - ? [{}] - : _.isEmpty(props.appealType.appealTypeOptions.value) - ? [{}] - : props.appealType.appealTypeOptions.value; + const appealOptionsObj = + props?.appealType?.appealTypeOptions?.value?.length > 0 + ? props.appealType.appealTypeOptions.value + : [{}]; - let lpaOptionsObj = _.isEmpty(props) - ? [{}] - : _.isEmpty(props.LPAData) - ? [{}] - : _.isEmpty(props.LPAData.LPAData) - ? [{}] - : _.isEmpty(props.LPAData.LPAData) - ? [{}] - : props.LPAData.LPAData.value; + const lpaOptionsObj = + props?.LPAData?.LPAData?.value?.length > 0 + ? props.LPAData.LPAData.value + : [{}]; const RenderTextfield = ({ id, diff --git a/components/newappeal/buildcheckrow.js b/components/newappeal/buildcheckrow.js index 3934ed05..bfdc866b 100644 --- a/components/newappeal/buildcheckrow.js +++ b/components/newappeal/buildcheckrow.js @@ -317,11 +317,11 @@ let BuildCheckRow = (props) => { datafieldname[0].value ].map((tenant, index) => { console.log( - typeof tenant.pinswg_owners + typeof tenant.pinswg_owners_firstname ); - return typeof tenant.pinswg_owners != + return typeof tenant.pinswg_owners_firstname != "undefined" || - typeof tenant.pinswg_agriculturaltenantname != + typeof tenant.pinswg_agriculturaltenantname_firstname != "undefined" ? (
{ }} >
- {tenant.pinswg_agriculturaltenantname || - tenant.pinswg_owners} + {tenant?.pinswg_agriculturaltenantname_firstname && + tenant.pinswg_agriculturaltenantname_firstname + + " " + + tenant.pinswg_agriculturaltenantname_lastname} + + {tenant?.pinswg_owners_firstname && + tenant.pinswg_owners_firstname + + " " + + tenant.pinswg_owners_lastname}
Served:{" "} diff --git a/components/newappeal/buildfield.js b/components/newappeal/buildfield.js index 7e7649e3..5af2c197 100644 --- a/components/newappeal/buildfield.js +++ b/components/newappeal/buildfield.js @@ -17,246 +17,227 @@ import { } from "../elements"; export default function BuildField(props) { - let { t } = useTranslation(); + const { t } = useTranslation(); + const { locale } = useRouter(); - const router = useRouter(); - const { locale } = router; - const { fieldType, label, datafieldname, mandatoryFieldData } = props; - const parser = new DOMParser(); + // Destructure frequently used props for clarity + const { + fieldType, + label, + datafieldname, + picklistData, + validation, + hint, + maxFieldLength, + dateStart, + dateEnd, + documentTypeCode, + uploadCount, + setUploadCount, + setFileCount, + parentField, + parentFieldShowOnValue, + requiredDocumentValue, + requiredDocumentLabel, + setDocumentsList, + documentList, + maxSubField, + datafieldcontent, + } = props; - const whichFieldType = (classid) => { - //console.log(props.datafieldname, classid); + // Extract deeply nested props for convenience (avoid props.props.props all over) + // Defensive checks in case nested props don't exist + const appealType = props?.props?.props?.appealType || {}; + const form = props?.props?.props?.form || {}; + const formProps = props?.props?.props?.props?.form || {}; + const setFilesForAppeal = props?.props?.props?.setFilesForAppeal; + const accountDetails = props?.props?.props?.props?.accountDetails || {}; + const ticketnumber = appealType.caseReference?.ticketnumber || ""; + const fileList = appealType.fileList || {}; + const containerID = accountDetails.containerID || ""; - switch (classid) { - case "{270BD3DB-D9AF-4782-9025-509E298DEC0A}": - return ( - - ); - break; - case "{3EF39988-22BB-4f0b-BBBE-64B5A3748AEE}": - return ( - - ); - break; - case "{67FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED}": - return ( - - ); - break; - case "{07FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED}": - return ( - - ); - break; - case "{4273EDBD-AC1D-40d3-9FB2-095C621B552D}": - const required = (value) => - value ? undefined : t("newappeal:is-required-label"); - - return ( - - ); - break; - case "{5B773807-9FB2-42db-97C3-7A91EFF8ADFF}": - return ( - - ); - break; - case "{E0DECE4B-6FC8-4a8f-A065-082708572369}": - return ( - - ); - break; - case "{E0DECE4B-6666-4a8f-A065-082708572369}": - return ( - - ); - break; - case "{C6D124CA-7EDA-4a60-AEA9-7FB8D318B68F}": - return ( - - ); - break; - case "{C3EFE0C3-0EC6-42be-8349-CBD9079DFD8E}": - return ( - - ); - break; - case "{16D63FD6-119B-4353-BDCA-18358721C3FE}": - return ( -
- -
- ); - break; - - case "{0273EDBD-AC1D-40d3-9FB2-095C621B552D}": - return ( - - ); - case "{9EF39988-22BB-4f0b-BBBE-64B5A3748AEE}": - return ( - - ); - break; - default: - return ( - - ); - } + // Mapping fieldType to components + const fieldTypeMap = { + "{270BD3DB-D9AF-4782-9025-509E298DEC0A}": ( + + ), + "{3EF39988-22BB-4f0b-BBBE-64B5A3748AEE}": ( + + ), + "{67FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED}": ( + + ), + "{07FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED}": ( + + ), + "{4273EDBD-AC1D-40d3-9FB2-095C621B552D}": ( + + ), + "{5B773807-9FB2-42db-97C3-7A91EFF8ADFF}": ( + + ), + "{E0DECE4B-6FC8-4a8f-A065-082708572369}": ( + + ), + "{E0DECE4B-6666-4a8f-A065-082708572369}": ( + + ), + "{C6D124CA-7EDA-4a60-AEA9-7FB8D318B68F}": ( + + ), + "{C3EFE0C3-0EC6-42be-8349-CBD9079DFD8E}": ( + + ), + "{16D63FD6-119B-4353-BDCA-18358721C3FE}": ( +
+ +
+ ), + "{0273EDBD-AC1D-40d3-9FB2-095C621B552D}": ( + + ), + "{9EF39988-22BB-4f0b-BBBE-64B5A3748AEE}": ( + + ), }; return ( -
{whichFieldType(props.fieldType)}
+
+ {fieldTypeMap[fieldType] || ( + + )} +
); } diff --git a/components/newappeal/buildprogress.js b/components/newappeal/buildprogress.js index 1e4a1429..21ab30aa 100644 --- a/components/newappeal/buildprogress.js +++ b/components/newappeal/buildprogress.js @@ -4,31 +4,65 @@ import { connect } from "react-redux"; import { setCurrentSection } from "../../store/appealType/action"; import { FieldsTranslations } from "../elements"; -const BuildProgress = (props) => { - let { t } = useTranslation(); +const BuildProgress = ({ + progObj, + titleList, + currentSection, + documentListObj, + formObjXML, + mandatoryFieldsData, + gotoSection, + setCurrentSection, + props: outerProps, +}) => { + const { t } = useTranslation(); const router = useRouter(); const { locale } = router; - const { - progObj, - titleList, - currentSection, - documentListObj, - formObjXML, - mandatoryFieldsData, - gotoSection, - setCurrentSection, - } = props; - const parser = new DOMParser(); + // Helper to safely access nested form values + const getFormValue = (field) => + outerProps?.props?.form?.appealForm?.values?.[field]; - //const progObj = getProgressObj( - // formObjXML, - // titleList, - // mandatoryFieldsData, - // props - // ); + const renderDocumentList = () => { + const formValues = outerProps?.props?.form?.appealForm?.values || {}; - //console.log(progObj); + return ( + <> +
  • {t("newappeal:application-form")}
  • + + {formValues.pinswg_developmentdescriptionchanged === "true" && ( +
  • Description of development change confirmation
  • + )} + + {formValues.pinswg_caseworkreason === "846040005" && ( +
  • {t("newappeal:registration-of-application-letter")}
  • + )} + + {formValues.pinswg_caseworkreason === "846040000" && ( +
  • Decision notice
  • + )} + + {formValues.pinswg_attachsoc === "true" && ( +
  • {t("newappeal:statement-of-case")}
  • + )} + + {formValues.pinswg_attachcostapplication === "true" && ( +
  • {t("newappeal:cost-application")}
  • + )} + + {formValues.pinswg_s106unilateralsubmitted === "true" && ( +
  • Planning obligation (S106/Unilateral)
  • + )} + + {/* Additional document list items from documentListObj if needed */} + {/* {Object.entries(documentListObj).map(([key, value]) => ( +
  • {value}
  • + ))} */} + +
  • {t("newappeal:site-location-plan")}
  • + + ); + }; return ( <> @@ -40,16 +74,17 @@ const BuildProgress = (props) => {

    {t("newappeal:new-appeal-progress-nav-label")}:{" "} - {props.props.appealType.caseReference.ticketnumber} + { + outerProps?.props?.appealType?.caseReference + ?.ticketnumber + }

    - {/*
    */} - + + ); + })}
    -
    +

    {t("newappeal:new-appeal-documentlist-nav")}:


      -
        -
      • -
          -
        1. {t("newappeal:application-form")}
        2. - - {props.props.props.form.hasOwnProperty( - "appealForm" - ) && - props.props.props.form[ - "appealForm" - ].hasOwnProperty("values") && - props.props.props.form[ - "appealForm" - ].values.hasOwnProperty( - "pinswg_developmentdescriptionchanged" - ) - ? props.props.props.form["appealForm"] - .values - .pinswg_developmentdescriptionchanged == - "true" && ( -
        3. - Description of development change - confirmation -
        4. - ) - : ""} - - {props.props.props.form.hasOwnProperty( - "appealForm" - ) && - props.props.props.form[ - "appealForm" - ].hasOwnProperty("values") && - props.props.props.form[ - "appealForm" - ].values.hasOwnProperty("pinswg_caseworkreason") - ? props.props.props.form["appealForm"] - .values.pinswg_caseworkreason == - "846040005" && ( -
        5. - {t( - "newappeal:registration-of-application-letter" - )} -
        6. - ) - : ""} - - {props.props.props.form.hasOwnProperty( - "appealForm" - ) && - props.props.props.form[ - "appealForm" - ].hasOwnProperty("values") && - props.props.props.form[ - "appealForm" - ].values.hasOwnProperty("pinswg_caseworkreason") - ? props.props.props.form["appealForm"] - .values.pinswg_caseworkreason == - "846040000" && ( -
        7. Decision notice
        8. - ) - : ""} - - {props.props.props.form.hasOwnProperty( - "appealForm" - ) && - props.props.props.form[ - "appealForm" - ].hasOwnProperty("values") && - props.props.props.form[ - "appealForm" - ].values.hasOwnProperty("pinswg_attachsoc") - ? props.props.props.form["appealForm"] - .values.pinswg_attachsoc == - "true" && ( -
        9. - {t("newappeal:statement-of-case")} -
        10. - ) - : ""} - - {props.props.props.form.hasOwnProperty( - "appealForm" - ) && - props.props.props.form[ - "appealForm" - ].hasOwnProperty("values") && - props.props.props.form[ - "appealForm" - ].values.hasOwnProperty( - "pinswg_attachcostapplication" - ) - ? props.props.props.form["appealForm"] - .values - .pinswg_attachcostapplication == - "true" && ( -
        11. - {t("newappeal:cost-application")} -
        12. - ) - : ""} - - {props.props.props.form.hasOwnProperty( - "appealForm" - ) && - props.props.props.form[ - "appealForm" - ].hasOwnProperty("values") && - props.props.props.form[ - "appealForm" - ].values.hasOwnProperty( - "pinswg_s106unilateralsubmitted" - ) - ? props.props.props.form["appealForm"] - .values - .pinswg_s106unilateralsubmitted == - "true" && ( -
        13. - Planning obligation - (S106/Unilateral) -
        14. - ) - : ""} - - {/* {Object.keys(documentListObj).length > 0 && - Object.entries(documentListObj).map( - ([key, value]) => { - return
        15. {value}
        16. ; - } - )} */} - -
        17. {t("newappeal:site-location-plan")}
        18. -
        -
      • -
      +
    1. +
        + {renderDocumentList()} +
      +
    -
    + ); }; -const mapStateToProps = (state) => { - return { - search: state.search, - searchResultsObj: state.searchResultsObj, - formData: state.formData, - appealType: state.appealType, - initialValues: state.appealType.caseReference.caseDetails, - //form: state.form, - }; -}; +const mapStateToProps = (state) => ({ + search: state.search, + searchResultsObj: state.searchResultsObj, + formData: state.formData, + appealType: state.appealType, + initialValues: state.appealType.caseReference.caseDetails, + //form: state.form, +}); -const mapDispatchToProps = (dispatch) => { - return { - gotoSection: (thisSection) => { - dispatch(setCurrentSection(thisSection)); - }, - }; -}; +const mapDispatchToProps = (dispatch) => ({ + gotoSection: (thisSection) => dispatch(setCurrentSection(thisSection)), +}); export default connect(mapStateToProps, mapDispatchToProps)(BuildProgress); diff --git a/components/newappeal/createCase.js b/components/newappeal/createCase.js index b7b29e07..8162e03b 100644 --- a/components/newappeal/createCase.js +++ b/components/newappeal/createCase.js @@ -376,25 +376,15 @@ let CreateCase = (props) => { const { LPAData, onSubmit, handleSubmit, formData } = props; - const appealOptionsObj = _.isEmpty(props) - ? [{}] - : _.isEmpty(props.appealType) - ? [{}] - : _.isEmpty(props.appealType.appealTypeOptions) - ? [{}] - : _.isEmpty(props.appealType.appealTypeOptions.value) - ? [{}] - : props.appealType.appealTypeOptions.value; + const appealOptionsObj = + props?.appealType?.appealTypeOptions?.value?.length > 0 + ? props.appealType.appealTypeOptions.value + : [{}]; - let lpaOptionsObj = _.isEmpty(props) - ? [{}] - : _.isEmpty(props.LPAData) - ? [{}] - : _.isEmpty(props.LPAData.LPAData) - ? [{}] - : _.isEmpty(props.LPAData.LPAData) - ? [{}] - : props.LPAData.LPAData.value; + const lpaOptionsObj = + props?.LPAData?.LPAData?.value?.length > 0 + ? props.LPAData.LPAData.value + : [{}]; const required = (value) => (value ? undefined : "Required"); diff --git a/components/pdftemplates/appealRow_pdf.js b/components/pdftemplates/appealRow_pdf.js index 06609d61..f83d2f58 100644 --- a/components/pdftemplates/appealRow_pdf.js +++ b/components/pdftemplates/appealRow_pdf.js @@ -526,8 +526,22 @@ export const AppealRow_pdf = (props) => { "20", }} > - {tenant.pinswg_agriculturaltenantname || - tenant.pinswg_owners} + {tenant?.pinswg_agriculturaltenantname_firstname && + tenant.pinswg_agriculturaltenantname_firstname + + " " + + tenant.pinswg_agriculturaltenantname_lastname} + + {tenant?.pinswg_owners_firstname && + tenant.pinswg_owners_firstname + + " " + + tenant.pinswg_owners_lastname} + { + " " + } + {tenant?.pinswg_owners_email && + tenant.pinswg_owners_email} + {tenant?.pinswg_agriculturaltenantname_email && + tenant.pinswg_agriculturaltenantname_email} { submitting, } = props; - const appealOptionsObj = _.isEmpty(props) - ? [{}] - : _.isEmpty(props.appealType) - ? [{}] - : _.isEmpty(props.appealType.appealTypeOptions) - ? [{}] - : _.isEmpty(props.appealType.appealTypeOptions.value) - ? [{}] - : props.appealType.appealTypeOptions.value; + const appealOptionsObj = + props?.appealType?.appealTypeOptions?.value?.length > 0 + ? props.appealType.appealTypeOptions.value + : [{}]; - const projecttypeOptionsObj = _.isEmpty(props) - ? [{}] - : _.isEmpty(props.appealType) - ? [{}] - : _.isEmpty(props.appealType.projectTypeOptions) - ? [{}] - : _.isEmpty(props.appealType.projectTypeOptions.value) - ? [{}] - : props.appealType.projectTypeOptions.value; + const projecttypeOptionsObj = + props?.appealType?.projectTypeOptions?.value?.length > 0 + ? props.appealType.projectTypeOptions.value + : [{}]; - let lpaOptionsObj = _.isEmpty(props) - ? [{}] - : _.isEmpty(props.LPAData) - ? [{}] - : _.isEmpty(props.LPAData.LPAData) - ? [{}] - : _.isEmpty(props.LPAData.LPAData) - ? [{}] - : props.LPAData.LPAData.value; + const lpaOptionsObj = + props?.LPAData?.LPAData?.value?.length > 0 + ? props.LPAData.LPAData.value + : [{}]; const RenderLPAList = ({ name, diff --git a/locales/cy/newappeal.json b/locales/cy/newappeal.json index 3fc577ac..a7ff3284 100644 --- a/locales/cy/newappeal.json +++ b/locales/cy/newappeal.json @@ -119,5 +119,6 @@ "previously-added-files": "Ffeiliau wedi'u llwytho i fyny", "new-appeal-finalising-heading": "Cwblhau cyflwyniad eich apĂȘl", "new-appeal-finalising-label": "Wrthi'n uwchlwytho ffeiliau ar hyn o bryd a chwblhau eich cyflwyniad apĂȘl", - "new-appeal-wait-label": "Arhoswch os gwelwch yn dda" + "new-appeal-wait-label": "Arhoswch os gwelwch yn dda", + "invalid-email-address-errormsg": "Cyfeiriad e-bost annilys" } \ No newline at end of file diff --git a/locales/en/newappeal.json b/locales/en/newappeal.json index 0dbdb358..7efe0599 100644 --- a/locales/en/newappeal.json +++ b/locales/en/newappeal.json @@ -119,5 +119,6 @@ "previously-added-files": "Uploaded files", "new-appeal-finalising-heading": "Finalising your appeal submission", "new-appeal-finalising-label": "Currently uploading files and finalising your appeal submission", - "new-appeal-wait-label": "Please wait" + "new-appeal-wait-label": "Please wait", + "invalid-email-address-errormsg": "Invalid email address" } \ No newline at end of file diff --git a/pages/_document.js b/pages/_document.js index c83ef42a..03d9d7e6 100644 --- a/pages/_document.js +++ b/pages/_document.js @@ -41,7 +41,7 @@ class MyDocument extends Document { //const generatedNonce = nanoid(); const generatedNonce = this.props.generatedNonce; - console.log("this is the nonce:", generatedNonce); + //console.log("this is the nonce:", generatedNonce); let csp = ``; csp += `base-uri 'self';`; diff --git a/pages/myportal/index.js b/pages/myportal/index.js index fa4e3ab1..5ba7fb94 100644 --- a/pages/myportal/index.js +++ b/pages/myportal/index.js @@ -1,4 +1,3 @@ -import _ from "lodash"; import { getSession, useSession } from "next-auth/react"; import useTranslation from "next-translate/useTranslation"; import Head from "next/head"; @@ -6,7 +5,6 @@ import { useRouter } from "next/router"; import { connect } from "react-redux"; import { createContainerProxy, - getAwaitingSubmission, getAwaitingSubmissionFromBlob, getCase, getIP, @@ -30,15 +28,10 @@ import { setLoggedInUserId, } from "../../store/accountDetails/action"; import { - setAwaitingSubmission, setAwaitingSubmissionDetails, setAwaitingSubmissionFromBlob, } from "../../store/awaitingSubmission/action"; -import { - setShowReps, - setLocale, - setFilesForRepresentation, -} from "../../store/currentView/action"; +import { setShowReps, setLocale } from "../../store/currentView/action"; import { setMyCases, setMyCasesDetails } from "../../store/myCases/action"; import { setMyRepresentations, @@ -56,7 +49,6 @@ import pLimit from "p-limit"; const Home = (props) => { const { footerLinks, - pages, myCases, myRepresentations, watchedCases, @@ -67,13 +59,11 @@ const Home = (props) => { currentView, mySubmittedReps, } = props; - let { t, lang } = useTranslation(); - - // const mySubmittedReps = myRepresentations.mySubmittedReps; + const { t } = useTranslation(); const router = useRouter(); - const { locale } = router; - const { appealtypes } = router.query; + const { locale, query } = router; + const { appealtypes } = query; const { data: session } = useSession(); @@ -91,9 +81,8 @@ const Home = (props) => { - {/* If they have a Twitter Handle, include the meta details below */} { export const getServerSideProps = wrapper.getServerSideProps( (store) => async (ctx) => { - const { query, req, res } = ctx; + const { query, req, locale } = ctx; getIP(req); - console.log("The query", query); - const { cookies } = req; - - let loggedInUserCookie = cookies.pinsUser; - - let thisSession = await getSession(ctx); - let loggedInUser = {}; + const cookies = req.cookies || {}; + const thisSession = await getSession(ctx); if (!thisSession) { - console.log("not has sesssion......."); return { redirect: { destination: "/auth/signin", permanent: false, }, }; - } else { - console.log(" has sesssion......."); - [loggedInUser] = await Promise.all([ - await getPortalLogin(thisSession.user.email), - ]); - - //grabs first contact on this list - - //jump out page for duplicates.... - - console.log( - "Number of contacts with this email:", - loggedInUser.value.length - ); - if (loggedInUser.value.length > 1) { - return { - redirect: { - destination: - ctx.locale == "cy" - ? "/cy/manylionpellach" - : "/furtherdetails", - permanent: false, - }, - }; - } - loggedInUser = loggedInUser.value[0].contactid; - //console.log("nextAuth Session:", thisSession); } - //Create Storage container for logged in user - await createContainerProxy(thisSession.user.id); + const loggedInUserResponse = await getPortalLogin( + thisSession.user.email + ); + const contacts = loggedInUserResponse?.value || []; + + if (contacts.length > 1) { + return { + redirect: { + destination: + locale === "cy" + ? "/cy/manylionpellach" + : "/furtherdetails", + permanent: false, + }, + }; + } + + const loggedInUser = contacts[0]?.contactid; + + await createContainerProxy(thisSession.user.id); const accountDetails = await getPersonalAccount(loggedInUser); - //console.log("----------", accountDetails); - - const lpaid = + const lpaId = accountDetails[ "pinswg_contact_associatedlpa@OData.Community.Display.V1.FormattedValue" ]; + const isLPA = accountDetails.pinswg_typeofinvolvement === 846040012; + + // Fetch cases, reps, watched cases, awaiting submission concurrently const [ myCases, myRepresentations, watchedCases, - //awaitingSubmission, awaitingSubmissionFromBlob, ] = await Promise.all([ - accountDetails.pinswg_typeofinvolvement == 846040012 - ? await getMyLPACases(lpaid) - : await getMyCases(loggedInUser), - - await getRepsFromBlob(thisSession.user.id), - await getWatchedCases(loggedInUser), - //await getAwaitingSubmission(loggedInUser), - await getAwaitingSubmissionFromBlob(thisSession.user.id), + isLPA ? getMyLPACases(lpaId) : getMyCases(loggedInUser), + getRepsFromBlob(thisSession.user.id), + getWatchedCases(loggedInUser), + getAwaitingSubmissionFromBlob(thisSession.user.id), ]); - //console.log( - // "/////////////////////////\n ", - // awaitingSubmissionFromBlob.value, - // awaitingSubmissionFromBlob.case - // ); - - console.log( - "preferred language:", - accountDetails.pinswg_preferredlanguage - ); - - console.log( - "locale :", - accountDetails.pinswg_preferredlanguage == "846040000" ? "cy" : "en" - ); - - console.log("req locale :", ctx.locale); - console.log("cookie locale :", cookies.pedw_locale); - - store.dispatch(setLocale(ctx.locale)); + // Set locale to store + store.dispatch(setLocale(locale)); + // Determine preferred locale (cookie overrides) let preferredLocale = - accountDetails.pinswg_preferredlanguage == "846040000" + accountDetails.pinswg_preferredlanguage === "846040000" ? "cy" : "en"; + if (cookies.pedw_locale) { + preferredLocale = cookies.pedw_locale; + } - // added to redirect if not the users preferred language - cookies.hasOwnProperty("pedw_locale") && - (preferredLocale = cookies.pedw_locale); - - if (preferredLocale != ctx.locale) { + if (preferredLocale !== locale) { return { redirect: { destination: `/${preferredLocale}`, @@ -286,290 +238,141 @@ export const getServerSideProps = wrapper.getServerSideProps( }; } - const showLoginCheck = process.env.SHOWLOGIN || false; - const showMapCheck = process.env.SHOWMAPS || false; - const showReps = process.env.SHOWREPRESENTATIONS || false; + const showLoginCheck = Boolean(process.env.SHOWLOGIN); + const showReps = Boolean(process.env.SHOWREPRESENTATIONS); store.dispatch(setShowReps(showReps, showLoginCheck)); - let showWatchedCases = (submittedArr) => { - const required = submittedArr.value.filter((el) => { - return el.pinswg_representationsubmitted == null; - }); - - let newObj = {}; - return Object.assign(newObj, { - "@odata.count": required.length, - "value": required, - }); + // Filter watched cases where reps not submitted + const filteredWatchedCases = { + "@odata.count": watchedCases.value.filter( + (c) => c.pinswg_representationsubmitted == null + ).length, + value: watchedCases.value.filter( + (c) => c.pinswg_representationsubmitted == null + ), }; - let filteredWatchedCases = showWatchedCases(watchedCases); + // Get submitted reps from watched cases + const mySubmittedReps = watchedCases.value.filter((el) => { + return el.pinswg_representationsubmitted != null; + }); - let showSubmittedReps = (submittedArr) => { - submittedArr = submittedArr.value; - const required = submittedArr.filter((el) => { - let IsSubmittedRep = _.has(el, "pinswg_representationsubmitted") - ? el.pinswg_representationsubmitted != null && - el.pinswg_representationsubmitted - : ""; - return IsSubmittedRep; - }); - return required; - }; - - const mySubmittedReps = showSubmittedReps(watchedCases); - - if (_.has(accountDetails, "errorCode") != false) { + if (accountDetails.errorCode) { return { redirect: { destination: "/myportal/error", permanent: false, }, }; - } else { - const [ - myCasesDetails, - watchedCasesDetails, - mySubmittedRepsDetails, - myRepresentationsDetails, - ] = await Promise.all([ - await getDetails(myCases, "myCases"), - await getDetails(filteredWatchedCases, "myWatchedCases"), - await getDetails(mySubmittedReps, "mySubmittedReps"), - await getDetails(myRepresentations, "myRepresentations"), - ]); - - // console.log( - // "=================================\nmySubmittedRepsDetails:", - // mySubmittedRepsDetails - // ); - - store.dispatch(setAccountDetails(accountDetails)); - store.dispatch(setLoggedInUserId(loggedInUser)); - store.dispatch(setMyCases(myCases)); - store.dispatch(setMyCasesDetails(myCasesDetails)); - store.dispatch(setMyRepresentations(myRepresentations)); - store.dispatch( - setMyRepresentationsDetails(myRepresentationsDetails) - ); - - store.dispatch(setWatchedCases(filteredWatchedCases)); - store.dispatch(setWatchedCasesDetails(watchedCasesDetails)); - store.dispatch(setMySubmittedReps(mySubmittedReps)); - store.dispatch(setMySubmittedRepsDetails(mySubmittedRepsDetails)); - //store.dispatch(setAwaitingSubmission(awaitingSubmission)); - store.dispatch( - setAwaitingSubmissionFromBlob(awaitingSubmissionFromBlob) - ); - - store.dispatch( - setAwaitingSubmissionDetails(awaitingSubmissionFromBlob) - ); - store.dispatch(setContainerID(thisSession.user.id)); - - return { - props: { - showFileUpload: process.env.SHOWFILEUPLOAD, - containerID: thisSession.user.id, - showLoginCheck: process.env.SHOWLOGIN, - }, - }; } + + // Helper function for fetching details with concurrency limit + const getDetails = async (resultsObj, detailsType) => { + const limitRequests = pLimit(5); + const arr = []; + resultsObj = + detailsType === "mySubmittedReps" + ? resultsObj + : resultsObj.value; + + const tasks = resultsObj.map((item) => + limitRequests(async () => { + try { + let caseID = ""; + switch (detailsType) { + case "myCases": + caseID = item.pinswg_title; + break; + case "myWatchedCases": + case "mySubmittedReps": + caseID = + item[ + "_pinswg_watchedcase_value@OData.Community.Display.V1.FormattedValue" + ]; + break; + case "awaitingSubmission": + caseID = item.ticketnumber; + break; + case "myRepresentations": + caseID = item.casereference; + break; + default: + caseID = item.pinswg_title; + } + + if (!item.pinswg_appealcasetype) return; + + const collectionName = getFormCollectionByID( + item.pinswg_appealcasetype + ).LogicalCollectionName; + const details = await getPortalModuleDetails( + collectionName, + caseID + ); + arr.push(details); + } catch (err) { + console.error("Error fetching details:", err); + } + }) + ); + + await Promise.all(tasks); + return arr; + }; + + const [ + myCasesDetails, + watchedCasesDetails, + mySubmittedRepsDetails, + myRepresentationsDetails, + ] = await Promise.all([ + getDetails(myCases, "myCases"), + getDetails(filteredWatchedCases, "myWatchedCases"), + getDetails(mySubmittedReps, "mySubmittedReps"), + getDetails(myRepresentations, "myRepresentations"), + ]); + + store.dispatch(setAccountDetails(accountDetails)); + store.dispatch(setLoggedInUserId(loggedInUser)); + store.dispatch(setMyCases(myCases)); + store.dispatch(setMyCasesDetails(myCasesDetails)); + store.dispatch(setMyRepresentations(myRepresentations)); + store.dispatch(setMyRepresentationsDetails(myRepresentationsDetails)); + store.dispatch(setWatchedCases(filteredWatchedCases)); + store.dispatch(setWatchedCasesDetails(watchedCasesDetails)); + store.dispatch(setMySubmittedReps(mySubmittedReps)); + store.dispatch(setMySubmittedRepsDetails(mySubmittedRepsDetails)); + store.dispatch( + setAwaitingSubmissionFromBlob(awaitingSubmissionFromBlob) + ); + store.dispatch( + setAwaitingSubmissionDetails(awaitingSubmissionFromBlob) + ); + store.dispatch(setContainerID(thisSession.user.id)); + + return { + props: { + showFileUpload: Boolean(process.env.SHOWFILEUPLOAD), + containerID: thisSession.user.id, + showLoginCheck, + }, + }; } ); -// const getDetails = async (resultsObj, detailsType) => { -// let detailsArr = []; -// const limitRequests = pLimit(1); // Limit to 5 concurrent requests - -// resultsObj = -// detailsType == "mySubmittedReps" ? resultsObj : resultsObj.value; - -// if (detailsType == "myRepresentations") { -// limitRequests(async () => { -// resultsObj.map((searchDetail, index) => { -// detailsArr.push( -// getCase(searchDetail["incidentID"]) -// .then(async (data) => { -// let caseID = ""; - -// switch (detailsType) { -// case "myCases": -// caseID = data.pinswg_title; -// break; -// case "myWatchedCases": -// case "mySubmittedReps": -// caseID = -// data[ -// "_pinswg_watchedcase_value@OData.Community.Display.V1.FormattedValue" -// ]; -// break; -// case "awaitingSubmission": -// case "myRepresentations": -// try { -// caseID = data.ticketnumber; -// } catch { -// console.log("missing:", data); -// } - -// break; -// default: -// caseID = data.pinswg_title; -// } -// return await getPortalModuleDetails( -// getFormCollectionByID( -// data.pinswg_appealcasetype -// ).LogicalCollectionName, -// caseID -// ).catch((error) => { -// console.log( -// "=============================\ngetPortalModuleDetails error", -// error -// ); -// }); -// }) -// .catch((error) => { -// console.log( -// "=============================\ngetCase error", -// error -// ); -// }) -// ); -// }); -// }); -// } -// //debugger; -// await Promise.all( -// resultsObj.map(async (searchDetail, index) => { -// limitRequests(async () => { -// try { -// let caseID = ""; - -// switch (detailsType) { -// case "myCases": -// caseID = searchDetail.pinswg_title; -// break; -// case "myWatchedCases": -// case "mySubmittedReps": -// caseID = -// searchDetail[ -// "_pinswg_watchedcase_value@OData.Community.Display.V1.FormattedValue" -// ]; -// break; -// case "awaitingSubmission": -// caseID = searchDetail.ticketnumber; -// break; -// case "myRepresentations": -// caseID = searchDetail.casereference; -// break; -// default: -// caseID = searchDetail.pinswg_title; -// } - -// console.log(detailsType, " case id : ", caseID); - -// searchDetail.pinswg_appealcasetype != null && -// detailsArr.push( -// getPortalModuleDetails( -// getFormCollectionByID( -// searchDetail.pinswg_appealcasetype -// ).LogicalCollectionName, -// caseID -// ) -// ); -// } catch (error) { -// console.log("Error processing case:", error); -// } -// }); -// }) -// ); - -// let detArr = Promise.all(detailsArr); -// // console.log(detArr); -// return detArr; -// }; - -const getDetails = async (resultsObj, detailsType) => { - let detailsArr = []; - const limitRequests = pLimit(5); // Allow up to 5 concurrent requests - - // Adjust resultsObj based on detailsType - resultsObj = - detailsType === "mySubmittedReps" ? resultsObj : resultsObj.value; - - const getDetailsForCase = async (searchDetail) => { - try { - let caseID = ""; - - // Determine the case ID based on the detailsType - switch (detailsType) { - case "myCases": - caseID = searchDetail.pinswg_title; - break; - case "myWatchedCases": - case "mySubmittedReps": - caseID = - searchDetail[ - "_pinswg_watchedcase_value@OData.Community.Display.V1.FormattedValue" - ]; - break; - case "awaitingSubmission": - caseID = searchDetail.ticketnumber; - break; - case "myRepresentations": - caseID = searchDetail.casereference; - break; - default: - caseID = searchDetail.pinswg_title; - } - - console.log(detailsType, " case id: ", caseID); - - // If the appeal case type is valid, fetch the portal module details - if (searchDetail.pinswg_appealcasetype != null) { - const formCollectionName = getFormCollectionByID( - searchDetail.pinswg_appealcasetype - ).LogicalCollectionName; - - const details = await getPortalModuleDetails( - formCollectionName, - caseID - ); - detailsArr.push(details); - } - } catch (error) { - console.log("Error processing case:", error); - } - }; - - // Use limitRequests to manage concurrency - const promises = resultsObj.map((searchDetail) => { - return limitRequests(() => getDetailsForCase(searchDetail)); - }); - - // Wait for all the requests to complete - await Promise.all(promises); - - return detailsArr; -}; - -const mapStateToProps = (state) => { - //console.log(state); - - return { - accountDetails: state.accountDetails, - currentView: state.currentView, - search: state.search, - searchResultsObj: state.searchResultsObj, - formData: state.formData, - appealType: state.appealType, - form: state.form, - myCases: state.myCases, - watchedCases: state.watchedCases, - myRepresentations: state.myRepresentations, - mySubmittedReps: state.myRepresentations.mySubmittedReps, - awaitingSubmission: state.awaitingSubmission, - }; -}; +const mapStateToProps = (state) => ({ + accountDetails: state.accountDetails, + currentView: state.currentView, + search: state.search, + searchResultsObj: state.searchResultsObj, + formData: state.formData, + appealType: state.appealType, + form: state.form, + myCases: state.myCases, + watchedCases: state.watchedCases, + myRepresentations: state.myRepresentations, + mySubmittedReps: state.myRepresentations.mySubmittedReps, + awaitingSubmission: state.awaitingSubmission, +}); export default connect(mapStateToProps)(Home);