Skip to content

Conversation

@rakeshSgr
Copy link
Collaborator

@rakeshSgr rakeshSgr commented Sep 3, 2025

Summary by CodeRabbit

  • New Features
    • Role change events now include tenant and organization context, providing clearer visibility for multi-tenant environments.
    • Audit logs and downstream integrations reflect these additional details, improving traceability of role updates.
    • Admins reviewing user access changes will see richer context, aiding faster troubleshooting and compliance reporting.
    • No user action required; existing workflows continue to function with enhanced contextual information.

@coderabbitai
Copy link

coderabbitai bot commented Sep 3, 2025

Walkthrough

The roleChange event payload in src/services/org-admin.js’s updateRoleForApprovedRequest now includes tenant_code and organization_code in addition to user_id, new_roles, and current_roles. Function signatures and control flow remain unchanged.

Changes

Cohort / File(s) Summary of changes
Role change event payload augmentation
src/services/org-admin.js
Extended roleChange event payload to include tenant_code and organization_code; no changes to function signatures or control flow.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant AdminService as Org Admin Service
  participant EventBus as Event Bus
  participant Consumers as Downstream Consumers

  AdminService->>AdminService: updateRoleForApprovedRequest(...)
  note over AdminService: Compute user_id, current_roles, new_roles
  AdminService-->>EventBus: Emit roleChange { user_id, current_roles, new_roles, tenant_code, organization_code }
  note right of EventBus: New fields: tenant_code, organization_code
  EventBus-->>Consumers: Dispatch roleChange payload
  Consumers->>Consumers: Handle with tenant/org context
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

  • updating orgCode #804: Adjusts organization identifier handling in org-admin.js, aligning with the addition of tenant_code and organization_code in roleChange payloads.
  • feat: add tenant code to role apis #786: Introduces tenant_code across role APIs/services, consistent with adding tenant context to roleChange events.

Poem

A rabbit taps the event drum—thump, thump, thump!
New fields hop in: tenant, org—bumpity bump!
Roles reshuffled, context clear,
Downstream listeners prick an ear.
With tidy paws, we ship this change—
A brighter trail across the range. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch updateRoleFix

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

@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: 0

Caution

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

⚠️ Outside diff range comments (7)
src/services/org-admin.js (7)

325-333: Fix potential TypeError when request not found.

requestDetail may be null; accessing requestDetail.status will throw.

Apply:

       const requestDetail = await orgRoleReqQueries.requestDetails({
         id: requestId,
         organization_id: tokenInformation.organization_id,
         tenant_code: tokenInformation.tenant_code,
       })

-      if (requestDetail.status !== common.REQUESTED_STATUS) {
+      if (!requestDetail) {
+        return responses.failureResponse({
+          message: 'REQUEST_NOT_FOUND',
+          statusCode: httpStatusCode.bad_request,
+          responseCode: 'CLIENT_ERROR',
+        })
+      }
+
+      if (requestDetail.status !== common.REQUESTED_STATUS) {

282-286: Prevent tenant/org scoping override via filters.

Merging arbitrary filters can let callers override tenant_code/organization_id, risking data leakage.

Apply:

-      if (params.body?.filters) {
-        for (const [key, value] of Object.entries(params.body.filters)) {
-          filterQuery[key] = value
-        }
-      }
+      if (params.body?.filters) {
+        const disallowed = new Set(['tenant_code', 'organization_id'])
+        for (const [key, value] of Object.entries(params.body.filters)) {
+          if (!disallowed.has(key)) filterQuery[key] = value
+        }
+      }

662-665: Promise never settles on error; use reject.

In catch, returning error leaves the Promise pending and hangs callers awaiting it.

Apply:

-      console.log(error, 'error')
-      return error
+      console.log(error, 'error')
+      return reject(error)

687-687: Fix email template variable: pass domain string, not object.

portalURL currently receives the entire tenantDomain object.

Apply:

-            portalURL: tenantDomain,
+            portalURL: tenantDomain?.domain || '',

166-166: Retry attempts logic is inverted.

1 || common.NO_OF_ATTEMPTS always yields 1, disabling configured retries.

Apply:

-          attempts: 1 || common.NO_OF_ATTEMPTS,
+          attempts: common.NO_OF_ATTEMPTS || 1,

595-603: Guard against empty/invalid role assignments.

findAll returns an array; falsy check won’t catch empty arrays and can wipe roles.

Apply:

-        if (!getRoleIds) {
+        if (!getRoleIds?.length) {
           return responses.failureResponse({
             message: 'INVALID_ROLE_ASSIGNMENTS',
             statusCode: httpStatusCode.bad_request,
             responseCode: 'CLIENT_ERROR',
           })
         }

333-333: Correct typo in error code key
Replace the misspelled INAVLID_ORG_ROLE_REQ with INVALID_ORG_ROLE_REQ in both locations to ensure the lookup remains consistent:

  • src/services/org-admin.js (line 333)
  • locales/en.json (line 118)
🧹 Nitpick comments (2)
src/services/org-admin.js (2)

631-667: Optional: simplify updateRoleForApprovedRequest to async function.

Avoid the manual new Promise anti-pattern; let async/await handle it.

I can provide a clean refactor if you want it in this PR.


456-456: Remove debug log.

console.log(rowsAffected, updatedUsers) is noisy in production.

Consider removing or guarding behind a debug flag.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7b7e749 and 029dbb2.

📒 Files selected for processing (1)
  • src/services/org-admin.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/services/**

⚙️ CodeRabbit configuration file

This is core business logic. Please check for correctness, efficiency, and potential edge cases.

Files:

  • src/services/org-admin.js
🧠 Learnings (1)
📓 Common learnings
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/services/entities.js:18-23
Timestamp: 2025-07-31T08:44:36.982Z
Learning: In the ELEVATE-Project/user codebase, organizationCode and tenantCode parameters passed to service methods always come from req.decodedToken.organization_code and req.decodedToken.tenant_code, which are guaranteed to be present after token validation. Additional validation for these parameters in service methods is unnecessary as the token validation process ensures they are always available.
🧬 Code graph analysis (1)
src/services/org-admin.js (3)
src/controllers/v1/organization.js (2)
  • tenantCode (214-214)
  • tenantCode (259-259)
src/controllers/v1/public.js (1)
  • tenantCode (7-7)
src/helpers/userInvite.js (1)
  • orgCode (1053-1061)
🔇 Additional comments (1)
src/services/org-admin.js (1)

646-654: Unify roleChange payload and verify consumer handling

  • src/services/org-admin.js now emits tenant_code/organization_code, but src/services/userInvite.js and src/helpers/userInvite.js still use organization_id; align all producers.
  • Confirm downstream consumers ignore or correctly process the new tenant_code and organization_code fields.

@rakeshSgr rakeshSgr merged commit 8aee6ee into develop Sep 3, 2025
1 of 2 checks passed
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