Skip to content

[Customer Entity] Implement cases search endpoint - #778

Merged
Rashmika998 merged 8 commits into
wso2-open-operations:v2from
cloby99:task/entity-service
Jun 1, 2026
Merged

Rashmika998 merged 8 commits into
wso2-open-operations:v2from
cloby99:task/entity-service

Conversation

@cloby99

@cloby99 cloby99 commented May 31, 2026 •

Copy link
Copy Markdown
Member

Purpose

  • Add cases table migration with case_priority_enum and case_state_enum types, referential integrity triggers (deployment → project, deployed product → deployment, catastrophic priority → managed_cloud_subscription only), and covering indexes
  • Add Case domain types with CasePriority, CaseState, and CaseSort (field + order) enums
  • Implement cases search repository with concurrent COUNT/SELECT, dynamic WHERE clause for project, deployment, deployed product, state, and priority filters, plus ILIKE search across subject, number, and wso2_id
  • Implement cases search service with UUID, enum, sort field/order validation and defaults
  • Register POST /cases/search handler and route
  • Add /cases/search path and request/response schemas to OpenAPI spec

Request payload

{
  "pagination": { "limit": 20, "offset": 0 },
  "searchQuery": "gateway",
  "projectIds": ["..."],
  "deploymentIds": ["..."],
  "deployedProductIds": ["..."],
  "stateKeys": ["open", "work_in_progress"],
  "priorityKeys": ["critical", "high"],
  "sortBy": { "field": "created_at", "order": "desc" }
}


<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

## Release Notes

**New Features**
- Added comprehensive case search capability with filtering by project, deployment, deployed product, state, and priority. Search results can be sorted by creation date, last update, or closure date with full pagination support.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@coderabbitai

coderabbitai Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@cloby99, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 13 minutes and 2 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d3d9eb3f-8149-4233-859c-b4363f90992f

📥 Commits

Reviewing files that changed from the base of the PR and between 8da6ae3 and b0b90d8.

📒 Files selected for processing (6)
  • entity-service/internal/domain/entity.go
  • entity-service/internal/repository/case_repo.go
  • entity-service/internal/service/case_service.go
  • entity-service/migrations/000008_create_cases.down.sql
  • entity-service/migrations/000008_create_cases.up.sql
  • entity-service/openapi.yaml
📝 Walkthrough

Walkthrough

This PR implements a complete case search feature for the entity service. It adds domain types for cases and search requests, database schema with validation triggers, a repository layer with dynamic SQL query building and concurrent execution, service-layer validation and orchestration, an HTTP handler, dependency wiring in the router, and OpenAPI documentation for the new /cases/search endpoint.

Changes

Case Search Feature

Layer / File(s) Summary
Domain contracts and data types
entity-service/internal/domain/entity.go, entity-service/internal/service/interfaces.go
Case priority and state enums, sorting options, Case entity with optional priority and closed-at fields, and SearchCasesRequest/SearchCasesResponse types for paginated search with optional project/deployment/product IDs, state/priority filter keys, and sort parameters.
Database schema and migrations
entity-service/migrations/000008_create_cases.up.sql, entity-service/migrations/000008_create_cases.down.sql
Creates cases table with uuid primary key, unique number/wso2_id, foreign keys to users/projects/deployments/deployed_products, priority/state enum fields, timestamp columns with check constraint enforcing closed_at consistency, three BEFORE INSERT/UPDATE triggers validating deployment/project membership and subscription gating for catastrophic priority, and indexes on identifiers and status fields.
Repository data access
entity-service/internal/repository/case_repo.go
Implements CaseRepository interface with SearchCases method that builds dynamic SQL WHERE clauses from optional filter arrays and free-text search with ILIKE escaping, derives ORDER BY from sort field/order, executes count and paginated SELECT queries concurrently via errgroup, scans rows into Case objects, and returns results plus total count.
Service validation and orchestration
entity-service/internal/service/case_service.go
Implements CaseService with SearchCases method that validates pagination (limit/offset), search query text, UUID filters, and state/priority keys against allowlists, defaults/sanitizes sort field and order, delegates to repository, and constructs SearchCasesResponse including HasMore flag computed from offset and result count.
HTTP handler and dependency wiring
entity-service/internal/handler/case_handler.go, entity-service/internal/server/routes.go
Implements CaseHandler that decodes POST /cases/search request body, invokes service layer, returns JSON responses with appropriate error handling; NewRouter extends dependency graph to construct case repository/service/handler and registers POST /cases/search route.
API documentation
entity-service/openapi.yaml
Adds /cases/search POST endpoint definition and SearchCasesRequest, Case, SearchCasesResponse schema definitions with pagination fields, multiple filter arrays, enumerated priority/state values, and nullable properties.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Handler as CaseHandler
  participant Service as CaseService
  participant Repository as CaseRepository
  participant Database as PostgreSQL
  Client->>Handler: POST /cases/search (SearchCasesRequest)
  Handler->>Service: SearchCases(ctx, req)
  Service->>Service: Validate pagination, query, filters, sort
  Service->>Repository: SearchCases(ctx, req)
  Repository->>Repository: Build WHERE and ORDER BY clauses
  par Concurrent Queries
    Repository->>Database: SELECT COUNT(*)
    Repository->>Database: SELECT * LIMIT/OFFSET
  and
  end
  Database-->>Repository: rows + count
  Repository->>Repository: Scan rows into Case objects
  Repository-->>Service: (cases, total, error)
  Service->>Service: Compute HasMore flag
  Service-->>Handler: SearchCasesResponse
  Handler-->>Client: JSON response 200/400/500
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • wso2-open-operations/cs-tools#750: Updates customer-portal request payload to send multi-select severityKeys and deploymentIds to match the backend case search filtering added in this PR.
  • wso2-open-operations/cs-tools#729: Extends the entity-service search stack in the same locations (domain types, routes, service interfaces) to add paginated user search, following the same architectural pattern as the case search implementation.
  • wso2-open-operations/cs-tools#706: Adds Agent Portal backend scaffolding that proxies requests to the newly introduced /cases/search endpoint in this PR.

Suggested labels

Type/New Feature, Area/Backend

Suggested reviewers

  • Rashmika998
  • v15a1

Poem

🐰 A warren of cases now searchable,
With filters, priorities, states detectably—
Migrations and schemas align,
Service and handler combine,
The feature complete and inspectable! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is largely incomplete against the template. It lacks: goals, user stories, release notes, documentation, training, certification, marketing, automation tests, security checks, samples, related PRs, migrations details, test environment, and learning sections. Complete the PR description by filling in all required template sections, particularly automation tests, security checks, and documentation requirements to ensure proper review and tracking.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title '[Customer Entity] Implement cases search endpoint' clearly and concisely describes the primary change - implementing a cases search endpoint in the customer/entity service.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@entity-service/migrations/000008_create_cases.up.sql`:
- Around line 42-97: The current checks (functions
check_case_deployment_belongs_to_project,
check_case_deployed_product_belongs_to_deployment,
check_case_catastrophic_priority and their trg_case_* triggers) only run on
cases INSERT/UPDATE and miss violations introduced when parent rows change; add
complementary parent-table triggers to enforce invariants when
deployments.project_id, deployed_products.deployment_id or
projects.subscription_type are updated (e.g., create AFTER UPDATE OF project_id
on deployments that scans cases and raises using the same logic as
check_case_deployment_belongs_to_project, AFTER UPDATE OF deployment_id on
deployed_products that scans cases using
check_case_deployed_product_belongs_to_deployment logic, and AFTER UPDATE OF
subscription_type on projects that scans cases for priority='catastrophic' using
check_case_catastrophic_priority logic), or alternatively prevent updates to
those parent columns by making them immutable via BEFORE UPDATE triggers on
deployments, deployed_products and projects; implement one of these fixes
referencing the existing function names and trigger purposes.
- Around line 99-108: The current btree indexes won't help ILIKE '%...%'
searches; update the migration to enable pg_trgm (CREATE EXTENSION IF NOT EXISTS
pg_trgm) and add trigram GIN indexes for the searchable text columns used by
/cases/search: create trigram indexes for subject, number and wso2_id (e.g.
idx_cases_subject_trgm, idx_cases_number_trgm, idx_cases_wso2_id_trgm) using
LOWER(...) or gin_trgm_ops so ILIKE queries can use them, and also add an index
for the exposed sort key updated_at (e.g. idx_cases_updated_at) so explicit
sorts avoid full scans; keep the existing btree indexes for equality filters
(project_id, state, etc.) as-is.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4024dd08-3513-40ba-a977-bc3ef9f5f2a5

📥 Commits

Reviewing files that changed from the base of the PR and between fe99fd1 and 8da6ae3.

📒 Files selected for processing (9)
  • entity-service/internal/domain/entity.go
  • entity-service/internal/handler/case_handler.go
  • entity-service/internal/repository/case_repo.go
  • entity-service/internal/server/routes.go
  • entity-service/internal/service/case_service.go
  • entity-service/internal/service/interfaces.go
  • entity-service/migrations/000008_create_cases.down.sql
  • entity-service/migrations/000008_create_cases.up.sql
  • entity-service/openapi.yaml

Comment thread entity-service/migrations/000008_create_cases.up.sql
Comment thread entity-service/migrations/000008_create_cases.up.sql Outdated
@cloby99
cloby99 requested a review from Rashmika998 June 1, 2026 05:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants