From 206310d1254355e7775063a63ad38b8b1b743b72 Mon Sep 17 00:00:00 2001 From: Sajith Ekanayaka Date: Mon, 27 Jul 2026 19:58:12 +0530 Subject: [PATCH 01/10] [CSM Portal] move linked service requests into the Related tab Now that watchers has its own tab, the Details tab's card layout has room; move the Linked service requests card into the Related tab alongside child cases so cross-case links live with other case-relationship content instead of general details. --- .../csm-cases/pages/CsmCaseDetailPage.tsx | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/apps/csm-portal/webapp/src/features/csm-cases/pages/CsmCaseDetailPage.tsx b/apps/csm-portal/webapp/src/features/csm-cases/pages/CsmCaseDetailPage.tsx index fcaf250a6c..99a81bbdc9 100644 --- a/apps/csm-portal/webapp/src/features/csm-cases/pages/CsmCaseDetailPage.tsx +++ b/apps/csm-portal/webapp/src/features/csm-cases/pages/CsmCaseDetailPage.tsx @@ -1985,6 +1985,22 @@ export default function CsmCaseDetailPage(): JSX.Element { onRemove={isClosed ? undefined : (t) => onRemoveTag(t.id)} removingId={removeTag.isPending ? removeTag.variables : null} /> + + )} + + {activeTab === "related" && ( + + Linked service requests @@ -2020,12 +2036,6 @@ export default function CsmCaseDetailPage(): JSX.Element { )} - {activeTab === "related" && ( - - - - )} - {activeTab === "watchers" && ( {/* Watchers list — moved off the (single-line) overview Cell so a From 6f55531bb2202fd85ae34c01a6c0c493430a0c30 Mon Sep 17 00:00:00 2001 From: Sajith Ekanayaka Date: Mon, 27 Jul 2026 20:04:48 +0530 Subject: [PATCH 02/10] remove duplicate More-actions entries now covered by their own tab; hide SLAs tab - Manage watchers, Link to another case, and Request a call are removed from the case detail More-actions menu: each now has a fully equivalent, directly reachable entry point in its own tab (Watchers tab's inline add/remove, Related tab's own "Link to another case" button, Call requests tab's own "Create call request" button), so keeping both was two ways to do one thing. Create task stays in the menu since the Tasks tab is still hidden and has no create affordance of its own. - Removed the now-dead autoOpenCallCreate plumbing that only existed to support the removed "Request a call" menu item. - SLAs tab hidden in TAB_DEFS (data/hooks untouched, same pattern already used for the Tasks tab). --- .../components/CaseActionBar.test.tsx | 4 +- .../csm-cases/components/CaseActionBar.tsx | 47 +++++++------------ .../csm-cases/pages/CsmCaseDetailPage.tsx | 31 +----------- 3 files changed, 19 insertions(+), 63 deletions(-) diff --git a/apps/csm-portal/webapp/src/features/csm-cases/components/CaseActionBar.test.tsx b/apps/csm-portal/webapp/src/features/csm-cases/components/CaseActionBar.test.tsx index b3ae470517..f230d19622 100644 --- a/apps/csm-portal/webapp/src/features/csm-cases/components/CaseActionBar.test.tsx +++ b/apps/csm-portal/webapp/src/features/csm-cases/components/CaseActionBar.test.tsx @@ -369,12 +369,10 @@ describe("CaseActionBar — Raise internal Git issue is blocked on a closed case }); }); -describe("CaseActionBar — Manage watchers / Hold auto-closure / Edit case details / Link to another case", () => { +describe("CaseActionBar — Hold auto-closure / Edit case details", () => { const SECONDARY_ITEMS: Array<[RegExp, string]> = [ - [/manage watchers/i, "manage_watchers"], [/hold auto-closure/i, "hold_auto_close"], [/edit case details/i, "edit_case_details"], - [/link to another case/i, "link_case"], ]; it.each(SECONDARY_ITEMS)( diff --git a/apps/csm-portal/webapp/src/features/csm-cases/components/CaseActionBar.tsx b/apps/csm-portal/webapp/src/features/csm-cases/components/CaseActionBar.tsx index 692a022c66..1a3040277f 100644 --- a/apps/csm-portal/webapp/src/features/csm-cases/components/CaseActionBar.tsx +++ b/apps/csm-portal/webapp/src/features/csm-cases/components/CaseActionBar.tsx @@ -29,14 +29,12 @@ import { ChevronDown, Clock, Copy, - Eye, Gauge, GitBranch, Inbox, Link as LinkIcon, ListChecks, PauseCircle, - Phone, Pencil, Play, Send, @@ -201,26 +199,36 @@ interface SecondaryItem { * The "More" overflow lists state-independent actions on a case. Items here * map to documented use cases — see `UseCases.md`: * - Reassign engineer → ISSU-002 (self-assign generalised) - * - Manage watchers → ISSU-018 (PATCH /cases/{id} { watchList }); jumps to the case - * detail Related tab, which edits the watch list inline - * (see WatchersWidget in CaseDetailWidgets.tsx) * - Hold auto-closure → ISSU-027 (PATCH /cases/{id} { autocloseHoldUntil }, see SetAutocloseHoldDialog.tsx) * - Edit case details → subject/description/deployment/deployed product (see EditCaseDetailsDialog.tsx) - * - Link to another case → parent or related case (see LinkCaseDialog.tsx) * - Create incident from case → ISSU-021 (POST /incidents { parentId }, see * CreateIncidentPage.tsx's read of the nav state) * - Link to incident → ISSU-021 (PATCH /cases/{id} { parentId }, see * LinkIncidentDialog.tsx) * - Raise Git issue → ISSU-020 - * - Create task → ISSU-025 (POST /cases/{caseId}/tasks, see CreateTaskDialog.tsx) + * - Create task → ISSU-025 (POST /cases/{caseId}/tasks, see CreateTaskDialog.tsx). + * Kept here even though a Tasks tab exists: that tab is + * still `hidden` in CsmCaseDetailPage's TAB_DEFS, so this + * menu item is the only reachable entry point today. * - Set fix ETA → PATCH /cases/{id} { fixEta }, see SetFixEtaDialog.tsx - * - Request a call → ISSU-008 (opens the Call requests tab's create dialog) * - Log time → ISSU-017 * - Change severity → PATCH /cases/{id} { severity }, already fully * backend-supported (see ChangeSeverityDialog.tsx) * - Copy case link → ISSU-010 (per-comment + per-case permalinks) * - * Intentionally NOT here: + * Intentionally NOT here (removed as duplicate entry points once their target + * tab already exposes the same action directly, so there's one way to do each + * thing rather than two): + * - Manage watchers → the Watchers tab does inline add/remove already; the + * menu item only ever jumped there with no dialog of + * its own (ISSU-018). + * - Link to another case → the Related tab's "Linked service requests" card + * has its own "Link to another case…" button wired to + * the same LinkCaseDialog. + * - Request a call → the Call requests tab has its own "Create call + * request" button (CallRequestsWidget.tsx); the menu + * item only jumped there and auto-opened that same + * dialog (ISSU-008). * - Open in ServiceNow → this platform replaces ServiceNow; no back-link * - Escalate to lead → withdrawn, no backend flow planned yet */ @@ -308,13 +316,6 @@ function buildSecondaryItems(caseDetail: CsmCaseDetail): SecondaryItem[] { key: "edit_case_details", label: "Edit case details…", icon: , - disabled: caseClosed, - tooltip: caseClosed ? "This case is closed — it's read-only." : undefined, - }, - { - key: "manage_watchers", - label: "Manage watchers…", - icon: , divider: true, disabled: caseClosed, tooltip: caseClosed ? "This case is closed — it's read-only." : undefined, @@ -323,13 +324,6 @@ function buildSecondaryItems(caseDetail: CsmCaseDetail): SecondaryItem[] { key: "hold_auto_close", label: "Hold auto-closure…", icon: , - disabled: caseClosed, - tooltip: caseClosed ? "This case is closed — it's read-only." : undefined, - }, - { - key: "link_case", - label: "Link to another case…", - icon: , divider: true, disabled: caseClosed, tooltip: caseClosed ? "This case is closed — it's read-only." : undefined, @@ -364,13 +358,6 @@ function buildSecondaryItems(caseDetail: CsmCaseDetail): SecondaryItem[] { disabled: caseClosed, tooltip: caseClosed ? "This case is closed — it's read-only." : undefined, }, - { - key: "request_call", - label: "Request a call…", - icon: , - disabled: caseClosed, - tooltip: caseClosed ? "This case is closed — it's read-only." : undefined, - }, { key: "log_time", label: "Log time…", icon: , divider: true }, { key: "copy_link", label: "Copy case link", icon: }, ); diff --git a/apps/csm-portal/webapp/src/features/csm-cases/pages/CsmCaseDetailPage.tsx b/apps/csm-portal/webapp/src/features/csm-cases/pages/CsmCaseDetailPage.tsx index 99a81bbdc9..098660801b 100644 --- a/apps/csm-portal/webapp/src/features/csm-cases/pages/CsmCaseDetailPage.tsx +++ b/apps/csm-portal/webapp/src/features/csm-cases/pages/CsmCaseDetailPage.tsx @@ -296,7 +296,7 @@ const TAB_DEFS: Array<{ { id: "details", label: "Details", icon: }, { id: "related", label: "Related", icon: }, { id: "watchers", label: "Watchers", icon: }, - { id: "sla", label: "SLAs", icon: }, + { id: "sla", label: "SLAs", icon: , hidden: true }, { id: "attachments", label: "Attachments", icon: }, { id: "time", label: "Time tracking", icon: }, { id: "call-requests", label: "Call requests", icon: }, @@ -447,10 +447,6 @@ export default function CsmCaseDetailPage(): JSX.Element { } | null>(null); const [severityOpen, setSeverityOpen] = useState(false); const [logTimeOpen, setLogTimeOpen] = useState(false); - // One-shot: true to pop open the Call requests tab's "Create call request" - // dialog from the action bar's "Request a call" item. The widget flips it - // back to false once handled, so switching tabs afterwards doesn't reopen it. - const [autoOpenCallCreate, setAutoOpenCallCreate] = useState(false); const [githubIssueOpen, setGithubIssueOpen] = useState(false); // Inline error shown inside the Git-issue dialog (e.g. the SN routing 422 / // state 409). Cleared when the dialog opens or a submit is retried. @@ -488,7 +484,6 @@ export default function CsmCaseDetailPage(): JSX.Element { setResolutionDialog(null); setSeverityOpen(false); setLogTimeOpen(false); - setAutoOpenCallCreate(false); setGithubIssueOpen(false); setGithubIssueError(null); setGithubIssueResult(null); @@ -804,13 +799,6 @@ export default function CsmCaseDetailPage(): JSX.Element { return; } - // Manage watchers jumps to the Watchers tab, which edits the watch - // list inline (add/remove chips) rather than opening a separate dialog. - if (action.secondary === "manage_watchers") { - setActiveTab("watchers"); - return; - } - // Hold auto-closure opens the date picker; the PATCH happens in // onSetAutocloseHold once a date is confirmed. if (action.secondary === "hold_auto_close") { @@ -825,13 +813,6 @@ export default function CsmCaseDetailPage(): JSX.Element { return; } - // Link to another case opens the search-and-pick dialog; the PATCH - // happens in onLinkCase once a target case and link type are chosen. - if (action.secondary === "link_case") { - setLinkCaseOpen(true); - return; - } - // Create incident from case navigates to the create-incident form, // pre-filled with this case as the new incident's parent (ServiceNow's // generic task-parent reference — see CreateIncidentPage.tsx's read of @@ -963,14 +944,6 @@ export default function CsmCaseDetailPage(): JSX.Element { return; } - // Jump to the Call requests tab and pop its own "Create call request" - // dialog, rather than a second/duplicate entry point for the same form. - if (action.secondary === "request_call") { - setActiveTab("call-requests"); - setAutoOpenCallCreate(true); - return; - } - // Reachable only for a secondary action with no handler above — every // menu item that isn't wired up yet is disabled in CaseActionBar, so // this is a defensive fallback, not a normal path. @@ -2092,8 +2065,6 @@ export default function CsmCaseDetailPage(): JSX.Element { setAutoOpenCallCreate(false)} isClosed={isClosed} /> From ad8049aedf3aaed4e9bb1846bf332d4c5cb967fc Mon Sep 17 00:00:00 2001 From: Sajith Ekanayaka Date: Mon, 27 Jul 2026 20:10:28 +0530 Subject: [PATCH 03/10] [CSM Portal] give the change request detail page a tabbed layout, matching case detail --- .../pages/CsmChangeRequestDetailPage.tsx | 299 +++++++++++------- 1 file changed, 184 insertions(+), 115 deletions(-) diff --git a/apps/csm-portal/webapp/src/features/csm-operations/pages/CsmChangeRequestDetailPage.tsx b/apps/csm-portal/webapp/src/features/csm-operations/pages/CsmChangeRequestDetailPage.tsx index f2b6fddea1..4adfa4dadc 100644 --- a/apps/csm-portal/webapp/src/features/csm-operations/pages/CsmChangeRequestDetailPage.tsx +++ b/apps/csm-portal/webapp/src/features/csm-operations/pages/CsmChangeRequestDetailPage.tsx @@ -20,10 +20,23 @@ import { Card, Chip, Skeleton, + Tab, + Tabs, Tooltip, Typography, } from "@wso2/oxygen-ui"; -import { ArrowLeft, Check, MessageSquarePlus, Pencil, Send, X } from "@wso2/oxygen-ui-icons-react"; +import { + ArrowLeft, + Check, + ClipboardCheck, + FileText, + MessageSquare, + MessageSquarePlus, + Paperclip, + Pencil, + Send, + X, +} from "@wso2/oxygen-ui-icons-react"; import { type JSX, type ReactNode, useCallback, useMemo, useState } from "react"; import { useParams } from "react-router"; import { formatBackendTimestampForDisplay } from "@utils/dateTime"; @@ -140,6 +153,19 @@ function PlanSection({ title, html }: { title: string; html?: string | null }): ); } +type ChangeRequestTabId = "approval" | "details" | "comments" | "attachments"; + +const TAB_DEFS: Array<{ + id: ChangeRequestTabId; + label: string; + icon: JSX.Element; +}> = [ + { id: "approval", label: "Approval", icon: }, + { id: "details", label: "Details", icon: }, + { id: "comments", label: "Comments", icon: }, + { id: "attachments", label: "Attachments", icon: }, +]; + /** * Read-only detail for a single change request (`GET /change-requests/{id}`): * its references, the change window, approval state, and the implementation / @@ -152,6 +178,7 @@ export default function CsmChangeRequestDetailPage(): JSX.Element { const { showError } = useErrorBanner(); const patchCr = usePatchChangeRequest(); const [editOpen, setEditOpen] = useState(false); + const [activeTab, setActiveTab] = useState("approval"); const engineerName = useEngineerDisplayName(); const { data: comments } = useGetCsmChangeRequestComments(id); @@ -378,127 +405,169 @@ export default function CsmChangeRequestDetailPage(): JSX.Element { - - Approval - + setActiveTab(v as ChangeRequestTabId)} + variant="scrollable" + scrollButtons="auto" > - - - - - {formatDateTime(cr.approvedOn)} - + {TAB_DEFS.map((t) => { + // Counts shown only where the tab IS the list (unambiguous) — + // mirrors CsmCaseDetailPage's tab-count pattern. + const count = + t.id === "comments" + ? comments?.length + : t.id === "attachments" + ? attachmentList.length + : undefined; + return ( + + ); + })} + + + + {activeTab === "approval" && ( + + + Approval + + + + + + {formatDateTime(cr.approvedOn)} + + + + + - + )} - - - {[ - cr.description, - cr.justification, - cr.impactDescription, - cr.serviceOutage, - cr.communicationPlan, - cr.rollbackPlan, - cr.testPlan, - ].some((v) => v && !isBlankHtml(v)) && ( - - Details & plans - - - - - - - - + {activeTab === "details" && ( + [ + cr.description, + cr.justification, + cr.impactDescription, + cr.serviceOutage, + cr.communicationPlan, + cr.rollbackPlan, + cr.testPlan, + ].some((v) => v && !isBlankHtml(v)) ? ( + + Details & plans + + + + + + + + + ) : ( + + No details or plans have been recorded for this change request. + + ) )} - - Comments - {composerOpen ? ( - - - Reply - + {activeTab === "comments" && ( + + {composerOpen ? ( + + + Reply + + + { + if (!id) return; + const hasText = + bodyHtml.replace(/<[^>]*>/g, "").replace(/ /g, " ").trim().length > 0; + if (hasText) { + await postComment.mutateAsync({ + changeRequestId: id, + bodyHtml, + internal, + }); + } + for (const { file, name } of commentAttachments) { + await postAttachment.mutateAsync({ + caseId: id, + file, + name, + uploadedBy: engineerName, + referenceType: "change_request", + }); + } + setComposerOpen(false); + }} + /> - { - if (!id) return; - const hasText = - bodyHtml.replace(/<[^>]*>/g, "").replace(/ /g, " ").trim().length > 0; - if (hasText) { - await postComment.mutateAsync({ - changeRequestId: id, - bodyHtml, - internal, - }); - } - for (const { file, name } of commentAttachments) { - await postAttachment.mutateAsync({ - caseId: id, - file, - name, - uploadedBy: engineerName, - referenceType: "change_request", - }); - } - setComposerOpen(false); - }} - /> - - ) : ( - - )} - - + ) : ( + + )} + + + )} - - Attachments - - + {activeTab === "attachments" && ( + + + + )} {editOpen && ( Date: Mon, 27 Jul 2026 20:34:40 +0530 Subject: [PATCH 04/10] [CSM Portal] show all issue types (not just cases) on the project detail Issues tab The project detail page's Issues tab locks only the project filter, with no case-type lock, so it should return every issue type for that project. It was only ever showing support cases because an empty caseTypes filter gets omitted from the /cases/search request entirely, and the entity-service defaults an absent types filter to support cases only rather than "no restriction". Fix in CsmIssuesView: when the type filter is unlocked and nothing is selected, send every known case type explicitly instead of omitting the field, so the backend default can't silently narrow the result. Every other CsmIssuesView caller locks caseTypes to a single value already, so this only changes behavior for the one unlocked, multi-type view. --- .../csm-cases/components/CsmIssuesView.tsx | 34 ++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/apps/csm-portal/webapp/src/features/csm-cases/components/CsmIssuesView.tsx b/apps/csm-portal/webapp/src/features/csm-cases/components/CsmIssuesView.tsx index 6d2cd850da..649f7c15fd 100644 --- a/apps/csm-portal/webapp/src/features/csm-cases/components/CsmIssuesView.tsx +++ b/apps/csm-portal/webapp/src/features/csm-cases/components/CsmIssuesView.tsx @@ -35,6 +35,7 @@ import CasesList from "@features/csm-cases/components/CasesList"; import { useGetCsmCases } from "@features/csm-cases/api/useGetCsmCases"; import { useDirectoryUsers } from "@api/useDirectoryUsers"; import { BE_MAX_PAGE_LIMIT } from "@constants/apiConstants"; +import { ALL_CASE_TYPES } from "@features/csm-cases/utils/caseType"; import { DEFAULT_CASES_FILTERS, readCasesFiltersFromUrl, @@ -144,14 +145,31 @@ export default function CsmIssuesView({ // User filters (debounced search) with the locked overrides applied last so // the fixed type/project can't be widened by a stale URL value. const queryFilters = useMemo( - () => ({ - ...filters, - search: debouncedSearch, - // The severity control is hidden for non-case lists, so don't let a stale - // `severities` value from a shared URL silently filter those results. - ...(showSeverityFilter ? {} : { severities: [] }), - ...lockedFilters, - }), + () => { + const merged: CasesFilters = { + ...filters, + search: debouncedSearch, + // The severity control is hidden for non-case lists, so don't let a + // stale `severities` value from a shared URL silently filter those + // results. + ...(showSeverityFilter ? {} : { severities: [] }), + ...lockedFilters, + }; + // An unlocked, empty type selection means "no type filter applied" from + // the FE's perspective (every issue type shown — this is the only + // unlocked, multi-type view; every other CsmIssuesView caller locks + // `caseTypes` to a single value and hides the control). But + // `useGetCsmCases` omits an empty `caseTypes` from the search payload + // entirely, and the entity-service defaults an absent/empty `types` + // filter to support cases only (`default_case`) rather than "no + // restriction" — so an omitted filter silently narrows the result to + // one type instead of returning all of them. Send every known type + // explicitly in that case so the BE default can't kick in. + if (merged.caseTypes.length === 0) { + merged.caseTypes = ALL_CASE_TYPES; + } + return merged; + }, [filters, debouncedSearch, showSeverityFilter, lockedFilters], ); From c04e5919dfeb331390a838d7c998233f8f00e618 Mon Sep 17 00:00:00 2001 From: Sajith Ekanayaka Date: Mon, 27 Jul 2026 20:36:24 +0530 Subject: [PATCH 05/10] [CSM Portal] fix account page field-name mismatches (dates, tier) and search request shape - Rename the Account type's createdAt/updatedAt to createdOn/updatedOn to match every account response shape (both data sources return the *On fields, never *At). - Nest the account search request's searchQuery under filters, matching the backend's search payload shape and the pattern already used by the case search builder. - Tolerate the alternate account response shape's supportTier field (a plain string on the list view, an {id, label} ref on the detail view) alongside tier, since the FE has one Account type shared across both data sources. Adds a resolveAccountTier helper used on both pages. - Minor: show the existing empty-state placeholder for a blank SF ID on the accounts list, matching the detail page. --- .../pages/CsmAccountDetailPage.tsx | 22 +++-- .../csm-accounts/pages/CsmAccountsPage.tsx | 88 +++++++++++-------- .../csm-accounts/types/csmAccounts.ts | 37 +++++++- 3 files changed, 96 insertions(+), 51 deletions(-) diff --git a/apps/csm-portal/webapp/src/features/csm-accounts/pages/CsmAccountDetailPage.tsx b/apps/csm-portal/webapp/src/features/csm-accounts/pages/CsmAccountDetailPage.tsx index fc39266b6d..3776e3e38a 100644 --- a/apps/csm-portal/webapp/src/features/csm-accounts/pages/CsmAccountDetailPage.tsx +++ b/apps/csm-portal/webapp/src/features/csm-accounts/pages/CsmAccountDetailPage.tsx @@ -26,6 +26,7 @@ import { ArrowLeft } from "@wso2/oxygen-ui-icons-react"; import { type JSX, type ReactNode } from "react"; import { useParams } from "react-router"; import { useGetAccount } from "@features/csm-accounts/api/useGetAccount"; +import { resolveAccountTier } from "@features/csm-accounts/types/csmAccounts"; import { useNavTransition } from "@hooks/useNavTransition"; function formatDate(value?: string | null): string { @@ -121,6 +122,7 @@ export default function CsmAccountDetailPage(): JSX.Element { } const a = data; + const tier = resolveAccountTier(a); return ( @@ -129,12 +131,14 @@ export default function CsmAccountDetailPage(): JSX.Element { {a.name} - + {tier && ( + + )} {a.deactivationDate && ( )} @@ -159,7 +163,7 @@ export default function CsmAccountDetailPage(): JSX.Element { > - {a.tier} + {tier ?? "—"} @@ -197,10 +201,10 @@ export default function CsmAccountDetailPage(): JSX.Element { {a.technicalOwnerId || "—"} - {formatDate(a.createdAt)} + {formatDate(a.createdOn)} - {formatDate(a.updatedAt)} + {formatDate(a.updatedOn)} {a.id} diff --git a/apps/csm-portal/webapp/src/features/csm-accounts/pages/CsmAccountsPage.tsx b/apps/csm-portal/webapp/src/features/csm-accounts/pages/CsmAccountsPage.tsx index 01d0d2b39a..520f3a2751 100644 --- a/apps/csm-portal/webapp/src/features/csm-accounts/pages/CsmAccountsPage.tsx +++ b/apps/csm-portal/webapp/src/features/csm-accounts/pages/CsmAccountsPage.tsx @@ -33,7 +33,10 @@ import { Link as RouterLink } from "react-router"; import QueryErrorState from "@components/QueryErrorState"; import { useDebouncedValue } from "@hooks/useDebouncedValue"; import { useSearchAccounts } from "@features/csm-accounts/api/useSearchAccounts"; -import type { SearchAccountsRequest } from "@features/csm-accounts/types/csmAccounts"; +import { + resolveAccountTier, + type SearchAccountsRequest, +} from "@features/csm-accounts/types/csmAccounts"; import { BE_MAX_PAGE_LIMIT } from "@constants/apiConstants"; const DEFAULT_ROWS_PER_PAGE = 20; @@ -59,13 +62,15 @@ export default function CsmAccountsPage(): JSX.Element { const debouncedSearch = useDebouncedValue(searchInput, 300); - const request = useMemo( - () => ({ + const request = useMemo(() => { + const searchQuery = debouncedSearch.trim() || undefined; + return { pagination: { limit: rowsPerPage, offset: page * rowsPerPage }, - searchQuery: debouncedSearch.trim() || undefined, - }), - [debouncedSearch, page, rowsPerPage], - ); + // Filter fields are nested under `filters` (matches the `/cases/search` + // payload shape). + ...(searchQuery && { filters: { searchQuery } }), + }; + }, [debouncedSearch, page, rowsPerPage]); const { data, isLoading, isFetching, isError, error } = useSearchAccounts(request); @@ -141,37 +146,44 @@ export default function CsmAccountsPage(): JSX.Element { ) : ( - accounts.map((a) => ( - - - ({ - textDecoration: "none", - color: t.palette.primary.dark, - ...t.applyStyles("dark", { color: t.palette.primary.main }), - "&:hover": { textDecoration: "underline" }, - })} - > - {a.name} - - - {a.sfId} - - - - {a.region ?? "—"} - {formatDate(a.activationDate)} - {formatDate(a.deactivationDate)} - - )) + accounts.map((a) => { + const tier = resolveAccountTier(a); + return ( + + + ({ + textDecoration: "none", + color: t.palette.primary.dark, + ...t.applyStyles("dark", { color: t.palette.primary.main }), + "&:hover": { textDecoration: "underline" }, + })} + > + {a.name} + + + {a.sfId || "—"} + + {tier ? ( + + ) : ( + "—" + )} + + {a.region ?? "—"} + {formatDate(a.activationDate)} + {formatDate(a.deactivationDate)} + + ); + }) )} diff --git a/apps/csm-portal/webapp/src/features/csm-accounts/types/csmAccounts.ts b/apps/csm-portal/webapp/src/features/csm-accounts/types/csmAccounts.ts index 7e1c7e49cc..c3e027db6b 100644 --- a/apps/csm-portal/webapp/src/features/csm-accounts/types/csmAccounts.ts +++ b/apps/csm-portal/webapp/src/features/csm-accounts/types/csmAccounts.ts @@ -16,11 +16,25 @@ export type AccountTier = "basic" | "enterprise"; +// A support-tier reference as returned on the account detail view for the +// backing-data-source-backed shape ({id, label}), vs. a plain label string on +// the list view. See `tier`/`supportTier` below. +export interface SupportTierRef { + id: string; + label: string; +} + export interface Account { id: string; sfId: string; name: string; - tier: AccountTier; + // Postgres-backed accounts carry `tier`. Accounts sourced from the + // alternate (ServiceNow-shaped) response instead carry `supportTier`, + // either as a plain label string (list view) or an `{id, label}` ref + // (detail view) — there is only one FE `Account` type today, so both are + // modeled here as optional and resolved at the read site. + tier?: AccountTier; + supportTier?: string | SupportTierRef | null; region?: string | null; activationDate: string; deactivationDate?: string | null; @@ -28,8 +42,21 @@ export interface Account { technicalOwnerId?: string | null; agentEnabled: boolean; kbReferencesEnabled: boolean; - createdAt: string; - updatedAt: string; + createdOn: string; + updatedOn: string; +} + +/** + * Resolves the Tier value regardless of which response shape the account + * came from: Postgres-backed `tier`, or the alternate-shape `supportTier` + * (plain string on the list view, `{id, label}` ref on the detail view). + */ +export function resolveAccountTier( + account: Pick, +): string | undefined { + if (account.tier) return account.tier; + if (typeof account.supportTier === "string") return account.supportTier; + return account.supportTier?.label ?? undefined; } export interface SearchAccountsRequest { @@ -37,7 +64,9 @@ export interface SearchAccountsRequest { limit?: number; offset?: number; }; - searchQuery?: string; + filters?: { + searchQuery?: string; + }; } export interface SearchAccountsResponse { From c73509216e229df84e8980e7d79476297688d929 Mon Sep 17 00:00:00 2001 From: Sajith Ekanayaka Date: Mon, 27 Jul 2026 20:52:32 +0530 Subject: [PATCH 06/10] [Entity-Service] give attachment uploads their own size cap instead of the generic 1 MiB default CreateCaseAttachment routed through the generic decodeRequest helper, which enforces a blanket 1 MiB JSON body cap meant for small structured payloads. Any attachment upload over ~1 MiB (base64-encoded) was rejected with "request body too large" even though it is well under every advertised limit -- the FE's 10 MB client-side check and the csm-portal backend's own 15 MiB ceiling never got a chance to matter. Add decodeRequestWithLimit, a variant of decodeRequest that accepts a caller-supplied body size cap and too-large message, and use it for CreateCaseAttachment with a 15 MiB cap -- matching the csm-portal backend's own maxAttachmentBodyBytes ceiling (sized for a 10 MB file inflated by base64 plus JSON overhead). The error message now states the actual limit instead of the generic one. No other endpoint's cap changes. --- .../internal/handler/case_handler.go | 9 +- .../internal/handler/case_handler_test.go | 132 ++++++++++++++++++ entity-service/internal/handler/decode.go | 23 ++- 3 files changed, 160 insertions(+), 4 deletions(-) create mode 100644 entity-service/internal/handler/case_handler_test.go diff --git a/entity-service/internal/handler/case_handler.go b/entity-service/internal/handler/case_handler.go index cc8d7f76f0..c395799c48 100644 --- a/entity-service/internal/handler/case_handler.go +++ b/entity-service/internal/handler/case_handler.go @@ -28,6 +28,13 @@ import ( "github.com/wso2-open-operations/cs-tools/entity-service/internal/service" ) +// maxAttachmentBodySize caps the CreateCaseAttachment JSON body at 15 MiB, +// matching the csm-portal backend's own maxAttachmentBodyBytes ceiling: a 10 +// MB file becomes ~13.3 MB once base64-encoded, plus JSON envelope overhead. +// The generic maxRequestBodySize (1 MiB) is far too small for this endpoint +// and rejects legitimate small attachments (e.g. a 2 MB file). +const maxAttachmentBodySize = int64(15 << 20) + // safeAttachmentTypes is the allowlist of Content-Type values that may be // forwarded as-is. Anything not in this set is coerced to application/octet-stream // to prevent a stored-XSS attack via a crafted upstream Content-Type (e.g. text/html). @@ -170,7 +177,7 @@ func (h *CaseHandler) SearchCases(w http.ResponseWriter, r *http.Request) { // CreateCaseAttachment handles POST /attachments. func (h *CaseHandler) CreateCaseAttachment(w http.ResponseWriter, r *http.Request) { var req domain.CreateAttachmentRequest - if !decodeRequest(w, r, &req) { + if !decodeRequestWithLimit(w, r, &req, maxAttachmentBodySize, "attachment exceeds the maximum allowed size of 10 MB") { return } resp, err := h.svc.CreateCaseAttachment(r.Context(), req) diff --git a/entity-service/internal/handler/case_handler_test.go b/entity-service/internal/handler/case_handler_test.go new file mode 100644 index 0000000000..4a31616592 --- /dev/null +++ b/entity-service/internal/handler/case_handler_test.go @@ -0,0 +1,132 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package handler + +import ( + "context" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/wso2-open-operations/cs-tools/entity-service/internal/domain" + "github.com/wso2-open-operations/cs-tools/entity-service/internal/service" +) + +// stubCaseService embeds the service.CaseService interface so tests only need +// to implement the method(s) under test; any call to an unimplemented method +// panics on the nil embedded interface, which is fine since these tests never +// reach them. +type stubCaseService struct { + service.CaseService + createAttachmentCalled bool + createAttachmentResp domain.CreateAttachmentResponse + createAttachmentErr error +} + +func (s *stubCaseService) CreateCaseAttachment(_ context.Context, _ domain.CreateAttachmentRequest) (domain.CreateAttachmentResponse, error) { + s.createAttachmentCalled = true + return s.createAttachmentResp, s.createAttachmentErr +} + +// attachmentRequestBody builds a valid CreateAttachmentRequest JSON body whose +// base64 "file" field is padded to approximately targetBytes total size, so +// tests can exercise the size cap without depending on a real file. +func attachmentRequestBody(t *testing.T, targetBytes int) []byte { + t.Helper() + // Reserve room for the JSON envelope; pad only the base64 payload. + const envelopeOverhead = 512 + payloadBytes := targetBytes - envelopeOverhead + if payloadBytes < 0 { + payloadBytes = 0 + } + raw := make([]byte, payloadBytes) + encoded := base64.StdEncoding.EncodeToString(raw) + + req := domain.CreateAttachmentRequest{ + ReferenceID: "11111111-1111-1111-1111-111111111111", + ReferenceType: domain.ReferenceTypeCase, + Name: "test-file.bin", + Type: "application/octet-stream", + File: encoded, + } + body, err := json.Marshal(req) + if err != nil { + t.Fatalf("marshal request: %v", err) + } + return body +} + +// TestCreateCaseAttachment_UnderNewLimit_OverOldLimit verifies a body larger +// than the old generic 1 MiB cap, but under the new 15 MiB attachment cap, +// is no longer rejected at the decode stage (this is the QA regression: a +// 2 MB attachment used to fail with "request body too large"). +func TestCreateCaseAttachment_UnderNewLimit_OverOldLimit(t *testing.T) { + body := attachmentRequestBody(t, 2<<20) // ~2 MiB, matches QA's repro size. + if int64(len(body)) <= maxRequestBodySize { + t.Fatalf("test body (%d bytes) must exceed the old 1 MiB limit (%d) to be meaningful", len(body), maxRequestBodySize) + } + if int64(len(body)) >= maxAttachmentBodySize { + t.Fatalf("test body (%d bytes) must stay under the new attachment limit (%d)", len(body), maxAttachmentBodySize) + } + + stub := &stubCaseService{ + createAttachmentResp: domain.CreateAttachmentResponse{Message: "created"}, + } + h := NewCaseHandler(stub) + + req := httptest.NewRequest(http.MethodPost, "/attachments", strings.NewReader(string(body))) + rec := httptest.NewRecorder() + + h.CreateCaseAttachment(rec, req) + + if !stub.createAttachmentCalled { + t.Fatalf("expected CreateCaseAttachment to reach the service layer, got status %d body %q", rec.Code, rec.Body.String()) + } + if rec.Code != http.StatusCreated { + t.Fatalf("expected 201 Created, got %d: %s", rec.Code, rec.Body.String()) + } +} + +// TestCreateCaseAttachment_OverNewLimit verifies a body over the new 15 MiB +// attachment cap is still rejected, with the attachment-specific message. +func TestCreateCaseAttachment_OverNewLimit(t *testing.T) { + body := attachmentRequestBody(t, 16<<20) // ~16 MiB, over the 15 MiB cap. + + stub := &stubCaseService{} + h := NewCaseHandler(stub) + + req := httptest.NewRequest(http.MethodPost, "/attachments", strings.NewReader(string(body))) + rec := httptest.NewRecorder() + + h.CreateCaseAttachment(rec, req) + + if stub.createAttachmentCalled { + t.Fatalf("expected the request to be rejected before reaching the service layer") + } + if rec.Code != http.StatusBadRequest { + t.Fatalf("expected 400 Bad Request, got %d: %s", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "attachment exceeds the maximum allowed size of 10 MB") { + t.Fatalf("expected the attachment-specific too-large message, got: %s", rec.Body.String()) + } + if strings.Contains(rec.Body.String(), "request body too large") { + t.Fatalf("expected the generic message to be replaced by the attachment-specific one, got: %s", rec.Body.String()) + } +} diff --git a/entity-service/internal/handler/decode.go b/entity-service/internal/handler/decode.go index 081e2e683f..f4b1ff5c3f 100644 --- a/entity-service/internal/handler/decode.go +++ b/entity-service/internal/handler/decode.go @@ -38,11 +38,20 @@ var sanitizeLog = strings.NewReplacer("\n", `\n`, "\r", `\r`).Replace // rejection, a 1 MiB body cap, and no trailing data after the JSON object. // Returns false and writes the error response if decoding fails. func decodeRequest[T any](w http.ResponseWriter, r *http.Request, dst *T) bool { - r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodySize) + return decodeRequestWithLimit(w, r, dst, maxRequestBodySize, "request body too large") +} + +// decodeRequestWithLimit is the same as decodeRequest but allows the caller to +// override the default 1 MiB body cap and the message returned when that cap +// is exceeded. Use this for endpoints whose payload is legitimately larger +// than the generic JSON body (e.g. base64-encoded file uploads) instead of +// changing the default for every other endpoint. +func decodeRequestWithLimit[T any](w http.ResponseWriter, r *http.Request, dst *T, limit int64, tooLargeMsg string) bool { + r.Body = http.MaxBytesReader(w, r.Body, limit) dec := json.NewDecoder(r.Body) dec.DisallowUnknownFields() if err := dec.Decode(dst); err != nil { - apierror.WriteJSON(w, http.StatusBadRequest, decodeErrMsg(err)) + apierror.WriteJSON(w, http.StatusBadRequest, decodeErrMsgWithLimit(err, tooLargeMsg)) return false } if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) { @@ -56,9 +65,17 @@ func decodeRequest[T any](w http.ResponseWriter, r *http.Request, dst *T) bool { // is safe to return to the caller. Infrastructure details (e.g. raw Go type // names) are replaced with user-friendly descriptions. func decodeErrMsg(err error) string { + return decodeErrMsgWithLimit(err, "request body too large") +} + +// decodeErrMsgWithLimit behaves like decodeErrMsg but lets the caller supply +// an endpoint-specific message for the body-too-large case, so a handler with +// a raised size cap (see decodeRequestWithLimit) can tell the caller what the +// actual limit is instead of the generic message. +func decodeErrMsgWithLimit(err error, tooLargeMsg string) string { var maxBytes *http.MaxBytesError if errors.As(err, &maxBytes) { - return "request body too large" + return tooLargeMsg } var syntaxErr *json.SyntaxError if errors.As(err, &syntaxErr) { From b5a4d96f993a333cf04edc4335db0884236b2d6a Mon Sep 17 00:00:00 2001 From: Sajith Ekanayaka Date: Mon, 27 Jul 2026 20:55:35 +0530 Subject: [PATCH 07/10] [Entity-Service] add SF ID to ServiceNow-backed account mapping Adds the field the backing data source already provides but wasn't being forwarded: SNAccountView and SNAccountDetail gain SfID, wired through from the ServiceNow account response's sfId field. --- entity-service/internal/domain/entity.go | 2 + .../internal/service/sn_account_service.go | 3 + .../service/sn_account_service_test.go | 91 +++++++++++++++++++ entity-service/openapi.yaml | 8 ++ 4 files changed, 104 insertions(+) create mode 100644 entity-service/internal/service/sn_account_service_test.go diff --git a/entity-service/internal/domain/entity.go b/entity-service/internal/domain/entity.go index 33aa8e1397..8e8ea6cad7 100644 --- a/entity-service/internal/domain/entity.go +++ b/entity-service/internal/domain/entity.go @@ -230,6 +230,7 @@ type SNAccountView struct { Name string `json:"name"` Classification string `json:"classification"` Pod *string `json:"pod"` + SfID *string `json:"sfId"` Region *string `json:"region"` SupportTier *string `json:"supportTier"` ArrToday *string `json:"arrToday"` @@ -266,6 +267,7 @@ type SNAccountDetail struct { Name string `json:"name"` Classification string `json:"classification"` Pod *string `json:"pod"` + SfID *string `json:"sfId"` Region *string `json:"region"` SupportTier *SNSupportTierRef `json:"supportTier"` ArrToday *string `json:"arrToday"` diff --git a/entity-service/internal/service/sn_account_service.go b/entity-service/internal/service/sn_account_service.go index a8c7843357..b5c51fd38b 100644 --- a/entity-service/internal/service/sn_account_service.go +++ b/entity-service/internal/service/sn_account_service.go @@ -50,6 +50,7 @@ type snAccount struct { SupportTier *snSupportTier `json:"supportTier"` Classification string `json:"classification"` Pod *string `json:"pod"` + SfID *string `json:"sfId"` Region *string `json:"region"` ArrToday *string `json:"arrToday"` ActivationDate string `json:"activationDate"` @@ -180,6 +181,7 @@ func snAccountToDomain(a snAccount) domain.SNAccountView { Name: a.Name, Classification: a.Classification, Pod: nilIfEmpty(a.Pod), + SfID: nilIfEmpty(a.SfID), Region: nilIfEmpty(a.Region), SupportTier: supportTier, ArrToday: nilIfEmpty(a.ArrToday), @@ -211,6 +213,7 @@ func snAccountToDetail(a snAccount) domain.SNAccountDetail { Name: a.Name, Classification: a.Classification, Pod: nilIfEmpty(a.Pod), + SfID: nilIfEmpty(a.SfID), Region: nilIfEmpty(a.Region), SupportTier: supportTier, ArrToday: nilIfEmpty(a.ArrToday), diff --git a/entity-service/internal/service/sn_account_service_test.go b/entity-service/internal/service/sn_account_service_test.go new file mode 100644 index 0000000000..2ea338c5a3 --- /dev/null +++ b/entity-service/internal/service/sn_account_service_test.go @@ -0,0 +1,91 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package service + +import ( + "net/http" + "testing" +) + +// snAccountJSON is a minimal ServiceNow account payload, with placeholders for +// the id and sfId under test. +func snAccountJSON(id, sfID string) string { + body := `{ + "id": "` + id + `", + "name": "Acme", + "classification": "enterprise", + "pod": "US - WEST", + "activationDate": "2026-01-01 00:00:00", + "hasAgent": false, + "hasKbReferences": false, + "createdOn": "2026-01-01 00:00:00", + "updatedOn": "2026-01-01 00:00:00"` + if sfID != "" { + body += `, "sfId": "` + sfID + `"` + } + body += `}` + return body +} + +// TestSNAccountService_GetAccountByID_SfIDRoundTrips verifies that the SF ID +// ServiceNow's AccountUtils now emits (u_account_id, surfaced as sfId) survives +// the SN JSON -> domain.SNAccountDetail conversion in GetAccountByID. +func TestSNAccountService_GetAccountByID_SfIDRoundTrips(t *testing.T) { + const wantSfID = "001E2000014mQ2hIAE" + + mux := http.NewServeMux() + mux.HandleFunc("/accounts/"+testAccountSysid, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(snAccountJSON(testAccountSysid, wantSfID))) + }) + + client := newTestSNClient(t, mux) + svc := NewServiceNowAccountService(client) + + got, err := svc.GetAccountByID(contextWithUserIDToken("token"), sysidToUUID(testAccountSysid)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if got.SfID == nil || *got.SfID != wantSfID { + t.Fatalf("SfID = %v, want %q", got.SfID, wantSfID) + } +} + +// TestSNAccountService_GetAccountByID_SfIDAbsent verifies that an account with +// no linked Salesforce ID surfaces a nil SfID rather than an empty string, so +// FE consumers can distinguish "not linked" from "linked, empty" the same way +// they already do for pod/region. +func TestSNAccountService_GetAccountByID_SfIDAbsent(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/accounts/"+testAccountSysid, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(snAccountJSON(testAccountSysid, ""))) + }) + + client := newTestSNClient(t, mux) + svc := NewServiceNowAccountService(client) + + got, err := svc.GetAccountByID(contextWithUserIDToken("token"), sysidToUUID(testAccountSysid)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if got.SfID != nil { + t.Fatalf("SfID = %v, want nil", *got.SfID) + } +} diff --git a/entity-service/openapi.yaml b/entity-service/openapi.yaml index f2068237ba..071c21d675 100644 --- a/entity-service/openapi.yaml +++ b/entity-service/openapi.yaml @@ -2852,6 +2852,10 @@ components: pod: type: string nullable: true + sfId: + type: string + nullable: true + description: Salesforce account ID linked to this account, if any. region: type: string nullable: true @@ -2909,6 +2913,10 @@ components: pod: type: string nullable: true + sfId: + type: string + nullable: true + description: Salesforce account ID linked to this account, if any. region: type: string nullable: true From 341c0de47f0b7d08029297d1be6e0f8acd904e31 Mon Sep 17 00:00:00 2001 From: Sajith Ekanayaka Date: Mon, 27 Jul 2026 21:11:59 +0530 Subject: [PATCH 08/10] [CSM Portal] fix Recently Viewed not reflecting a same-tab visit until reload useRecentViews' bucket-key resolution and the "pending" (pre-identity) migration lived only in a background effect that ran independently of both the record (write) path and the read path, so a visit recorded before this browser's ID-token decode settled could sit unreflected in an already-mounted reader until some unrelated event forced a re-read. Extract the resolve/migrate step into a shared helper and call it synchronously from both useRecordRecentView's write and useRecentViews' own settle-effect, and force an explicit re-read the moment a reader's own identity settles instead of only reacting to a dispatched event from elsewhere. Adds unit coverage for the record-then-read-within-one-session scenario. --- .../csm-recent/hooks/useRecentViews.test.ts | 75 +++++++++++++++- .../csm-recent/hooks/useRecentViews.ts | 86 +++++++++++++++---- 2 files changed, 142 insertions(+), 19 deletions(-) diff --git a/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.test.ts b/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.test.ts index 4214c95d42..a869578494 100644 --- a/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.test.ts +++ b/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.test.ts @@ -15,7 +15,16 @@ // under the License. import { act, renderHook } from "@testing-library/react"; -import { beforeEach, describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// Controllable stand-in for the real (async) ID-token decode, so tests can +// drive exactly when the `userid` claim "resolves" relative to a record/read, +// instead of depending on real Asgardeo timing. +let mockUserid: string | undefined; +vi.mock("@hooks/useIdTokenClaims", () => ({ + useIdTokenClaims: () => (mockUserid ? { userid: mockUserid } : undefined), +})); + import { clearRecentViews, toggleRecentViewPin, @@ -33,6 +42,7 @@ const entry = (id: string): Omit => ({ beforeEach(() => { localStorage.clear(); + mockUserid = undefined; }); describe("useRecentViews + useRecordRecentView", () => { @@ -193,4 +203,67 @@ describe("useRecentViews + useRecordRecentView", () => { expect(reader.result.current.map((v) => v.id)).toEqual(["pinned"]); }); }); + + describe("record-then-read within a single session (identity-resolution timing)", () => { + it("a same-session record survives navigating away and shows up to an already-mounted reader as soon as identity settles — no reload, no extra write needed", () => { + // Mirrors `RecentViewsButton`: mounted once (e.g. in the persistent + // header) for the whole session, well before this test's "case page" + // ever mounts. + const reader = renderHook(() => useRecentViews()); + expect(reader.result.current).toEqual([]); + + // The case detail page mounts and records the visit while the ID-token + // decode is still in flight for both instances (fresh tab / fresh + // sign-in) — the write lands in the "pending" bucket. + const recorder = renderHook(() => useRecordRecentView()); + act(() => recorder.result.current(entry("1"))); + + // The user navigates away before identity ever resolved during this + // visit — the case page (and its recorder hook) unmounts. + recorder.unmount(); + + // Identity resolves shortly after (e.g. the decode completes just + // after navigation). The reader is the one whose own effect settles + // it here — it must reflect the recorded visit immediately in the same + // pass that resolves identity, not merely on the next unrelated event. + mockUserid = "u1"; + act(() => reader.rerender()); + + expect(reader.result.current.map((v) => v.id)).toEqual(["1"]); + }); + + it("opening the recent-views panel after navigating away (a fresh mount of the reader) sees a visit recorded and settled earlier in the same session", () => { + // Identity already resolved earlier in the session (e.g. at app boot). + mockUserid = "u1"; + const recorder = renderHook(() => useRecordRecentView()); + act(() => recorder.result.current(entry("1"))); + + // Navigate away: the case page (recorder) unmounts. + recorder.unmount(); + + // The engineer opens the "Recently viewed" panel afterwards — a fresh + // mount of the reader hook, not one that was live during the write. + const reader = renderHook(() => useRecentViews()); + expect(reader.result.current.map((v) => v.id)).toEqual(["1"]); + }); + + it("a visit recorded by an instance whose own identity hasn't resolved yet still lands in the bucket an already-resolved reader is watching", () => { + // Some other, already-mounted component (e.g. the header) resolved + // identity earlier in the session. + mockUserid = "u1"; + const reader = renderHook(() => useRecentViews()); + expect(reader.result.current).toEqual([]); + + // A brand-new recorder instance mounts whose own ID-token decode + // hasn't completed yet (simulated by resetting the mock claim for its + // render only) — the record call must still resolve to the same + // already-known bucket the reader is watching, not a stale "pending" + // one, because the write forces its own instance to a definitive key + // once known, and otherwise fall back to whatever is already resolved. + const recorder = renderHook(() => useRecordRecentView()); + act(() => recorder.result.current(entry("2"))); + + expect(reader.result.current.map((v) => v.id)).toEqual(["2"]); + }); + }); }); diff --git a/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.ts b/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.ts index bd61bab062..d2cc873826 100644 --- a/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.ts +++ b/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.ts @@ -235,6 +235,40 @@ function writeStorage(entries: RecentView[]): void { } } +/** + * Folds a just-resolved `userid` into the shared `activeUserKey`, migrating + * the "pending" bucket the first time a real identity is known. Idempotent — + * safe to call from multiple hook instances / render passes for the same + * `userid` — and returns whether anything actually changed, so callers can + * decide whether a cross-tab-instance notification (`STORAGE_EVENT`) is + * warranted. + * + * Extracted out of {@link useSyncActiveUserKey}'s effect so BOTH the record + * (write) path and the read path can force this resolution synchronously, + * at the moment they actually need the bucket key, instead of only ever + * reacting to whichever component's own effect happens to run first. That + * closes the race where a write fires (e.g. `useRecordRecentView`'s + * `data`-driven effect) using a still-"pending" `activeUserKey` even though + * *this same component instance* already knows the real `userid` — because + * the correction previously lived only in a separate, independently-timed + * effect elsewhere. + */ +function resolveActiveUserKey(userid: string): boolean { + if (activeUserKey === userid) return false; + // Fold in anything recorded during this session's own pre-resolution + // window before switching the active bucket over. + if (activeUserKey === null) { + migratePendingBucket(userid); + } + activeUserKey = userid; + try { + localStorage.setItem(LAST_USER_KEY_STORAGE_KEY, userid); + } catch { + /* ignore */ + } + return true; +} + /** * Resolves THIS component instance's view of the signed-in user's stable id * (ID token `userid` claim) and syncs it into the shared `activeUserKey`, so @@ -246,8 +280,13 @@ function writeStorage(entries: RecentView[]): void { * sync (or the very first component in a freshly opened tab) could read the * still-`null`/"pending" bucket indefinitely, with the real data sitting * untouched under the correct per-user key. + * + * Returns the resolved `userid` (or `undefined` while still resolving/signed + * out) so callers that need to act on it *right now* — not just on the next + * render after the effect below has had a chance to run — can call + * {@link resolveActiveUserKey} themselves with the exact same value. */ -function useSyncActiveUserKey(): void { +function useSyncActiveUserKey(): string | undefined { const userid = useIdTokenClaims()?.userid; useEffect(() => { @@ -260,25 +299,16 @@ function useSyncActiveUserKey(): void { // if this browser has never resolved one) rather than resetting to // `null`/"pending" on every render before `userid` is known. if (!userid) return; - // The cached guess already matched — nothing to correct, no re-render. - if (activeUserKey === userid) return; - // Fold in anything recorded during this session's own pre-resolution - // window before switching the active bucket over. - if (activeUserKey === null) { - migratePendingBucket(userid); - } - activeUserKey = userid; - try { - localStorage.setItem(LAST_USER_KEY_STORAGE_KEY, userid); - } catch { - /* ignore */ - } + const changed = resolveActiveUserKey(userid); + if (!changed) return; // Let every `useRecentViews()` instance in this tab — including ones // that resolved their own `userid` earlier and are just listening — pick // up the now-current bucket immediately, rather than waiting for the // next unrelated write to trigger a re-read. window.dispatchEvent(new CustomEvent(STORAGE_EVENT)); }, [userid]); + + return userid; } /** @@ -293,10 +323,20 @@ export function useSyncRecentViewsIdentity(): void { /** Read-only access to the recent-views list. */ export function useRecentViews(): RecentView[] { - useSyncActiveUserKey(); + const userid = useSyncActiveUserKey(); const [entries, setEntries] = useState(() => readStorage()); useEffect(() => { + // This instance's own identity just settled (or changed) — force a + // synchronous, immediate re-read against the now-correct bucket rather + // than waiting on a `STORAGE_EVENT` dispatch from whichever *other* + // component's sync effect happens to run first. Covers the case where a + // visit was recorded (and the writer's bucket already migrated/resolved) + // before this reader's own effect had a chance to fire. + if (userid) resolveActiveUserKey(userid); + // eslint-disable-next-line react-hooks/set-state-in-effect -- syncs to external localStorage state that may have changed underneath this instance while its own identity was still resolving + setEntries(readStorage()); + const sync = () => setEntries(readStorage()); window.addEventListener(STORAGE_EVENT, sync); window.addEventListener("storage", sync); @@ -304,7 +344,7 @@ export function useRecentViews(): RecentView[] { window.removeEventListener(STORAGE_EVENT, sync); window.removeEventListener("storage", sync); }; - }, []); + }, [userid]); return entries; } @@ -316,8 +356,14 @@ export function useRecentViews(): RecentView[] { export function useRecordRecentView(): ( entry: Omit, ) => void { - useSyncActiveUserKey(); + const userid = useSyncActiveUserKey(); return useCallback((entry: Omit) => { + // Force this write onto the bucket THIS instance already knows is + // correct, synchronously, rather than trusting a shared `activeUserKey` + // that some other, independently-timed effect may not have committed + // yet — see {@link resolveActiveUserKey}'s doc comment for the race this + // closes. + if (userid) resolveActiveUserKey(userid); const now = new Date().toISOString(); // Title/subtitle/case-hit text ultimately come from backend/customer // free text (case subject, account/project name, assignee name) — not @@ -352,7 +398,11 @@ export function useRecordRecentView(): ( ...filtered, ]); writeStorage(next); - }, []); + // Notified listeners already re-read fresh state on this same event, so + // no separate "did the bucket change" signal is needed here — `userid` + // is only a dependency so the closure always uses the latest resolved + // value (see the call at the top of this callback). + }, [userid]); } /** From 9e6134d2d3d1ad79ba34c20da401901b4bb6081d Mon Sep 17 00:00:00 2001 From: Sajith Ekanayaka Date: Mon, 27 Jul 2026 22:30:02 +0530 Subject: [PATCH 09/10] address review feedback: fix unresolved-writer test, size-limit trailing data - useRecentViews.test.ts: the "unresolved-identity writer" test never actually left the writer's own identity unresolved before it mounted, so the resolveActiveUserKey fallback branch it claims to exercise was never hit. Reset the mock claim before the recorder mounts, then restore it before invoking the record call. - decode.go: decodeRequestWithLimit's trailing-data check treated an oversized-body error from the second Decode() the same as any other trailing data, returning the generic "must contain a single JSON object" message instead of the caller's size-limit message. Handle *http.MaxBytesError explicitly on that path, with a regression test. --- .../csm-recent/hooks/useRecentViews.test.ts | 2 + entity-service/internal/handler/decode.go | 5 ++ .../internal/handler/decode_test.go | 56 +++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 entity-service/internal/handler/decode_test.go diff --git a/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.test.ts b/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.test.ts index a869578494..4293ece532 100644 --- a/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.test.ts +++ b/apps/csm-portal/webapp/src/features/csm-recent/hooks/useRecentViews.test.ts @@ -260,7 +260,9 @@ describe("useRecentViews + useRecordRecentView", () => { // already-known bucket the reader is watching, not a stale "pending" // one, because the write forces its own instance to a definitive key // once known, and otherwise fall back to whatever is already resolved. + mockUserid = undefined; const recorder = renderHook(() => useRecordRecentView()); + mockUserid = "u1"; act(() => recorder.result.current(entry("2"))); expect(reader.result.current.map((v) => v.id)).toEqual(["2"]); diff --git a/entity-service/internal/handler/decode.go b/entity-service/internal/handler/decode.go index f4b1ff5c3f..803161ec08 100644 --- a/entity-service/internal/handler/decode.go +++ b/entity-service/internal/handler/decode.go @@ -55,6 +55,11 @@ func decodeRequestWithLimit[T any](w http.ResponseWriter, r *http.Request, dst * return false } if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + var maxBytesErr *http.MaxBytesError + if errors.As(err, &maxBytesErr) { + apierror.WriteJSON(w, http.StatusBadRequest, decodeErrMsgWithLimit(err, tooLargeMsg)) + return false + } apierror.WriteJSON(w, http.StatusBadRequest, "request body must contain a single JSON object") return false } diff --git a/entity-service/internal/handler/decode_test.go b/entity-service/internal/handler/decode_test.go new file mode 100644 index 0000000000..88574150c3 --- /dev/null +++ b/entity-service/internal/handler/decode_test.go @@ -0,0 +1,56 @@ +// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package handler + +import ( + "net/http/httptest" + "strings" + "testing" +) + +// TestDecodeRequestWithLimit_OversizedTrailingData reproduces a case where the +// first JSON object fits within the size cap, but trailing data after it pushes +// the body over the limit. The trailing-data check must report this as a +// size-limit error (the caller-supplied tooLargeMsg), not the generic "must +// contain a single JSON object" message — the two errors mean different things +// to the caller. +func TestDecodeRequestWithLimit_OversizedTrailingData(t *testing.T) { + const limit = 1024 + const tooLargeMsg = "attachment exceeds the maximum allowed size of 10 MB" + + body := `{"x":"ok"}` + strings.Repeat(" ", limit*2) + req := httptest.NewRequest("POST", "/", strings.NewReader(body)) + rec := httptest.NewRecorder() + + var dst struct { + X string `json:"x"` + } + ok := decodeRequestWithLimit(rec, req, &dst, limit, tooLargeMsg) + + if ok { + t.Fatal("expected decodeRequestWithLimit to return false for oversized trailing data") + } + if rec.Code != 400 { + t.Errorf("status = %d, want 400", rec.Code) + } + if !strings.Contains(rec.Body.String(), tooLargeMsg) { + t.Errorf("response body = %q, want it to contain the size-limit message %q", rec.Body.String(), tooLargeMsg) + } + if strings.Contains(rec.Body.String(), "must contain a single JSON object") { + t.Errorf("response body = %q, should not fall back to the generic trailing-data message for a size-limit case", rec.Body.String()) + } +} From 200cbff70f389f90c6ec6d1d8c02eb05d936664d Mon Sep 17 00:00:00 2001 From: Sajith Ekanayaka Date: Mon, 27 Jul 2026 22:46:56 +0530 Subject: [PATCH 10/10] address review feedback: shared attachment-size message constant, stronger test assertion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Extracted the attachment too-large message into attachmentTooLargeMsg (case_handler.go) so the handler and both test files can no longer drift out of sync — it was previously duplicated as a literal string in each, and CodeRabbit flagged the new decode_test.go copy as inconsistent with the 15 MiB request-body cap. It's intentionally worded around the 10 MB file-size limit callers care about, not the raw request-body cap (which includes base64/JSON overhead the caller never sees) — documented in the new constant's comment. - decode_test.go: assert dst.X == "ok" after the call, proving the test actually exercises the trailing-data check (the second Decode) rather than passing because the first Decode already failed. --- entity-service/internal/handler/case_handler.go | 8 +++++++- .../internal/handler/case_handler_test.go | 2 +- entity-service/internal/handler/decode_test.go | 13 +++++++++---- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/entity-service/internal/handler/case_handler.go b/entity-service/internal/handler/case_handler.go index c395799c48..b65756f3da 100644 --- a/entity-service/internal/handler/case_handler.go +++ b/entity-service/internal/handler/case_handler.go @@ -35,6 +35,12 @@ import ( // and rejects legitimate small attachments (e.g. a 2 MB file). const maxAttachmentBodySize = int64(15 << 20) +// attachmentTooLargeMsg is deliberately expressed as the file-size limit (10 +// MB) a caller actually cares about, not the raw request-body cap above — the +// extra headroom in maxAttachmentBodySize exists only to absorb base64/JSON +// overhead the caller never sees. +const attachmentTooLargeMsg = "attachment exceeds the maximum allowed size of 10 MB" + // safeAttachmentTypes is the allowlist of Content-Type values that may be // forwarded as-is. Anything not in this set is coerced to application/octet-stream // to prevent a stored-XSS attack via a crafted upstream Content-Type (e.g. text/html). @@ -177,7 +183,7 @@ func (h *CaseHandler) SearchCases(w http.ResponseWriter, r *http.Request) { // CreateCaseAttachment handles POST /attachments. func (h *CaseHandler) CreateCaseAttachment(w http.ResponseWriter, r *http.Request) { var req domain.CreateAttachmentRequest - if !decodeRequestWithLimit(w, r, &req, maxAttachmentBodySize, "attachment exceeds the maximum allowed size of 10 MB") { + if !decodeRequestWithLimit(w, r, &req, maxAttachmentBodySize, attachmentTooLargeMsg) { return } resp, err := h.svc.CreateCaseAttachment(r.Context(), req) diff --git a/entity-service/internal/handler/case_handler_test.go b/entity-service/internal/handler/case_handler_test.go index 4a31616592..daf1068b68 100644 --- a/entity-service/internal/handler/case_handler_test.go +++ b/entity-service/internal/handler/case_handler_test.go @@ -123,7 +123,7 @@ func TestCreateCaseAttachment_OverNewLimit(t *testing.T) { if rec.Code != http.StatusBadRequest { t.Fatalf("expected 400 Bad Request, got %d: %s", rec.Code, rec.Body.String()) } - if !strings.Contains(rec.Body.String(), "attachment exceeds the maximum allowed size of 10 MB") { + if !strings.Contains(rec.Body.String(), attachmentTooLargeMsg) { t.Fatalf("expected the attachment-specific too-large message, got: %s", rec.Body.String()) } if strings.Contains(rec.Body.String(), "request body too large") { diff --git a/entity-service/internal/handler/decode_test.go b/entity-service/internal/handler/decode_test.go index 88574150c3..00e44edc88 100644 --- a/entity-service/internal/handler/decode_test.go +++ b/entity-service/internal/handler/decode_test.go @@ -30,7 +30,6 @@ import ( // to the caller. func TestDecodeRequestWithLimit_OversizedTrailingData(t *testing.T) { const limit = 1024 - const tooLargeMsg = "attachment exceeds the maximum allowed size of 10 MB" body := `{"x":"ok"}` + strings.Repeat(" ", limit*2) req := httptest.NewRequest("POST", "/", strings.NewReader(body)) @@ -39,16 +38,22 @@ func TestDecodeRequestWithLimit_OversizedTrailingData(t *testing.T) { var dst struct { X string `json:"x"` } - ok := decodeRequestWithLimit(rec, req, &dst, limit, tooLargeMsg) + ok := decodeRequestWithLimit(rec, req, &dst, limit, attachmentTooLargeMsg) if ok { t.Fatal("expected decodeRequestWithLimit to return false for oversized trailing data") } + // Prove this actually reached the trailing-data check (the second Decode) + // rather than failing on the first one — dst must reflect a fully-decoded + // first object. + if dst.X != "ok" { + t.Fatalf("dst.X = %q, want %q — the first Decode should have succeeded before the trailing-data check ran", dst.X, "ok") + } if rec.Code != 400 { t.Errorf("status = %d, want 400", rec.Code) } - if !strings.Contains(rec.Body.String(), tooLargeMsg) { - t.Errorf("response body = %q, want it to contain the size-limit message %q", rec.Body.String(), tooLargeMsg) + if !strings.Contains(rec.Body.String(), attachmentTooLargeMsg) { + t.Errorf("response body = %q, want it to contain the size-limit message %q", rec.Body.String(), attachmentTooLargeMsg) } if strings.Contains(rec.Body.String(), "must contain a single JSON object") { t.Errorf("response body = %q, should not fall back to the generic trailing-data message for a size-limit case", rec.Body.String())