diff --git a/apps/csm-portal/backend/internal/dashboard/widgets.go b/apps/csm-portal/backend/internal/dashboard/widgets.go index 2b86287adc..3d741c97b1 100644 --- a/apps/csm-portal/backend/internal/dashboard/widgets.go +++ b/apps/csm-portal/backend/internal/dashboard/widgets.go @@ -54,24 +54,53 @@ type Shape string const ( ShapeCount Shape = "count" // single resolved number ShapeList Shape = "list" // top-N matching records - ShapePie Shape = "pie" // grouped counts — NOT resolvable by any /search endpoint today (no aggregate endpoint exists anywhere in the stack); keep the const so a future dashboard doesn't need a schema migration, but do not wire any rendering logic for it beyond accepting the value - ShapeBar Shape = "bar" // same caveat as ShapePie + ShapePie Shape = "pie" // one search per Slices entry, each resolved via its own total — see PieSlice + ShapeBar Shape = "bar" // same resolution as ShapePie (one search per Slices entry); differs only in how the frontend renders the resolved data ) +// PieSlice is one wedge of a Shape "pie" widget. The caller resolves its +// value by issuing that widget's own ResourceType's /search with Filters +// merged under the widget's own base Filters (this slice's keys win on +// conflict) and pagination.limit=1, reading total off the response — the +// exact same mechanism Shape "count" uses, just once per slice. +type PieSlice struct { + Label string `json:"label"` + // Color is a palette key ("primary", "secondary", "success", "error", + // "info", "warning") the frontend already uses elsewhere in this system + // (see WidgetTemplate's own icon color convention on the frontend) — not + // validated here, forwarded verbatim. Falls back to a fixed rotation over + // the same palette on the frontend if omitted. + Color string `json:"color,omitempty"` + Filters map[string]any `json:"filters"` +} + // WidgetTemplate is resource-agnostic: Filters is opaque JSON, forwarded // verbatim (after __current_user__ substitution) as the filters object of // that ResourceType's own /search payload (every resource's search payload // shape is {filters: {...}, pagination: {...}}). The BE never interprets // filter contents beyond substituting the current-user placeholder. type WidgetTemplate struct { - ID string `json:"id"` - DisplayName string `json:"displayName"` + ID string `json:"id"` + DisplayName string `json:"displayName"` + // Description is an explanatory subtitle shown under DisplayName — + // config-owned text, not hardcoded per ResourceType/Shape on the + // frontend. + Description string `json:"description,omitempty"` ResourceType ResourceType `json:"resourceType"` Shape Shape `json:"shape"` GridWidth int `json:"gridWidth"` // 1-12, CSS grid columns out of 12 Filters map[string]any `json:"filters"` - GroupBy string `json:"groupBy,omitempty"` // only meaningful for Shape pie/bar — see the caveat on those consts; unused by every widget below + GroupBy string `json:"groupBy,omitempty"` // unused ListLimit int `json:"listLimit,omitempty"` // only meaningful for Shape list; how many records to show + Slices []PieSlice `json:"slices,omitempty"` // only meaningful for Shape pie/bar; one search per slice + // Section groups widgets sharing the same (non-empty) value under a + // titled sub-section within the dashboard, in the order that value + // first appears among the dashboard's widgets — e.g. a handful of + // "count" widgets all set to Section: "SLA Violation" render together + // under that heading, separately from the dashboard's other widgets. + // Widgets with no Section (the common case) render in one untitled + // group, exactly as before this field existed. + Section string `json:"section,omitempty"` } // Dashboard is a single dashboard's metadata plus its widget templates. @@ -138,6 +167,18 @@ func ResolveFilters(tpl WidgetTemplate, currentUserID string) map[string]any { return substituteCurrentUser(tpl.Filters, currentUserID).(map[string]any) } +// ResolveSliceFilters is ResolveFilters' counterpart for one Shape "pie" +// slice: substitutes CurrentUserPlaceholder in slice.Filters only. It +// deliberately does NOT merge in the widget's own base Filters — the caller +// (frontend) merges this slice's filters under the widget's own resolved +// Filters itself (this slice's keys win on conflict), the same way it +// already merges any other per-slice override. Sending the two separately, +// rather than one pre-merged object per slice, avoids repeating the base +// filters' JSON in every slice over the wire. Does not mutate slice.Filters. +func ResolveSliceFilters(slice PieSlice, currentUserID string) map[string]any { + return substituteCurrentUser(slice.Filters, currentUserID).(map[string]any) +} + func substituteCurrentUser(v any, currentUserID string) any { switch val := v.(type) { case map[string]any: diff --git a/apps/csm-portal/backend/internal/dashboard/widgets_test.go b/apps/csm-portal/backend/internal/dashboard/widgets_test.go index d39477faa2..020a85bfc1 100644 --- a/apps/csm-portal/backend/internal/dashboard/widgets_test.go +++ b/apps/csm-portal/backend/internal/dashboard/widgets_test.go @@ -126,3 +126,80 @@ func TestParseDashboardsConfig_ValidRoundTrip(t *testing.T) { t.Errorf("ResolveFilters(...)[assignedUserIds] = %v, want [\"user-123\"]", resolved["assignedUserIds"]) } } + +func TestParseDashboardsConfig_PieWidgetSlicesAndDescription(t *testing.T) { + const raw = `[ + { + "id": "team_performance", + "displayName": "Team performance", + "widgets": [ + { + "id": "cases_by_severity", + "displayName": "Cases by severity", + "description": "Share of active cases at each severity level.", + "resourceType": "case", + "shape": "pie", + "gridWidth": 6, + "filters": {"states": ["open"]}, + "slices": [ + {"label": "Critical", "color": "error", "filters": {"severities": ["critical"]}}, + {"label": "Mine", "filters": {"assignedUserIds": ["__current_user__"]}} + ] + } + ] + } + ]` + + got := ParseDashboardsConfig(raw) + if len(got) != 1 || len(got[0].Widgets) != 1 { + t.Fatalf("ParseDashboardsConfig(raw) = %+v, want 1 dashboard with 1 widget", got) + } + + w := got[0].Widgets[0] + if w.Description != "Share of active cases at each severity level." { + t.Errorf("WidgetTemplate.Description = %q, want the configured subtitle", w.Description) + } + if len(w.Slices) != 2 { + t.Fatalf("len(WidgetTemplate.Slices) = %d, want 2", len(w.Slices)) + } + if w.Slices[0].Label != "Critical" || w.Slices[0].Color != "error" { + t.Errorf("Slices[0] = %+v, want {Label: Critical, Color: error}", w.Slices[0]) + } + + // A slice's own filters resolve the current-user placeholder + // independently of the widget's own base Filters — ResolveSliceFilters + // must not require (or merge in) the base at all. + resolved := ResolveSliceFilters(w.Slices[1], "user-123") + assigned, ok := resolved["assignedUserIds"].([]any) + if !ok || len(assigned) != 1 || assigned[0] != "user-123" { + t.Errorf("ResolveSliceFilters(Slices[1], ...)[assignedUserIds] = %v, want [\"user-123\"]", resolved["assignedUserIds"]) + } + if _, present := resolved["states"]; present { + t.Errorf("ResolveSliceFilters must not merge in the widget's own base filters, got %v", resolved) + } +} + +func TestParseDashboardsConfig_WidgetSection(t *testing.T) { + const raw = `[ + { + "id": "team_performance", + "displayName": "Team performance", + "widgets": [ + {"id": "team_open_cases", "displayName": "Team Open P0/P1", "resourceType": "case", "shape": "count", "gridWidth": 6, "filters": {}}, + {"id": "incident_wow", "displayName": "Incident WOW", "section": "SLA Violation", "resourceType": "incident", "shape": "count", "gridWidth": 6, "filters": {}} + ] + } + ]` + + got := ParseDashboardsConfig(raw) + if len(got) != 1 || len(got[0].Widgets) != 2 { + t.Fatalf("ParseDashboardsConfig(raw) = %+v, want 1 dashboard with 2 widgets", got) + } + + if section := got[0].Widgets[0].Section; section != "" { + t.Errorf("team_open_cases.Section = %q, want empty (no section configured)", section) + } + if section := got[0].Widgets[1].Section; section != "SLA Violation" { + t.Errorf("incident_wow.Section = %q, want %q", section, "SLA Violation") + } +} diff --git a/apps/csm-portal/backend/internal/handler/dashboards.go b/apps/csm-portal/backend/internal/handler/dashboards.go index 2466767e86..3ba56dbdc0 100644 --- a/apps/csm-portal/backend/internal/handler/dashboards.go +++ b/apps/csm-portal/backend/internal/handler/dashboards.go @@ -25,19 +25,32 @@ import ( "github.com/wso2-open-operations/cs-tools/apps/csm-portal/backend/internal/middleware" ) +// dashboardPieSliceView is one wedge of a Shape "pie" widget — see +// dashboard.PieSlice. Filters is this slice's own criteria only (already +// __current_user__-resolved), meant to be merged under the parent widget's +// own (also resolved) Filters by the caller. +type dashboardPieSliceView struct { + Label string `json:"label"` + Color string `json:"color,omitempty"` + Filters map[string]any `json:"filters"` +} + // dashboardWidgetView is a single widget's filter criteria and display // metadata, returned as part of GET /dashboards/{dashboardId}. The caller // resolves each widget's own data by issuing its own POST /{resourceType}s/search // request (see ResourceType) with Filters. type dashboardWidgetView struct { - WidgetID string `json:"widgetId"` - DisplayName string `json:"displayName"` - ResourceType dashboard.ResourceType `json:"resourceType"` - Shape dashboard.Shape `json:"shape"` - GridWidth int `json:"gridWidth"` - Filters map[string]any `json:"filters"` - GroupBy string `json:"groupBy,omitempty"` - ListLimit int `json:"listLimit,omitempty"` + WidgetID string `json:"widgetId"` + DisplayName string `json:"displayName"` + Description string `json:"description,omitempty"` + ResourceType dashboard.ResourceType `json:"resourceType"` + Shape dashboard.Shape `json:"shape"` + GridWidth int `json:"gridWidth"` + Filters map[string]any `json:"filters"` + GroupBy string `json:"groupBy,omitempty"` + ListLimit int `json:"listLimit,omitempty"` + Slices []dashboardPieSliceView `json:"slices,omitempty"` + Section string `json:"section,omitempty"` } // dashboardListItemView is a dashboard's list-level metadata, returned by @@ -150,15 +163,29 @@ func (h *DashboardHandler) GetDashboardDetail(w http.ResponseWriter, r *http.Req widgets := make([]dashboardWidgetView, 0, len(d.Widgets)) for _, tpl := range d.Widgets { + var slices []dashboardPieSliceView + if len(tpl.Slices) > 0 { + slices = make([]dashboardPieSliceView, 0, len(tpl.Slices)) + for _, slice := range tpl.Slices { + slices = append(slices, dashboardPieSliceView{ + Label: slice.Label, + Color: slice.Color, + Filters: dashboard.ResolveSliceFilters(slice, currentUserID), + }) + } + } widgets = append(widgets, dashboardWidgetView{ WidgetID: tpl.ID, DisplayName: tpl.DisplayName, + Description: tpl.Description, ResourceType: tpl.ResourceType, Shape: tpl.Shape, GridWidth: tpl.GridWidth, Filters: dashboard.ResolveFilters(tpl, currentUserID), GroupBy: tpl.GroupBy, ListLimit: tpl.ListLimit, + Slices: slices, + Section: tpl.Section, }) } diff --git a/apps/csm-portal/backend/internal/handler/dashboards_test.go b/apps/csm-portal/backend/internal/handler/dashboards_test.go index 9f02ebc93b..07b6a696ae 100644 --- a/apps/csm-portal/backend/internal/handler/dashboards_test.go +++ b/apps/csm-portal/backend/internal/handler/dashboards_test.go @@ -61,7 +61,12 @@ const testDashboardsConfigJSON = `[ ]}, {"id":"team_performance","displayName":"Team performance","targetTeam":"cs_team_leads","isTeamBased":true,"widgets":[ {"id":"time_cards_pending_approval","displayName":"Time Cards Pending Approval","resourceType":"time_card","shape":"count","gridWidth":6,"filters":{"states":["pending"]}}, - {"id":"team_open_cases","displayName":"Team Open P0/P1","resourceType":"case","shape":"count","gridWidth":6,"filters":{"severities":["catastrophic","critical"],"states":["open","work_in_progress"]}} + {"id":"team_open_cases","displayName":"Team Open P0/P1","resourceType":"case","shape":"count","gridWidth":6,"filters":{"severities":["catastrophic","critical"],"states":["open","work_in_progress"]}}, + {"id":"cases_by_severity","displayName":"Cases by severity","description":"Share of active cases at each severity level.","resourceType":"case","shape":"pie","gridWidth":6,"filters":{"states":["open","work_in_progress"]},"slices":[ + {"label":"Critical","color":"error","filters":{"severities":["critical"]}}, + {"label":"Mine","filters":{"assignedUserIds":["__current_user__"]}} + ]}, + {"id":"incident_wow","displayName":"Incident WOW","section":"SLA Violation","resourceType":"incident","shape":"count","gridWidth":6,"filters":{}} ]} ]` @@ -508,6 +513,118 @@ func TestGetDashboardDetail(t *testing.T) { } }) + t.Run("team_performance's pie widget resolves description, slices, and per-slice current-user placeholders", func(t *testing.T) { + h := NewDashboardHandler(&mockEntityUserClient{}) + r := withUser(withDashboardID(httptest.NewRequest(http.MethodGet, "/dashboards/team_performance", nil), "team_performance")) + w := httptest.NewRecorder() + h.GetDashboardDetail(w, r) + + assertStatus(t, w, http.StatusOK) + body := w.Body.Bytes() + t.Logf("GET /dashboards/team_performance response: %s", body) + + var result dashboardDetailView + if err := json.Unmarshal(body, &result); err != nil { + t.Fatalf("decode response body: %v; raw: %s", err, body) + } + + byID := make(map[string]dashboardWidgetView) + for _, wd := range result.Widgets { + byID[wd.WidgetID] = wd + } + pie, ok := byID["cases_by_severity"] + if !ok { + t.Fatalf("missing widget %q in response", "cases_by_severity") + } + if pie.Description != "Share of active cases at each severity level." { + t.Errorf("cases_by_severity Description = %q, want the configured subtitle", pie.Description) + } + if len(pie.Slices) != 2 { + t.Fatalf("len(cases_by_severity.Slices) = %d, want 2", len(pie.Slices)) + } + + var critical, mine *dashboardPieSliceView + for i := range pie.Slices { + switch pie.Slices[i].Label { + case "Critical": + critical = &pie.Slices[i] + case "Mine": + mine = &pie.Slices[i] + } + } + if critical == nil { + t.Fatalf("missing the %q slice in cases_by_severity.Slices", "Critical") + } + if critical.Color != "error" { + t.Errorf("Critical slice Color = %q, want %q", critical.Color, "error") + } + if _, present := critical.Filters["states"]; present { + t.Errorf("Critical slice Filters must not carry the widget's own base filters, got %v", critical.Filters) + } + + if mine == nil { + t.Fatalf("missing the %q slice in cases_by_severity.Slices", "Mine") + } + assigned, ok := mine.Filters["assignedUserIds"].([]any) + if !ok || len(assigned) != 1 || assigned[0] != resolvedCurrentUserID { + t.Errorf("Mine slice assignedUserIds = %v, want [%q] (resolved, not the raw placeholder)", mine.Filters["assignedUserIds"], resolvedCurrentUserID) + } + + // Confirm the wire keys match the updated openapi.yaml schema. + var raw map[string]json.RawMessage + if err := json.Unmarshal(body, &raw); err != nil { + t.Fatalf("decode response body as raw keys: %v; raw: %s", err, body) + } + var rawWidgets []map[string]json.RawMessage + if err := json.Unmarshal(raw["widgets"], &rawWidgets); err != nil { + t.Fatalf("decode widgets as raw keys: %v; raw: %s", err, raw["widgets"]) + } + var rawPie map[string]json.RawMessage + for _, obj := range rawWidgets { + var id string + if err := json.Unmarshal(obj["widgetId"], &id); err == nil && id == "cases_by_severity" { + rawPie = obj + } + } + if rawPie == nil { + t.Fatalf("cases_by_severity not found among raw widgets: %v", rawWidgets) + } + assertJSONKeysSuperset(t, rawPie, append(append([]string(nil), dashboardWidgetJSONKeys...), "description", "slices"), "cases_by_severity") + }) + + t.Run("team_performance's incident_wow widget carries its configured section, unset for widgets with no section", func(t *testing.T) { + h := NewDashboardHandler(&mockEntityUserClient{}) + r := withUser(withDashboardID(httptest.NewRequest(http.MethodGet, "/dashboards/team_performance", nil), "team_performance")) + w := httptest.NewRecorder() + h.GetDashboardDetail(w, r) + + assertStatus(t, w, http.StatusOK) + var result dashboardDetailView + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatalf("decode response body: %v; raw: %s", err, w.Body.Bytes()) + } + byID := make(map[string]dashboardWidgetView) + for _, wd := range result.Widgets { + byID[wd.WidgetID] = wd + } + + wow, ok := byID["incident_wow"] + if !ok { + t.Fatalf("missing widget %q in response", "incident_wow") + } + if wow.Section != "SLA Violation" { + t.Errorf("incident_wow.Section = %q, want %q", wow.Section, "SLA Violation") + } + + teamOpenCases, ok := byID["team_open_cases"] + if !ok { + t.Fatalf("missing widget %q in response", "team_open_cases") + } + if teamOpenCases.Section != "" { + t.Errorf("team_open_cases.Section = %q, want empty (no section configured)", teamOpenCases.Section) + } + }) + t.Run("every dashboard in the registry now has at least one widget", func(t *testing.T) { h := NewDashboardHandler(&mockEntityUserClient{}) for _, d := range dashboard.Dashboards { diff --git a/apps/csm-portal/backend/openapi.yaml b/apps/csm-portal/backend/openapi.yaml index 261eae031a..4e73ab20e2 100644 --- a/apps/csm-portal/backend/openapi.yaml +++ b/apps/csm-portal/backend/openapi.yaml @@ -5282,6 +5282,11 @@ components: description: Static id of the widget template within its dashboard displayName: type: string + description: + type: string + description: > + Explanatory subtitle shown under displayName. Config-owned text, + not hardcoded per resourceType/shape on the frontend. resourceType: type: string enum: @@ -5303,10 +5308,11 @@ components: - pie - bar description: > - How the widget's data should be rendered once resolved. pie/bar - are not resolvable by any /search endpoint today (no aggregate - endpoint exists anywhere in the stack); reserved for a future - dashboard. + How the widget's data should be rendered once resolved. shapes + "pie" and "bar" both resolve one search per slices entry, the + same way "count" resolves its own single search (see slices + below) — they differ only in how the frontend renders the same + resolved data (wedges vs. bars), not in how it's fetched. gridWidth: type: integer minimum: 1 @@ -5319,13 +5325,50 @@ components: Filter criteria for this widget, with any current-user placeholder already substituted. Pass this directly as the filters of that resourceType's own POST /{resourceType}s/search - request to resolve the widget's data. + request to resolve the widget's data. For shapes "pie"/"bar" + this is a shared base merged under every slices entry's own + filters (caller-side; slices entry keys win on conflict) rather + than queried on its own. groupBy: type: string - description: Only meaningful for shape pie/bar; the field to group counts by + description: Unused listLimit: type: integer description: Only meaningful for shape list; how many records to show + slices: + type: array + description: > + Only meaningful for shapes "pie"/"bar": one search per entry, + each resolved via its own total, the same mechanism shape + "count" uses. Merge each entry's filters under this widget's + own filters (entry keys win on conflict) before searching. + items: + type: object + properties: + label: + type: string + color: + type: string + description: > + Palette key (e.g. "primary", "error") the frontend already + uses elsewhere in this system; not validated here, forwarded + verbatim. Falls back to a fixed rotation over the same + palette on the frontend if omitted. + filters: + type: object + additionalProperties: true + description: > + This slice's own criteria only, with any current-user + placeholder already substituted — merge under the parent + widget's own filters to resolve this slice's total. + section: + type: string + description: > + Groups widgets sharing the same (non-empty) value under a + titled sub-section within the dashboard, in the order that + value first appears among the dashboard's widgets. Widgets + with no section (the common case) render in one untitled + group, same as before this field existed. DashboardListItem: type: object diff --git a/apps/csm-portal/webapp/src/api/backend/types.ts b/apps/csm-portal/webapp/src/api/backend/types.ts index 37261de98a..570f04b586 100644 --- a/apps/csm-portal/webapp/src/api/backend/types.ts +++ b/apps/csm-portal/webapp/src/api/backend/types.ts @@ -2712,12 +2712,36 @@ export type BeWidgetResourceType = | "product_vulnerability"; /** - * How a widget's resolved data should be rendered. `pie`/`bar` are not - * resolvable by any `/search` endpoint today (no aggregate endpoint exists - * anywhere in the stack) — reserved for a future dashboard. + * How a widget's resolved data should be rendered. `pie` and `bar` both + * resolve the same way `count` does, just once per slice — see + * {@link BeDashboardWidget.slices} — differing only in how the frontend + * renders the resolved data (wedges vs. bars), not in how it's fetched. */ export type BeWidgetShape = "count" | "list" | "pie" | "bar"; +/** Palette key a dashboard config can use to color a pie slice — the same + * vocabulary `WidgetResourceConfig.iconColor` already uses elsewhere in this + * system, so one dashboard has one consistent color language. */ +export type BeWidgetPaletteColor = + | "primary" + | "secondary" + | "success" + | "error" + | "info" + | "warning"; + +/** One wedge of a `shape: "pie"` widget. Resolved by issuing this + * resourceType's own `POST /{resourceType}s/search` with `filters` merged + * under the widget's own base `filters` (this slice's keys win on + * conflict) and `pagination: { limit: 1 }`, reading `total` — the exact + * same mechanism `shape: "count"` uses, just once per slice. */ +export interface BeDashboardPieSlice { + label: string; + /** Falls back to a fixed rotation over the same palette if omitted. */ + color?: BeWidgetPaletteColor; + filters: Record; +} + /** * A single widget template, embedded in {@link BeDashboard}: display metadata * plus its already-resolved filter criteria. The caller resolves the @@ -2727,6 +2751,9 @@ export type BeWidgetShape = "count" | "list" | "pie" | "bar"; export interface BeDashboardWidget { widgetId: string; displayName: string; + /** Explanatory subtitle shown under `displayName` — config-owned text, + * not hardcoded per resourceType/shape on the frontend. */ + description?: string; resourceType: BeWidgetResourceType; shape: BeWidgetShape; /** CSS grid columns out of 12 this widget should occupy. */ @@ -2734,13 +2761,25 @@ export interface BeDashboardWidget { /** * Opaque filter criteria, with any current-user placeholder already * substituted. Pass this directly as the `filters` of that - * `resourceType`'s own `POST /{resourceType}s/search` request. + * `resourceType`'s own `POST /{resourceType}s/search` request. For + * shapes "pie"/"bar" this is a shared base merged under every slice's own + * `filters` (see {@link BeDashboardPieSlice}), rather than queried on + * its own. */ filters: Record; /** Only meaningful for shape pie/bar; the field to group counts by. */ groupBy?: string; + /** Only meaningful for shapes "pie"/"bar": one search per slice, each + * read via its own `total`. */ + slices?: BeDashboardPieSlice[]; /** Only meaningful for shape list; how many records to show. */ listLimit?: number; + /** Groups widgets sharing the same (non-empty) value under a titled + * sub-section within the dashboard, in the order that value first + * appears among the dashboard's widgets. Widgets with no `section` (the + * common case) render in one untitled group, same as before this field + * existed. */ + section?: string; } /** diff --git a/apps/csm-portal/webapp/src/features/csm-dashboard/api/useWidgetPieData.test.tsx b/apps/csm-portal/webapp/src/features/csm-dashboard/api/useWidgetPieData.test.tsx new file mode 100644 index 0000000000..14a38eee32 --- /dev/null +++ b/apps/csm-portal/webapp/src/features/csm-dashboard/api/useWidgetPieData.test.tsx @@ -0,0 +1,101 @@ +// 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. + +import { renderHook, waitFor } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { describe, expect, it, vi, beforeEach } from "vitest"; +import type { ReactNode } from "react"; + +const postMock = vi.fn(); + +vi.mock("@api/backend/client", () => ({ + useBackendApi: () => ({ post: postMock }), +})); + +import { useWidgetPieData } from "@features/csm-dashboard/api/useWidgetPieData"; + +function wrapper({ children }: { children: ReactNode }) { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + return {children}; +} + +describe("useWidgetPieData", () => { + beforeEach(() => { + postMock.mockReset(); + }); + + it("issues one search per slice, own filters merged under the widget's base filters, limit 1", async () => { + postMock.mockImplementation((_path: string, body: { filters: Record }) => { + if (body.filters.severities === "critical") return Promise.resolve({ total: 1 }); + if (body.filters.severities === "high") return Promise.resolve({ total: 3 }); + return Promise.resolve({ total: 0 }); + }); + + const { result } = renderHook( + () => + useWidgetPieData("case", { states: ["open"] }, [ + { label: "Critical", filters: { severities: "critical" } }, + { label: "High", filters: { severities: "high" } }, + ]), + { wrapper }, + ); + + await waitFor(() => expect(result.current.isLoading).toBe(false)); + + expect(postMock).toHaveBeenCalledTimes(2); + expect(postMock).toHaveBeenCalledWith("/cases/search", { + filters: { states: ["open"], severities: "critical" }, + pagination: { offset: 0, limit: 1 }, + }); + expect(postMock).toHaveBeenCalledWith("/cases/search", { + filters: { states: ["open"], severities: "high" }, + pagination: { offset: 0, limit: 1 }, + }); + expect(result.current.slices).toEqual([ + { label: "Critical", filters: { severities: "critical" }, value: 1 }, + { label: "High", filters: { severities: "high" }, value: 3 }, + ]); + expect(result.current.total).toBe(4); + }); + + it("fires no queries and returns a zero total for an empty slices array", () => { + const { result } = renderHook(() => useWidgetPieData("case", {}, []), { wrapper }); + + expect(postMock).not.toHaveBeenCalled(); + expect(result.current.slices).toEqual([]); + expect(result.current.total).toBe(0); + expect(result.current.isLoading).toBe(false); + }); + + it("surfaces isError when any one slice's search fails", async () => { + postMock + .mockResolvedValueOnce({ total: 2 }) + .mockRejectedValueOnce(new Error("boom")); + + const { result } = renderHook( + () => + useWidgetPieData("case", {}, [ + { label: "A", filters: { a: "1" } }, + { label: "B", filters: { b: "2" } }, + ]), + { wrapper }, + ); + + await waitFor(() => expect(result.current.isError).toBe(true)); + }); +}); diff --git a/apps/csm-portal/webapp/src/features/csm-dashboard/api/useWidgetPieData.ts b/apps/csm-portal/webapp/src/features/csm-dashboard/api/useWidgetPieData.ts new file mode 100644 index 0000000000..8718a5732a --- /dev/null +++ b/apps/csm-portal/webapp/src/features/csm-dashboard/api/useWidgetPieData.ts @@ -0,0 +1,88 @@ +// 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. + +import { useQueries } from "@tanstack/react-query"; +import { ApiQueryKeys } from "@constants/apiConstants"; +import { useBackendApi } from "@api/backend/client"; +import type { BeDashboardPieSlice, BeWidgetResourceType } from "@api/backend/types"; +import { WIDGET_RESOURCE_CONFIG } from "@features/csm-dashboard/config/widgetResourceConfig"; + +export interface PieSliceResult extends BeDashboardPieSlice { + value: number; +} + +export interface WidgetPieData { + slices: PieSliceResult[]; + total: number; + isLoading: boolean; + isError: boolean; +} + +/** + * Resolves a `shape: "pie"` widget's per-slice values: one independent + * `POST {resourceType}/search` per slice — its own `filters` merged under + * the widget's own base `filters` (slice keys win on conflict) — with + * `pagination: { limit: 1 }`, reading `total` off each. The exact same + * mechanism `shape: "count"` (see `useWidgetData`) uses, just fired once + * per slice instead of once for the whole widget. An empty `slices` array + * fires no queries at all. + */ +export function useWidgetPieData( + resourceType: BeWidgetResourceType, + baseFilters: Record, + slices: BeDashboardPieSlice[], +): WidgetPieData { + const api = useBackendApi(); + const config = WIDGET_RESOURCE_CONFIG[resourceType]; + + const queries = useQueries({ + queries: slices.map((slice) => { + const filters = { ...baseFilters, ...slice.filters }; + return { + queryKey: [ + ApiQueryKeys.CSM_DASHBOARD_WIDGET_DATA, + "pie-slice", + resourceType, + filters, + ], + queryFn: async (): Promise => { + if (!config) { + throw new Error(`Unsupported widget resourceType: ${resourceType}`); + } + const res = await api.post< + { filters: Record; pagination: { offset: number; limit: number } }, + Record + >(config.searchEndpoint, { + filters, + pagination: { offset: 0, limit: 1 }, + }); + return typeof res.total === "number" ? res.total : 0; + }, + staleTime: 60_000, + }; + }), + }); + + const isLoading = queries.some((q) => q.isLoading); + const isError = queries.some((q) => q.isError); + const results: PieSliceResult[] = slices.map((slice, i) => ({ + ...slice, + value: queries[i]?.data ?? 0, + })); + const total = results.reduce((sum, s) => sum + s.value, 0); + + return { slices: results, total, isLoading, isError }; +} diff --git a/apps/csm-portal/webapp/src/features/csm-dashboard/components/AgentsLandingPagePilot.test.tsx b/apps/csm-portal/webapp/src/features/csm-dashboard/components/AgentsLandingPagePilot.test.tsx index 86464bf41b..536d9ac00a 100644 --- a/apps/csm-portal/webapp/src/features/csm-dashboard/components/AgentsLandingPagePilot.test.tsx +++ b/apps/csm-portal/webapp/src/features/csm-dashboard/components/AgentsLandingPagePilot.test.tsx @@ -188,4 +188,51 @@ describe("AgentsLandingPagePilot", () => { await waitFor(() => expect(postMock).toHaveBeenCalledTimes(6)); expect(screen.getByText("My Patches")).toBeInTheDocument(); }); + + it("groups widgets sharing a `section` under a titled heading, separate from unsectioned widgets", async () => { + getMock.mockResolvedValue({ + id: "team_performance", + displayName: "Team performance", + isDefault: false, + widgets: [ + { + widgetId: "team_open_cases", + displayName: "Team Open P0/P1", + resourceType: "case", + shape: "count", + gridWidth: 6, + filters: {}, + }, + { + widgetId: "incident_wow", + displayName: "Incident WOW", + section: "SLA Violation", + resourceType: "case", + shape: "count", + gridWidth: 6, + filters: {}, + }, + { + widgetId: "query_wow", + displayName: "Query WOW", + section: "SLA Violation", + resourceType: "case", + shape: "count", + gridWidth: 6, + filters: {}, + }, + ], + }); + postMock.mockResolvedValue(searchResponseFor(3)); + + renderWithClient(); + + await waitFor(() => expect(screen.getByText("Team Open P0/P1")).toBeInTheDocument()); + expect(screen.getByText("Incident WOW")).toBeInTheDocument(); + expect(screen.getByText("Query WOW")).toBeInTheDocument(); + + // Exactly one "SLA Violation" heading — both of its widgets share the + // section, they don't each get their own repeated heading. + expect(screen.getAllByText("SLA Violation")).toHaveLength(1); + }); }); diff --git a/apps/csm-portal/webapp/src/features/csm-dashboard/components/AgentsLandingPagePilot.tsx b/apps/csm-portal/webapp/src/features/csm-dashboard/components/AgentsLandingPagePilot.tsx index ea39dfff47..14c89e8553 100644 --- a/apps/csm-portal/webapp/src/features/csm-dashboard/components/AgentsLandingPagePilot.tsx +++ b/apps/csm-portal/webapp/src/features/csm-dashboard/components/AgentsLandingPagePilot.tsx @@ -14,10 +14,11 @@ // specific language governing permissions and limitations // under the License. -import { Box, Card, Skeleton, Typography } from "@wso2/oxygen-ui"; +import { Box, Card, Divider, Skeleton, Typography } from "@wso2/oxygen-ui"; import { useQueryClient } from "@tanstack/react-query"; -import { useState, type JSX } from "react"; +import { Fragment, useState, type JSX } from "react"; import { ApiQueryKeys } from "@constants/apiConstants"; +import type { BeDashboardWidget } from "@api/backend/types"; import { useDashboard } from "@features/csm-dashboard/api/useDashboard"; import DashboardWidgetTile from "@features/csm-dashboard/components/DashboardWidgetTile"; import SectionCard from "@features/csm-dashboard/components/SectionCard"; @@ -26,6 +27,59 @@ import RefreshButton from "@features/csm-dashboard/components/RefreshButton"; /** Placeholder tile count while the dashboard detail is in flight. */ const PILOT_TILE_COUNT = 3; +/** 12-column grid, matching each widget's own `gridWidth`; on very small + * screens there's only room for 4 columns, so a wide widget there wraps to + * (at most) one extra row rather than overflowing. */ +const WIDGET_GRID_SX = { + display: "grid", + gap: 1.5, + gridTemplateColumns: { + xs: "repeat(4, minmax(0, 1fr))", + sm: "repeat(12, minmax(0, 1fr))", + }, +} as const; + +interface WidgetGroup { + /** `undefined` for the untitled/default group — every widget with no + * `section` set lands here, rendered exactly as before this field + * existed (no heading). */ + section?: string; + widgets: BeDashboardWidget[]; +} + +/** Groups widgets by `section`, preserving the order each distinct section + * value (including the untitled default) first appears among `widgets` — + * see `BeDashboardWidget.section`. */ +function groupWidgetsBySection(widgets: BeDashboardWidget[]): WidgetGroup[] { + const groups: WidgetGroup[] = []; + const indexBySection = new Map(); + for (const widget of widgets) { + const key = widget.section || undefined; + let index = indexBySection.get(key); + if (index === undefined) { + index = groups.length; + indexBySection.set(key, index); + groups.push({ section: key, widgets: [] }); + } + groups[index].widgets.push(widget); + } + return groups; +} + +function widgetGridColumnSx(widget: BeDashboardWidget) { + // A list-shape widget renders a real table (4 rows, several columns) — + // its configured `gridWidth` was sized for the old compact text list, so + // it always spans the full row here regardless of that value. + return widget.shape === "list" + ? { gridColumn: "1 / -1" } + : { + gridColumn: { + xs: `span ${Math.min(widget.gridWidth, 4)}`, + sm: `span ${widget.gridWidth}`, + }, + }; +} + interface AgentsLandingPagePilotProps { /** Id of the dashboard to render (e.g. "agents_pilot"). */ dashboardId: string; @@ -82,55 +136,71 @@ export default function AgentsLandingPagePilot({ Could not load the widget pilot. - ) : ( - - {isLoading || isRefreshing - ? Array.from({ length: PILOT_TILE_COUNT }, (_, i) => ( - - - - )) - : (data?.widgets ?? []).map((widget) => ( - - - - ))} + ) : isLoading || isRefreshing ? ( + + {Array.from({ length: PILOT_TILE_COUNT }, (_, i) => ( + + + + ))} + ) : ( + (() => { + const widgets = data?.widgets ?? []; + const renderTile = (widget: BeDashboardWidget) => { + return ( + + + + ); + }; + + const groups = groupWidgetsBySection(widgets); + + return ( + + {groups.map((group, i) => { + // Chart-shaped widgets (pie/bar) are visually grouped into + // their own row below this group's count/list tiles, rather + // than sharing one undifferentiated grid with them. + const mainWidgets = group.widgets.filter((w) => w.shape !== "pie" && w.shape !== "bar"); + const chartWidgets = group.widgets.filter((w) => w.shape === "pie" || w.shape === "bar"); + if (mainWidgets.length === 0 && chartWidgets.length === 0) return null; + + return ( + + {i > 0 && } + + {group.section && ( + + {group.section} + + )} + {mainWidgets.length > 0 && ( + {mainWidgets.map(renderTile)} + )} + {chartWidgets.length > 0 && ( + <> + {mainWidgets.length > 0 && } + {chartWidgets.map(renderTile)} + + )} + + + ); + })} + + ); + })() )} ); diff --git a/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardBarChart.tsx b/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardBarChart.tsx new file mode 100644 index 0000000000..d26d562484 --- /dev/null +++ b/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardBarChart.tsx @@ -0,0 +1,163 @@ +// 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. + +import { Box, Skeleton, Typography, alpha, useTheme } from "@wso2/oxygen-ui"; +import { Inbox } from "@wso2/oxygen-ui-icons-react"; +import { Bar, BarChart, Cell } from "@wso2/oxygen-ui-charts-react"; +import { useState, type JSX } from "react"; +import type { BeWidgetPaletteColor } from "@api/backend/types"; +import type { PieSliceResult } from "@features/csm-dashboard/api/useWidgetPieData"; +import { useDarkMode } from "@utils/useDarkMode"; + +const CHART_HEIGHT_PX = 220; + +/** Used in order when a slice's own config omits `color`. */ +const DEFAULT_COLOR_ROTATION: BeWidgetPaletteColor[] = [ + "primary", + "warning", + "secondary", + "info", + "success", + "error", +]; + +interface DashboardBarChartProps { + slices: PieSliceResult[]; + total: number; + isLoading: boolean; + isError: boolean; + onSliceClick: (slice: PieSliceResult) => void; +} + +/** + * Bar chart for a `shape: "bar"` dashboard widget — one bar per slice + * (`useWidgetPieData` is shape-agnostic: it resolves N labeled slice totals + * the same way regardless of whether they render as wedges or bars), each + * clickable through to that slice's own filtered case list, same as + * `DashboardPieChart`'s wedges/legend rows. A total of 0 renders an empty + * state instead of an all-grey chart, same treatment as `DashboardPieChart`. + */ +export default function DashboardBarChart({ + slices, + total, + isLoading, + isError, + onSliceClick, +}: DashboardBarChartProps): JSX.Element { + const theme = useTheme(); + const isDarkMode = useDarkMode(); + const [activeIndex, setActiveIndex] = useState(undefined); + + const colorFor = (slice: PieSliceResult, i: number): string => { + const key = slice.color ?? DEFAULT_COLOR_ROTATION[i % DEFAULT_COLOR_ROTATION.length]; + return theme.palette[key].main; + }; + + if (isLoading) { + return ; + } + + if (isError) { + return ( + + Could not load this widget. + + ); + } + + if (total === 0) { + return ( + + + + + + Nothing to show here right now + + + ); + } + + const chartData = slices.map((slice) => ({ name: slice.label, value: slice.value })); + + return ( + + + setActiveIndex(i)} + onMouseLeave={() => setActiveIndex(undefined)} + onClick={(_data: unknown, i: number) => { + const slice = slices[i]; + if (slice) onSliceClick(slice); + }} + > + {slices.map((slice, i) => ( + + ))} + + + + ); +} diff --git a/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardPieChart.tsx b/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardPieChart.tsx new file mode 100644 index 0000000000..bcf3f74d34 --- /dev/null +++ b/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardPieChart.tsx @@ -0,0 +1,246 @@ +// 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. + +import { Box, Skeleton, Typography, alpha, useTheme } from "@wso2/oxygen-ui"; +import { Inbox } from "@wso2/oxygen-ui-icons-react"; +import { Cell, Pie, PieChart } from "@wso2/oxygen-ui-charts-react"; +import { useState, type JSX } from "react"; +import type { BeWidgetPaletteColor } from "@api/backend/types"; +import type { PieSliceResult } from "@features/csm-dashboard/api/useWidgetPieData"; +import { useDarkMode } from "@utils/useDarkMode"; + +const CHART_SIZE_PX = 180; +const INNER_RADIUS_PX = 62; +const OUTER_RADIUS_PX = 88; + +/** Used in order when a slice's own config omits `color`. */ +const DEFAULT_COLOR_ROTATION: BeWidgetPaletteColor[] = [ + "primary", + "warning", + "secondary", + "info", + "success", + "error", +]; + +interface DashboardPieChartProps { + slices: PieSliceResult[]; + total: number; + isLoading: boolean; + isError: boolean; + onSliceClick: (slice: PieSliceResult) => void; +} + +/** + * Donut chart + legend for a `shape: "pie"` dashboard widget — a fixed + * center total, one wedge (and one legend row) per slice, both clickable + * through to that slice's own filtered case list (see + * `DashboardWidgetTile`'s pie branch for how the destination href is + * built). A total of 0 renders an empty state (same treatment as the + * customer-portal app's own dashboard charts) instead of an all-grey ring. + */ +export default function DashboardPieChart({ + slices, + total, + isLoading, + isError, + onSliceClick, +}: DashboardPieChartProps): JSX.Element { + const theme = useTheme(); + const isDarkMode = useDarkMode(); + const [activeIndex, setActiveIndex] = useState(undefined); + + const colorFor = (slice: PieSliceResult, i: number): string => { + const key = slice.color ?? DEFAULT_COLOR_ROTATION[i % DEFAULT_COLOR_ROTATION.length]; + return theme.palette[key].main; + }; + + if (isLoading) { + return ( + + + + {slices.map((slice) => ( + + ))} + + + ); + } + + if (isError) { + return ( + + Could not load this widget. + + ); + } + + if (total === 0) { + return ( + + + {/* text.disabled/text.secondary render too close to the + background's own color in this app's dark theme (same issue + fixed for the bar chart's value labels) — grey[400] is legible + against a dark background without looking harsh in light mode. */} + + + + Nothing to show here right now + + + ); + } + + const chartData = slices.map((slice) => ({ name: slice.label, value: slice.value })); + + return ( + + + {/* wrapperStyle's zIndex matches the same fix the customer-portal + app's own dashboard charts use (see OutstandingIncidentsChart.tsx) + — without it the tooltip can render underneath/get clipped by + this tile's own header, looking cut off / see-through. + margin: PieChart's own default is {top:12,right:24,left:24, + bottom:40} — the large bottom value reserves room for a legend, + which is disabled here. Left uncleared, that asymmetric margin + shifts the plot's (and so the ring's) center downward within the + 180x180 box, making the top of the donut look pushed toward / + cut off by this tile's own header above it. */} + + setActiveIndex(i)} + onMouseLeave={() => setActiveIndex(undefined)} + onClick={(_data: unknown, i: number) => { + const slice = slices[i]; + if (slice) onSliceClick(slice); + }} + > + {slices.map((slice, i) => ( + + ))} + + + + {total} + + Total + + + + + + {slices.map((slice, i) => { + const pct = total > 0 ? Math.round((slice.value / total) * 100) : 0; + return ( + onSliceClick(slice)} + sx={{ + display: "flex", + alignItems: "center", + gap: 1, + px: 0.5, + py: 0.25, + borderRadius: 1, + cursor: "pointer", + "&:hover": { bgcolor: "action.hover" }, + }} + > + + + {slice.label} + + + {slice.value} ({pct}%) + + + ); + })} + + + ); +} diff --git a/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardWidgetTile.test.tsx b/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardWidgetTile.test.tsx index 3a8c700895..6c2ec71667 100644 --- a/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardWidgetTile.test.tsx +++ b/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardWidgetTile.test.tsx @@ -14,12 +14,12 @@ // specific language governing permissions and limitations // under the License. -import { render, screen, waitFor } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { describe, expect, it, vi, beforeEach } from "vitest"; import "@testing-library/jest-dom/vitest"; -import type { ReactNode } from "react"; -import { MemoryRouter } from "react-router"; +import { Children, cloneElement, isValidElement, type ReactElement, type ReactNode } from "react"; +import { MemoryRouter, Route, Routes, useLocation } from "react-router"; const postMock = vi.fn(); @@ -39,6 +39,63 @@ vi.mock("@context/current-user/CurrentUserContext", () => ({ isError: false, }), })); +// Recharts' ResponsiveContainer measures a real layout size, which jsdom +// always reports as 0 — nothing would render. Stubbed to a plain list of +// slice buttons (label + value), enough to assert on data/clicks without +// depending on actual SVG geometry (same approach the customer-portal app's +// own chart tests use for this same package). +vi.mock("@wso2/oxygen-ui-charts-react", () => ({ + ResponsiveContainer: ({ children }: { children: ReactNode }) =>
{children}
, + PieChart: ({ children }: { children: ReactNode }) =>
{children}
, + Pie: ({ + data, + onClick, + }: { + data: { name: string; value: number }[]; + onClick?: (item: unknown, index: number) => void; + }) => ( +
+ {data.map((item, i) => ( + + ))} +
+ ), + Cell: () => null, + // `data` is a BarChart-level prop (not Bar's own) in the real package — + // clone it onto the Bar child so the mock below can read it. + BarChart: ({ + children, + data, + }: { + children: ReactNode; + data?: { name: string; value: number }[]; + }) => ( +
+ {Children.map(children, (child) => + isValidElement(child) + ? cloneElement(child as ReactElement<{ data?: typeof data }>, { data }) + : child, + )} +
+ ), + Bar: ({ + data, + onClick, + }: { + data?: { name: string; value: number }[]; + onClick?: (item: unknown, index: number) => void; + }) => ( +
+ {(data ?? []).map((item, i) => ( + + ))} +
+ ), +})); import DashboardWidgetTile from "@features/csm-dashboard/components/DashboardWidgetTile"; @@ -53,6 +110,29 @@ function renderWithClient(ui: ReactNode) { ); } +function LocationProbe() { + const location = useLocation(); + return
{location.pathname + location.search}
; +} + +/** For tests that need to observe where a click actually navigated to — + * `renderWithClient` has no destination route to land on. */ +function renderWithRoutes(ui: ReactNode, destinationPath: string) { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + return render( + + + + + } /> + + + , + ); +} + describe("DashboardWidgetTile", () => { beforeEach(() => { postMock.mockReset(); @@ -255,22 +335,149 @@ describe("DashboardWidgetTile", () => { expect(params.get("states")).toBe("open"); }); - it("renders a not-yet-supported message for shape pie/bar instead of crashing", async () => { - postMock.mockResolvedValue({ total: 0, cases: [], limit: 1, offset: 0, hasMore: false }); + it("shape bar: issues one search per slice and renders a bar per slice, clickable the same way as a pie slice", async () => { + postMock.mockImplementation( + (_path: string, body: { filters: Record }) => { + const severities = body.filters.severities as string[] | undefined; + if (severities?.includes("critical")) return Promise.resolve({ total: 1 }); + if (severities?.includes("high")) return Promise.resolve({ total: 3 }); + return Promise.resolve({ total: 0 }); + }, + ); - renderWithClient( + renderWithRoutes( , + "/cases", + ); + + await waitFor(() => expect(screen.getByText("bar:S1 · Critical:1")).toBeInTheDocument()); + expect(screen.getByText("bar:S2 · High:3")).toBeInTheDocument(); + expect(postMock).toHaveBeenCalledWith("/cases/search", { + filters: { states: ["open"], severities: ["critical"] }, + pagination: { offset: 0, limit: 1 }, + }); + + fireEvent.click(screen.getByText("bar:S1 · Critical:1")); + await waitFor(() => expect(screen.getByTestId("location-probe")).toBeInTheDocument()); + const probeText = screen.getByTestId("location-probe").textContent ?? ""; + const params = new URLSearchParams(probeText.split("?")[1]); + expect(params.get("severities")).toBe("S1"); + expect(params.get("states")).toBe("open"); + }); + + it("shape pie: issues one search per slice (own filters merged under the widget's base filters) and renders values + percentages", async () => { + postMock.mockImplementation( + (_path: string, body: { filters: Record }) => { + const severities = body.filters.severities as string[] | undefined; + if (severities?.includes("critical")) return Promise.resolve({ total: 1 }); + if (severities?.includes("high")) return Promise.resolve({ total: 3 }); + return Promise.resolve({ total: 0 }); + }, + ); + + renderWithClient( + , + ); + + expect(screen.getByText("Share of active cases at each severity level.")).toBeInTheDocument(); + await waitFor(() => expect(screen.getByText("slice:S1 · Critical:1")).toBeInTheDocument()); + expect(screen.getByText("slice:S2 · High:3")).toBeInTheDocument(); + expect(screen.getByText("1 (25%)")).toBeInTheDocument(); + expect(screen.getByText("3 (75%)")).toBeInTheDocument(); + expect(postMock).toHaveBeenCalledWith("/cases/search", { + filters: { states: ["open"], severities: ["critical"] }, + pagination: { offset: 0, limit: 1 }, + }); + expect(postMock).toHaveBeenCalledWith("/cases/search", { + filters: { states: ["open"], severities: ["high"] }, + pagination: { offset: 0, limit: 1 }, + }); + }); + + it("shape pie: clicking a slice navigates to /cases with the widget's base filters merged under that slice's own filters", async () => { + postMock.mockResolvedValue({ total: 2 }); + + renderWithRoutes( + , + "/cases", + ); + + await waitFor(() => expect(screen.getByText("slice:Critical:2")).toBeInTheDocument()); + fireEvent.click(screen.getByText("slice:Critical:2")); + + await waitFor(() => expect(screen.getByTestId("location-probe")).toBeInTheDocument()); + const probeText = screen.getByTestId("location-probe").textContent ?? ""; + expect(probeText.startsWith("/cases?")).toBe(true); + const params = new URLSearchParams(probeText.split("?")[1]); + expect(params.get("severities")).toBe("S1"); + expect(params.get("states")).toBe("open"); + }); + + it("shape pie: clicking a legend row navigates the same way as clicking the slice", async () => { + postMock.mockResolvedValue({ total: 2 }); + + renderWithRoutes( + , + "/cases", ); - await waitFor(() => - expect(screen.getByText("Not yet supported.")).toBeInTheDocument(), + await waitFor(() => expect(screen.getByText("Critical")).toBeInTheDocument()); + fireEvent.click(screen.getByText("Critical")); + + await waitFor(() => expect(screen.getByTestId("location-probe")).toBeInTheDocument()); + const probeText = screen.getByTestId("location-probe").textContent ?? ""; + expect(new URLSearchParams(probeText.split("?")[1]).get("severities")).toBe("S1"); + }); + + it("shape pie: renders an empty state (no slices, zero total) rather than crashing when a widget has no slices configured yet", async () => { + renderWithClient( + , ); + + expect(screen.getByText("Cases by severity")).toBeInTheDocument(); + expect(screen.getByText("Nothing to show here right now")).toBeInTheDocument(); + expect(postMock).not.toHaveBeenCalled(); }); it("renders an unsupported-widget message instead of crashing for an unrecognized resourceType", () => { diff --git a/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardWidgetTile.tsx b/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardWidgetTile.tsx index 70dd64c9a7..6a2a8fbd88 100644 --- a/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardWidgetTile.tsx +++ b/apps/csm-portal/webapp/src/features/csm-dashboard/components/DashboardWidgetTile.tsx @@ -17,17 +17,23 @@ import { Box, Button, Card, Skeleton, Tooltip, Typography, alpha, useTheme } from "@wso2/oxygen-ui"; import { ArrowRight, Info } from "@wso2/oxygen-ui-icons-react"; import type { JSX, ReactNode } from "react"; -import { Link as RouterLink } from "react-router"; -import type { BeWidgetResourceType, BeWidgetShape } from "@api/backend/types"; +import { Link as RouterLink, useNavigate } from "react-router"; +import type { BeDashboardPieSlice, BeWidgetResourceType, BeWidgetShape } from "@api/backend/types"; import { useCurrentUser } from "@context/current-user/CurrentUserContext"; import { useWidgetData } from "@features/csm-dashboard/api/useWidgetData"; +import { useWidgetPieData, type PieSliceResult } from "@features/csm-dashboard/api/useWidgetPieData"; import { WIDGET_RESOURCE_CONFIG } from "@features/csm-dashboard/config/widgetResourceConfig"; import { WIDGET_LIST_RENDERERS } from "@features/csm-dashboard/config/widgetListConfig"; import { buildWidgetPreviewHref } from "@features/csm-dashboard/utils/widgetPreviewUrl"; +import DashboardPieChart from "@features/csm-dashboard/components/DashboardPieChart"; +import DashboardBarChart from "@features/csm-dashboard/components/DashboardBarChart"; interface DashboardWidgetTileProps { widgetId: string; displayName: string; + /** Explanatory subtitle shown under `displayName` — only rendered for + * shapes "pie"/"bar" today, but not shape-specific by design. */ + description?: string; resourceType: BeWidgetResourceType; shape: BeWidgetShape; filters: Record; @@ -35,6 +41,10 @@ interface DashboardWidgetTileProps { * 4 (see useWidgetData's DEFAULT_LIST_LIMIT) — set explicitly per-widget * via the backend's DASHBOARDS_CONFIG, not overridden here. */ listLimit?: number; + /** Only meaningful for shape "pie"/"bar"; one search per slice (see + * `useWidgetPieData`). Empty/absent renders an empty chart rather than + * crashing. */ + slices?: BeDashboardPieSlice[]; } /** @@ -56,19 +66,33 @@ interface DashboardWidgetTileProps { export default function DashboardWidgetTile({ widgetId, displayName, + description, resourceType, shape, filters, listLimit, + slices, }: DashboardWidgetTileProps): JSX.Element { const theme = useTheme(); + const navigate = useNavigate(); const { user } = useCurrentUser(); + // Shape "pie" resolves via useWidgetPieData instead (one search per + // slice) — skip this one's own network call rather than wasting it, but + // still call the hook unconditionally (rules of hooks; a widget's shape + // never changes across this component's lifetime). const { data, isLoading, isError } = useWidgetData( widgetId, resourceType, filters, shape, listLimit, + 0, + shape !== "pie" && shape !== "bar", + ); + const pieData = useWidgetPieData( + resourceType, + filters, + shape === "pie" || shape === "bar" ? (slices ?? []) : [], ); const config = WIDGET_RESOURCE_CONFIG[resourceType]; @@ -185,6 +209,39 @@ export default function DashboardWidgetTile({ ); } + if (shape === "pie" || shape === "bar") { + // Each slice/legend row (or bar) navigates independently, so — same + // rationale as shape "list" — this can't be one big link the way shape + // "count" is; it's a plain, non-link Card with its own nested click + // targets. + const ChartComponent = shape === "pie" ? DashboardPieChart : DashboardBarChart; + return ( + + {/* The header's own bottom padding — not just a top margin on the + chart below it — so the chart's top edge (and, at the size this + chart renders at, its tooltip) never sits flush against/behind + the title row above it. */} + {header} + {description && ( + + {description} + + )} + + + navigate(config.buildHref({ ...filters, ...slice.filters })) + } + /> + + + ); + } + let body: ReactNode; if (isLoading) { body = ; @@ -194,7 +251,7 @@ export default function DashboardWidgetTile({ Could not load this widget. ); - } else if (shape === "count") { + } else { body = ( ); - } else { - // pie/bar: no aggregate endpoint exists anywhere in the stack today, so - // there is nothing to resolve or render yet — see `BeWidgetShape`. - body = ( - - - - - - - {displayName} - - - Not yet supported. - - - - ); } return (