Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 46 additions & 5 deletions apps/csm-portal/backend/internal/dashboard/widgets.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down
77 changes: 77 additions & 0 deletions apps/csm-portal/backend/internal/dashboard/widgets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
43 changes: 35 additions & 8 deletions apps/csm-portal/backend/internal/handler/dashboards.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
})
}

Expand Down
119 changes: 118 additions & 1 deletion apps/csm-portal/backend/internal/handler/dashboards_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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":{}}
]}
]`

Expand Down Expand Up @@ -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 {
Expand Down
Loading