diff --git a/apps/csm-portal/backend/cmd/server/main.go b/apps/csm-portal/backend/cmd/server/main.go index 9b04590b78..24d4d45070 100644 --- a/apps/csm-portal/backend/cmd/server/main.go +++ b/apps/csm-portal/backend/cmd/server/main.go @@ -64,6 +64,7 @@ func main() { productVulnerabilityHandler := handler.NewProductVulnerabilityHandler(entityClient) conversationHandler := handler.NewConversationHandler(entityClient) taskSlaHandler := handler.NewTaskSlaHandler(entityClient) + taskHandler := handler.NewTaskHandler(entityClient) incidentHandler := handler.NewIncidentHandler(entityClient) problemHandler := handler.NewProblemHandler(entityClient) @@ -153,6 +154,8 @@ func main() { mux.HandleFunc("POST /conversations/search", conversationHandler.SearchConversations) mux.HandleFunc("POST /slas/search", taskSlaHandler.SearchTaskSlas) mux.HandleFunc("GET /slas/{id}", taskSlaHandler.GetTaskSla) + mux.HandleFunc("POST /cases/{caseId}/tasks/search", taskHandler.SearchCaseTasks) + mux.HandleFunc("GET /tasks/{id}", taskHandler.GetTask) mux.HandleFunc("POST /incidents/search", incidentHandler.SearchIncidents) mux.HandleFunc("POST /incidents", incidentHandler.CreateIncident) mux.HandleFunc("GET /incidents/{id}", incidentHandler.GetIncident) diff --git a/apps/csm-portal/backend/internal/entity/entity.go b/apps/csm-portal/backend/internal/entity/entity.go index 5b3d33551b..a41d1cbd44 100644 --- a/apps/csm-portal/backend/internal/entity/entity.go +++ b/apps/csm-portal/backend/internal/entity/entity.go @@ -372,3 +372,15 @@ func (c *Client) SearchTaskSlas(ctx context.Context, body []byte) ([]byte, error func (c *Client) GetTaskSla(ctx context.Context, id string) ([]byte, error) { return c.do(ctx, http.MethodGet, fmt.Sprintf("/slas/%s", url.PathEscape(id)), nil) } + +// SearchCaseTasks calls POST /cases/{caseId}/tasks/search on the entity service. +// Response is returned as raw JSON; typed response structs are deferred. +func (c *Client) SearchCaseTasks(ctx context.Context, caseID string, body []byte) ([]byte, error) { + return c.do(ctx, http.MethodPost, fmt.Sprintf("/cases/%s/tasks/search", url.PathEscape(caseID)), body) +} + +// GetTask calls GET /tasks/{id} on the entity service. +// Response is returned as raw JSON; typed response structs are deferred. +func (c *Client) GetTask(ctx context.Context, id string) ([]byte, error) { + return c.do(ctx, http.MethodGet, fmt.Sprintf("/tasks/%s", url.PathEscape(id)), nil) +} diff --git a/apps/csm-portal/backend/internal/handler/helpers_test.go b/apps/csm-portal/backend/internal/handler/helpers_test.go index 4ab9488bec..15f3a1595b 100644 --- a/apps/csm-portal/backend/internal/handler/helpers_test.go +++ b/apps/csm-portal/backend/internal/handler/helpers_test.go @@ -635,3 +635,24 @@ func (m *mockEntityTaskSlaClient) GetTaskSla(ctx context.Context, id string) ([] } return []byte(`{"id":"11111111-1111-1111-1111-111111111111"}`), nil } + +// ----- mock entity task client ----- + +type mockEntityTaskClient struct { + searchCaseTasksFn func(ctx context.Context, caseID string, body []byte) ([]byte, error) + getTaskFn func(ctx context.Context, id string) ([]byte, error) +} + +func (m *mockEntityTaskClient) SearchCaseTasks(ctx context.Context, caseID string, body []byte) ([]byte, error) { + if m.searchCaseTasksFn != nil { + return m.searchCaseTasksFn(ctx, caseID, body) + } + return []byte(`{"tasks":[],"total":0,"limit":20,"offset":0}`), nil +} + +func (m *mockEntityTaskClient) GetTask(ctx context.Context, id string) ([]byte, error) { + if m.getTaskFn != nil { + return m.getTaskFn(ctx, id) + } + return []byte(`{"id":"11111111-1111-1111-1111-111111111111"}`), nil +} diff --git a/apps/csm-portal/backend/internal/handler/tasks.go b/apps/csm-portal/backend/internal/handler/tasks.go new file mode 100644 index 0000000000..ff7d817758 --- /dev/null +++ b/apps/csm-portal/backend/internal/handler/tasks.go @@ -0,0 +1,109 @@ +// 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/json" + "io" + "log/slog" + "net/http" + + "github.com/wso2-open-operations/cs-tools/apps/csm-portal/backend/internal/middleware" +) + +// entityTaskClient abstracts the entity service task operations. +type entityTaskClient interface { + SearchCaseTasks(ctx context.Context, caseID string, body []byte) ([]byte, error) + GetTask(ctx context.Context, id string) ([]byte, error) +} + +// TaskHandler handles HTTP requests for task operations. +type TaskHandler struct { + entity entityTaskClient +} + +// NewTaskHandler creates a TaskHandler backed by the given entity client. +func NewTaskHandler(entity entityTaskClient) *TaskHandler { + return &TaskHandler{entity: entity} +} + +// SearchCaseTasks handles POST /cases/{caseId}/tasks/search. +// The endpoint is path-scoped, so the request body (e.g. {"pagination":{"limit":...,"offset":...}}) +// is capped and forwarded to the entity service as-is, and the response is returned verbatim. +func (h *TaskHandler) SearchCaseTasks(w http.ResponseWriter, r *http.Request) { + user := middleware.UserInfoFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrMsgUnauthorized) + return + } + + caseID := r.PathValue("caseId") + if caseID == "" || !uuidRe.MatchString(caseID) { + writeError(w, http.StatusBadRequest, ErrMsgInvalidUUID) + return + } + + r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes) + body, err := io.ReadAll(r.Body) + if err != nil { + if _, ok := err.(*http.MaxBytesError); ok { + writeError(w, http.StatusRequestEntityTooLarge, ErrMsgTooLarge) + return + } + writeError(w, http.StatusBadRequest, errMsgReadBody) + return + } + + if len(body) > 0 && !json.Valid(body) { + writeError(w, http.StatusBadRequest, ErrMsgBadRequest) + return + } + + result, err := h.entity.SearchCaseTasks(r.Context(), caseID, body) + if err != nil { + slog.ErrorContext(r.Context(), "entity SearchCaseTasks failed", "userID", user.UserID, "caseID", caseID, "err", err) + mapUpstreamError(w, err, "Failed to retrieve case tasks.") + return + } + + writeJSON(w, http.StatusOK, result) +} + +// GetTask handles GET /tasks/{id}. +func (h *TaskHandler) GetTask(w http.ResponseWriter, r *http.Request) { + user := middleware.UserInfoFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrMsgUnauthorized) + return + } + + id := r.PathValue("id") + if id == "" || !uuidRe.MatchString(id) { + writeError(w, http.StatusBadRequest, ErrMsgInvalidUUID) + return + } + + result, err := h.entity.GetTask(r.Context(), id) + if err != nil { + slog.ErrorContext(r.Context(), "entity GetTask failed", "userID", user.UserID, "id", id, "err", err) + mapUpstreamError(w, err, "Failed to retrieve task.") + return + } + + writeJSON(w, http.StatusOK, result) +} diff --git a/apps/csm-portal/backend/internal/handler/tasks_test.go b/apps/csm-portal/backend/internal/handler/tasks_test.go new file mode 100644 index 0000000000..881be10e9c --- /dev/null +++ b/apps/csm-portal/backend/internal/handler/tasks_test.go @@ -0,0 +1,218 @@ +// 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" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +const testTaskCaseID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" +const testTaskID = "11111111-1111-1111-1111-111111111111" + +func TestSearchCaseTasks(t *testing.T) { + t.Run("requires authenticated user", func(t *testing.T) { + h := NewTaskHandler(&mockEntityTaskClient{}) + r := httptest.NewRequest(http.MethodPost, "/cases/"+testTaskCaseID+"/tasks/search", strings.NewReader(`{}`)) + r.SetPathValue("caseId", testTaskCaseID) + w := httptest.NewRecorder() + h.SearchCaseTasks(w, r) + assertStatus(t, w, http.StatusUnauthorized) + assertErrorMessage(t, w, ErrMsgUnauthorized) + assertContentType(t, w, "application/json") + }) + + t.Run("rejects malformed case UUID", func(t *testing.T) { + h := NewTaskHandler(&mockEntityTaskClient{}) + r := withUser(httptest.NewRequest(http.MethodPost, "/cases/not-a-uuid/tasks/search", strings.NewReader(`{}`))) + r.SetPathValue("caseId", "not-a-uuid") + w := httptest.NewRecorder() + h.SearchCaseTasks(w, r) + assertStatus(t, w, http.StatusBadRequest) + assertErrorMessage(t, w, ErrMsgInvalidUUID) + assertContentType(t, w, "application/json") + }) + + t.Run("rejects empty case id", func(t *testing.T) { + h := NewTaskHandler(&mockEntityTaskClient{}) + r := withUser(httptest.NewRequest(http.MethodPost, "/cases//tasks/search", strings.NewReader(`{}`))) + w := httptest.NewRecorder() + h.SearchCaseTasks(w, r) + assertStatus(t, w, http.StatusBadRequest) + assertErrorMessage(t, w, ErrMsgInvalidUUID) + assertContentType(t, w, "application/json") + }) + + t.Run("rejects body exceeding 1 MiB", func(t *testing.T) { + h := NewTaskHandler(&mockEntityTaskClient{}) + r := withUser(httptest.NewRequest(http.MethodPost, "/cases/"+testTaskCaseID+"/tasks/search", strings.NewReader(strings.Repeat("x", maxRequestBodyBytes+1)))) + r.SetPathValue("caseId", testTaskCaseID) + w := httptest.NewRecorder() + h.SearchCaseTasks(w, r) + assertStatus(t, w, http.StatusRequestEntityTooLarge) + assertErrorMessage(t, w, ErrMsgTooLarge) + assertContentType(t, w, "application/json") + }) + + t.Run("rejects invalid JSON body", func(t *testing.T) { + h := NewTaskHandler(&mockEntityTaskClient{}) + r := withUser(httptest.NewRequest(http.MethodPost, "/cases/"+testTaskCaseID+"/tasks/search", strings.NewReader(`not-json`))) + r.SetPathValue("caseId", testTaskCaseID) + w := httptest.NewRecorder() + h.SearchCaseTasks(w, r) + assertStatus(t, w, http.StatusBadRequest) + assertErrorMessage(t, w, ErrMsgBadRequest) + assertContentType(t, w, "application/json") + }) + + t.Run("forwards case id and body verbatim to upstream", func(t *testing.T) { + var capturedCaseID string + var capturedBody []byte + reqBody := `{"pagination":{"limit":20,"offset":0}}` + client := &mockEntityTaskClient{ + searchCaseTasksFn: func(_ context.Context, caseID string, body []byte) ([]byte, error) { + capturedCaseID = caseID + capturedBody = body + return []byte(`{"tasks":[{"id":"` + testTaskID + `"}],"total":1,"limit":20,"offset":0}`), nil + }, + } + h := NewTaskHandler(client) + r := withUser(httptest.NewRequest(http.MethodPost, "/cases/"+testTaskCaseID+"/tasks/search", strings.NewReader(reqBody))) + r.SetPathValue("caseId", testTaskCaseID) + w := httptest.NewRecorder() + h.SearchCaseTasks(w, r) + + assertStatus(t, w, http.StatusOK) + assertContentType(t, w, "application/json") + + if capturedCaseID != testTaskCaseID { + t.Errorf("upstream received caseID %q, want %q", capturedCaseID, testTaskCaseID) + } + if string(capturedBody) != reqBody { + t.Errorf("upstream body = %q, want verbatim %q", string(capturedBody), reqBody) + } + resp := decodeJSON[map[string]any](t, w) + if resp["total"] != float64(1) { + t.Errorf("total = %v, want 1", resp["total"]) + } + }) + + t.Run("upstream errors are mapped correctly", func(t *testing.T) { + for _, tc := range upstreamErrors("Failed to retrieve case tasks.") { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + client := &mockEntityTaskClient{ + searchCaseTasksFn: func(_ context.Context, _ string, _ []byte) ([]byte, error) { + return nil, tc.err + }, + } + h := NewTaskHandler(client) + r := withUser(httptest.NewRequest(http.MethodPost, "/cases/"+testTaskCaseID+"/tasks/search", strings.NewReader(`{}`))) + r.SetPathValue("caseId", testTaskCaseID) + w := httptest.NewRecorder() + h.SearchCaseTasks(w, r) + assertStatus(t, w, tc.wantCode) + assertErrorMessage(t, w, tc.wantMsg) + assertContentType(t, w, "application/json") + }) + } + }) +} + +func TestGetTask(t *testing.T) { + t.Run("requires authenticated user", func(t *testing.T) { + h := NewTaskHandler(&mockEntityTaskClient{}) + r := httptest.NewRequest(http.MethodGet, "/tasks/"+testTaskID, nil) + r.SetPathValue("id", testTaskID) + w := httptest.NewRecorder() + h.GetTask(w, r) + assertStatus(t, w, http.StatusUnauthorized) + assertErrorMessage(t, w, ErrMsgUnauthorized) + assertContentType(t, w, "application/json") + }) + + t.Run("rejects malformed UUID", func(t *testing.T) { + h := NewTaskHandler(&mockEntityTaskClient{}) + r := withUser(httptest.NewRequest(http.MethodGet, "/tasks/not-a-uuid", nil)) + r.SetPathValue("id", "not-a-uuid") + w := httptest.NewRecorder() + h.GetTask(w, r) + assertStatus(t, w, http.StatusBadRequest) + assertErrorMessage(t, w, ErrMsgInvalidUUID) + assertContentType(t, w, "application/json") + }) + + t.Run("rejects empty id", func(t *testing.T) { + h := NewTaskHandler(&mockEntityTaskClient{}) + r := withUser(httptest.NewRequest(http.MethodGet, "/tasks/", nil)) + w := httptest.NewRecorder() + h.GetTask(w, r) + assertStatus(t, w, http.StatusBadRequest) + assertErrorMessage(t, w, ErrMsgInvalidUUID) + assertContentType(t, w, "application/json") + }) + + t.Run("forwards id to upstream and returns 200", func(t *testing.T) { + var capturedID string + client := &mockEntityTaskClient{ + getTaskFn: func(_ context.Context, id string) ([]byte, error) { + capturedID = id + return []byte(`{"id":"` + testTaskID + `","subject":"Investigate outage","state":"in_progress"}`), nil + }, + } + h := NewTaskHandler(client) + r := withUser(httptest.NewRequest(http.MethodGet, "/tasks/"+testTaskID, nil)) + r.SetPathValue("id", testTaskID) + w := httptest.NewRecorder() + h.GetTask(w, r) + + assertStatus(t, w, http.StatusOK) + assertContentType(t, w, "application/json") + + if capturedID != testTaskID { + t.Errorf("upstream received id %q, want %q", capturedID, testTaskID) + } + resp := decodeJSON[map[string]any](t, w) + if resp["subject"] != "Investigate outage" { + t.Errorf("response subject = %v, want %q", resp["subject"], "Investigate outage") + } + }) + + t.Run("upstream errors are mapped correctly", func(t *testing.T) { + for _, tc := range upstreamErrors("Failed to retrieve task.") { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + client := &mockEntityTaskClient{ + getTaskFn: func(_ context.Context, _ string) ([]byte, error) { + return nil, tc.err + }, + } + h := NewTaskHandler(client) + r := withUser(httptest.NewRequest(http.MethodGet, "/tasks/"+testTaskID, nil)) + r.SetPathValue("id", testTaskID) + w := httptest.NewRecorder() + h.GetTask(w, r) + assertStatus(t, w, tc.wantCode) + assertErrorMessage(t, w, tc.wantMsg) + assertContentType(t, w, "application/json") + }) + } + }) +} diff --git a/apps/csm-portal/backend/openapi.yaml b/apps/csm-portal/backend/openapi.yaml index 44161acafb..59eeac3e99 100644 --- a/apps/csm-portal/backend/openapi.yaml +++ b/apps/csm-portal/backend/openapi.yaml @@ -2645,6 +2645,126 @@ paths: schema: $ref: '#/components/schemas/ErrorPayload' + /cases/{caseId}/tasks/search: + post: + summary: Search tasks for a case, paginated (ServiceNow data source only). + description: > + The case ID is taken from the URL path; the request body is forwarded to + the integration service as-is and the response is returned verbatim. + operationId: searchCaseTasks + security: + - bearerAuth: [] + parameters: + - name: caseId + in: path + required: true + schema: + type: string + format: uuid + description: Case UUID. + requestBody: + description: Case task search payload. + required: false + content: + application/json: + schema: + $ref: '#/components/schemas/CaseTaskSearchPayload' + responses: + "200": + description: Paginated list of tasks for the case. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskSearchResponse' + "400": + description: Bad request (invalid UUID or request body). + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + "401": + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + "403": + description: Forbidden. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + "404": + description: Case not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + "413": + description: Request entity too large. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + "500": + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + + /tasks/{id}: + get: + summary: Get a single task by ID (ServiceNow data source only). + operationId: getTask + security: + - bearerAuth: [] + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + description: Task UUID. + responses: + "200": + description: The task. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDetail' + "400": + description: Bad request. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + "401": + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + "403": + description: Forbidden. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + "404": + description: Task not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + "500": + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorPayload' + /catalogs/{catalogId}/items/{catalogItemId}/variables: get: summary: Get variables (form fields) for a catalog item (ServiceNow data source only). @@ -5786,6 +5906,86 @@ components: type: string nullable: true + TaskSummary: + type: object + properties: + id: + type: string + format: uuid + subject: + type: string + nullable: true + state: + type: string + nullable: true + description: Current workflow state (e.g. "open", "in_progress", "closed") + dueDate: + type: string + nullable: true + assignedTo: + $ref: '#/components/schemas/EntityRef' + nullable: true + updatedOn: + type: string + + TaskSearchResponse: + type: object + properties: + tasks: + type: array + items: + $ref: '#/components/schemas/TaskSummary' + total: + type: integer + description: Total number of matching tasks + limit: + type: integer + offset: + type: integer + + CaseTaskSearchPayload: + type: object + nullable: true + description: > + Payload for paginating the tasks of a case. The case ID is taken from + the URL path. The payload is forwarded to the integration service as-is. + properties: + pagination: + allOf: + - $ref: '#/components/schemas/Pagination' + - properties: + limit: + default: 20 + maximum: 100 + + TaskDetail: + allOf: + - $ref: '#/components/schemas/TaskSummary' + - type: object + properties: + visibleToCustomer: + type: boolean + requestType: + type: string + nullable: true + requestTypeLabel: + type: string + nullable: true + environment: + type: string + nullable: true + environmentLabel: + type: string + nullable: true + product: + $ref: '#/components/schemas/EntityRef' + nullable: true + parentCase: + $ref: '#/components/schemas/EntityRef' + nullable: true + createdOn: + type: string + ChangeRequestApprover: type: object properties: diff --git a/apps/csm-portal/webapp/src/api/backend/types.ts b/apps/csm-portal/webapp/src/api/backend/types.ts index 069c129275..986c47f04d 100644 --- a/apps/csm-portal/webapp/src/api/backend/types.ts +++ b/apps/csm-portal/webapp/src/api/backend/types.ts @@ -1312,6 +1312,62 @@ export interface BeUpdateCallRequestResponse { }; } +// --------------------------------------------------------------------------- +// Tasks — a lightweight, case-scoped to-do item (distinct from call requests +// and change requests: no multi-stage lifecycle). Only 2 real live `state` +// values are seen in this org's data (`OPEN`/`CLOSED`); `OTHER` is a genuine +// fallback for undocumented raw values and must be handled, not treated as +// unreachable. `dueDate` is sparsely populated (~13% of records) — render its +// absence as a normal, expected case rather than a broken layout. +// --------------------------------------------------------------------------- + +export type BeTaskState = "OPEN" | "CLOSED" | "OTHER"; + +/** A task list item returned by `POST /cases/{caseId}/tasks/search`. */ +export interface BeTaskSummary { + id: string; + subject: string; + state: BeTaskState | null; + dueDate: string | null; + assignedTo: BeEntityRef | null; + updatedOn: string; +} + +/** `POST /cases/{caseId}/tasks/search` request payload. */ +export interface BeCaseTasksSearchPayload { + pagination?: BePagination; +} + +/** `POST /cases/{caseId}/tasks/search` response. */ +export interface BeListCaseTasksResponse { + tasks: BeTaskSummary[]; + total: number; + offset: number; + limit: number; +} + +/** + * `GET /tasks/{id}` response. `visibleToCustomer` is confirmed `false` on + * every sampled record for this org — it is shown as a plain fact, never used + * to drive conditional UI. + */ +export interface BeTaskDetail { + id: string; + subject: string; + state: BeTaskState | null; + dueDate: string | null; + visibleToCustomer: boolean; + assignedTo: BeEntityRef | null; + requestType: string | null; + requestTypeLabel: string | null; + environment: string | null; + environmentLabel: string | null; + product: BeEntityRef | null; + parentCase: BeCaseNumberRef; + createdOn: string; + updatedOn: string; +} + // --------------------------------------------------------------------------- // Change requests (managed-cloud; ServiceNow data source only) // --------------------------------------------------------------------------- diff --git a/apps/csm-portal/webapp/src/constants/apiConstants.ts b/apps/csm-portal/webapp/src/constants/apiConstants.ts index 0c2826ae72..1070675e0d 100644 --- a/apps/csm-portal/webapp/src/constants/apiConstants.ts +++ b/apps/csm-portal/webapp/src/constants/apiConstants.ts @@ -56,6 +56,8 @@ export const ApiQueryKeys = { PRODUCT_VULNERABILITIES_SEARCH: "product-vulnerabilities-search", PRODUCT_VULNERABILITIES_META: "product-vulnerabilities-meta", CASE_CALL_REQUESTS: "case-call-requests", + CASE_TASKS: "case-tasks", + TASK_DETAILS: "task-details", PROJECT_CONTACTS: "project-contacts", TIME_TRACKING_DETAILS: "time-tracking-details", TIME_CARDS_SEARCH: "time-cards-search", diff --git a/apps/csm-portal/webapp/src/features/csm-cases/api/useGetTask.ts b/apps/csm-portal/webapp/src/features/csm-cases/api/useGetTask.ts new file mode 100644 index 0000000000..7b2e937094 --- /dev/null +++ b/apps/csm-portal/webapp/src/features/csm-cases/api/useGetTask.ts @@ -0,0 +1,39 @@ +// 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 { useQuery, type UseQueryResult } from "@tanstack/react-query"; +import { ApiQueryKeys } from "@constants/apiConstants"; +import { useBackendApi } from "@api/backend/client"; +import type { BeTaskDetail } from "@api/backend/types"; + +/** + * Look up a single task by id via `GET /tasks/{id}`. Returns `null` when the + * id is unknown so the caller (e.g. a detail dialog) can render a not-found + * state rather than an error. + */ +export function useGetTask( + id: string | undefined, +): UseQueryResult { + const api = useBackendApi(); + + return useQuery({ + queryKey: [ApiQueryKeys.TASK_DETAILS, id ?? ""], + queryFn: (): Promise => + api.get(`/tasks/${encodeURIComponent(id as string)}`), + enabled: !!id, + staleTime: 30_000, + }); +} diff --git a/apps/csm-portal/webapp/src/features/csm-cases/api/useSearchCaseTasks.ts b/apps/csm-portal/webapp/src/features/csm-cases/api/useSearchCaseTasks.ts new file mode 100644 index 0000000000..209077b6ee --- /dev/null +++ b/apps/csm-portal/webapp/src/features/csm-cases/api/useSearchCaseTasks.ts @@ -0,0 +1,52 @@ +// 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 { useQuery, type UseQueryResult } from "@tanstack/react-query"; +import { ApiQueryKeys } from "@constants/apiConstants"; +import { useBackendApi } from "@api/backend/client"; +import type { BeCaseTasksSearchPayload, BeListCaseTasksResponse } from "@api/backend/types"; + +/** + * Page size for the case-scoped tasks list. Tasks are a lightweight sub-item + * (no multi-stage lifecycle like call requests / change requests), so a + * single wide-ish page is expected to cover the vast majority of cases + * without needing pagination controls in the UI yet. + */ +const CASE_TASKS_PAGE_LIMIT = 20; + +/** + * Lists the tasks attached to a case via `POST /cases/{caseId}/tasks/search`. + * Only runs while `caseId` is set, so callers that mount this hook + * conditionally (e.g. only while the Tasks tab is active) get lazy fetching. + */ +export function useSearchCaseTasks( + caseId: string | undefined, +): UseQueryResult { + const api = useBackendApi(); + + return useQuery({ + queryKey: [ApiQueryKeys.CASE_TASKS, caseId ?? ""], + queryFn: async (): Promise => { + if (!caseId) return null; + return api.post( + `/cases/${encodeURIComponent(caseId)}/tasks/search`, + { pagination: { limit: CASE_TASKS_PAGE_LIMIT, offset: 0 } }, + ); + }, + enabled: !!caseId, + staleTime: 10_000, + }); +} diff --git a/apps/csm-portal/webapp/src/features/csm-cases/components/TaskDetailDialog.tsx b/apps/csm-portal/webapp/src/features/csm-cases/components/TaskDetailDialog.tsx new file mode 100644 index 0000000000..497c084895 --- /dev/null +++ b/apps/csm-portal/webapp/src/features/csm-cases/components/TaskDetailDialog.tsx @@ -0,0 +1,192 @@ +// 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, + Button, + Chip, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + Divider, + IconButton, + Skeleton, + Typography, +} from "@wso2/oxygen-ui"; +import { RefreshCw, X } from "@wso2/oxygen-ui-icons-react"; +import type { JSX } from "react"; +import { useGetTask } from "@features/csm-cases/api/useGetTask"; +import { taskStateColor, taskStateLabel } from "@features/csm-cases/utils/taskState"; +import { formatAbsoluteForUser } from "@utils/dateTime"; + +interface TaskDetailDialogProps { + taskId: string; + onClose: () => void; +} + +function DetailCell({ + label, + children, +}: { + label: string; + children: React.ReactNode; +}): JSX.Element { + return ( + + + {label} + + {children} + + ); +} + +/** + * Read-only detail view for a single task, opened from a row click on + * {@link TasksWidget}. A lightweight dialog rather than a full separate + * detail page/route — a task's data shape is much smaller than a call + * request or change request, and the parent case is already known from the + * page it's opened from. + */ +export function TaskDetailDialog({ taskId, onClose }: TaskDetailDialogProps): JSX.Element { + const { data: task, isLoading, isError, refetch } = useGetTask(taskId); + + return ( + + + + Task details + + + + + + + {isLoading && ( + + + + + )} + + {isError && ( + + + Could not load this task. + + + + )} + + {!isLoading && !isError && task && ( + <> + + + {task.requestTypeLabel && ( + + )} + + + + {task.subject} + + + + + + + + {task.parentCase.number ?? task.parentCase.id} + + + + {task.assignedTo?.name ?? "—"} + + + {task.product?.name ?? "—"} + + {/* Environment is only shown when populated — most tasks won't + carry one, and this isn't the primary field on this record. */} + {task.environmentLabel && ( + + {task.environmentLabel} + + )} + {/* dueDate is genuinely sparse (~13% populated) — omitted from + the grid entirely rather than shown as a bare dash when + absent, so most tasks don't render an obviously-empty cell. */} + {task.dueDate && ( + + + {formatAbsoluteForUser(task.dueDate) ?? "—"} + + + )} + + + {formatAbsoluteForUser(task.createdOn) ?? "—"} + + + + + {formatAbsoluteForUser(task.updatedOn) ?? "—"} + + + + {task.visibleToCustomer ? "Yes" : "No"} + + + + )} + + + + + + ); +} + +export default TaskDetailDialog; diff --git a/apps/csm-portal/webapp/src/features/csm-cases/components/TasksWidget.test.tsx b/apps/csm-portal/webapp/src/features/csm-cases/components/TasksWidget.test.tsx new file mode 100644 index 0000000000..ff54a397d1 --- /dev/null +++ b/apps/csm-portal/webapp/src/features/csm-cases/components/TasksWidget.test.tsx @@ -0,0 +1,161 @@ +// 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 { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi, beforeEach } from "vitest"; +import "@testing-library/jest-dom/vitest"; +import { TasksWidget } from "@features/csm-cases/components/TasksWidget"; +import type { BeListCaseTasksResponse, BeTaskDetail } from "@api/backend/types"; +import { useSearchCaseTasks } from "@features/csm-cases/api/useSearchCaseTasks"; +import { useGetTask } from "@features/csm-cases/api/useGetTask"; + +vi.mock("@features/csm-cases/api/useSearchCaseTasks", () => ({ + useSearchCaseTasks: vi.fn(), +})); +vi.mock("@features/csm-cases/api/useGetTask", () => ({ + useGetTask: vi.fn(), +})); + +const mockedUseSearchCaseTasks = vi.mocked(useSearchCaseTasks); +const mockedUseGetTask = vi.mocked(useGetTask); + +function mockListResult(overrides: Partial>): void { + mockedUseSearchCaseTasks.mockReturnValue({ + data: null, + isLoading: false, + isError: false, + isFetching: false, + refetch: vi.fn(), + ...overrides, + } as unknown as ReturnType); +} + +function mockDetailResult(overrides: Partial>): void { + mockedUseGetTask.mockReturnValue({ + data: null, + isLoading: false, + isError: false, + refetch: vi.fn(), + ...overrides, + } as unknown as ReturnType); +} + +const TASK_ROW = { + id: "task-1", + subject: "Extract logs for CS0440062", + state: "OPEN" as const, + dueDate: null, + assignedTo: { id: "u-1", name: "Jane Doe" }, + updatedOn: "2026-07-15T10:00:00Z", +}; + +describe("TasksWidget", () => { + beforeEach(() => { + mockedUseSearchCaseTasks.mockReset(); + mockedUseGetTask.mockReset(); + mockDetailResult({}); + }); + + it("renders a loading skeleton while the query is in flight", () => { + mockListResult({ isLoading: true }); + render(); + expect(screen.getByText("Tasks")).toBeInTheDocument(); + }); + + it("renders an empty state when there are no tasks", () => { + const empty: BeListCaseTasksResponse = { tasks: [], total: 0, offset: 0, limit: 20 }; + mockListResult({ data: empty }); + render(); + expect(screen.getByText("No tasks on this case.")).toBeInTheDocument(); + }); + + it("renders an error state with a retry action that refetches", () => { + const refetch = vi.fn(); + mockListResult({ isError: true, refetch }); + render(); + expect(screen.getByText("Could not load tasks for this case.")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: /retry/i })); + expect(refetch).toHaveBeenCalled(); + }); + + it("renders a row with subject, state, assignee, and a dash for a missing due date", () => { + const list: BeListCaseTasksResponse = { + tasks: [TASK_ROW], + total: 1, + offset: 0, + limit: 20, + }; + mockListResult({ data: list }); + render(); + expect(screen.getByText("Extract logs for CS0440062")).toBeInTheDocument(); + expect(screen.getByText("Open")).toBeInTheDocument(); + expect(screen.getByText("Jane Doe")).toBeInTheDocument(); + // dueDate is null on this row — rendered as a plain dash, not a broken cell. + expect(screen.getAllByText("—").length).toBeGreaterThan(0); + }); + + it("renders a neutral badge for an OTHER/null state instead of assuming only OPEN/CLOSED", () => { + const list: BeListCaseTasksResponse = { + tasks: [ + { ...TASK_ROW, id: "task-2", state: "OTHER" }, + { ...TASK_ROW, id: "task-3", state: null, subject: "Task with null state" }, + ], + total: 2, + offset: 0, + limit: 20, + }; + mockListResult({ data: list }); + render(); + expect(screen.getByText("Other")).toBeInTheDocument(); + // A null state falls back to the "—" label rather than crashing or + // showing "undefined". + expect(screen.getByText("Task with null state")).toBeInTheDocument(); + }); + + it("opens the task detail dialog when a row is clicked", () => { + const list: BeListCaseTasksResponse = { + tasks: [TASK_ROW], + total: 1, + offset: 0, + limit: 20, + }; + mockListResult({ data: list }); + const detail: BeTaskDetail = { + id: "task-1", + subject: TASK_ROW.subject, + state: "OPEN", + dueDate: null, + visibleToCustomer: false, + assignedTo: TASK_ROW.assignedTo, + requestType: "1", + requestTypeLabel: "Log Extraction", + environment: null, + environmentLabel: null, + product: null, + parentCase: { id: "case-1", number: "CS0440062" }, + createdOn: "2026-07-01T00:00:00Z", + updatedOn: "2026-07-15T10:00:00Z", + }; + mockDetailResult({ data: detail }); + + render(); + fireEvent.click(screen.getByRole("button", { name: /view task/i })); + + expect(screen.getByText("Task details")).toBeInTheDocument(); + expect(screen.getByText("Log Extraction")).toBeInTheDocument(); + expect(screen.getByText("CS0440062")).toBeInTheDocument(); + }); +}); diff --git a/apps/csm-portal/webapp/src/features/csm-cases/components/TasksWidget.tsx b/apps/csm-portal/webapp/src/features/csm-cases/components/TasksWidget.tsx new file mode 100644 index 0000000000..df2e3b247a --- /dev/null +++ b/apps/csm-portal/webapp/src/features/csm-cases/components/TasksWidget.tsx @@ -0,0 +1,208 @@ +// 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, + Button, + Card, + Chip, + IconButton, + Skeleton, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography, +} from "@wso2/oxygen-ui"; +import { ListChecks, RefreshCw } from "@wso2/oxygen-ui-icons-react"; +import { useState, type JSX } from "react"; +import { useSearchCaseTasks } from "@features/csm-cases/api/useSearchCaseTasks"; +import { taskStateColor, taskStateLabel } from "@features/csm-cases/utils/taskState"; +import { formatAbsoluteForUser } from "@utils/dateTime"; +import RelativeTime from "@components/RelativeTime"; +import { TaskDetailDialog } from "./TaskDetailDialog"; + +const TASKS_TABLE_COLUMNS = ["Subject", "State", "Due date", "Assignee", "Updated"]; + +interface TasksWidgetProps { + caseId: string; +} + +/** + * Tasks tab content on the case detail page. Tasks are a lightweight, + * case-scoped to-do item (no multi-stage lifecycle, unlike call requests / + * change requests), so the list is a plain table with a row click opening a + * small read-only detail dialog rather than a full separate detail page. + */ +export function TasksWidget({ caseId }: TasksWidgetProps): JSX.Element { + const { data, isLoading, isError, isFetching, refetch } = useSearchCaseTasks(caseId); + const [selectedTaskId, setSelectedTaskId] = useState(null); + + const tasks = data?.tasks ?? []; + const total = data?.total ?? tasks.length; + const isTruncated = !isLoading && !isError && tasks.length < total; + + return ( + <> + + {/* Header */} + + + + Tasks + {!isLoading && !isError && ( + + )} + + void refetch()} + disabled={isFetching} + aria-label="Refresh tasks" + > + + + + + {isTruncated ? ( + + {`Showing first ${tasks.length} of ${total}`} + + ) : null} + + {/* Content */} + {isError ? ( + + + Could not load tasks for this case. + + + + ) : ( + + + + + {TASKS_TABLE_COLUMNS.map((col) => ( + {col} + ))} + + + + {isLoading ? ( + [0, 1, 2].map((i) => ( + + {TASKS_TABLE_COLUMNS.map((col) => ( + + + + ))} + + )) + ) : tasks.length === 0 ? ( + + + + No tasks on this case. + + + + ) : ( + tasks.map((task) => ( + setSelectedTaskId(task.id)} + onKeyDown={(e) => { + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + setSelectedTaskId(task.id); + } + }} + tabIndex={0} + role="button" + aria-label={`View task ${task.subject}`} + sx={{ cursor: "pointer" }} + > + {task.subject} + + + + {/* dueDate is sparse (~13% populated) — a plain dash for + the rest is the expected common case, not a broken + layout. */} + + {task.dueDate ? (formatAbsoluteForUser(task.dueDate) ?? "—") : "—"} + + {task.assignedTo?.name ?? "—"} + + + + + )) + )} + +
+
+ )} +
+ + {selectedTaskId && ( + setSelectedTaskId(null)} + /> + )} + + ); +} + +export default TasksWidget; 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 5dd536ccbd..edff0f9f2d 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 @@ -33,6 +33,7 @@ import { import { Activity, ArrowLeft, + CheckSquare, Clock, Layers, Link as LinkIcon, @@ -91,6 +92,8 @@ import { } from "@features/csm-cases/components/CaseDetailWidgets"; import { CallRequestsWidget } from "@features/csm-cases/components/CallRequestsWidget"; import { useGetCsmCaseCallRequests } from "@features/csm-cases/api/useCsmCaseCallRequests"; +import { TasksWidget } from "@features/csm-cases/components/TasksWidget"; +import { useSearchCaseTasks } from "@features/csm-cases/api/useSearchCaseTasks"; import { useSearchDeployments } from "@features/csm-cases/api/useSearchDeployments"; import { useGetProject } from "@features/csm-projects/api/useGetProject"; import { CaseSlaTable } from "@features/csm-cases/components/CaseSlaTable"; @@ -216,7 +219,8 @@ type CaseTabId = | "sla" | "attachments" | "time" - | "call-requests"; + | "call-requests" + | "tasks"; /** * Walk the parent chain to find the nearest vertically-scrollable element. @@ -250,6 +254,7 @@ const TAB_DEFS: Array<{ { id: "attachments", label: "Attachments", icon: }, { id: "time", label: "Time tracking", icon: }, { id: "call-requests", label: "Call requests", icon: }, + { id: "tasks", label: "Tasks", icon: }, ]; export default function CsmCaseDetailPage(): JSX.Element { @@ -330,6 +335,9 @@ export default function CsmCaseDetailPage(): JSX.Element { const { data: callRequests } = useGetCsmCaseCallRequests( isAnnouncement ? undefined : caseId, ); + const { data: caseTasks } = useSearchCaseTasks( + isAnnouncement ? undefined : caseId, + ); // Live deployment lookup for the Details tab's "Deployment info" widget — // only runs when the case actually has a deployment link (SN-sourced cases // may have none). Reuses the project's deployment list rather than a @@ -430,7 +438,10 @@ export default function CsmCaseDetailPage(): JSX.Element { // above rather than an effect, to avoid an extra render pass. if ( isAnnouncement && - (activeTab === "sla" || activeTab === "time" || activeTab === "call-requests") + (activeTab === "sla" || + activeTab === "time" || + activeTab === "call-requests" || + activeTab === "tasks") ) { setActiveTab("activities"); } @@ -1259,7 +1270,10 @@ export default function CsmCaseDetailPage(): JSX.Element { {TAB_DEFS.filter( (t) => !isAnnouncement || - (t.id !== "sla" && t.id !== "time" && t.id !== "call-requests"), + (t.id !== "sla" && + t.id !== "time" && + t.id !== "call-requests" && + t.id !== "tasks"), ).map((t) => { // Counts shown only where the tab IS the list (unambiguous). const count = @@ -1271,7 +1285,9 @@ export default function CsmCaseDetailPage(): JSX.Element { ? c.timeLogs.length : t.id === "call-requests" ? callRequests?.length - : undefined; + : t.id === "tasks" + ? caseTasks?.total + : undefined; return ( )} + {activeTab === "tasks" && caseId && ( + + + + )} + {assignOpen && ( = { + OPEN: "Open", + CLOSED: "Closed", + OTHER: "Other", +}; + +const STATE_COLOR: Record = { + OPEN: "info", + CLOSED: "success", + OTHER: "default", +}; + +/** All task states, for a filter control if one is ever added. */ +export const TASK_STATES = Object.keys(STATE_LABEL) as BeTaskState[]; + +export function taskStateLabel(state?: BeTaskState | string | null): string { + if (!state) return "—"; + return STATE_LABEL[state as BeTaskState] ?? "Other"; +} + +export function taskStateColor(state?: BeTaskState | string | null): ChipColor { + if (!state) return "default"; + return STATE_COLOR[state as BeTaskState] ?? "default"; +} diff --git a/entity-service/internal/domain/entity.go b/entity-service/internal/domain/entity.go index 42edd3cd5f..1988783374 100644 --- a/entity-service/internal/domain/entity.go +++ b/entity-service/internal/domain/entity.go @@ -2413,6 +2413,64 @@ type TaskSlaDetail struct { Schedule *TaskSlaScheduleRef `json:"schedule"` } +// TaskSummary is a single task record in a case's task list, returned by +// POST /cases/{id}/tasks/search. +// +// State is deliberately a plain *string, not a closed Go enum/const-validated +// type: ServiceNow's task state choice-list carries raw values beyond the +// well-known ones (e.g. an undocumented raw "0" has been observed live, which +// the Ballerina layer maps to "OTHER"). A closed enum would fail deserialization +// or drop data the moment SN returns a value we haven't enumerated. Known +// values as currently mapped by the upstream integration: "OPEN", "CLOSED", +// "OTHER" (fallback for any unmapped raw value), or nil if state is unset. +type TaskSummary struct { + ID string `json:"id"` + Subject string `json:"subject"` + State *string `json:"state"` + DueDate *string `json:"dueDate"` + AssignedTo *EntityRef `json:"assignedTo"` + UpdatedOn string `json:"updatedOn"` +} + +// SearchCaseTasksRequest is the request body for POST /cases/{id}/tasks/search. +type SearchCaseTasksRequest struct { + Pagination Pagination `json:"pagination"` +} + +// SearchCaseTasksResponse is the response for POST /cases/{id}/tasks/search. +type SearchCaseTasksResponse struct { + Tasks []TaskSummary `json:"tasks"` + Total int `json:"total"` + Offset int `json:"offset"` + Limit int `json:"limit"` +} + +// TaskDetail is the full task record returned by GET /tasks/{id}. +// +// RequestType/RequestTypeLabel and Environment/EnvironmentLabel follow the same +// plain-*string rule as TaskSummary.State above: these are ServiceNow choice-list +// fields (raw key + resolved label) and must not be modeled as closed enums for +// the same reason — an unmapped raw value must degrade to nil, not break the +// response. Known RequestType values are SN-configuration-dependent (e.g. "1" +// observed live for "Log Extraction"); Environment is currently unobserved live +// (nil) but follows the identical key/label shape. +type TaskDetail struct { + ID string `json:"id"` + Subject string `json:"subject"` + State *string `json:"state"` + DueDate *string `json:"dueDate"` + VisibleToCustomer bool `json:"visibleToCustomer"` + AssignedTo *EntityRef `json:"assignedTo"` + RequestType *string `json:"requestType"` + RequestTypeLabel *string `json:"requestTypeLabel"` + Environment *string `json:"environment"` + EnvironmentLabel *string `json:"environmentLabel"` + Product *EntityRef `json:"product"` + ParentCase *CaseNumberRef `json:"parentCase"` + CreatedOn string `json:"createdOn"` + UpdatedOn string `json:"updatedOn"` +} + // IncidentPriority represents the priority level of an incident. type IncidentPriority string diff --git a/entity-service/internal/handler/task_handler.go b/entity-service/internal/handler/task_handler.go new file mode 100644 index 0000000000..974992495b --- /dev/null +++ b/entity-service/internal/handler/task_handler.go @@ -0,0 +1,65 @@ +// 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 ( + "encoding/json" + "net/http" + + "github.com/wso2-open-operations/cs-tools/entity-service/internal/domain" + "github.com/wso2-open-operations/cs-tools/entity-service/internal/service" +) + +// TaskHandler handles HTTP requests for the tasks resource. +type TaskHandler struct { + svc service.TaskService +} + +// NewTaskHandler constructs a TaskHandler with the given service. +func NewTaskHandler(svc service.TaskService) *TaskHandler { + return &TaskHandler{svc: svc} +} + +// SearchCaseTasks handles POST /cases/{id}/tasks/search. +func (h *TaskHandler) SearchCaseTasks(w http.ResponseWriter, r *http.Request) { + caseID := r.PathValue("id") + + var req domain.SearchCaseTasksRequest + if !decodeRequest(w, r, &req) { + return + } + + resp, err := h.svc.SearchCaseTasks(r.Context(), caseID, req) + if err != nil { + writeServiceError(w, r, err) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(resp) +} + +// GetTask handles GET /tasks/{id}. +func (h *TaskHandler) GetTask(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + result, err := h.svc.GetTask(r.Context(), id) + if err != nil { + writeServiceError(w, r, err) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(result) +} diff --git a/entity-service/internal/server/routes.go b/entity-service/internal/server/routes.go index 9ac54b3e5a..c5e2fa50fa 100644 --- a/entity-service/internal/server/routes.go +++ b/entity-service/internal/server/routes.go @@ -207,6 +207,11 @@ func NewRouter(db *pgxpool.Pool, cfg *config.Config) http.Handler { snUserHandler = handler.NewSNUserHandler(service.NewServiceNowUserService(serviceNowIntegrationServiceClient)) } + var taskHandler *handler.TaskHandler + if cfg.DataSource == config.DataSourceServiceNow { + taskHandler = handler.NewTaskHandler(service.NewServiceNowTaskService(serviceNowIntegrationServiceClient)) + } + mux := http.NewServeMux() mux.HandleFunc("GET /health", handler.HealthCheck) @@ -321,6 +326,11 @@ func NewRouter(db *pgxpool.Pool, cfg *config.Config) http.Handler { mux.HandleFunc("POST /slas/search", taskSlaHandler.SearchTaskSlas) } + if taskHandler != nil { + mux.HandleFunc("POST /cases/{id}/tasks/search", taskHandler.SearchCaseTasks) + mux.HandleFunc("GET /tasks/{id}", taskHandler.GetTask) + } + if incidentHandler != nil { mux.HandleFunc("GET /incidents/{id}", incidentHandler.GetIncident) mux.HandleFunc("PATCH /incidents/{id}", incidentHandler.PatchIncident) diff --git a/entity-service/internal/service/interfaces.go b/entity-service/internal/service/interfaces.go index bcce140f33..348158d97d 100644 --- a/entity-service/internal/service/interfaces.go +++ b/entity-service/internal/service/interfaces.go @@ -332,6 +332,18 @@ type TaskSlaService interface { GetTaskSla(ctx context.Context, id string) (domain.TaskSlaDetail, error) } +// TaskService defines the operations available on the tasks entity. +// All methods require the ServiceNow data source; there is no Postgres fallback. +type TaskService interface { + // SearchCaseTasks returns a paginated list of tasks for the case identified by + // caseID. A ValidationError is returned for invalid input (e.g. malformed UUID); + // an UnauthorizedError is returned when x-user-id-token is absent. + SearchCaseTasks(ctx context.Context, caseID string, req domain.SearchCaseTasksRequest) (domain.SearchCaseTasksResponse, error) + // GetTask returns the full detail of a single task by its UUID. + // A NotFoundError is returned if the task does not exist. + GetTask(ctx context.Context, id string) (domain.TaskDetail, error) +} + // ProductVulnerabilityService defines the operations available on product vulnerabilities. // All methods require the ServiceNow data source; there is no Postgres fallback. type ProductVulnerabilityService interface { diff --git a/entity-service/internal/service/sn_task_service.go b/entity-service/internal/service/sn_task_service.go new file mode 100644 index 0000000000..865bf7b095 --- /dev/null +++ b/entity-service/internal/service/sn_task_service.go @@ -0,0 +1,224 @@ +// 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 ( + "context" + "encoding/json" + "fmt" + + "github.com/wso2-open-operations/cs-tools/entity-service/internal/apierror" + "github.com/wso2-open-operations/cs-tools/entity-service/internal/domain" + "github.com/wso2-open-operations/cs-tools/entity-service/internal/middleware" + integrationservice "github.com/wso2-open-operations/cs-tools/entity-service/internal/servicenow-integration-service" +) + +// snTaskAssignedTo is the assignee reference embedded in a task record. +type snTaskAssignedTo struct { + ID *string `json:"id"` + Name *string `json:"name"` +} + +// snTask is a single task record as returned by GET /cases/{id}/tasks. +type snTask struct { + ID string `json:"id"` + Subject *string `json:"subject"` + State *string `json:"state"` + DueDate *string `json:"dueDate"` + AssignedTo *snTaskAssignedTo `json:"assignedTo"` + UpdatedOn *string `json:"updatedOn"` +} + +// snCaseTasksResponse mirrors the Choreo POST /cases/{id}/tasks/search response. +type snCaseTasksResponse struct { + Tasks []snTask `json:"tasks"` + Total int `json:"total"` + Offset int `json:"offset"` + Limit int `json:"limit"` +} + +// snCaseTasksSearchPayload is the Choreo POST /cases/{id}/tasks/search request body. +type snCaseTasksSearchPayload struct { + Pagination snProjectPagination `json:"pagination"` +} + +// snProductRef is a named product reference embedded in a task detail record. +type snProductRef struct { + ID *string `json:"id"` + Name *string `json:"name"` +} + +// snTaskParentCase is the parent case reference embedded in a task detail record. +type snTaskParentCase struct { + ID *string `json:"id"` + Number *string `json:"number"` +} + +// snTaskDetail mirrors the Choreo GET /tasks/{id} response. +type snTaskDetail struct { + ID string `json:"id"` + Subject *string `json:"subject"` + State *string `json:"state"` + DueDate *string `json:"dueDate"` + VisibleToCustomer bool `json:"visibleToCustomer"` + AssignedTo *snTaskAssignedTo `json:"assignedTo"` + RequestType *string `json:"requestType"` + RequestTypeLabel *string `json:"requestTypeLabel"` + Environment *string `json:"environment"` + EnvironmentLabel *string `json:"environmentLabel"` + Product *snProductRef `json:"product"` + ParentCase *snTaskParentCase `json:"parentCase"` + CreatedOn *string `json:"createdOn"` + UpdatedOn *string `json:"updatedOn"` +} + +// snAssignedToToEntityRef converts an snTaskAssignedTo reference to a domain +// EntityRef, converting the sysid to a UUID. Returns nil if the reference or +// its id is absent. +func snAssignedToToEntityRef(a *snTaskAssignedTo) *domain.EntityRef { + if a == nil || a.ID == nil || *a.ID == "" { + return nil + } + ref := &domain.EntityRef{ID: sysidToUUID(*a.ID)} + if a.Name != nil { + ref.Name = *a.Name + } + return ref +} + +type snTaskService struct { + client *integrationservice.Client +} + +// NewServiceNowTaskService constructs a TaskService backed by the Choreo API. +func NewServiceNowTaskService(client *integrationservice.Client) TaskService { + return &snTaskService{client: client} +} + +func (s *snTaskService) SearchCaseTasks(ctx context.Context, caseID string, req domain.SearchCaseTasksRequest) (domain.SearchCaseTasksResponse, error) { + token := middleware.UserIDTokenFromContext(ctx) + if token == "" { + return domain.SearchCaseTasksResponse{}, &apierror.UnauthorizedError{Msg: "x-user-id-token header is required"} + } + + if err := validateUUIDs("id", []string{caseID}); err != nil { + return domain.SearchCaseTasksResponse{}, err + } + + if err := normalizePagination(&req.Pagination); err != nil { + return domain.SearchCaseTasksResponse{}, err + } + + payload := snCaseTasksSearchPayload{ + Pagination: snProjectPagination{Limit: req.Pagination.Limit, Offset: req.Pagination.Offset}, + } + + path := "/cases/" + uuidToSysid(caseID) + "/tasks/search" + raw, err := s.client.Post(ctx, path, token, payload) + if err != nil { + return domain.SearchCaseTasksResponse{}, err + } + + var snResp snCaseTasksResponse + if err := json.Unmarshal(raw, &snResp); err != nil { + return domain.SearchCaseTasksResponse{}, fmt.Errorf("sn case tasks: parse response: %w", err) + } + + tasks := make([]domain.TaskSummary, 0, len(snResp.Tasks)) + for _, t := range snResp.Tasks { + task := domain.TaskSummary{ + ID: sysidToUUID(t.ID), + State: t.State, + DueDate: t.DueDate, + AssignedTo: snAssignedToToEntityRef(t.AssignedTo), + } + if t.Subject != nil { + task.Subject = *t.Subject + } + if t.UpdatedOn != nil { + task.UpdatedOn = *t.UpdatedOn + } + tasks = append(tasks, task) + } + + return domain.SearchCaseTasksResponse{ + Tasks: tasks, + Total: snResp.Total, + Offset: snResp.Offset, + Limit: snResp.Limit, + }, nil +} + +func (s *snTaskService) GetTask(ctx context.Context, id string) (domain.TaskDetail, error) { + token := middleware.UserIDTokenFromContext(ctx) + if token == "" { + return domain.TaskDetail{}, &apierror.UnauthorizedError{Msg: "x-user-id-token header is required"} + } + + if err := validateUUIDs("id", []string{id}); err != nil { + return domain.TaskDetail{}, err + } + + raw, err := s.client.Get(ctx, "/tasks/"+uuidToSysid(id), token) + if err != nil { + return domain.TaskDetail{}, err + } + + var t snTaskDetail + if err := json.Unmarshal(raw, &t); err != nil { + return domain.TaskDetail{}, fmt.Errorf("sn get task: parse response: %w", err) + } + + detail := domain.TaskDetail{ + ID: sysidToUUID(t.ID), + State: t.State, + DueDate: t.DueDate, + VisibleToCustomer: t.VisibleToCustomer, + AssignedTo: snAssignedToToEntityRef(t.AssignedTo), + RequestType: t.RequestType, + RequestTypeLabel: t.RequestTypeLabel, + Environment: t.Environment, + EnvironmentLabel: t.EnvironmentLabel, + } + if t.Subject != nil { + detail.Subject = *t.Subject + } + if t.CreatedOn != nil { + detail.CreatedOn = *t.CreatedOn + } + if t.UpdatedOn != nil { + detail.UpdatedOn = *t.UpdatedOn + } + + if t.Product != nil && t.Product.ID != nil && *t.Product.ID != "" { + ref := &domain.EntityRef{ID: sysidToUUID(*t.Product.ID)} + if t.Product.Name != nil { + ref.Name = *t.Product.Name + } + detail.Product = ref + } + + if t.ParentCase != nil && t.ParentCase.ID != nil && *t.ParentCase.ID != "" { + ref := &domain.CaseNumberRef{ID: sysidToUUID(*t.ParentCase.ID)} + if t.ParentCase.Number != nil { + ref.Number = *t.ParentCase.Number + } + detail.ParentCase = ref + } + + return detail, nil +} diff --git a/entity-service/openapi.yaml b/entity-service/openapi.yaml index bdc638e71d..aa0ecb9b0e 100644 --- a/entity-service/openapi.yaml +++ b/entity-service/openapi.yaml @@ -1837,6 +1837,98 @@ paths: schema: $ref: '#/components/schemas/ErrorResponse' + /cases/{id}/tasks/search: + post: + summary: List tasks for a case (ServiceNow data source only). + operationId: searchCaseTasks + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SearchCaseTasksRequest' + responses: + "200": + description: Tasks for the case. + content: + application/json: + schema: + $ref: '#/components/schemas/SearchCaseTasksResponse' + "400": + description: Bad request. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + "401": + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + "404": + description: Case not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + "500": + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + + /tasks/{id}: + get: + summary: Get a task by ID (ServiceNow data source only). + operationId: getTask + parameters: + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + "200": + description: The task record. + content: + application/json: + schema: + $ref: '#/components/schemas/TaskDetail' + "400": + description: Bad request. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + "401": + description: Unauthorized. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + "404": + description: Task not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + "500": + description: Internal server error. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /comments/search: post: summary: Search comments by reference entity (ServiceNow data source only). @@ -5811,6 +5903,109 @@ components: $ref: '#/components/schemas/TaskSlaScheduleRef' nullable: true + TaskSummary: + type: object + required: [id, subject, updatedOn] + properties: + id: + type: string + format: uuid + subject: + type: string + state: + type: string + nullable: true + description: > + Plain string, not a closed enum. Known values: OPEN, CLOSED, OTHER + (fallback for any unmapped raw ServiceNow value), or null. + dueDate: + type: string + nullable: true + assignedTo: + $ref: '#/components/schemas/EntityRef' + nullable: true + updatedOn: + type: string + + SearchCaseTasksRequest: + type: object + properties: + pagination: + type: object + properties: + offset: + type: integer + minimum: 0 + default: 0 + limit: + type: integer + minimum: 1 + maximum: 100 + default: 20 + + SearchCaseTasksResponse: + type: object + properties: + tasks: + type: array + items: + $ref: '#/components/schemas/TaskSummary' + total: + type: integer + offset: + type: integer + limit: + type: integer + + TaskDetail: + type: object + required: [id, subject, visibleToCustomer, createdOn, updatedOn] + properties: + id: + type: string + format: uuid + subject: + type: string + state: + type: string + nullable: true + description: > + Plain string, not a closed enum. Known values: OPEN, CLOSED, OTHER + (fallback for any unmapped raw ServiceNow value), or null. + dueDate: + type: string + nullable: true + visibleToCustomer: + type: boolean + assignedTo: + $ref: '#/components/schemas/EntityRef' + nullable: true + requestType: + type: string + nullable: true + description: > + Raw ServiceNow choice-list key. Plain string, not a closed enum, + since the set of valid keys is SN-configuration-dependent. + requestTypeLabel: + type: string + nullable: true + environment: + type: string + nullable: true + environmentLabel: + type: string + nullable: true + product: + $ref: '#/components/schemas/EntityRef' + nullable: true + parentCase: + $ref: '#/components/schemas/CaseNumberRef' + nullable: true + createdOn: + type: string + updatedOn: + type: string + SearchIncidentsRequest: type: object properties: