Files
pedwfrontend/lib/representation/pageLoaders.js
T
Robert Bond 37a81522d5 Merged PR 2260: refactor(representations): complete slice-based refactor of representations flow
## Representations Refactor — Behaviour-Preserving Structural Improvements

This PR delivers a full refactor of the representations flow, improving structure, readability, and maintainability while preserving all existing behaviour.

The work was completed using a controlled, slice-based approach with strict guardrails and regression validation at each step. No changes have been made to user journeys, payloads, routing, or EN/CY behaviour.

The result is a cleaner, more maintainable codebase with reduced coupling and clearer separation of concerns, ready for future enhancements without increased risk.

---

## What Was Done

The refactor was delivered incrementally across the following slices:

- **R1** — Representation entry logic extraction
- **R2** — Page loader separation (SSR/data orchestration)
- **R3** — Journey step resolution extraction
- **R4** — Flow shell decomposition
- **R5** — Representation elements normalisation
- **R6** — Data/service layer cleanup
- **R7** — Summary rendering proof slice
- **R8** — Submission/finalisation boundary isolation
- **R9** — Summary rollout (Batch 1)

Each slice:
- was isolated to a single concern
- followed strict guardrails
- was validated before merge

Full detail is available in:
`context/representations-refactor-tracker.md`

---

## Key Improvements

- Reduced coupling across the representations journey
- Separated data loading, orchestration, and rendering concerns
- Simplified complex conditional logic into testable helpers
- Standardised summary rendering using shared primitives (`SummaryCard`, `SummaryRow`)
- Isolated submission/finalisation sequencing into explicit boundaries
- Improved overall readability and maintainability

---

## Behaviour Preservation

This refactor does **not** change:

- User journeys (APP / IP / Agent / LPA)
- Route and query behaviour
- Payload contracts and API interactions
- Redux state shape and usage
- Validation rules and messaging
- EN/CY behaviour
- File upload / PDF / email sequencing
- Linked-case logic

All changes are structural only.

---

## Validation

### Automated

- `npm run lint` — passed (warnings only, no new errors)
- `npm run test:reps` — passed (7/7)

### Manual

Validated end-to-end across:

- APP
- IP
- Agent
- LPA

Including:

- representation creation
- editing/resuming representations
- submission flow
- confirmation/completion behaviour
- summary rendering across case types
- EN/CY parity

---

## Risk Management

The refactor targeted several high-risk areas:

- Case summary entry logic
- Representation submission/finalisation sequencing
- Dual-mode entry (new vs existing representation)

Risk was controlled through:

- small, incremental slices
- one branch per slice
- regression validation per slice
- strict behaviour-preservation guardrails
- controlled rollout for summary rendering changes

---

## Reviewer Guidance

Suggested areas to focus on:

- End-to-end representation journey (create → submit → complete)
- S...
2026-04-20 13:09:07 +00:00

271 lines
8.1 KiB
JavaScript

import { getSession } from "next-auth/react";
import {
getPersonalAccount,
getPortalLogin
} from "../../actions/services/accountService";
import {
getCase,
getPortalModuleDetails
} from "../../actions/services/caseService";
import { getRepsFromBlob } from "../../actions/services/documentService";
import { getBasicSearch } from "../../actions/services/searchService";
import {
getFormCollectionByID,
getSearchDetails
} from "../../components/utils";
import {
setAccountDetails,
setContainerID
} from "../../store/accountDetails/action";
import {
setCurrentReference,
setCurrentView,
setFilesForRepresentations,
setRepresentationCapacity
} from "../../store/currentView/action";
import {
setMyRepresentations,
setMyRepresentationsDetails
} from "../../store/myRepresentations/action";
import {
setSearchDetails,
setSearchResults
} from "../../store/searchOutput/action";
import { setSearch } from "../../store/search/action";
import { getRepsFilesBlobs } from "../../actions/azurestorage";
const getDetails = (resultsObj, detailsType) => {
let detailsArr = [];
resultsObj =
detailsType == "mySubmittedReps" ? resultsObj : resultsObj.value;
if (detailsType == "myRepresentations") {
const repsObj = resultsObj.map((searchDetail, index) => {
detailsArr.push(
getCase(searchDetail["incidentID"]).then((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":
caseID = data.ticketnumber;
break;
default:
caseID = data.pinswg_title;
}
return getPortalModuleDetails(
getFormCollectionByID(data.pinswg_appealcasetype)
.LogicalCollectionName,
caseID
);
})
);
});
}
let detArr = Promise.all(detailsArr);
console.log(detArr);
return detArr;
};
export const loadRepresentationBootstrap = async ({ ctx }) => {
const { query } = ctx;
console.log("The query", query);
let thisSession = await getSession(ctx);
let loggedInUser = {};
if (!thisSession) {
console.log("not has sesssion.......");
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
} else {
[loggedInUser] = await Promise.all([
await getPortalLogin(thisSession.user.email)
]);
console.log(
"=====//////////=====",
thisSession,
thisSession.user.email,
loggedInUser
);
loggedInUser = loggedInUser.value[0].contactid;
}
const [accountDetails, myRepresentations] = await Promise.all([
await getPersonalAccount(loggedInUser),
await getRepsFromBlob(thisSession.user.id)
]);
const myRepresentationsDetails = await getDetails(
myRepresentations,
"myRepresentations"
);
console.log(accountDetails);
const isLPA =
accountDetails[
"pinswg_typeofinvolvement@OData.Community.Display.V1.FormattedValue"
] == "LPA"
? true
: false;
return {
query,
thisSession,
loggedInUser,
accountDetails,
myRepresentations,
myRepresentationsDetails,
isLPA
};
};
export const loadExistingRepresentation = async ({ store, ctx, bootstrap }) => {
const { query } = ctx;
const {
thisSession,
myRepresentations,
myRepresentationsDetails,
accountDetails,
isLPA
} = bootstrap;
console.log("is lpa?:", isLPA);
store.dispatch(setContainerID(thisSession.user.id));
store.dispatch(setMyRepresentations(myRepresentations));
store.dispatch(setMyRepresentationsDetails(myRepresentationsDetails));
function findObjectByKeyValue(arr, key, value) {
return arr.find((obj) => obj[key] === value);
}
const result = findObjectByKeyValue(
myRepresentations.value,
"repfile_name",
query.created
);
store.dispatch(
setCurrentReference({
"ticketnumber":
result.ticketnumber || result.caseRef || result.pinswg_name,
"currentReference": result.caseRef,
"currentType": "myRepresentations",
"incidentid": result.incidentID,
"appealType": result.appealType,
"repDetails": result,
"filesList": result.filesList
})
);
store.dispatch(setRepresentationCapacity(result.representationCapacity));
const repsFileListObj = await getRepsFilesBlobs(
result.containerID,
result.ticketnumber || result.caseRef,
result.repfile_name
);
store.dispatch(setAccountDetails(accountDetails));
store.dispatch(setFilesForRepresentations(repsFileListObj));
return {
props: {
containerID: thisSession.user.id,
docsOffline: process.env.DOCAPI_OFFLINE || false
}
};
};
export const loadNewRepresentation = async ({ store, ctx, bootstrap }) => {
const { query } = ctx;
const { thisSession, accountDetails } = bootstrap;
const searchResultsObj = await getBasicSearch(query.case);
const searchDetailsObj = await getSearchDetails(searchResultsObj);
store.dispatch(setContainerID(thisSession.user.id));
store.dispatch(setSearchResults(searchResultsObj));
store.dispatch(setSearchDetails(searchDetailsObj));
store.dispatch(setSearch(query.case));
store.dispatch(
setCurrentView({
"viewName": "My Representations",
"viewKey": "myRepresentations"
})
);
console.log(
accountDetails,
"===================== is nrw",
accountDetails.emailaddress1.includes(process.env.NRWDOMAIN),
"===================== "
);
store.dispatch(
setCurrentReference({
"isNRW":
accountDetails.emailaddress1.includes(process.env.NRWDOMAIN) ||
false,
"ticketnumber": searchResultsObj.value[0].ticketnumber,
"currentReference": searchResultsObj.value[0].title,
"currentType": "myRepresentations",
"incidentid": searchResultsObj.value[0].incidentid,
"appealType": searchResultsObj.value[0].pinswg_appealcasetype,
"specialistProcess":
searchDetailsObj[0].value[0].pinswg_speacialistcaseprocess !=
null ||
searchDetailsObj[0].value[0].pinswg_specialistcaseprocess !=
null
? searchDetailsObj[0].value[0]
.pinswg_speacialistcaseprocess ||
searchDetailsObj[0].value[0].pinswg_specialistcaseprocess
: ""
})
);
store.dispatch(setAccountDetails(accountDetails));
return {
props: {
containerID: thisSession.user.id,
docsOffline: process.env.DOCAPI_OFFLINE || false
}
};
};
export const loadRepresentationPage = async ({ store, ctx }) => {
const bootstrap = await loadRepresentationBootstrap({ ctx });
if (bootstrap?.redirect) {
return bootstrap;
}
const { query } = ctx;
if (query.hasOwnProperty("state")) {
return loadExistingRepresentation({ store, ctx, bootstrap });
}
return loadNewRepresentation({ store, ctx, bootstrap });
};