Files
pedwfrontend/lib/representation/pageLoaders.js
T
Robert Bond 9595ad86df Merged PR 2374: addeding domain layer extrraction
# Summary

This PR introduces a **Case Lifecycle Domain Boundary** to centralize lifecycle decision logic and reduce coupling within the appeals application.

The work is **behaviour-preserving** and introduces no intentional changes to business rules, CRM integrations, translations, dashboards, API routes, or user-facing functionality.

## What was added

New lifecycle boundary:

```text
lib/domain/case-lifecycle/
```

Key responsibilities extracted:

- Specialist process normalization
- Appeal type mapping
- Specialist process stage override mapping
- Stage case-type resolution
- Stage catalogue lookup
- Closed-case status recognition
- Lifecycle stage index resolution
- Lifecycle stage status assignment

## Behaviour preserved

Characterization tests were added before each extraction to preserve:

- Appeal type mapping and aliases
- Specialist process handling
- Lifecycle stage progression
- Closed-case handling
- Status assignment (`complete`, `in-progress`, `not-started`)
- Existing ROW behaviour
- Existing `statuscode` lifecycle semantics

Closed-case recognition remains unchanged for:

```text
1000
5
6
846040013
846040059
846040060
```

## Documentation

Added:

```text
lib/domain/case-lifecycle/README.md
```

Documenting:

- Boundary ownership
- Non-goals
- Lifecycle invariants
- Known architectural constraints
- Future extraction roadmap

## Testing

Added lifecycle characterization coverage for:

- Stage wrapper behaviour
- Specialist process normalization
- Appeal type mapping
- Specialist process stage mapping
- Stage case-type resolution
- Stage catalogue lookup
- Progress behaviour
- Closed-case status handling
- Stage index resolution
- Stage status assignment

## Validation

- Lifecycle characterization tests passed
- `npm run lint` passed with no errors

## Out of Scope

No changes to:

- Stage catalogue ownership
- Representation eligibility
- Dashboard calculations
- CRM/OData queries
- API routes
- Redux state
- EN/CY translations
- Event visibility logic

## Risk

**Low risk**

The refactor was delivered through small, characterization-first slices with no functional changes intended.

Related work items: #23527
2026-06-08 09:34:30 +00:00

346 lines
10 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 { consoleLogger } from "../../actions/core/logger";
import { normalizeSpecialistProcess } from "../domain/case-lifecycle";
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") {
resultsObj.map((searchDetail) => {
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);
return detArr;
};
export const loadRepresentationBootstrap = async ({ ctx }) => {
const { query } = ctx;
let thisSession = await getSession(ctx);
let loggedInUser = null;
if (!thisSession) {
consoleLogger({
name: "RepresentationLoaderMissingSession",
message:
"loadRepresentationBootstrap missing session; redirecting to signin"
});
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
} else {
loggedInUser = await getPortalLogin(thisSession.user.email);
loggedInUser = loggedInUser?.value?.[0]?.contactid || null;
}
if (!loggedInUser) {
consoleLogger({
name: "RepresentationLoaderMissingContact",
message:
"loadRepresentationBootstrap missing CRM contact id; redirecting to signin",
hasSessionEmail: !!thisSession?.user?.email
});
return {
redirect: {
destination: "/auth/signin",
permanent: false
}
};
}
const [accountDetails, myRepresentations] = await Promise.all([
getPersonalAccount(loggedInUser),
getRepsFromBlob(thisSession.user.id)
]);
const myRepresentationsDetails = await getDetails(
myRepresentations,
"myRepresentations"
);
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;
const searchResultsObj = await getBasicSearch(query.case);
if (!searchResultsObj?.value?.[0]) {
consoleLogger({
name: "RepresentationExistingMissingSearchResult",
message:
"loadExistingRepresentation missing search result; redirecting to myportal",
hasCaseQuery: !!query?.case
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
const searchDetailsObj = await getSearchDetails(searchResultsObj);
store.dispatch(setSearchResults(searchResultsObj));
store.dispatch(setSearchDetails(searchDetailsObj));
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
);
if (!result) {
consoleLogger({
name: "RepresentationExistingMissingBlobEntry",
message:
"loadExistingRepresentation missing representation blob entry; redirecting to myportal",
hasCreatedQuery: !!query?.created
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
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 || thisSession.user.id,
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);
if (!searchResultsObj?.value?.[0]) {
consoleLogger({
name: "RepresentationNewMissingSearchResult",
message:
"loadNewRepresentation missing search result; redirecting to myportal",
hasCaseQuery: !!query?.case
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
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"
})
);
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": normalizeSpecialistProcess(
searchDetailsObj?.[0]?.value?.[0]
)
})
);
store.dispatch(setAccountDetails(accountDetails));
return {
props: {
containerID: thisSession.user.id,
docsOffline: process.env.DOCAPI_OFFLINE || false
}
};
};
export const loadRepresentationPage = async ({ store, ctx }) => {
const { query } = ctx;
if (!query?.case) {
consoleLogger({
name: "RepresentationLoaderMissingCaseQuery",
message:
"loadRepresentationPage missing case query; redirecting to myportal"
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
if (
Object.prototype.hasOwnProperty.call(query, "state") &&
!query?.created
) {
consoleLogger({
name: "RepresentationLoaderMissingCreatedQuery",
message:
"loadRepresentationPage missing created query for state flow; redirecting to myportal"
});
return {
redirect: {
destination: "/myportal",
permanent: false
}
};
}
const bootstrap = await loadRepresentationBootstrap({ ctx });
if (bootstrap?.redirect) {
return bootstrap;
}
if (Object.prototype.hasOwnProperty.call(query, "state")) {
return loadExistingRepresentation({ store, ctx, bootstrap });
}
return loadNewRepresentation({ store, ctx, bootstrap });
};