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...
This commit is contained in:
Robert Bond
2026-04-20 13:09:07 +00:00
parent c8b08a04a6
commit 37a81522d5
52 changed files with 9357 additions and 8201 deletions
+131 -242
View File
@@ -33,6 +33,25 @@ 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();
@@ -105,6 +124,11 @@ let MakeRepresentation = (props) => {
: false;
const isNRW = currentView.caseReference?.isNRW;
const { showCheckStage } = resolveJourneyStageFlags({
"representationSubmit": currentView.representationSubmit,
"representationSubmitConfirmation":
currentView.representationSubmitConfirmation
});
const setRepFileName = (values) => {
if (
@@ -250,52 +274,31 @@ let MakeRepresentation = (props) => {
const isEditState = router.query.state === "edit";
const hasState = router.query.hasOwnProperty("state");
const getCaseDetailsObj = () => {
if (hasState) {
return isEditState
? props.props.myRepresentations.myRepresentations
: props.props.searchResultsObj.searchDetailsObj;
}
return props.currentType === "watchedCases"
? props.props.watchedCases.watchedCasesDetails
: props.props.searchResultsObj.searchDetailsObj;
};
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
});
const getCaseResultsObj = () => {
if (hasState) {
return isEditState
? props.props.myRepresentations.myRepresentations
: props.props.searchResultsObj.searchResultsObj;
}
return props.currentType === "watchedCases"
? props.props.watchedCases.watchedCasesDetails
: props.props.searchResultsObj.searchResultsObj;
};
const setCaseDetailsObj = getCaseDetailsObj();
const setCaseResultsObj = getCaseResultsObj();
let resultsObj = jsonpath({
path: `$..[?(@ && @.ticketnumber=="${currentView.caseReference.currentReference}")]`,
json: setCaseResultsObj,
eval: true
})[0];
let resultsObj = findResultsObjForCurrentReference({
"currentReference": currentView.caseReference.currentReference,
"caseResultsSource": caseResultsSource
});
// let detailsObj;
if (hasState && isEditState) {
detailsObj = jsonpath({
path: `$..[?(@ && @.repfile_name=="${router.query.created}")]`,
json: setCaseDetailsObj,
eval: true
})[0];
} else {
detailsObj = jsonpath({
path: `$..[?(@ && @.ticketnumber=="${currentView.caseReference.ticketnumber}")]`,
json: setCaseDetailsObj,
eval: true
})[0];
}
detailsObj = findDetailsObjForView({
hasState,
isEditState,
"queryCreated": router.query.created,
"ticketnumber": currentView.caseReference.ticketnumber,
"caseDetailsSource": caseDetailsSource
});
const safeDetailsObj = detailsObj || {};
const safeResultsObj = resultsObj || {};
@@ -586,19 +589,16 @@ let MakeRepresentation = (props) => {
setCurrentReference
};
const getNormalizedCapacity = () => {
const rawCapacity =
currentView.representationCapacity ||
currentView.caseReference?.repDetails?.representationCapacity ||
"false";
return rawCapacity.toLowerCase();
};
const { controlKey } = resolveRepresentationControlKey({
"isLPA": isLPA,
"representationCapacity": currentView.representationCapacity,
"repDetailsCapacity":
currentView.caseReference?.repDetails?.representationCapacity,
"appealType": appealType,
"normalizeCapacity": normalizeCapacity
});
if (
isLPA &&
(!currentView.representationCapacity ||
currentView.representationCapacity === "")
) {
if (controlKey === "lpa-capacity-selection") {
return (
<RepLPACapacitySelection
{...commonProps}
@@ -616,10 +616,8 @@ let MakeRepresentation = (props) => {
);
}
const capacity = normalizeCapacity(getNormalizedCapacity());
switch (capacity) {
case "appellant": {
switch (controlKey) {
case "capacity-appellant": {
const Component =
appealType === 846040002
? ConsultationAppellant
@@ -634,7 +632,7 @@ let MakeRepresentation = (props) => {
);
}
case "lpa": {
case "capacity-lpa": {
return (
<RepLPA
{...commonProps}
@@ -650,7 +648,7 @@ let MakeRepresentation = (props) => {
);
}
case "agent": {
case "capacity-agent": {
const Component =
appealType === 846040002 ? ConsultationAgent : RepAgent;
return (
@@ -663,7 +661,7 @@ let MakeRepresentation = (props) => {
);
}
case "interestedparty": {
case "capacity-interestedparty": {
const Component =
appealType === 846040002
? ConsultationInterestedPartyPerson
@@ -678,7 +676,7 @@ let MakeRepresentation = (props) => {
);
}
case "landowner": {
case "capacity-landowner": {
return (
<RepLandOwner
{...commonProps}
@@ -879,24 +877,10 @@ let MakeRepresentation = (props) => {
]
};
let updateBody = setRepFileName(formattedValues);
// Clean and sanitize the body
const sanitizedBody = Object.entries(updateBody).reduce(
(acc, [key, val]) => {
if (val !== null && val !== undefined && !key.startsWith("_")) {
acc[key] = val;
}
return acc;
},
{}
);
// Normalize "Yes"/"No" to booleans
const stringified = JSON.stringify(sanitizedBody)
.replace(/:"Yes"/g, ":true")
.replace(/:"No"/g, ":false");
updateBody = JSON.parse(stringified);
const updateBody = buildRepresentationUpdateBody({
formattedValues,
setRepFileName
});
const sendEmailIfNeeded = () => {
if (sendSavedEmail) {
@@ -957,24 +941,20 @@ let MakeRepresentation = (props) => {
return;
}
// Determine case data source
const getCaseDetailsSource = () => {
if (router.query?.state === "edit") {
return props.props.myRepresentations.myRepresentations;
}
return props.currentType === "watchedCases"
? props.props.watchedCases.watchedCasesDetails
: props.props.searchResultsObj.searchDetailsObj;
};
const setCaseDetailsObj = getCaseDetailsSource();
const caseDetailsSource = resolveSubmitCaseDetailsSource({
"isEditState": router.query?.state === "edit",
"currentType": props.currentType,
"myRepresentations":
props.props.myRepresentations.myRepresentations,
"watchedCasesDetails": props.props.watchedCases.watchedCasesDetails,
"searchDetailsObj": props.props.searchResultsObj.searchDetailsObj
});
// Find correct case details
let detailsObj = jsonpath({
path: `$..[?(@ && @.ticketnumber=="${ticketnumber}")]`,
json: setCaseDetailsObj,
eval: true
})[0];
let detailsObj = findDetailsObjForSubmit({
ticketnumber,
caseDetailsSource
});
// Cancel submit status if editing
if (router.query?.state === "edit") {
@@ -988,23 +968,6 @@ let MakeRepresentation = (props) => {
) {
const formValues = formObj.representationForm.values;
const buildSiteAddress = () => {
const {
pinswg_siteaddressline1,
pinswg_siteaddressline2,
pinswg_siteaddresstown,
pinswg_siteaddresspostcode
} = detailsObj;
return [
pinswg_siteaddressline1,
pinswg_siteaddressline2,
pinswg_siteaddresstown,
pinswg_siteaddresspostcode
]
.filter(Boolean)
.join(" ");
};
const representationCapacity =
router.query?.state === "edit"
? props.props.currentView.representationCapacity
@@ -1012,55 +975,19 @@ let MakeRepresentation = (props) => {
? "LPA"
: values.representationCapacity;
Object.assign(values, {
...formValues,
containerID: props.props.accountDetails.containerID,
appealType:
appealType || caseReferenceObj.repDetails.appealType,
incidentID:
caseReferenceObj.incidentid ||
caseReferenceObj.repDetails.incidentid,
caseRef: caseReferenceObj.currentReference,
casereference: caseReferenceObj.currentReference,
pinswg_questionnaireduedate:
detailsObj.pinswg_questionnaireduedate,
pinswg_endofrepresentationperiod:
detailsObj.pinswg_endofrepresentationperiod,
pinswg_applicationacceptedasvalid:
detailsObj.pinswg_applicationacceptedasvalid,
pinswg_statementduedate: detailsObj.pinswg_statementduedate,
pinswg_statementsduedate: detailsObj.pinswg_statementsduedate,
pinswg_finalcommentsduedate:
detailsObj.pinswg_finalcommentsduedate,
pinswg_name: caseReferenceObj.currentReference,
firstname: accountDetails.firstname,
lastname: accountDetails.lastname,
emailAddress: accountDetails.emailaddress1,
siteAddress: buildSiteAddress(),
pinswg_siteaddressline1: detailsObj.pinswg_siteaddressline1,
pinswg_siteaddressline2: detailsObj.pinswg_siteaddressline2,
pinswg_siteaddresstown: detailsObj.pinswg_siteaddresstown,
pinswg_siteaddresspostcode:
detailsObj.pinswg_siteaddresspostcode,
pinswg_lpareference: resultsObj?.pinswg_lpareference,
_pinswg_appellant_value: detailsObj._pinswg_appellant_value,
"_pinswg_appellant_value@OData.Community.Display.V1.FormattedValue":
detailsObj[
"_pinswg_appellant_value@OData.Community.Display.V1.FormattedValue"
],
_pinswg_localplanningauthority_value:
detailsObj._pinswg_localplanningauthority_value ||
detailsObj._pinswg_associatedlpa_value,
"_pinswg_localplanningauthority_value@OData.Community.Display.V1.FormattedValue":
detailsObj[
"_pinswg_localplanningauthority_value@OData.Community.Display.V1.FormattedValue"
] ||
detailsObj[
"_pinswg_associatedlpa_value@OData.Community.Display.V1.FormattedValue"
],
representationCapacity,
locale: router.locale
});
Object.assign(
values,
buildSubmitEnrichedValues({
formValues,
accountDetails,
appealType,
caseReferenceObj,
detailsObj,
resultsObj,
representationCapacity,
locale: router.locale
})
);
}
const shouldSubmit = !currentView.representationSubmit;
@@ -1078,19 +1005,20 @@ let MakeRepresentation = (props) => {
: normalizeCapacity(values.representationCapacity);
setRepresentationCapacity(capacity);
} else {
if (repType === "Questionnaire") {
if (
questionnaireCount !== 0 &&
showQuestionnaireSection < questionnaireCount
) {
setShowQuestionnaireSection(
showQuestionnaireSection + 1
);
updateRepresentation(values, false, false);
} else {
updateRepresentation(values, false, false);
setRepresentationSubmit(true);
}
const submitTransition = resolveSubmitTransition({
"representationType": repType,
"showQuestionnaireSection": showQuestionnaireSection,
"questionnaireCount": questionnaireCount
});
if (submitTransition === "advanceQuestionnaire") {
setShowQuestionnaireSection(
getQuestionnaireNextSection(
showQuestionnaireSection,
questionnaireCount
)
);
updateRepresentation(values, false, false);
} else {
updateRepresentation(values, false, false);
setRepresentationSubmit(true);
@@ -1113,19 +1041,19 @@ let MakeRepresentation = (props) => {
}
// Final PDF & upload
setFinaliseAppealProcess(true);
generateRepPDF(
runFinalisationSequence({
values,
props.props.accountDetails.containerID,
props.currentView.caseReference.currentReference
).then((data) => {
containerID: props.props.accountDetails.containerID,
currentReference:
props.currentView.caseReference.currentReference,
setFinaliseAppealProcess,
generateRepPDF,
updateLinks,
uploadRepresentationFiles,
setRepresentationSubmit,
setRepresentationSubmitConfirmation
}).then((data) => {
console.log(data, "");
if (data.status === "success") {
values = updateLinks(values);
uploadRepresentationFiles(values);
setRepresentationSubmit(true);
setRepresentationSubmitConfirmation(true);
}
});
}
};
@@ -1252,7 +1180,7 @@ let MakeRepresentation = (props) => {
return (
<div>
<form onSubmit={handleSubmit(onHandleSubmit)}>
{currentView.representationSubmit ? (
{showCheckStage ? (
<RepCompleteSubmit
formObj={formObj}
capacityOptionsArr={capacityOptionsArr}
@@ -1279,61 +1207,22 @@ let MakeRepresentation = (props) => {
docsOffline={docsOffline}
/>
) : (
<>
<h1 className="govuk-heading-l">
{appealIsConsultation
? t(
"myrepresentations:make-a-consultation-on-label"
)
: t(
"myrepresentations:make-a-representation-on-label"
)}{" "}
{currentView.caseReference.currentReference}{" "}
</h1>
<div id="rep-form">
<div className="govuk-grid-column-three-quarters wgForm">
{whichControl()}
</div>
<div className="govuk-grid-column-one-quarter">
<div className="card">
<div className="card-body">
<h2 className="govuk-heading-s">
{t(
"myrepresentations:timetable-title"
)}
</h2>
<div className="govuk-summary-list">
<div className="govuk-body-s">
{appealIsLocalImpact
? t(
"myrepresentations:local-impact-report"
)
: t(
"myrepresentations:questionnaire-due-label"
)}
:{" "}
<span className="govuk-body-s">
{renderDueDate()}
</span>
</div>
{!appealIsConsultation &&
renderStatementsDue()}
{renderMarineImpact()}
{renderConsultationClose()}
{renderFinalCommentsDue()}
</div>
</div>
</div>
{isQuestionnaire && whichProgress()}
</div>
</div>
</>
<RepresentationFlowFormStage
t={t}
appealIsConsultation={appealIsConsultation}
currentReference={
currentView.caseReference.currentReference
}
whichControl={whichControl}
appealIsLocalImpact={appealIsLocalImpact}
renderDueDate={renderDueDate}
renderStatementsDue={renderStatementsDue}
renderMarineImpact={renderMarineImpact}
renderConsultationClose={renderConsultationClose}
renderFinalCommentsDue={renderFinalCommentsDue}
isQuestionnaire={isQuestionnaire}
whichProgress={whichProgress}
/>
)}
</form>
</div>