Skip to content

[Customer Entity] Extend POST /cases/search with date range, createdBy, and createdByMe filters - #902

Merged
cloby99 merged 1 commit into
wso2-open-operations:v2from
cloby99:task/entity-service
Jun 22, 2026
Merged

[Customer Entity] Extend POST /cases/search with date range, createdBy, and createdByMe filters#902
cloby99 merged 1 commit into
wso2-open-operations:v2from
cloby99:task/entity-service

Conversation

@cloby99

@cloby99 cloby99 commented Jun 22, 2026

Copy link
Copy Markdown
Member

Summary

  • Added closedStartDate, closedEndDate, startCreatedDate, endCreatedDate, startUpdatedDate, endUpdatedDate (UTC datetime) filters to POST /cases/search
  • Added createdBy (array of emails) and createdByMe (boolean) filters; createdByMe resolves the caller's email from the JWT and appends it to createdBy
  • For the Postgres data source, new filters are applied directly in the SQL query; for ServiceNow, priorityKeys is mapped to severityKeys integers and new filter fields are forwarded to the SN API

Summary by CodeRabbit

  • New Features
    • Expanded case search filtering capabilities for better case discovery
      • New date-range filters for cases closed, created, or updated within specified periods
      • New creator filters to search for cases created by specific users or limit results to cases you created
      • Integrated validation ensures all date range filters maintain logical consistency

@coderabbitai

coderabbitai Bot commented Jun 22, 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 53 minutes and 29 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ 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.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

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: 96bf1f29-2c8a-4f31-aa61-4720471ec52c

📥 Commits

Reviewing files that changed from the base of the PR and between ff1da6c and 7bc7751.

📒 Files selected for processing (4)
  • entity-service/internal/domain/entity.go
  • entity-service/internal/repository/case_repo.go
  • entity-service/internal/service/case_service.go
  • entity-service/internal/service/sn_case_service.go
📝 Walkthrough

Walkthrough

Eight new optional filter fields are added to SearchCasesFilters (date ranges for closed/created/updated timestamps, CreatedBy list, and CreatedByMe boolean). The service layer resolves CreatedByMe via JWT context and validates date-range ordering. The repository extends the SQL WHERE clause with these filters and fixes the count query to include the necessary JOIN. The ServiceNow integration maps these filters into the outbound search payload using a new formatSNDate helper.

Changes

Case Search Filter Expansion

Layer / File(s) Summary
SearchCasesFilters struct additions
entity-service/internal/domain/entity.go
Adds eight new optional fields to SearchCasesFilters: nullable *time.Time pointers for closed/created/updated date ranges, CreatedBy []string, and CreatedByMe bool.
Service-layer CreatedByMe resolution and date-range validation
entity-service/internal/service/case_service.go
When CreatedByMe is set, extracts the user email from the JWT context (x-user-id-token) and appends it to CreatedBy, returning UnauthorizedError or ValidationError on failure. Also validates that each date-range pair is correctly ordered (end ≥ start). validCaseWorkState is relocated without content change.
Repository SQL WHERE clause and count query fix
entity-service/internal/repository/case_repo.go
Appends conditional WHERE clauses for CreatedBy (matched via u.email), closed_at, created_at, and updated_at date ranges with advancing parameter indices. Refactors countQuery to include the same joins fragment as the data query so joined-table conditions remain valid for counting.
ServiceNow filter struct, formatSNDate helper, and payload mapping
entity-service/internal/service/sn_case_service.go
Extends snCaseFilters with date-range string fields and creator fields. Introduces formatSNDate(*time.Time) string to safely convert nullable date pointers to snCreatedOnLayout UTC strings. Updates SearchCases payload construction to use formatSNDate and pass through CreatedBy/CreatedByMe.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • wso2-open-operations/cs-tools#891: Adds the same startCreatedDate/endCreatedDate/startUpdatedDate/endUpdatedDate filter fields to the case-search request flow on the customer-portal side, directly corresponding to the backend filter support introduced here.

Suggested reviewers

  • Rashmika998

Poem

🐇 Hop through dates with nimble paws,
Closed, created, updated—no flaws!
CreatedByMe? I'll sniff the JWT,
And validate ranges carefully.
The count query now JOINs along,
ServiceNow gets the dates — so long! 🌟

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is incomplete. It lacks most required template sections including Purpose, Goals, Approach, User stories, Release notes, Documentation, Training, Certification, Marketing, Tests, Security checks, and others. Complete the PR description by filling in all required template sections from the repository template, particularly Purpose, Goals, User stories, Testing details, and Security checks.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: extending POST /cases/search with new date range and creator filters.
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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
entity-service/internal/service/sn_case_service.go (1)

905-948: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Apply the same date-range ordering validation in the ServiceNow search path.

Line 905 flow forwards filters without rejecting inverted ranges, while the Postgres path (case_service) rejects them. That makes /cases/search behavior backend-dependent and can send invalid filters downstream.

Suggested fix
 func (s *snCaseService) SearchCases(ctx context.Context, req domain.SearchCasesRequest) (domain.SearchCasesResponse, error) {
 	if err := normalizePagination(&req.Pagination); err != nil {
 		return domain.SearchCasesResponse{}, err
 	}
 	if err := validateSearchQuery(req.Filters.SearchQuery); err != nil {
 		return domain.SearchCasesResponse{}, err
 	}
+	if req.Filters.ClosedEndDate != nil && req.Filters.ClosedStartDate != nil &&
+		req.Filters.ClosedEndDate.Before(*req.Filters.ClosedStartDate) {
+		return domain.SearchCasesResponse{}, &apierror.ValidationError{Msg: "closedEndDate must not be before closedStartDate"}
+	}
+	if req.Filters.EndCreatedDate != nil && req.Filters.StartCreatedDate != nil &&
+		req.Filters.EndCreatedDate.Before(*req.Filters.StartCreatedDate) {
+		return domain.SearchCasesResponse{}, &apierror.ValidationError{Msg: "endCreatedDate must not be before startCreatedDate"}
+	}
+	if req.Filters.EndUpdatedDate != nil && req.Filters.StartUpdatedDate != nil &&
+		req.Filters.EndUpdatedDate.Before(*req.Filters.StartUpdatedDate) {
+		return domain.SearchCasesResponse{}, &apierror.ValidationError{Msg: "endUpdatedDate must not be before startUpdatedDate"}
+	}
 
 	token := middleware.UserIDTokenFromContext(ctx)
 	if token == "" {
 		return domain.SearchCasesResponse{}, &apierror.UnauthorizedError{Msg: "x-user-id-token header is required"}
 	}
🤖 Prompt for 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.

In `@entity-service/internal/service/sn_case_service.go` around lines 905 - 948,
The SearchCases method in snCaseService is missing date-range ordering
validation that exists in the Postgres path (case_service). Add validation early
in the SearchCases function to ensure that for all date range pairs in
req.Filters (ClosedStartDate/ClosedEndDate, StartCreatedDate/EndCreatedDate,
StartUpdatedDate/EndUpdatedDate), the start date is not greater than the end
date. Return a ValidationError if any inverted ranges are detected, matching the
pattern used in the Postgres implementation.
🤖 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.

Outside diff comments:
In `@entity-service/internal/service/sn_case_service.go`:
- Around line 905-948: The SearchCases method in snCaseService is missing
date-range ordering validation that exists in the Postgres path (case_service).
Add validation early in the SearchCases function to ensure that for all date
range pairs in req.Filters (ClosedStartDate/ClosedEndDate,
StartCreatedDate/EndCreatedDate, StartUpdatedDate/EndUpdatedDate), the start
date is not greater than the end date. Return a ValidationError if any inverted
ranges are detected, matching the pattern used in the Postgres implementation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: db5de7b1-6dcd-4bd6-bf32-2fa15f261810

📥 Commits

Reviewing files that changed from the base of the PR and between c8b0b96 and ff1da6c.

📒 Files selected for processing (4)
  • entity-service/internal/domain/entity.go
  • entity-service/internal/repository/case_repo.go
  • entity-service/internal/service/case_service.go
  • entity-service/internal/service/sn_case_service.go

@cloby99
cloby99 force-pushed the task/entity-service branch from ff1da6c to 7bc7751 Compare June 22, 2026 05:22
@cloby99
cloby99 merged commit 673d6e5 into wso2-open-operations:v2 Jun 22, 2026
1 check passed
Rashmika998 added a commit that referenced this pull request Jun 22, 2026
…case search filters

- Add POST /service-requests/search endpoint (entity-service PR #903)
- Extend CaseSearchFilters with date range (closed/created/updated),
  createdBy, and createdByMe fields (entity-service PR #902)
- Update OpenAPI spec with new path, schemas, and filter fields
- Extend entityCaseClient interface and update test mock

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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