Skip to content
Merged
2 changes: 1 addition & 1 deletion entity-service/cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func main() {
srv := server.New(addr, pool)

go func() {
log.Printf("listening on %s", addr)
log.Printf("Customer Entity REST Service started in PORT : %s", cfg.ServerPort)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("server error: %v", err)
}
Expand Down
71 changes: 57 additions & 14 deletions entity-service/internal/domain/entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,23 +374,66 @@ type CaseSort struct {
}

// Case represents a customer support case as stored in the database.
// Priority and ClosedAt are optional and omitted from JSON when absent.
// ClosedAt is the only nullable field; all others are required.
// Used as the response for write operations (create).
type Case struct {
ID string `json:"id"`
Number string `json:"number"`
Wso2ID string `json:"wso2Id"`
CreatedBy string `json:"createdBy"`
ProjectID string `json:"projectId"`
DeploymentID string `json:"deploymentId"`
DeployedProductID string `json:"deployedProductId"`
Subject string `json:"subject"`
Description string `json:"description"`
ID string `json:"id"`
Number string `json:"number"`
Wso2ID string `json:"wso2Id"`
CreatedBy string `json:"createdBy"`
ProjectID string `json:"projectId"`
DeploymentID string `json:"deploymentId"`
DeployedProductID string `json:"deployedProductId"`
Subject string `json:"subject"`
Description string `json:"description"`
Priority CasePriority `json:"priority"`
IssueType CaseIssueType `json:"issueType"`
State CaseState `json:"state"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
ClosedAt *time.Time `json:"closedAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
ClosedAt *time.Time `json:"closedAt,omitempty"`
}

// UserRef is a reference to a user with key display fields.
type UserRef struct {
ID string `json:"id"`
DisplayName string `json:"displayName"`
UserID string `json:"userId,omitempty"`
Email string `json:"email,omitempty"`
}

// EntityRef is a compact reference to a named entity (project or deployment).
type EntityRef struct {
ID string `json:"id"`
Name string `json:"name"`
}

// DeployedProductRef is a compact reference to a deployed product with a
// computed display name combining the product name and version.
type DeployedProductRef struct {
ID string `json:"id"`
DisplayName string `json:"displayName"`
}

// CaseView is the enriched read representation of a case. It carries all
// original Case fields plus display-value references for each FK, resolved via
// JOIN at query time. ClosedAt is the only nullable field.
type CaseView struct {
ID string `json:"id"`
Number string `json:"number"`
Wso2ID string `json:"wso2Id"`
Subject string `json:"subject"`
Description string `json:"description"`
Priority CasePriority `json:"priority"`
IssueType CaseIssueType `json:"issueType"`
State CaseState `json:"state"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
ClosedAt *time.Time `json:"closedAt,omitempty"`
CreatedByDetails UserRef `json:"createdBy"`
ProjectDetails EntityRef `json:"project"`
DeploymentDetails EntityRef `json:"deployment"`
DeployedProductDetails DeployedProductRef `json:"deployedProduct"`
}

// SearchCasesRequest is the input for a case search operation.
Expand All @@ -411,7 +454,7 @@ type SearchCasesRequest struct {
// SearchCasesResponse is the paginated result of a case search.
// HasMore is true when additional pages are available beyond the current offset.
type SearchCasesResponse struct {
Cases []Case `json:"cases"`
Cases []CaseView `json:"cases"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
Expand Down
113 changes: 72 additions & 41 deletions entity-service/internal/repository/case_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@ type CaseRepository interface {
// CreateCase inserts a new case row. number and wso2_id are generated from
// DB sequences; id is generated by the DB default.
CreateCase(ctx context.Context, req domain.CreateCaseRequest) (domain.Case, error)
// GetCaseByID returns the case with the given UUID, or a NotFoundError if
// no matching row exists.
GetCaseByID(ctx context.Context, id string) (domain.Case, error)
// SearchCases returns a filtered, paginated slice of cases together with the
// total count of matching rows before pagination.
// GetCaseByID returns the enriched case view for the given UUID, or a
// NotFoundError if no matching row exists.
GetCaseByID(ctx context.Context, id string) (domain.CaseView, error)
// SearchCases returns a filtered, paginated slice of enriched case views
// together with the total count of matching rows before pagination.
// COUNT and SELECT are executed concurrently on separate pool connections.
SearchCases(ctx context.Context, req domain.SearchCasesRequest) ([]domain.Case, int, error)
SearchCases(ctx context.Context, req domain.SearchCasesRequest) ([]domain.CaseView, int, error)
// CreateCaseComment inserts a new comment row for the given case.
CreateCaseComment(ctx context.Context, req domain.CreateCaseCommentRequest) (domain.CaseComment, error)
// SearchCaseComments returns a paginated slice of comments for the given case
Expand Down Expand Up @@ -98,25 +98,40 @@ func (r *caseRepo) CreateCase(ctx context.Context, req domain.CreateCaseRequest)
}

// GetCaseByID implements CaseRepository.
func (r *caseRepo) GetCaseByID(ctx context.Context, id string) (domain.Case, error) {
var c domain.Case
func (r *caseRepo) GetCaseByID(ctx context.Context, id string) (domain.CaseView, error) {
var cv domain.CaseView
err := r.db.QueryRow(ctx,
`SELECT id, number, wso2_id, created_by, project_id, deployment_id, deployed_product_id,
subject, description, priority, issue_type, state, created_at, updated_at, closed_at
FROM cases WHERE id = $1`, id,
`SELECT c.id, c.number, c.wso2_id,
c.subject, c.description, c.priority, c.issue_type, c.state,
c.created_at, c.updated_at, c.closed_at,
u.id, u.first_name || ' ' || u.last_name, u.user_name, u.email,
p.id, p.name,
d.id, d.name,
dp.id, prod.name || COALESCE(' ' || pv.version, '')
FROM cases c
JOIN users u ON u.id = c.created_by
JOIN projects p ON p.id = c.project_id
JOIN deployments d ON d.id = c.deployment_id
JOIN deployed_products dp ON dp.id = c.deployed_product_id
JOIN products prod ON prod.id = dp.product_id
LEFT JOIN product_versions pv ON pv.id = dp.product_version_id
WHERE c.id = $1`, id,
).Scan(
&c.ID, &c.Number, &c.Wso2ID, &c.CreatedBy,
&c.ProjectID, &c.DeploymentID, &c.DeployedProductID,
&c.Subject, &c.Description, &c.Priority, &c.IssueType, &c.State,
&c.CreatedAt, &c.UpdatedAt, &c.ClosedAt,
&cv.ID, &cv.Number, &cv.Wso2ID,
&cv.Subject, &cv.Description, &cv.Priority, &cv.IssueType, &cv.State,
&cv.CreatedAt, &cv.UpdatedAt, &cv.ClosedAt,
&cv.CreatedByDetails.ID, &cv.CreatedByDetails.DisplayName, &cv.CreatedByDetails.UserID, &cv.CreatedByDetails.Email,
&cv.ProjectDetails.ID, &cv.ProjectDetails.Name,
&cv.DeploymentDetails.ID, &cv.DeploymentDetails.Name,
&cv.DeployedProductDetails.ID, &cv.DeployedProductDetails.DisplayName,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Case{}, &apierror.NotFoundError{Msg: "case not found"}
return domain.CaseView{}, &apierror.NotFoundError{Msg: "case not found"}
}
if err != nil {
return domain.Case{}, fmt.Errorf("get case by id: %w", err)
return domain.CaseView{}, fmt.Errorf("get case by id: %w", err)
}
return c, nil
return cv, nil
}

// CreateCaseComment implements CaseRepository.
Expand Down Expand Up @@ -196,26 +211,26 @@ func (r *caseRepo) SearchCaseComments(ctx context.Context, req domain.SearchCase
}

// SearchCases implements CaseRepository.
func (r *caseRepo) SearchCases(ctx context.Context, req domain.SearchCasesRequest) ([]domain.Case, int, error) {
func (r *caseRepo) SearchCases(ctx context.Context, req domain.SearchCasesRequest) ([]domain.CaseView, int, error) {
filterArgs := []any{}
argIdx := 1

where := "WHERE 1=1"

if len(req.ProjectIDs) > 0 {
where += fmt.Sprintf(" AND project_id = ANY($%d::uuid[])", argIdx)
where += fmt.Sprintf(" AND c.project_id = ANY($%d::uuid[])", argIdx)
filterArgs = append(filterArgs, req.ProjectIDs)
argIdx++
}

if len(req.DeploymentIDs) > 0 {
where += fmt.Sprintf(" AND deployment_id = ANY($%d::uuid[])", argIdx)
where += fmt.Sprintf(" AND c.deployment_id = ANY($%d::uuid[])", argIdx)
filterArgs = append(filterArgs, req.DeploymentIDs)
argIdx++
}

if len(req.DeployedProductIDs) > 0 {
where += fmt.Sprintf(" AND deployed_product_id = ANY($%d::uuid[])", argIdx)
where += fmt.Sprintf(" AND c.deployed_product_id = ANY($%d::uuid[])", argIdx)
filterArgs = append(filterArgs, req.DeployedProductIDs)
argIdx++
}
Expand All @@ -225,7 +240,7 @@ func (r *caseRepo) SearchCases(ctx context.Context, req domain.SearchCasesReques
for i, s := range req.StateKeys {
stateStrings[i] = string(s)
}
where += fmt.Sprintf(" AND state = ANY($%d::case_state_enum[])", argIdx)
where += fmt.Sprintf(" AND c.state = ANY($%d::case_state_enum[])", argIdx)
filterArgs = append(filterArgs, stateStrings)
argIdx++
}
Expand All @@ -235,7 +250,7 @@ func (r *caseRepo) SearchCases(ctx context.Context, req domain.SearchCasesReques
for i, p := range req.PriorityKeys {
priorityStrings[i] = string(p)
}
where += fmt.Sprintf(" AND priority = ANY($%d::case_priority_enum[])", argIdx)
where += fmt.Sprintf(" AND c.priority = ANY($%d::case_priority_enum[])", argIdx)
filterArgs = append(filterArgs, priorityStrings)
argIdx++
}
Expand All @@ -245,36 +260,48 @@ func (r *caseRepo) SearchCases(ctx context.Context, req domain.SearchCasesReques
for i, it := range req.IssueTypeKeys {
issueTypeStrings[i] = string(it)
}
where += fmt.Sprintf(" AND issue_type = ANY($%d::case_issue_type_enum[])", argIdx)
where += fmt.Sprintf(" AND c.issue_type = ANY($%d::case_issue_type_enum[])", argIdx)
filterArgs = append(filterArgs, issueTypeStrings)
argIdx++
}

if req.SearchQuery != "" {
escaped := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(req.SearchQuery)
pattern := "%" + escaped + "%"
where += fmt.Sprintf(` AND (subject ILIKE $%d ESCAPE '\' OR number ILIKE $%d ESCAPE '\' OR wso2_id ILIKE $%d ESCAPE '\')`, argIdx, argIdx, argIdx)
where += fmt.Sprintf(` AND (c.subject ILIKE $%d ESCAPE '\' OR c.number ILIKE $%d ESCAPE '\' OR c.wso2_id ILIKE $%d ESCAPE '\')`, argIdx, argIdx, argIdx)
filterArgs = append(filterArgs, pattern)
argIdx++
}

sortCol := string(req.SortBy.Field)
sortCol := "c." + string(req.SortBy.Field)
sortDir := string(req.SortBy.Order)

countQuery := "SELECT COUNT(*) FROM cases " + where
countQuery := "SELECT COUNT(*) FROM cases c " + where

joins := `JOIN users u ON u.id = c.created_by
JOIN projects p ON p.id = c.project_id
JOIN deployments d ON d.id = c.deployment_id
JOIN deployed_products dp ON dp.id = c.deployed_product_id
JOIN products prod ON prod.id = dp.product_id
LEFT JOIN product_versions pv ON pv.id = dp.product_version_id`

dataQuery := fmt.Sprintf(
`SELECT id, number, wso2_id, created_by, project_id, deployment_id, deployed_product_id,
subject, description, priority, issue_type, state, created_at, updated_at, closed_at
FROM cases %s
ORDER BY %s %s NULLS LAST, id
`SELECT c.id, c.number, c.wso2_id,
c.subject, c.description, c.priority, c.issue_type, c.state,
c.created_at, c.updated_at, c.closed_at,
u.id, u.first_name || ' ' || u.last_name, u.user_name, u.email,
p.id, p.name,
d.id, d.name,
dp.id, prod.name || COALESCE(' ' || pv.version, '')
FROM cases c %s %s
ORDER BY %s %s NULLS LAST, c.id
LIMIT $%d OFFSET $%d`,
where, sortCol, sortDir, argIdx, argIdx+1,
joins, where, sortCol, sortDir, argIdx, argIdx+1,
)
dataArgs := append(append([]any{}, filterArgs...), req.Pagination.Limit, req.Pagination.Offset)

var total int
var cases []domain.Case
var cases []domain.CaseView

eg, egCtx := errgroup.WithContext(ctx)

Expand All @@ -292,18 +319,22 @@ func (r *caseRepo) SearchCases(ctx context.Context, req domain.SearchCasesReques
}
defer rows.Close()

result := make([]domain.Case, 0, req.Pagination.Limit)
result := make([]domain.CaseView, 0, req.Pagination.Limit)
for rows.Next() {
var c domain.Case
var cv domain.CaseView
var ignoredUserID, ignoredEmail string
if err := rows.Scan(
&c.ID, &c.Number, &c.Wso2ID, &c.CreatedBy,
&c.ProjectID, &c.DeploymentID, &c.DeployedProductID,
&c.Subject, &c.Description, &c.Priority, &c.IssueType, &c.State,
&c.CreatedAt, &c.UpdatedAt, &c.ClosedAt,
&cv.ID, &cv.Number, &cv.Wso2ID,
&cv.Subject, &cv.Description, &cv.Priority, &cv.IssueType, &cv.State,
&cv.CreatedAt, &cv.UpdatedAt, &cv.ClosedAt,
&cv.CreatedByDetails.ID, &cv.CreatedByDetails.DisplayName, &ignoredUserID, &ignoredEmail,
&cv.ProjectDetails.ID, &cv.ProjectDetails.Name,
&cv.DeploymentDetails.ID, &cv.DeploymentDetails.Name,
&cv.DeployedProductDetails.ID, &cv.DeployedProductDetails.DisplayName,
); err != nil {
return fmt.Errorf("scan case: %w", err)
}
result = append(result, c)
result = append(result, cv)
}
if err := rows.Err(); err != nil {
return fmt.Errorf("iterate cases: %w", err)
Expand Down
4 changes: 2 additions & 2 deletions entity-service/internal/service/case_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,9 @@ func (s *caseService) CreateCase(ctx context.Context, req domain.CreateCaseReque
}

// GetCaseByID implements CaseService.
func (s *caseService) GetCaseByID(ctx context.Context, id string) (domain.Case, error) {
func (s *caseService) GetCaseByID(ctx context.Context, id string) (domain.CaseView, error) {
if err := validateUUIDs("id", []string{id}); err != nil {
return domain.Case{}, err
return domain.CaseView{}, err
}
return s.repo.GetCaseByID(ctx, id)
}
Expand Down
6 changes: 3 additions & 3 deletions entity-service/internal/service/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,9 @@ type CaseService interface {
// CreateCase creates a new case with auto-generated id, number, and wso2_id.
// State defaults to open. A ValidationError is returned for invalid input.
CreateCase(ctx context.Context, req domain.CreateCaseRequest) (domain.Case, error)
// GetCaseByID returns the case with the given UUID. A ValidationError is
// returned for a malformed UUID; a NotFoundError if no case matches.
GetCaseByID(ctx context.Context, id string) (domain.Case, error)
// GetCaseByID returns the enriched case view for the given UUID. A
// ValidationError is returned for a malformed UUID; a NotFoundError if no case matches.
GetCaseByID(ctx context.Context, id string) (domain.CaseView, error)
// SearchCases returns a paginated list of cases filtered by optional project IDs,
// deployment IDs, deployed product IDs, state keys, priority keys, and search query.
// A ValidationError is returned for invalid input; any other error indicates an
Expand Down
Loading