Skip to content

Conversation

@holashchand
Copy link
Collaborator

@holashchand holashchand commented May 7, 2025

Summary by CodeRabbit

  • New Features
    • Added support for multi-tenant schema handling, enabling tenant-specific database queries and Kafka topic resolution.
    • Included tenant context in notification and payment processing workflows for improved message routing.
  • Bug Fixes
    • Improved error handling for invalid tenant IDs during database operations.
  • Chores
    • Enhanced migration script to support database migrations for multiple schemas in a single run.

@holashchand holashchand requested a review from a team as a code owner May 7, 2025 05:36
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 7, 2025

Walkthrough

The changes introduce multi-tenant support across the expense backend by dynamically resolving schema names in SQL queries and Kafka topics based on tenant IDs. This is achieved by injecting a utility for schema/topic resolution, updating repository and producer classes, and modifying service methods to pass tenant IDs. The Flyway migration script is also updated to support migrations for multiple schemas.

Changes

File(s) Change Summary
backend/expense/pom.xml Added a new dependency on org.egov.services:services-common:2.9.0-SNAPSHOT.
backend/expense/src/main/java/org/egov/digit/expense/config/Constants.java Updated SQL query constants to use a schema replacement string; added INVALID_TENANT_ID_ERR_CODE constant.
backend/expense/src/main/java/org/egov/digit/expense/kafka/ExpenseProducer.java Added multi-state Kafka topic resolution; updated constructor and push method to accept tenant ID; added logging.
backend/expense/src/main/java/org/egov/digit/expense/repository/BillRepository.java Injected schema utility; updated queries to replace schema placeholder with tenant-specific schema; added error handling for invalid tenant IDs.
backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java Injected schema utility; updated queries to replace schema placeholder with tenant-specific schema; added error handling for invalid tenant IDs.
backend/expense/src/main/java/org/egov/digit/expense/service/BillService.java Service methods updated to extract tenant ID and pass it to expenseProducer.push.
backend/expense/src/main/java/org/egov/digit/expense/service/NotificationService.java Service methods updated to extract tenant ID and pass it to expenseProducer.push.
backend/expense/src/main/java/org/egov/digit/expense/service/PaymentService.java Service methods updated to extract tenant ID and pass it to expenseProducer.push.
backend/expense/src/main/resources/db/migrate.sh Script updated to support Flyway migrations for multiple schemas; iterates over comma-separated schema names.
backend/expense/src/main/java/org/egov/digit/expense/ExpenseApplication.java Added import and inclusion of MultiStateInstanceUtil in @Import; removed explicit @ComponentScan.

Sequence Diagram(s)

sequenceDiagram
    participant Service as Service Layer (Bill/Payment/Notification)
    participant Producer as ExpenseProducer
    participant Util as MultiStateInstanceUtil
    participant Kafka as Kafka

    Service->>Service: Extract tenantId from request
    Service->>Producer: push(tenantId, topic, payload)
    Producer->>Util: getStateSpecificTopicName(tenantId, topic)
    Util-->>Producer: stateSpecificTopic
    Producer->>Kafka: Send payload to stateSpecificTopic
Loading
sequenceDiagram
    participant Repository as Bill/PaymentRepository
    participant Util as MultiStateInstanceUtil
    participant DB as Database

    Repository->>Repository: Build SQL with schema placeholder
    Repository->>Util: replaceSchemaPlaceholder(query, tenantId)
    alt Valid tenantId
        Util-->>Repository: queryWithSchema
        Repository->>DB: Execute queryWithSchema
    else Invalid tenantId
        Util-->>Repository: throw InvalidTenantIdException
        Repository->>Repository: Throw CustomException("INVALID_TENANT_ID")
    end
Loading

Suggested reviewers

  • shailesh-egov

Poem

🐇
Across the fields of multi-tenant land,
Schemas and topics now shift on demand.
With tenant IDs guiding each hop,
Our messages and queries never stop.
Migration scripts loop, Kafka topics align—
In this warren, all tenants shine!
🥕✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 43e794d and 1fed57d.

📒 Files selected for processing (1)
  • backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (2)
Learnt from: holashchand
PR: egovernments/DIGIT-Works#1916
File: backend/expense/src/main/java/org/egov/digit/expense/repository/BillRepository.java:42-47
Timestamp: 2025-05-22T10:39:15.595Z
Learning: In the DIGIT-Works project's expense service, tenant ID validation is performed upstream before reaching the repository layer, so null checks on tenant ID in the repository methods are not necessary.
Learnt from: holashchand
PR: egovernments/DIGIT-Works#1916
File: backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java:45-49
Timestamp: 2025-05-22T10:39:45.956Z
Learning: In the DIGIT-Works application, tenant ID validation occurs at a higher level (controller/API layer) before requests reach the service/repository layer, so null checks for tenant ID in repositories like PaymentRepository are unnecessary.
🧬 Code Graph Analysis (1)
backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (2)
backend/expense/src/main/java/org/egov/digit/expense/repository/BillRepository.java (1)
  • Repository (19-62)
backend/expense/src/main/java/org/egov/digit/expense/config/Constants.java (1)
  • Constants (12-161)
🔇 Additional comments (4)
backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (4)

8-9: LGTM! Import statements correctly added for multi-tenant support.

The new imports are appropriate for the multi-tenant functionality:

  • InvalidTenantIdException and MultiStateInstanceUtil from common utilities
  • CustomException for error handling
  • Static import for the error code constant

Also applies to: 14-14, 19-19


30-30: LGTM! Dependency injection properly implemented.

The MultiStateInstanceUtil dependency is correctly added as a private final field and properly injected through the constructor with appropriate assignment.

Also applies to: 33-33, 37-37


44-49: LGTM! Schema replacement logic correctly implemented.

The implementation follows the exact same pattern as BillRepository (from relevant code snippets), ensuring consistency across the codebase. The error handling properly catches InvalidTenantIdException and converts it to a CustomException with the appropriate error code.

Based on retrieved learnings, tenant ID validation occurs upstream, so the direct usage here is appropriate.


56-61: LGTM! Count method schema replacement implemented consistently.

The schema replacement logic in the count method follows the same pattern as the search method and maintains consistency with the established pattern used in BillRepository. The error handling and tenant ID extraction are correctly implemented.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 7

♻️ Duplicate comments (1)
backend/expense/src/main/java/org/egov/digit/expense/config/Constants.java (1)

112-115: Duplicate: dynamic schema injection in COUNT query
Same as above, this COUNT query also injects SCHEMA_REPLACE_STRING. Ensure the placeholder is sanitized and consider applying the same refactor (query builder or parameterized approach).

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between df6f5db and 4ad7af6.

📒 Files selected for processing (9)
  • backend/expense/pom.xml (1 hunks)
  • backend/expense/src/main/java/org/egov/digit/expense/config/Constants.java (3 hunks)
  • backend/expense/src/main/java/org/egov/digit/expense/kafka/ExpenseProducer.java (1 hunks)
  • backend/expense/src/main/java/org/egov/digit/expense/repository/BillRepository.java (2 hunks)
  • backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (2 hunks)
  • backend/expense/src/main/java/org/egov/digit/expense/service/BillService.java (5 hunks)
  • backend/expense/src/main/java/org/egov/digit/expense/service/NotificationService.java (2 hunks)
  • backend/expense/src/main/java/org/egov/digit/expense/service/PaymentService.java (4 hunks)
  • backend/expense/src/main/resources/db/migrate.sh (1 hunks)
🔇 Additional comments (19)
backend/expense/pom.xml (1)

111-115: Addition of services-common dependency looks good

This change properly adds the services-common library that provides multi-tenant support through utilities like MultiStateInstanceUtil, which is essential for the schema/topic resolution based on tenant IDs.

backend/expense/src/main/java/org/egov/digit/expense/service/NotificationService.java (4)

41-41: Good extraction of tenant ID for multi-tenant support

This change correctly extracts the tenant ID from the bill request for use in the notification processing pipeline.


64-64: Properly updated producer call with tenant ID

The expenseProducer.push method call now correctly includes the tenant ID as the first parameter, which aligns with the multi-tenant Kafka topic resolution approach.


69-69: Good extraction of tenant ID for multi-tenant support

Similar to the previous method, correctly extracting tenant ID for multi-tenant notification handling in supervision bills.


77-77: Properly updated producer call with tenant ID

The producer call correctly includes the tenant ID, ensuring notifications are sent to the appropriate tenant-specific Kafka topic.

backend/expense/src/main/java/org/egov/digit/expense/service/BillService.java (6)

67-67: Good extraction of tenant ID for multi-tenant support

This change correctly extracts the tenant ID from the bill object for use in tenant-specific processing.


94-94: Properly updated producer call with tenant ID

The expenseProducer.push method call now includes the tenant ID parameter, enabling proper resolution of tenant-specific Kafka topics.


113-113: Good extraction of tenant ID for multi-tenant support

Consistent with the create method, this correctly extracts the tenant ID for the update operation.


136-136: Properly updated producer call with tenant ID

The producer call correctly includes the tenant ID for topic resolution during bill updates.


204-204: Good extraction of tenant ID for batch processing

Correctly extracts tenant ID for use in the batch processing of bill details.


211-211: Properly updated producer call with tenant ID for batch processing

The producer call within the batch processing loop correctly includes the tenant ID parameter, ensuring consistent multi-tenant handling.

backend/expense/src/main/java/org/egov/digit/expense/service/PaymentService.java (6)

62-62: Good extraction of tenant ID for multi-tenant support

This change correctly extracts the tenant ID from the payment object for use in payment processing.


66-66: Properly updated producer call with tenant ID

The producer call now correctly includes the tenant ID, enabling proper resolution of tenant-specific Kafka topics for payment creation.


80-80: Good extraction of tenant ID for payment updates

Consistent tenant ID extraction for the payment update operation.


87-87: Properly updated producer call with tenant ID

The producer call correctly includes the tenant ID for payment updates.


118-118: Good extraction of tenant ID for bill back-updates

Correctly extracts tenant ID for use in the bill back-update process after payment processing.


187-187: Properly updated producer call with tenant ID

The producer call for bill updates in the back-update logic correctly includes the tenant ID.

backend/expense/src/main/java/org/egov/digit/expense/config/Constants.java (2)

10-10: Static import of SCHEMA_REPLACE_STRING is correctly added
Using a static import here keeps the SQL constants cleaner and aligns with how the schema placeholder is used throughout the file.


100-109:

❓ Verification inconclusive

Verify and sanitize the dynamic schema placeholder in your SQL
You now inject SCHEMA_REPLACE_STRING directly into raw SQL; please confirm that MultiStateInstanceUtil strictly validates and escapes tenant‐derived schema names to prevent any risk of SQL injection.
Additionally, consider using a query builder or parameterized access layer for dynamic schema resolution to improve maintainability.


🏁 Script executed:

#!/bin/bash
# Locate the SCHEMA_REPLACE_STRING constant declaration
rg -n "SCHEMA_REPLACE_STRING" .

# Find the MultiStateInstanceUtil class and any references to schema validation
rg -n "MultiStateInstanceUtil" .

Length of output: 9259


Verify and Sanitize SCHEMA_REPLACE_STRING Usage
Please ensure that your dynamic schema placeholder cannot be abused for SQL injection and consider a more robust approach:

  • Confirm that MultiStateInstanceUtil.SCHEMA_REPLACE_STRING strictly validates and escapes tenant-derived schema names before substitution.
  • Review all usages in backend/expense/src/main/java/org/egov/digit/expense/config/Constants.java (e.g., lines 100–109, 112–114, 145–151, 153–158) to ensure consistency.
  • For long-term maintainability and safety, evaluate using a query builder or a parameterized access layer that supports dynamic schema resolution.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (3)
backend/expense/src/main/java/org/egov/digit/expense/kafka/ExpenseProducer.java (1)

31-35: 🛠️ Refactor suggestion

Add null-safety & failure handling around topic resolution

The push method still forwards tenantId and topic directly to multiStateInstanceUtil.getStateSpecificTopicName. A null or empty value for either argument will bubble up as an NPE or an unchecked exception from the util, taking down the calling thread. Guard-clauses plus a try/catch would make this producer safer (same concern flagged in an earlier review).

+        if (tenantId == null || tenantId.isBlank() || topic == null || topic.isBlank()) {
+            log.error("Kafka push aborted – tenantId/topic is blank. tenantId: {}, topic: {}", tenantId, topic);
+            throw new IllegalArgumentException("tenantId and topic must be non-blank");
+        }
+
         String updatedTopic = multiStateInstanceUtil.getStateSpecificTopicName(tenantId, topic);
         log.info("The Kafka topic for the tenantId : {} is : {}", tenantId, updatedTopic);
-        this.kafkaTemplate.send(updatedTopic, value);
+        try {
+            this.kafkaTemplate.send(updatedTopic, value);
+        } catch (Exception ex) {
+            log.error("Failed to publish to topic {} for tenant {}", updatedTopic, tenantId, ex);
+            throw ex;
+        }
backend/expense/src/main/java/org/egov/digit/expense/repository/BillRepository.java (1)

42-48: 🧹 Nitpick (assertive)

Extract repeated schema-replacement logic into a private helper

The try-catch block that calls multiStateInstanceUtil.replaceSchemaPlaceholder is duplicated in both search and searchCount. Encapsulating it in a private String applySchemaReplacement(String query, String tenantId) (or moving it to a common base/utility class shared by repositories) will eliminate duplication and make it easier to evolve error handling in one place.

Also applies to: 54-59

backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (1)

44-50: 🧹 Nitpick (assertive)

Centralise schema-placeholder replacement for maintainability

As with BillRepository, the identical try-catch block appears in both search and count. Extracting it into a helper will reduce repeated code and the risk of diverging behaviour between methods or repositories.

Also applies to: 56-61

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c2690ed and c4b9ca2.

📒 Files selected for processing (3)
  • backend/expense/src/main/java/org/egov/digit/expense/kafka/ExpenseProducer.java (1 hunks)
  • backend/expense/src/main/java/org/egov/digit/expense/repository/BillRepository.java (2 hunks)
  • backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (2)
backend/expense/src/main/java/org/egov/digit/expense/repository/BillRepository.java (1)
  • Repository (19-62)
backend/expense/src/main/java/org/egov/digit/expense/config/Constants.java (1)
  • Constants (12-161)

coderabbitai[bot]
coderabbitai bot previously approved these changes May 22, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c4b9ca2 and 43e794d.

📒 Files selected for processing (1)
  • backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (2)
Learnt from: holashchand
PR: egovernments/DIGIT-Works#1916
File: backend/expense/src/main/java/org/egov/digit/expense/repository/BillRepository.java:42-47
Timestamp: 2025-05-22T10:39:15.595Z
Learning: In the DIGIT-Works project's expense service, tenant ID validation is performed upstream before reaching the repository layer, so null checks on tenant ID in the repository methods are not necessary.
Learnt from: holashchand
PR: egovernments/DIGIT-Works#1916
File: backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java:45-49
Timestamp: 2025-05-22T10:39:45.956Z
Learning: In the DIGIT-Works application, tenant ID validation occurs at a higher level (controller/API layer) before requests reach the service/repository layer, so null checks for tenant ID in repositories like PaymentRepository are unnecessary.
🔇 Additional comments (4)
backend/expense/src/main/java/org/egov/digit/expense/repository/PaymentRepository.java (4)

8-9: LGTM!

The imports are correctly added to support multi-tenant schema resolution functionality.

Also applies to: 14-14, 19-20


30-31: LGTM!

The field declaration follows the established pattern and is properly encapsulated.


44-50: LGTM!

The schema replacement implementation is correct with proper error handling. The approach is consistent with the application's architecture where tenant validation occurs upstream.


56-61: LGTM!

The schema replacement implementation in the count method is consistent with the search method and follows the same error handling pattern.

Sreejit-K
Sreejit-K previously approved these changes May 28, 2025
@sonarqubecloud
Copy link

@holashchand
Copy link
Collaborator Author

closing as already merged in another pr 1935

@holashchand holashchand deleted the HCMPRE-2739-expense branch June 30, 2025 09:47
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.

3 participants