Skip to content

Conversation

@nevil-mathew
Copy link
Collaborator

@nevil-mathew nevil-mathew commented Aug 12, 2025

Summary by CodeRabbit

  • New Features
    • Organization deactivation now deactivates all associated users and ends their active sessions.
    • Tenant-aware deactivation: supports specifying a tenant for targeted org actions.
    • Response now includes the number of users deactivated.
  • Bug Fixes
    • Clearer errors when the requester lacks admin permissions or when deactivation isn’t possible.
  • Refactor
    • Streamlined deactivation flow for improved reliability and consistency across multi-tenant environments.

@coderabbitai
Copy link

coderabbitai bot commented Aug 12, 2025

Walkthrough

Controller now forwards tenant-id and requester ID to the service when deactivating an organization. Service refactored to deactivate by organizationCode + tenantCode, cascade-deactivate users, remove their sessions, and broadcast end-session events. JSDoc expanded; method signature in service updated accordingly.

Changes

Cohort / File(s) Summary
Controller plumbing update
src/controllers/v1/admin.js
Passes tenant-id from headers to adminService.deactivateOrg(orgCode, tenantCode, userId). Expanded JSDoc; admin check and error handling unchanged.
Service refactor: org deactivation flow
src/services/admin.js
Changes signature to (organizationCode, tenantCode, loggedInUserId). Deactivates org by code+tenant, deactivates users via helper, removes sessions for affected users, broadcasts end-session events, returns result with deactivated_users count, added logging and JSDoc.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Admin as Admin User
  participant Ctrl as Controller (v1/admin)
  participant Svc as AdminService
  participant Org as Org Store
  participant Users as User Helper
  participant Sess as Session Service
  participant Bus as Event Bus

  Admin->>Ctrl: POST /deactivateOrg (orgCode, headers.tenant-id)
  Ctrl->>Svc: deactivateOrg(orgCode, tenantCode, requesterId)
  Svc->>Org: Deactivate organization (orgCode, tenantCode)
  Org-->>Svc: Rows affected
  Svc->>Users: deactivateUserInOrg(orgCode, tenantCode)
  Users-->>Svc: {count, users[]}
  alt users deactivated
    Svc->>Sess: removeSessions(userIds)
    Svc->>Bus: broadcastEndUpcomingSessions(userIds)
  end
  Svc-->>Ctrl: {status: ORG_DEACTIVATED, deactivated_users: count}
  Ctrl-->>Admin: HTTP 200 response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

A hop and a bop through tenant land,
I toggled an org with a gentle hand.
Users snoozed, sessions said goodbye,
Events took wing across the sky.
Thump-thump! my paws in tidy sync—
Deactivate, propagate, then sip a clover drink. 🐇✨

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

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

🧹 Nitpick comments (2)
src/services/admin.js (1)

648-649: Consider including more context in error logs.

While error logging is present, consider including the organizationCode and tenantCode in the error log for better debugging.

-console.error('Error in deactivateOrg:', error)
+console.error('Error in deactivateOrg:', { error, organizationCode, tenantCode, loggedInUserId })
src/controllers/v1/admin.js (1)

157-157: Consider adding validation for the tenant-id header.

While the optional chaining prevents runtime errors, consider validating that the tenant-id header is present before calling the service method, as it's a required parameter.

+if (!req.headers?.['tenant-id']) {
+    throw responses.failureResponse({
+        message: 'TENANT_ID_REQUIRED',
+        statusCode: httpStatusCode.bad_request,
+        responseCode: 'CLIENT_ERROR',
+    })
+}
+
 const result = await adminService.deactivateOrg(
     req.params.id,
     req.headers?.['tenant-id'],
     req.decodedToken.id
 )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3a745fc and 5dad396.

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

⚙️ CodeRabbit Configuration File

These are API controllers. Focus on request/response handling, security (auth middleware usage), and proper status codes.

Files:

  • src/controllers/v1/admin.js
src/services/**

⚙️ CodeRabbit Configuration File

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

Files:

  • src/services/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.
🔇 Additional comments (6)
src/services/admin.js (4)

570-588: Excellent JSDoc documentation!

The comprehensive documentation clearly describes the method's behavior, parameters, return values, and error scenarios. This will greatly help maintainability.


590-591: Method signature updated correctly to support tenant-based operations.

The new signature with organizationCode, tenantCode, and loggedInUserId parameters aligns well with the multi-tenant architecture and provides proper audit tracking.


626-637: Robust cascade deactivation with proper session cleanup.

The implementation correctly handles the cascade deactivation of users, removes their sessions, and broadcasts events for upcoming session termination. This ensures a clean deactivation flow.


613-624: Verified deactivateUserInOrg signature and return structure
The deactivateUserInOrg method is defined in src/database/queries/users.js and returns [rowsAffected, returnUpdatedUsers ? users : []], matching the [userRowsAffected, updatedUsers] tuple expected by the call in src/services/admin.js. No changes required.

src/controllers/v1/admin.js (2)

122-143: Well-documented controller method with clear parameter descriptions.

The JSDoc clearly describes all parameters including the tenant-id header and expected responses. This improves API maintainability.


155-159: Validate route parameter for organization deactivation

Ensure that req.params.id actually carries the organization code (as required by adminService.deactivateOrg) rather than a numeric database ID. The interface-routes config uses /user/v1/admin/deactivateOrg/:id, which by convention suggests an integer ID. Please verify the route-to-controller mapping and either confirm that this param is indeed the code or rename it to :organizationCode for clarity.

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