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 { 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/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], ); 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..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. @@ -1985,6 +1958,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 +2009,6 @@ export default function CsmCaseDetailPage(): JSX.Element { )} - {activeTab === "related" && ( - - - - )} - {activeTab === "watchers" && ( {/* Watchers list — moved off the (single-line) overview Cell so a @@ -2082,8 +2065,6 @@ export default function CsmCaseDetailPage(): JSX.Element { setAutoOpenCallCreate(false)} isClosed={isClosed} /> 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 && ( ({ + 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,69 @@ 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. + 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/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]); } /** diff --git a/entity-service/internal/domain/entity.go b/entity-service/internal/domain/entity.go index 4cc99d71b5..3941e0b9c3 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"` @@ -267,6 +268,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/handler/case_handler.go b/entity-service/internal/handler/case_handler.go index cc8d7f76f0..b65756f3da 100644 --- a/entity-service/internal/handler/case_handler.go +++ b/entity-service/internal/handler/case_handler.go @@ -28,6 +28,19 @@ 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) + +// 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). @@ -170,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 !decodeRequest(w, r, &req) { + 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 new file mode 100644 index 0000000000..daf1068b68 --- /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(), 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") { + 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..803161ec08 100644 --- a/entity-service/internal/handler/decode.go +++ b/entity-service/internal/handler/decode.go @@ -38,14 +38,28 @@ 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) { + 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 } @@ -56,9 +70,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) { diff --git a/entity-service/internal/handler/decode_test.go b/entity-service/internal/handler/decode_test.go new file mode 100644 index 0000000000..00e44edc88 --- /dev/null +++ b/entity-service/internal/handler/decode_test.go @@ -0,0 +1,61 @@ +// 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 + + 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, 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(), 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()) + } +} diff --git a/entity-service/internal/service/sn_account_service.go b/entity-service/internal/service/sn_account_service.go index 01b0282168..146243d791 100644 --- a/entity-service/internal/service/sn_account_service.go +++ b/entity-service/internal/service/sn_account_service.go @@ -51,6 +51,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"` @@ -188,6 +189,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), @@ -220,6 +222,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 1b90686c0a..52f0ec93e4 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 @@ -2913,6 +2917,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