Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 4 additions & 0 deletions apps/csm-portal/backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,10 @@ backend/
- `POST /products/vulnerabilities/search` — Search product vulnerabilities; requires `pagination`, optional `filters` (`priority`, `searchQuery`, `productName`, `productVersion`) (ServiceNow data source only)
- `GET /products/vulnerabilities/{id}` — Get product vulnerability by ID (ServiceNow data source only)

### Conversations

- `GET /conversations/{id}/messages` — Get paginated messages for a conversation; optional query params `limit` (1–100, default 20) and `offset` (default 0) (ServiceNow data source only)

### Updates

- `GET /updates/product-update-levels` — Get product update levels
Expand Down
2 changes: 2 additions & 0 deletions apps/csm-portal/backend/cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func main() {
catalogHandler := handler.NewCatalogHandler(entityClient)
timeCardHandler := handler.NewTimeCardHandler(entityClient)
productVulnerabilityHandler := handler.NewProductVulnerabilityHandler(entityClient)
conversationHandler := handler.NewConversationHandler(entityClient)

updatesCfg := updates.Config{
BaseURL: mustEnv("UPDATES_BASE_URL"),
Expand Down Expand Up @@ -141,6 +142,7 @@ func main() {
mux.HandleFunc("GET /catalogs/{catalogId}/items/{catalogItemId}/variables", catalogHandler.GetCatalogItemVariables)
mux.HandleFunc("POST /products/vulnerabilities/search", productVulnerabilityHandler.SearchProductVulnerabilities)
mux.HandleFunc("GET /products/vulnerabilities/{id}", productVulnerabilityHandler.GetProductVulnerability)
mux.HandleFunc("GET /conversations/{id}/messages", conversationHandler.GetConversationMessages)

addr := envOrDefault("PORT", ":8080")

Expand Down
6 changes: 6 additions & 0 deletions apps/csm-portal/backend/internal/entity/entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,3 +287,9 @@ func (c *Client) SearchConfigurationItems(ctx context.Context, body []byte) ([]b
func (c *Client) CreateCaseGithubIssue(ctx context.Context, caseID string, body []byte) ([]byte, error) {
return c.do(ctx, http.MethodPost, fmt.Sprintf("/cases/%s/github-issues", url.PathEscape(caseID)), body)
}

// SearchComments calls POST /comments/search on the entity service.
// The body must be a JSON-encoded SearchCommentsRequest (referenceId, referenceType, pagination).
func (c *Client) SearchComments(ctx context.Context, body []byte) ([]byte, error) {
return c.do(ctx, http.MethodPost, "/comments/search", body)
}
18 changes: 14 additions & 4 deletions apps/csm-portal/backend/internal/handler/cases.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ type entityCaseClient interface {
CreateCase(ctx context.Context, body []byte) ([]byte, error)
PatchCase(ctx context.Context, caseID string, body []byte) ([]byte, error)
CreateCaseComment(ctx context.Context, caseID string, body []byte) ([]byte, error)
SearchCaseComments(ctx context.Context, caseID string, body []byte) ([]byte, error)
SearchComments(ctx context.Context, body []byte) ([]byte, error)
SearchCases(ctx context.Context, body []byte) ([]byte, error)
GetCase(ctx context.Context, caseID string) ([]byte, error)
CreateCaseAttachment(ctx context.Context, body []byte) ([]byte, error)
Expand Down Expand Up @@ -224,6 +224,7 @@ func (h *CaseHandler) CreateCaseComment(w http.ResponseWriter, r *http.Request)
}

// SearchCaseComments handles POST /cases/{id}/comments/search.
// Injects referenceId and referenceType into the payload and forwards to POST /comments/search.
func (h *CaseHandler) SearchCaseComments(w http.ResponseWriter, r *http.Request) {
user := middleware.UserInfoFromContext(r.Context())
if user == nil {
Expand All @@ -248,14 +249,23 @@ func (h *CaseHandler) SearchCaseComments(w http.ResponseWriter, r *http.Request)
return
}

if !json.Valid(body) {
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
writeError(w, http.StatusBadRequest, ErrMsgBadRequest)
return
}
payload["referenceId"] = caseID
payload["referenceType"] = "case"

newBody, err := json.Marshal(payload)
if err != nil {
writeError(w, http.StatusInternalServerError, ErrMsgInternal)
return
}

result, err := h.entity.SearchCaseComments(r.Context(), caseID, body)
result, err := h.entity.SearchComments(r.Context(), newBody)
if err != nil {
slog.ErrorContext(r.Context(), "entity SearchCaseComments failed", "userID", user.UserID, "caseID", caseID, "err", err)
slog.ErrorContext(r.Context(), "entity SearchComments failed", "userID", user.UserID, "caseID", caseID, "err", err)
mapUpstreamError(w, err, "Failed to search case comments.")
return
}
Expand Down
22 changes: 12 additions & 10 deletions apps/csm-portal/backend/internal/handler/cases_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,14 +399,12 @@ func TestSearchCaseComments(t *testing.T) {
assertContentType(t, w, "application/json")
})

t.Run("forwards case ID and body to upstream and returns 200", func(t *testing.T) {
var capturedCaseID string
t.Run("injects referenceId and referenceType into SearchComments payload", func(t *testing.T) {
var capturedBody []byte
client := &mockEntityCaseClient{
searchCaseCommentsFn: func(_ context.Context, caseID string, body []byte) ([]byte, error) {
capturedCaseID = caseID
searchCommentsFn: func(_ context.Context, body []byte) ([]byte, error) {
capturedBody = body
return []byte(`{"comments":[{"id":"c-1","caseId":"case-42","type":"comment","content":"First comment","createdBy":"user-1","createdOn":"2026-06-03T00:00:00Z"}],"total":1,"limit":20,"offset":0,"hasMore":false}`), nil
return []byte(`{"comments":[{"id":"c-1","referenceId":"case-42","type":"comment","content":"First comment","createdBy":"user-1","createdOn":"2026-06-03T00:00:00Z"}],"total":1,"limit":20,"offset":0,"hasMore":false}`), nil
},
}
h := NewCaseHandler(client)
Expand All @@ -419,11 +417,15 @@ func TestSearchCaseComments(t *testing.T) {
assertStatus(t, w, http.StatusOK)
assertContentType(t, w, "application/json")

if capturedCaseID != "case-42" {
t.Errorf("upstream received caseID %q, want %q", capturedCaseID, "case-42")
var payload map[string]any
if err := json.Unmarshal(capturedBody, &payload); err != nil {
t.Fatalf("upstream received invalid JSON: %v", err)
}
if !json.Valid(capturedBody) {
t.Errorf("upstream received invalid JSON body: %s", capturedBody)
if payload["referenceId"] != "case-42" {
t.Errorf("referenceId = %v, want %q", payload["referenceId"], "case-42")
}
if payload["referenceType"] != "case" {
t.Errorf("referenceType = %v, want %q", payload["referenceType"], "case")
}

resp := decodeJSON[map[string]any](t, w)
Expand All @@ -437,7 +439,7 @@ func TestSearchCaseComments(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
client := &mockEntityCaseClient{
searchCaseCommentsFn: func(_ context.Context, _ string, _ []byte) ([]byte, error) {
searchCommentsFn: func(_ context.Context, _ []byte) ([]byte, error) {
return nil, tc.err
},
}
Expand Down
106 changes: 106 additions & 0 deletions apps/csm-portal/backend/internal/handler/conversations.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// 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"
"log/slog"
"net/http"
"strconv"

"github.com/wso2-open-operations/cs-tools/apps/csm-portal/backend/internal/middleware"
)

const (
defaultCommentLimit = 20
maxCommentLimit = 100
)

// entityConversationClient abstracts the entity service conversation operations.
type entityConversationClient interface {
SearchComments(ctx context.Context, body []byte) ([]byte, error)
}

// ConversationHandler handles HTTP requests for conversation operations.
type ConversationHandler struct {
entity entityConversationClient
}

// NewConversationHandler creates a ConversationHandler backed by the given entity client.
func NewConversationHandler(entity entityConversationClient) *ConversationHandler {
return &ConversationHandler{entity: entity}
}

// GetConversationMessages handles GET /conversations/{id}/messages.
// Builds a POST /comments/search payload with referenceType=conversation and forwards it.
func (h *ConversationHandler) GetConversationMessages(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
}

limit := defaultCommentLimit
offset := 0

q := r.URL.Query()
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 || n > maxCommentLimit {
writeError(w, http.StatusBadRequest, "limit must be an integer between 1 and 100")
return
}
limit = n
}
if v := q.Get("offset"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 0 {
writeError(w, http.StatusBadRequest, "offset must be a non-negative integer")
return
}
offset = n
}

payload, err := json.Marshal(map[string]any{
"referenceId": id,
"referenceType": "conversation",
"pagination": map[string]int{
"limit": limit,
"offset": offset,
},
})
if err != nil {
writeError(w, http.StatusInternalServerError, ErrMsgInternal)
return
}

result, err := h.entity.SearchComments(r.Context(), payload)
if err != nil {
slog.ErrorContext(r.Context(), "entity SearchComments failed", "userID", user.UserID, "conversationID", id, "err", err)
mapUpstreamError(w, err, "Failed to retrieve conversation messages.")
return
}

writeJSON(w, http.StatusOK, result)
}
146 changes: 146 additions & 0 deletions apps/csm-portal/backend/internal/handler/conversations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// 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"
"net/http"
"net/http/httptest"
"testing"
)

func TestGetConversationMessages(t *testing.T) {
const validID = "11111111-1111-1111-1111-111111111111"

t.Run("requires authenticated user", func(t *testing.T) {
h := NewConversationHandler(&mockEntityConversationClient{})
r := httptest.NewRequest(http.MethodGet, "/conversations/"+validID+"/messages", nil)
r.SetPathValue("id", validID)
w := httptest.NewRecorder()
h.GetConversationMessages(w, r)
assertStatus(t, w, http.StatusUnauthorized)
assertErrorMessage(t, w, ErrMsgUnauthorized)
})

t.Run("rejects empty conversation ID", func(t *testing.T) {
h := NewConversationHandler(&mockEntityConversationClient{})
r := withUser(httptest.NewRequest(http.MethodGet, "/conversations//messages", nil))
r.SetPathValue("id", "")
w := httptest.NewRecorder()
h.GetConversationMessages(w, r)
assertStatus(t, w, http.StatusBadRequest)
assertErrorMessage(t, w, ErrMsgInvalidUUID)
})

t.Run("rejects non-UUID conversation ID", func(t *testing.T) {
h := NewConversationHandler(&mockEntityConversationClient{})
r := withUser(httptest.NewRequest(http.MethodGet, "/conversations/not-a-uuid/messages", nil))
r.SetPathValue("id", "not-a-uuid")
w := httptest.NewRecorder()
h.GetConversationMessages(w, r)
assertStatus(t, w, http.StatusBadRequest)
assertErrorMessage(t, w, ErrMsgInvalidUUID)
})

t.Run("rejects invalid limit", func(t *testing.T) {
h := NewConversationHandler(&mockEntityConversationClient{})
r := withUser(httptest.NewRequest(http.MethodGet, "/conversations/"+validID+"/messages?limit=abc", nil))
r.SetPathValue("id", validID)
w := httptest.NewRecorder()
h.GetConversationMessages(w, r)
assertStatus(t, w, http.StatusBadRequest)
})

t.Run("rejects negative offset", func(t *testing.T) {
h := NewConversationHandler(&mockEntityConversationClient{})
r := withUser(httptest.NewRequest(http.MethodGet, "/conversations/"+validID+"/messages?offset=-1", nil))
r.SetPathValue("id", validID)
w := httptest.NewRecorder()
h.GetConversationMessages(w, r)
assertStatus(t, w, http.StatusBadRequest)
})

t.Run("sends referenceType=conversation payload with correct ID and pagination", func(t *testing.T) {
var capturedBody []byte
client := &mockEntityConversationClient{
searchCommentsFn: func(_ context.Context, body []byte) ([]byte, error) {
capturedBody = body
return []byte(`{"comments":[],"total":0,"limit":10,"offset":5,"hasMore":false}`), nil
},
}
h := NewConversationHandler(client)
r := withUser(httptest.NewRequest(http.MethodGet, "/conversations/"+validID+"/messages?limit=10&offset=5", nil))
r.SetPathValue("id", validID)
w := httptest.NewRecorder()
h.GetConversationMessages(w, r)
assertStatus(t, w, http.StatusOK)

var payload map[string]any
if err := json.Unmarshal(capturedBody, &payload); err != nil {
t.Fatalf("captured body is not valid JSON: %v", err)
}
if payload["referenceId"] != validID {
t.Errorf("referenceId = %v, want %q", payload["referenceId"], validID)
}
if payload["referenceType"] != "conversation" {
t.Errorf("referenceType = %v, want %q", payload["referenceType"], "conversation")
}
pag, _ := payload["pagination"].(map[string]any)
if pag["limit"] != float64(10) {
t.Errorf("pagination.limit = %v, want 10", pag["limit"])
}
if pag["offset"] != float64(5) {
t.Errorf("pagination.offset = %v, want 5", pag["offset"])
}
})

t.Run("returns 200 with messages payload", func(t *testing.T) {
const payload = `{"comments":[{"id":"22222222-2222-2222-2222-222222222222","content":"Hello","type":"comment"}],"total":1,"limit":20,"offset":0,"hasMore":false}`
client := &mockEntityConversationClient{
searchCommentsFn: func(_ context.Context, _ []byte) ([]byte, error) {
return []byte(payload), nil
},
}
h := NewConversationHandler(client)
r := withUser(httptest.NewRequest(http.MethodGet, "/conversations/"+validID+"/messages", nil))
r.SetPathValue("id", validID)
w := httptest.NewRecorder()
h.GetConversationMessages(w, r)
assertStatus(t, w, http.StatusOK)
assertContentType(t, w, "application/json")
})

t.Run("maps upstream errors", func(t *testing.T) {
for _, tc := range upstreamErrors("Failed to retrieve conversation messages.") {
t.Run(tc.name, func(t *testing.T) {
client := &mockEntityConversationClient{
searchCommentsFn: func(_ context.Context, _ []byte) ([]byte, error) {
return nil, tc.err
},
}
h := NewConversationHandler(client)
r := withUser(httptest.NewRequest(http.MethodGet, "/conversations/"+validID+"/messages", nil))
r.SetPathValue("id", validID)
w := httptest.NewRecorder()
h.GetConversationMessages(w, r)
assertStatus(t, w, tc.wantCode)
assertErrorMessage(t, w, tc.wantMsg)
})
}
})
}
Loading