Merged PR 2246: refactor reps first slice

Related work items: #22570, #22576, #22577, #22583, #22586, #22587, #22588, #22590, #22591
This commit is contained in:
Robert Bond
2026-04-15 09:28:50 +00:00
parent 15c35d201e
commit ecd6075c3a
9 changed files with 1520 additions and 371 deletions
+122 -116
View File
@@ -2,15 +2,18 @@
## Purpose
This file defines the active working rules for this refactor branch.
This file defines the active working rules for the **refactor branch**.
This branch is focused on **safe, behaviour-preserving refactor of the new appeal flow**.
This branch is focused on **safe, behaviour-preserving refactor of portal journeys**, including:
- New Appeal Flow (completed baseline)
- Representations Flow (active refactor stream)
---
## Core Rule (Highest Priority)
Do not change live S78 behaviour unless explicitly instructed.
Do not change live behaviour unless explicitly instructed.
Refactor = improve structure, not behaviour.
@@ -18,30 +21,62 @@ Refactor = improve structure, not behaviour.
## Primary Objectives
1. Make the new appeal flow easier to understand and maintain
1. Make core portal journeys easier to understand and maintain
2. Reduce risk when making future changes
3. Prepare the system for multiple appeal types
4. Improve separation of concerns (UI, workflow, data, integrations)
3. Improve separation of concerns (UI, workflow, data, integrations)
4. Prepare flows for future extensibility (e.g. multiple appeal types, additional journey types)
---
## Active Refactor Streams
### Completed
- New Appeal Flow (S78)
### Active
- Representations Flow
Each stream must follow **slice-based, behaviour-preserving refactor discipline**.
---
## Non-Negotiable Rules
- Preserve all current user journeys:
- start appeal
- save and exit
- resume appeal
- upload documents
- check answers
- submit appeal
- confirmation
- Do not:
- change payload structures
- change validation rules
- change business logic
- hardcode logic that is currently dynamic/config-driven
- mix refactor with feature work
### Appeals
- start appeal
- save and exit
- resume appeal
- upload documents
- check answers
- submit appeal
- confirmation
### Representations
- start from case summary CTA
- select capacity
- select representation type
- enter content / upload files
- check answers
- submit representation
- completion
---
Do not:
- change payload structures
- change validation rules
- change business logic
- change route/query behaviour
- change navigation or side-effect sequencing
- introduce EN/CY drift
- mix refactor with feature work
---
@@ -62,6 +97,41 @@ Always:
- Prefer small PRs (<400 LOC where possible)
- Avoid large multi-concern changes
- Split work into safe slices
- One slice = one branch = one commit
---
## Branch Model (Critical)
### Branch Roles
- `SIPS-Development`
- BAU branch
- ongoing feature and bugfix work
- must remain stable
- `refactor`
- integration branch for refactor work
- all refactor slices merge here first
- feature branches (short-lived)
- created from `refactor`
- one per slice
- merged back into `refactor`
---
### Flow
SIPS-Development
refactor
feature/slice-x
refactor
↓ (when stable & validated)
SIPS-Development
---
@@ -70,30 +140,25 @@ Always:
### Default context (only load these):
- `context/refactor-branch-charter.md`
- `context/newappeal-refactor-guardrails.md`
- `context/architecture.md`
- `context/domain-flows.md`
### Only load additional context when needed:
### Only load when needed:
- integrations → `integration-map.md`
- testing gaps → `test-coverage-map.md`
- release concerns → `runbook.md`
- specific work plan → `context/plans/*`
- appeal work → `newappeal-refactor-guardrails.md`
- representation work → `representations-refactor-guardrails.md`
- plans → `context/plans/*`
### Never load by default:
- all context files
- onboarding or overview docs
- onboarding docs
- all templates
- memory-bank contents
---
## Templates Usage
Templates are optional helpers.
- Use only ONE template when needed
- Do not load all templates
- Do not treat templates as baseline context
@@ -110,25 +175,41 @@ Templates are optional helpers.
---
## Testing & Validation Expectations
## Regression Safety Rule (Critical)
Minimum:
This is a live system. All refactor work must prove behaviour is unchanged.
- `npm run lint`
- targeted manual verification
- EN/CY checks (if user-facing)
- negative-path checks (for sensitive flows)
Before completing any slice:
Before changing critical logic:
### Appeals
- add or update regression protection where possible
- start appeal
- save and exit
- resume
- upload
- check answers
- submit
- confirmation
### Representations
- navigate from case summary → make representation
- complete full journey
- submit successfully
- confirmation shown
Also:
- verify EN/CY parity
- verify no navigation or state regressions
If regression cannot be ruled out:
→ do not proceed
---
## When Unsure
If any uncertainty exists:
1. Choose the safest option
2. Do not change behaviour
3. Call out assumptions
@@ -142,87 +223,12 @@ A successful change:
- preserves behaviour
- reduces complexity
- improves clarity or structure
- improves clarity
- is small and safe to merge
- does not introduce regression risk
- introduces no regression risk
---
## One-Line Rule
If in doubt:
> Keep behaviour the same, reduce risk, and make the smallest safe change.
---
## Documentation Rule (Minimal and Targeted)
Only document information that is necessary to safely understand or change the system later.
Document:
- key decisions (why something was changed)
- non-obvious behaviour
- risks or constraints (what must not be changed)
- important assumptions
Do not document:
- obvious code behaviour
- step-by-step implementation details
- temporary or experimental work
- duplicated explanations across files
Prefer short, focused notes over long explanations.
If unsure:
> Will someone break the system in the future if this is not written down?
If yes → document it
If no → do not document it
Documentation should be minimal, high-signal, and never outweigh the value of the code itself.
## Branch Safety Rule
This refactor stream uses the `refactor` branch as its working base branch.
For refactor work:
- do all implementation from the `refactor` branch or a short-lived feature branch created from `refactor`
- do not implement refactor work directly on `SIPS-Development`
`SIPS-Development` remains the BAU integration branch.
Refactor changes may be merged into `SIPS-Development` only when proven safe.
If branch context is unclear, stop and confirm before making changes.
## Branch Model
- `SIPS-Development` = BAU branch
- `refactor` = refactor integration branch
- optional short-lived working branches for individual slices should be created from `refactor`
## Regression Safety Rule (Critical)
This is a live system. All refactor work must prove behaviour is unchanged.
Before completing any slice:
- verify core journey behaviour has not changed
- verify protected flows still work:
- save and exit
- resume appeal
- upload documents
- check answers
- submit appeal
- confirmation
- verify EN/CY parity for any affected areas
A slice is NOT complete until regression behaviour is confirmed.
If regression cannot be confidently ruled out:
→ do not proceed to next slice
+155 -197
View File
@@ -37,14 +37,21 @@ import * as CaseTypes from "./summaryTypes"; // ✅ must match filename exactly
import {
capitalizeFirstLetter,
formatDates,
showReps,
hasValidKey,
isObjectNotEmpty,
hasOwnPropertyAndNotNull,
linkedCasesList,
showRepsEnded,
getBilingualText
} from "./summary/utils/helpers";
import {
isConsultationWindowOpen,
isGeneralRepresentationWindowOpen,
canShowRepButtonForAppealType,
getEntryCtaLabelKey,
shouldSuppressBlockedMessage,
getGeneralBlockedEndDate,
isRepresentationPeriodEnded
} from "./summary/utils/representationEntry";
import {
resolveSearchResultsHref,
isDnsRoutePath
@@ -806,16 +813,22 @@ const CaseSummary = (props) => {
appealTypeID
).PrimaryIdAttribute ==
"pinswg_sipscase" &&
showReps(
detailsObj.pinswg_consultationopen,
detailsObj.pinswg_consultationclose
isConsultationWindowOpen(
detailsObj
) && (
<>
{showRepButton(
props
.currentView
.caseReference
.appealType
{canShowRepButtonForAppealType(
{
"appealType":
props
.currentView
.caseReference
.appealType,
"isLPA":
isLPA,
"searchDetailsObj":
props.searchDetailsObj
}
) ? (
<>
<Link
@@ -838,25 +851,27 @@ const CaseSummary = (props) => {
}}
className="govuk-button"
>
{props
.currentView
.caseReference
.appealType ==
846040002
? t(
"case:summary-make-consultation-label"
)
: t(
"case:summary-make-representation-label"
)}
{t(
getEntryCtaLabelKey(
props
.currentView
.caseReference
.appealType
)
)}
</Link>
</>
) : !isLPA &&
props
.currentView
.caseReference
.appealType ==
846040004 ? (
) : shouldSuppressBlockedMessage(
{
"appealType":
props
.currentView
.caseReference
.appealType,
"isLPA":
isLPA
}
) ? (
""
) : (
<>
@@ -899,114 +914,122 @@ const CaseSummary = (props) => {
)}
</>
)}
{(_.has(
detailsObj,
"pinswg_startdate"
) ||
_.has(
detailsObj,
"pinswg_applicationacceptedasvalid"
) ||
_.has(
detailsObj,
"pinswg_startdates"
)) &&
showReps(
detailsObj.pinswg_startdate ||
detailsObj.pinswg_startdates ||
detailsObj.pinswg_applicationacceptedasvalid,
detailsObj.pinswg_finalcommentsduedate ||
detailsObj.pinswg_endofrepresentationperiod
) && (
<>
{showRepButton(
props
.currentView
.caseReference
.appealType
) ? (
<>
<Link
href={{
pathname:
"/myportal/representation",
query: {
case:
currentType ==
"searchResultsObj"
{isGeneralRepresentationWindowOpen(
detailsObj
) && (
<>
{canShowRepButtonForAppealType(
{
"appealType":
props
.currentView
.caseReference
.appealType,
"isLPA":
isLPA,
"searchDetailsObj":
props.searchDetailsObj
}
) ? (
<>
<Link
href={{
pathname:
"/myportal/representation",
query: {
case:
currentType ==
"searchResultsObj"
? detailsObj.ticketnumber
: currentType ==
"watchedCases"
? casesObj.pinswg_title
: currentType ==
"directResultsObj"
? detailsObj.ticketnumber
: currentType ==
"watchedCases"
? casesObj.pinswg_title
: currentType ==
"directResultsObj"
? detailsObj.ticketnumber
: casesObj.reference
}
}}
className="govuk-button"
>
{t(
"case:summary-make-representation-label"
)}
</Link>
</>
) : !isLPA &&
props
.currentView
.caseReference
.appealType ==
846040004 ? (
""
) : (
<>
<div className="govuk-grid-column-full govuk-!-padding-left-0">
<div className="govuk-button-group">
<p className="govuk-body">
{t(
"case:representation-date-passed-label",
{
startDate:
formatDates(
detailsObj.pinswg_startdate
),
endDate:
props
.currentView
.caseReference
.appealType ==
846040019
? formatDates(
detailsObj.pinswg_statementduedate
: casesObj.reference
}
}}
className="govuk-button"
>
{t(
"case:summary-make-representation-label"
)}
</Link>
</>
) : shouldSuppressBlockedMessage(
{
"appealType":
props
.currentView
.caseReference
.appealType,
"isLPA":
isLPA
}
) ? (
""
) : (
<>
<div className="govuk-grid-column-full govuk-!-padding-left-0">
<div className="govuk-button-group">
<p className="govuk-body">
{t(
"case:representation-date-passed-label",
{
startDate:
formatDates(
detailsObj.pinswg_startdate
),
endDate:
props
.currentView
.caseReference
.appealType ==
846040019
? formatDates(
getGeneralBlockedEndDate(
detailsObj,
props
.currentView
.caseReference
.appealType
)
: formatDates(
detailsObj.pinswg_finalcommentsduedate
)
: formatDates(
getGeneralBlockedEndDate(
detailsObj,
props
.currentView
.caseReference
.appealType
)
}
)}
<br />{" "}
{t(
"case:representation-date-passed-additional-label"
)}{" "}
<Link
href={
"mailto:" +
t(
"home:login-contact-email"
)
}
>
{t(
)
}
)}
<br />{" "}
{t(
"case:representation-date-passed-additional-label"
)}{" "}
<Link
href={
"mailto:" +
t(
"home:login-contact-email"
)}
</Link>
</p>
</div>
)
}
>
{t(
"home:login-contact-email"
)}
</Link>
</p>
</div>
</>
)}
</>
)}
</div>
</>
)}
</>
)}
<Link
className="govuk-button govuk-button--secondary"
@@ -1352,9 +1375,8 @@ const CaseSummary = (props) => {
null ||
detailsObj.pinswg_finalcommentsduedate !=
null) &&
showRepsEnded(
detailsObj.pinswg_startdate,
detailsObj.pinswg_finalcommentsduedate
isRepresentationPeriodEnded(
detailsObj
) && (
<div className="govuk-body">
{props.currentView
@@ -2043,70 +2065,6 @@ const CaseSummary = (props) => {
);
}
function showReps(startDate, endDate) {
let date = new Date();
date = new Date(date.toDateString());
const start = new Date(startDate);
const end = new Date(endDate);
return date >= start && date <= end ? true : false;
}
function showRepButton(appealType) {
switch (appealType) {
case 846040012:
case 846040013:
case 846040014:
//for ROW case 846040015:
case 846040020:
case 846040021:
case 846040023:
case 846040024:
return false;
case 846040004:
return isLPA ? true : false;
case 846040015:
return props.searchDetailsObj[0].value[0]
.pinswg_specialistcaseprocess == 846040001
? showReps(
props.searchDetailsObj[0].value[0].pinswg_startdate,
props.searchDetailsObj[0].value[0]
.pinswg_finalcommentsduedate
)
: true;
case 846040018:
let shouldShow =
props.searchDetailsObj[0].value[0]
.pinswg_speacialistcaseprocess == 846040000 && isLPA
? true
: props.searchDetailsObj[0].value[0]
.pinswg_speacialistcaseprocess == 846040001
? true
: false;
return shouldShow;
case 846040019:
return showReps(
props.searchDetailsObj[0].value[0].pinswg_startdate,
props.searchDetailsObj[0].value[0].pinswg_statementduedate
);
default:
return true;
}
}
function showRepsEnded(startDate, endDate) {
let date = new Date();
date = new Date(date.toDateString());
const start = new Date(startDate);
const end = new Date(endDate);
return date > start && date > end ? true : false;
}
if (status == "authenticated" && cookies.pedwWatchCase != null) {
selectWatchedCase(
props.accountDetails.accountDetails.contactid,
@@ -0,0 +1,117 @@
export function showRepsLocal(startDate, endDate) {
let date = new Date();
date = new Date(date.toDateString());
const start = new Date(startDate);
const end = new Date(endDate);
return date >= start && date <= end ? true : false;
}
export function showRepsEndedLocal(startDate, endDate) {
let date = new Date();
date = new Date(date.toDateString());
const start = new Date(startDate);
const end = new Date(endDate);
return date > start && date > end ? true : false;
}
export function isConsultationWindowOpen(detailsObj) {
return showRepsLocal(
detailsObj.pinswg_consultationopen,
detailsObj.pinswg_consultationclose
);
}
export function isGeneralRepresentationWindowOpen(detailsObj) {
return (
(Object.prototype.hasOwnProperty.call(detailsObj, "pinswg_startdate") ||
Object.prototype.hasOwnProperty.call(
detailsObj,
"pinswg_applicationacceptedasvalid"
) ||
Object.prototype.hasOwnProperty.call(
detailsObj,
"pinswg_startdates"
)) &&
showRepsLocal(
detailsObj.pinswg_startdate ||
detailsObj.pinswg_startdates ||
detailsObj.pinswg_applicationacceptedasvalid,
detailsObj.pinswg_finalcommentsduedate ||
detailsObj.pinswg_endofrepresentationperiod
)
);
}
export function canShowRepButtonForAppealType({
appealType,
isLPA,
searchDetailsObj
}) {
switch (appealType) {
case 846040012:
case 846040013:
case 846040014:
//for ROW case 846040015:
case 846040020:
case 846040021:
case 846040023:
case 846040024:
return false;
case 846040004:
return isLPA ? true : false;
case 846040015:
return searchDetailsObj[0].value[0].pinswg_specialistcaseprocess ==
846040001
? showRepsLocal(
searchDetailsObj[0].value[0].pinswg_startdate,
searchDetailsObj[0].value[0].pinswg_finalcommentsduedate
)
: true;
case 846040018:
let shouldShow =
searchDetailsObj[0].value[0].pinswg_speacialistcaseprocess ==
846040000 && isLPA
? true
: searchDetailsObj[0].value[0]
.pinswg_speacialistcaseprocess == 846040001
? true
: false;
return shouldShow;
case 846040019:
return showRepsLocal(
searchDetailsObj[0].value[0].pinswg_startdate,
searchDetailsObj[0].value[0].pinswg_statementduedate
);
default:
return true;
}
}
export function getEntryCtaLabelKey(appealType) {
return appealType == 846040002
? "case:summary-make-consultation-label"
: "case:summary-make-representation-label";
}
export function shouldSuppressBlockedMessage({ appealType, isLPA }) {
return !isLPA && appealType == 846040004;
}
export function getGeneralBlockedEndDate(detailsObj, appealType) {
return appealType == 846040019
? detailsObj.pinswg_statementduedate
: detailsObj.pinswg_finalcommentsduedate;
}
export function isRepresentationPeriodEnded(detailsObj) {
return showRepsEndedLocal(
detailsObj.pinswg_startdate,
detailsObj.pinswg_finalcommentsduedate
);
}
+1 -1
View File
@@ -99,7 +99,7 @@ const Header = (props) => {
const switchLocale = router.asPath.startsWith("/cy") ? "en" : "cy";
console.log("switch locale", locale === "en" ? "cy" : "en");
//console.log("switch locale", locale === "en" ? "cy" : "en");
// const handleLocaleSwitch = () => {
// // const router = useRouter();
+354
View File
@@ -0,0 +1,354 @@
# New Appeal Refactor — Current State of Play
## Purpose
This note updates the earlier **pre-refactor analysis** with the **current state after the Slice 18 refactor stream**.
Scope remains the new appeal flow areas:
- `pages/newappeal/**`
- `components/newappeal/**`
---
## Executive summary
The planned refactor stream has been completed through **Slice 8** on the `refactor` branch integration line.
- Behaviour-preserving objective has been maintained (S78 flow)
- Core journeys remained stable through regression checks
- Structural clarity has improved in the highest-risk areas
- The codebase is in a safer state for future controlled change
---
## Slice completion status (current)
All planned slices are complete:
1. Slice 1 — XML/Form derivation extraction ✅
2. Slice 2a — Payload cleanup helpers ✅
3. Slice 2b — File merge/dedupe helpers ✅
4. Slice 3 — Side-effect facade wrappers ✅
5. Slice 4 — BuildSection UI extraction ✅
6. Slice 5 — BuildCheckSection UI extraction ✅
7. Slice 6 — BuildCheckRow formatter-map cleanup ✅
8. Slice 7 — Nested prop-boundary simplification ✅
9. Slice 8 — Start flow readability cleanup (`createCase` / `aboutyou`) ✅
Tracker reference: `context/refactor-tracker.md`
---
## What changed overall
### Structural improvements delivered
- Repeated XML/form derivation logic moved into dedicated lib helpers
- Payload shaping and file-list merge/dedupe logic normalized into focused helpers
- Side effects wrapped behind clearer journey-effect boundaries
- Large UI-heavy files split with clearer presentational structure (Slices 45)
- Check-row formatting logic simplified into more maintainable mapping style
- Deep nested prop access reduced with local boundary aliases
- Start-flow components (`createCase`, `aboutyou`) made easier to read using local predicates/aliases
### What was intentionally preserved
- Business rules (including S78 behaviour)
- HASCAS mapping behaviour
- Appellant/agent branching behaviour
- Field names/IDs and payload shape
- Redirect/query construction (`lpa`, `apt`, `id`)
- Validation messages/rules
- Navigation and side-effect ordering/timing
- EN/CY parity
---
## Current architecture quality (post-stream)
### Stronger than before
- Better separation between derivation/formatting/helpers and component rendering
- Reduced duplication in payload/file processing paths
- Safer change surfaces in `buildsection`, `buildchecksection`, and start flow
- Improved readability of high-churn components
### Still sensitive / needs caution
- `buildsection.js` and `buildchecksection.js` remain central orchestration points
- Save/resume and submit/finalise paths still require strict regression discipline
- Some legacy patterns/comments remain and can obscure intent
---
## Risk position now
### Risks reduced
- Regression risk from duplicated transformation logic
- Coupling risk from deep nested prop traversal
- Reviewability risk in large mixed-concern components
- Formatting-logic drift risk in check-answers rendering
### Risks still present (manageable)
- Live-flow sensitivity for save/resume/upload/submit remains inherently high
- Manual regression burden is still significant for confidence
- Further cleanup must continue to avoid behaviour changes
---
## Deferred follow-up items (post-stream)
These are **not part of Slice 18** and should be handled as separate scoped work:
1. Add/expand targeted automated regression coverage for protected journeys
2. Remove stale/commented legacy code in touched components (safe cleanup slices)
3. Document critical invariants for save/resume/submit paths in a concise maintainer note
4. Continue incremental decomposition of remaining orchestration-heavy components only if behaviour can be proven unchanged
---
## Validation position
Regression evidence recorded across slices indicates preserved behaviour for:
- Start appeal and section navigation
- Save and exit
- Resume
- Upload and file handling
- Check answers rendering
- Submit/finalisation
- Confirmation/email paths
- EN/CY parity
- CRM insertion smoke
- Lint baseline (warnings-only, no new blocking errors)
---
## Conclusion
Compared to the earlier analysis, the new appeal flow is now in a materially safer and more maintainable state while preserving live behaviour.
The planned refactor stream (Slices 18) is complete. Any additional improvements should proceed as new, tightly scoped, behaviour-preserving slices.
---
## What should be done next
## 1) Stabilise and release safely (immediate)
Before any merge into `SIPS-Development`, run a formal readiness pass on `refactor`:
1. `npm run lint` (confirm no new blocking issues)
2. Full protected-journey manual regression:
- start appeal
- save and exit
- resume
- upload documents
- check answers
- submit
- confirmation
3. EN/CY parity pass on touched paths
4. Negative-path checks on validation and conditional branches
5. CRM insertion smoke validation
6. Rollback verification (revert path by merge commit)
If any check fails, fix in a separate, minimal safety slice.
## 2) Close out stream documentation (short, high-signal)
Add a concise closeout note (or PR summary block) that captures:
- stream scope and completed slices
- behaviour-preservation statement
- validation evidence references
- known constraints that must not change in future work
Keep this short and avoid duplicating implementation detail.
## 3) Start a post-stream backlog (separate from Slice 18)
Create a small follow-up backlog of **new, independent slices** (do not reopen completed slices):
- automated regression coverage for protected journeys
- safe removal of stale commented/dead code
- targeted cleanup of remaining orchestration hotspots (`buildsection`, `buildchecksection`) only when backed by tests/regression checks
- brief maintainer notes for critical invariants (payload shape, route/query contract, side-effect ordering)
## 4) Recommended execution order for follow-ups
Safest sequence:
1. Release-readiness and merge safety checks
2. Regression automation improvements
3. Documentation/invariant notes
4. Small structural cleanups in high-risk files (one concern per slice)
## 5) Guardrails for all next work
Continue to enforce refactor-branch rules:
- no business-rule changes
- no payload/field-name/query-shape drift
- no side-effect timing/order changes unless explicitly scoped and proven safe
- preserve EN/CY parity
- keep slices small, reversible, and independently testable
---
## Potential improvements to logic and functionality (future work)
These items are intentionally listed as **future enhancements** (not part of completed refactor slices).
Any item that changes user-facing behaviour, business rules, or decision logic should be delivered as product-approved feature work with explicit regression protection.
## 1) Validation and data-quality improvements
- Strengthen cross-field validation where dependencies are currently implicit (for example, conditional requirements tied to prior answers).
- Introduce clearer, field-level validation feedback for complex text/rich-text inputs.
- Add stricter normalization for user-entered contact data (format quality, consistency) while preserving accepted legacy cases.
## 2) Save/resume robustness
- Add structured save/resume integrity checks to detect and recover from partial or stale payloads.
- Improve diagnostics around resume hydration mismatches (field missing, incompatible shape, stale section state).
- Add explicit handling for interrupted upload/save sequences to reduce user recovery friction.
## 3) Upload/document experience and safety
- Improve duplicate-document handling feedback (clear user messaging when dedupe occurs).
- Provide more explicit upload status and retry outcomes for failed or partial uploads.
- Add stronger document-type validation messaging and edge-case handling for borderline file metadata.
## 4) Submit/finalisation resilience
- Add clearer user-safe fallback states for finalisation failures (e.g., PDF generation or downstream completion messaging failures).
- Improve idempotency safeguards in final submission steps to reduce accidental duplicate side effects.
- Strengthen auditability of submit transitions for operational support/debugging.
## 5) Start-flow usability enhancements
- Improve guidance for appeal-type selection and conditional HASCAS confirmation to reduce user error.
- Consider smarter defaults/prefill where policy allows, especially for known user profile/contact fields.
- Improve branch-specific helper copy for appellant vs agent pathways.
## 6) Performance and maintainability improvements
- Reduce repeated in-component derivation cost by introducing safe memoization where values are stable.
- Continue incremental decomposition of remaining orchestration-heavy components into testable units.
- Expand targeted automated tests (journey-level + high-risk utility-level) to lower regression burden.
## 7) Recommended delivery model for these improvements
- Treat each enhancement area as a separate, tightly scoped slice.
- Prioritise by user risk and operational impact:
1. save/resume robustness
2. submit/finalisation resilience
3. validation/data-quality improvements
4. upload/document UX resilience
5. usability/performance refinements
- For each slice, require:
- explicit statement of intended behaviour change (or confirmation of no change)
- EN/CY parity checks
- negative-path checks
- rollback plan
---
## Evolving this into a multi-appeal-type platform (beyond S78)
To move from an S78-focused journey to a reusable **new appeal platform**, the safest path is to keep S78 as the baseline contract and introduce platform capabilities in additive slices.
## Platform principles
- Keep **S78 as reference behaviour** (do not regress)
- Drive variation via **configuration and schema**, not hardcoded branching
- Keep a stable core runtime for:
- start/resume/save
- section rendering
- validation execution
- upload/check/submit/finalise
- Isolate appeal-type specifics behind explicit adapters
## Recommended platform workstreams
## 1) Appeal-type definition contract
Define a typed “appeal definition” model for each appeal type, covering:
- metadata (id, route key, labels, EN/CY text references)
- section order and visibility rules
- field/validation rules
- required-doc rules
- submission/finalisation behaviour flags
Start by expressing S78 in this contract first, then add new appeal types using the same contract.
## 2) Start-flow strategy model
Generalise `createCase`/`aboutyou` into a strategy-driven start flow:
- shared start-flow shell
- per-appeal-type start-step configuration
- clear branching policy hooks (e.g., HASCAS-style gates as config)
This avoids adding new hardcoded conditions per appeal type.
## 3) Validation engine boundary
Move towards a validation layer that consumes appeal-definition rules:
- common validator primitives
- per-appeal rule sets loaded by appeal type
- explicit cross-field dependency maps
Preserve existing messages/behaviour for S78 while introducing extension points.
## 4) Section and field rendering registry
Introduce a registry pattern for section/field rendering rules:
- field-type renderer map (already partially established)
- appeal-type-specific section decorators where needed
- strict fallback behaviour for unsupported fields
This enables incremental onboarding of new forms without rewriting core flow components.
## 5) Submission and integration adapters
Define adapter interfaces for variation points:
- payload mapping by appeal type
- finalisation actions by appeal type
- notification templates by appeal type/locale
Core workflow should call adapters, not branch inline by appeal type.
## 6) Platform test matrix and release gates
Adopt a matrix-driven regression model:
- rows: appeal types
- columns: protected journeys + EN/CY parity + negative paths
Require S78 baseline pass + new-type pass before release.
## Suggested delivery sequence (safe)
1. Define appeal-type contract (S78 only)
2. Map current S78 start flow to strategy model (no behaviour change)
3. Introduce validation/section registries behind existing behaviour
4. Add adapter boundaries for submit/finalise integrations
5. Pilot one additional appeal type behind feature flag/config gating
6. Expand matrix automation and observability
## Guardrails while platformising
- Do not change S78 business behaviour unintentionally
- No payload/field/query contract drift for existing types
- Preserve save/resume compatibility
- Preserve EN/CY parity across all onboarded types
- Keep rollout incremental with clear rollback per slice
+128 -57
View File
@@ -1,90 +1,161 @@
# Refactor Branch Charter — New Appeal Flow
# Refactor Branch Charter — Portal Journeys
## Purpose
This branch exists to safely refactor the live new appeal flow so it is easier to maintain, safer to change, and better prepared to support additional appeal types beyond the current S78 planning appeal flow.
This branch exists to safely refactor **core portal journeys** so they are:
- easier to maintain
- safer to change
- better structured for future extensibility
This is a **behaviour-preserving refactor branch**, not a feature branch.
---
## Primary Goal
Create a safer internal structure for the new appeal flow while preserving current live behaviour for the S78 appeal journey.
Improve internal structure of portal workflows while preserving all current live behaviour.
## Why This Branch Exists
The current new appeal implementation has grown over time to meet business need and now contains a mix of:
- page composition
- flow orchestration
- XML-driven form rendering
- validation
- file/document handling
- progress/save logic
- submission/finalisation logic
- integration shaping for CRM, PDF generation, and notifications
This branch exists to improve those boundaries incrementally without disrupting the live service.
---
## Scope
In scope:
### In Scope
- behaviour-preserving refactor of `pages/newappeal/**` and `components/newappeal/**`
- extraction of reusable workflow logic from UI-heavy components
- improved boundaries between rendering, workflow, and integration logic
- regression test coverage for critical S78 journeys
- preparing the codebase for future appeal-type extensibility
- behaviour-preserving refactor of:
- new appeal flow (`pages/newappeal/**`, `components/newappeal/**`)
- representations flow (case summary → representation journey)
- extraction of reusable workflow logic
- improved separation between:
- UI
- workflow orchestration
- data fetching
- integrations
- preparation for future extensibility
Out of scope unless explicitly requested:
---
### Out of Scope
- business rule changes
- visual redesign
- broad framework/library migration
- replacing working dynamic form behaviour with hardcoded appeal-specific logic
- changes to live BAU behaviour beyond strictly necessary bug fixes
- UI redesign
- payload/schema changes
- replacing dynamic/config-driven logic with hardcoding
- feature delivery mixed with refactor work
## Branch Relationship to BAU
---
- BAU continues on `SIPS-Development`
- this branch is the protected refactor lane
- safe, proven slices may be merged back into `SIPS-Development` when ready
- urgent live fixes should go to `SIPS-Development` first, then be synced into this branch
## Branch Model
### Roles
- `SIPS-Development`
- BAU branch
- ongoing production work
- `refactor`
- refactor integration branch
- feature branches
- created from `refactor`
- one per slice
---
### Flow
SIPS-Development → refactor → slice branches → refactor → SIPS-Development
---
## Refactor Streams
### 1. New Appeal Flow (Completed)
- Slice-based refactor (Slices 18)
- Behaviour preserved (S78)
- Improved structure and maintainability
This serves as the **reference model for future refactors**
---
### 2. Representations Flow (Active)
Scope includes:
- Case summary entry (CTA logic)
- Representation journey:
- capacity selection
- representation type
- content entry
- file upload
- check answers
- submission
- completion
- SSR/data loading and Redux hydration
- integration points (CRM, blob storage)
---
## Non-Negotiable Principles
1. Preserve live S78 behaviour unless explicitly told otherwise.
2. Prefer extraction over rewrite.
3. Prefer small, mergeable slices over long-lived hidden change.
4. Add or update regression protection before changing critical flow logic.
5. Keep English/Welsh behaviour aligned.
6. Treat save/resume/upload/check/submit/complete as protected journey stages.
1. Preserve live behaviour
2. Prefer extraction over rewrite
3. Work in small, safe slices
4. Keep changes reversible
5. Protect:
- save/resume flows
- upload behaviour
- submission/finalisation
6. Maintain EN/CY parity
---
## Target Direction
The long-term direction is:
Move towards:
- shared new appeal workflow engine
- appeal-type definitions/configuration separated from UI rendering
- smaller, clearer components
- isolated validation and payload-shaping logic
- safer addition of future appeal types through definition + bounded type-specific rules
- shared journey/workflow engine
- smaller, composable components
- clear separation of:
- decision logic
- rendering
- integration logic
- ability to support:
- multiple appeal types
- additional portal journeys (like representations)
---
## Definition of Success
This branch is succeeding when:
This branch is successful when:
- core S78 journey behaviour remains stable
- regression confidence increases
- high-risk logic moves out of large render-heavy components
- new appeal code becomes easier to understand and test
- future appeal types can be added with less change to core flow code
- behaviour is preserved across all journeys
- complexity is reduced
- code is easier to understand and change
- regression risk is lower
- new journeys/types can be added safely
## Working Branch Model
---
This refactor stream uses the `refactor` branch as its working base.
## Delivery Model
- BAU continues on `SIPS-Development`
- refactor work is performed from `refactor`
- safe refactor slices may later be merged into `SIPS-Development`
Each refactor stream must:
This branch should not be treated as BAU, and BAU should not be treated as the refactor workspace.
1. follow slice-based approach
2. implement one concern per slice
3. validate behaviour after each slice
4. merge into `refactor` only when safe
5. merge to `SIPS-Development` only when stable
---
## Safety Reminder
This is a live system.
If there is any doubt:
> Preserve behaviour, reduce risk, and keep changes small.
@@ -0,0 +1,300 @@
# Representations Refactor — Current State of Play
## Purpose
This document captures the **pre-refactor state** of the representations flow and defines the starting point for the behaviour-preserving refactor stream.
It mirrors the approach used for the new appeal refactor and will be updated as slices are completed.
---
## Executive Summary
The representations flow is:
- functionally complete and live
- behaviourally stable
- structurally complex and tightly coupled
The flow currently:
- spans multiple entry points
- mixes UI, workflow, and data logic
- contains duplicated branching and rendering logic
- relies heavily on shared global state (`currentView`, `searchResultsObj`)
---
## Journey Overview
The user journey is:
1. Navigate to case summary page
2. Click **Make representation / consultation**
3. Enter representation flow
4. Select capacity
5. Select representation type
6. Enter content and upload files
7. Review check answers
8. Submit representation
9. View confirmation/completion
---
## Entry Points
### Primary Entry
- `CaseSummary` component
- CTA button logic determines:
- whether representation is allowed
- which label to display
- which route to navigate to
### Route
- `/myportal/representation?case=<caseRef>`
---
## Dual Mode Behaviour (Critical)
The flow operates in two modes:
### 1. New Representation (from search/case)
- triggered from case summary CTA
- loads case data via search + details APIs
- initializes new representation state
---
### 2. Existing Representation (resume/edit)
- triggered via query param (`state`)
- loads representation from blob storage
- hydrates existing data and files
---
This dual-mode behaviour is a **major complexity driver**.
---
## Architecture Overview
### High-Level Structure
- Page layer (SSR + Redux hydration)
- Case component (core orchestration)
- Representation flow components (capacity/type/content/check)
- Shared helpers (`representationElements`)
- Service layer (case data, blob storage, CRM integration)
---
### Key Components
- `CaseSummary` → entry + CTA logic
- `Case` → main orchestration component
- Representation flow components:
- capacity selection
- representation type selection
- content entry
- check answers
- completion
---
### State Management
Primary state dependencies:
- `currentView`
- `searchResultsObj`
- `myRepresentations`
- `filesForRepresentations`
Heavy reliance on deeply nested props.
---
## Current Architecture Issues
### 1. High Coupling
- UI, workflow logic, and data fetching are tightly mixed
- large components handle multiple responsibilities
---
### 2. Deep Prop Chains
Examples:
- `props.currentView.caseReference.*`
- `props.searchResultsObj.*`
This reduces readability and increases fragility.
---
### 3. Duplicated Logic
- appeal-type branching repeated across components
- summary rendering duplicated by case type
- representation form structure repeated across capacity types
---
### 4. Dual Entry Complexity
- separate logic paths for new vs existing representation
- mixed within the same components
---
### 5. Async Data Complexity
- chained service calls:
- `getCase`
- `getPortalModuleDetails`
- repeated across different contexts
- hard to reason about and test
---
### 6. Inline Business Logic
- eligibility rules embedded in UI components
- date checks and appeal-type logic duplicated
- LPA-specific behaviour scattered
---
## Risk Areas
High-risk areas that require extra caution:
- CaseSummary eligibility logic
- SSR/data-loading logic for representation page
- submission/finalisation flow
- file upload handling
- dual-mode entry (new vs existing)
- Redux hydration and state consistency
---
## Behavioural Constraints (Must Not Change)
- eligibility rules for making a representation
- journey step order and navigation
- validation rules and messaging
- payload structure sent to backend/CRM
- file upload and metadata behaviour
- submission/finalisation behaviour
- confirmation page behaviour
- route/query parameter structure
- EN/CY parity
---
## Comparison to New Appeal Flow
### Similarities
- step-based user journey
- check answers before submission
- file upload and validation steps
- finalisation/confirmation stage
---
### Differences (Important)
- dual-mode entry (new vs existing)
- more reliance on external data sources
- less structured “engine” (more implicit logic)
- heavier coupling to case summary and search flows
---
## Refactor Readiness
The flow is suitable for refactor because:
- behaviour is stable
- clear boundaries can be identified
- repeated patterns exist
- appeal refactor provides a proven model
---
## Refactor Strategy
The refactor will follow a **slice-based, behaviour-preserving approach**:
1. Extract entry logic (CaseSummary)
2. Separate SSR/data-loading concerns
3. isolate step resolution logic
4. decompose large components
5. clean up shared helpers
6. stabilize async/service layers
7. isolate submission/finalisation
---
## Initial Slice Focus
### Slice R1 — Entry Logic Extraction
Target:
- representation eligibility logic in `CaseSummary`
Goal:
- reduce coupling
- isolate decision logic
- prepare for safe downstream refactor
---
## Validation Position
At start of refactor:
- behaviour is assumed correct
- no structural isolation exists
- regression testing is manual
Each slice must:
- prove behaviour unchanged
- reduce complexity incrementally
---
## Conclusion
The representations flow is:
- behaviourally stable
- structurally complex
- suitable for controlled refactor
The goal is to:
- reduce coupling
- improve clarity
- enable safer future changes
without altering live behaviour.
---
## Next Step
Begin **Slice R1 — Representation Entry Logic Extraction**
Following strict guardrails and regression validation.
@@ -0,0 +1,137 @@
# Representations Refactor Guardrails
## Purpose
These guardrails apply to all work on the **representations refactor stream**.
This stream follows the same discipline as the new appeal refactor:
> Behaviour-preserving, slice-based refactor of a live journey.
---
## Critical Rule
Preserve the current live behaviour of the representations journey.
Do not assume a cleaner implementation allows behaviour changes.
---
## Protected Journey
The following user journey must not regress:
1. Enter case summary page
2. Click **Make representation / consultation**
3. Navigate to representation flow
4. Select capacity
5. Select representation type
6. Enter content and upload files
7. View check answers
8. Submit representation
9. View completion/confirmation
---
## Protected Behaviour
Do not change:
- representation eligibility logic (dates, appeal type, specialist process)
- CTA visibility and routing from case summary
- capacity selection behaviour
- representation type branching
- validation rules and messaging
- payload shape sent to backend/CRM
- file upload handling and metadata
- submission/finalisation flow
- confirmation behaviour
- navigation order or step progression
- route/query parameters
- EN/CY behaviour
---
## Refactor Approach
When refactoring:
1. Understand current behaviour first
2. Identify smallest safe boundary
3. Prefer extraction over rewrite
4. Keep interfaces stable
5. Avoid mixing concerns in one change
6. Keep slices small and reversible
---
## Required Testing Mindset
Before completing any slice:
- manually walk the full representation journey
- verify:
- start from case summary CTA
- capacity → type → content → check → submit
- successful completion
- verify EN/CY parity
- verify no navigation or state regression
If behaviour cannot be confidently verified:
→ do not proceed
---
## Payload / Integration Safety
Do not change without explicit requirement:
- CRM payload structure
- field names or mapping
- document/file metadata shape
- blob storage structure
- submission API behaviour
---
## i18n / Accessibility Safety
For any user-facing change:
- maintain EN/CY parity
- do not change translation keys unless required
- preserve accessibility semantics and structure
- maintain focus and validation behaviour
---
## What To Avoid
Do not:
- rewrite large components in one step
- introduce new business rules
- hardcode dynamic logic
- mix refactor with feature work
- change multiple concerns in one slice
---
## Refactor Success Criteria
A slice is successful when:
- behaviour is unchanged
- complexity is reduced
- readability is improved
- regression risk is controlled
- change is small and reviewable
---
## One-Line Rule
If in doubt:
> Keep behaviour the same, reduce risk, and make the smallest safe change.
+206
View File
@@ -0,0 +1,206 @@
# Representations Refactor Tracker
Base branch: `refactor`
---
## Status
Current slice: Slice R1 — Representation Entry Logic Extraction
Status: COMPLETE
---
## Slice List
---
### Slice R1 — Representation Entry Logic Extraction
**Goal:**
Extract representation eligibility and CTA logic from `CaseSummary`.
**Scope:**
- showRepButton logic
- date window checks (showReps / showRepsEnded)
- appeal type branching
- LPA-specific behaviour
- CTA route construction
**Rules:**
- No behaviour change
- No UI change
- Same inputs/outputs
**Completion notes (this slice):**
- Extracted representation-entry decision logic from `components/case/summary.js` into `components/case/summary/utils/representationEntry.js`.
- Preserved existing branch structure/order and duplicated consultation/general render branches.
- Preserved existing data-source usage (`detailsObj` vs `searchDetailsObj`) and existing constants/field names.
- Preserved local date-check behaviour via extracted local-equivalent helpers (`showRepsLocal`, `showRepsEndedLocal`).
- Validation evidence:
- `npm run lint` completed (warnings only, no new errors).
- Manual regression checks reported as passed (APP/IP/Agent/LPA), including EN/CY parity and route/query behaviour.
---
### Slice R2 — Representation Page Loader Separation
**Goal:**
Separate SSR/data-loading paths.
**Scope:**
- existing representation (state param)
- new representation (from search/case)
**Target:**
- `loadExistingRepresentation()`
- `loadNewRepresentation()`
---
### Slice R3 — Journey Step Resolution Extraction
**Goal:**
Isolate step navigation logic.
**Scope:**
- current step determination
- next/previous step logic
- validation gating between steps
---
### Slice R4 — Flow Shell Decomposition
**Goal:**
Break large flow component into smaller parts.
**Target components:**
- Capacity selection
- Representation type selection
- Content entry
- Check answers
- Completion
---
### Slice R5 — Representation Elements Normalisation
**Goal:**
Clean up shared UI helpers and duplicated patterns.
**Scope:**
- input rendering
- file upload handling (structure only, not behaviour)
- shared UI logic extraction
---
### Slice R6 — Async Data / Service Layer Cleanup
**Goal:**
Reduce duplication and coupling in data fetching.
**Scope:**
- getCase → getPortalModuleDetails chains
- blob/file retrieval
- representation detail aggregation
---
### Slice R7 — Summary / Case-Type Rendering Simplification (Optional)
**Goal:**
Reduce duplication in summary-type components.
**Scope:**
- unify repeated rendering patterns
- introduce shared summary renderer where safe
---
### Slice R8 — Submission / Finalisation Boundary Isolation
**Goal:**
Isolate submission logic.
**Scope:**
- payload shaping
- submit calls
- completion handling
**Risk Level:** HIGH
(Must only be done after earlier slices stabilised)
---
## Rules
- Only work on ONE slice at a time
- Do not combine slices
- One branch per slice
- One commit per slice
- Update tracker after completion
- Do not proceed if regression risk exists
---
## Regression Checklist (Run After Each Slice)
### Core Journey
- Navigate from case summary → Make representation
- Select capacity
- Select representation type
- Enter content
- Upload files (if applicable)
- View check answers
- Submit representation
- View confirmation page
---
### Validation
- EN/CY parity maintained
- No navigation regressions
- No state inconsistencies
- No console errors
---
### Technical
- `npm run lint` passes
- No new warnings/errors introduced
---
## Notes
- CaseSummary is a high-risk entry point
- Eligibility logic is complex and must not drift
- Submission flow is highly sensitive
- Dual-mode entry (new vs existing representation) is a key complexity
---
## Definition of Done (Per Slice)
A slice is complete when:
- behaviour is preserved
- regression checks pass
- code is cleaner and easier to understand
- change is small and safe to merge