Skip to content

Conversation

@adithyadinesh0412
Copy link
Collaborator

@adithyadinesh0412 adithyadinesh0412 commented Aug 1, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a script to clean up all data related to a specified organization code and tenant code, featuring confirmation prompts and detailed reporting of deleted records.
  • Chores

    • Updated database migration to handle an additional foreign key constraint for organization user invites.

@coderabbitai
Copy link

coderabbitai bot commented Aug 1, 2025

Walkthrough

This change updates a migration script to handle an additional foreign key constraint on the organization_user_invites table, ensuring it is disabled and re-enabled during migrations. Additionally, a new standalone Node.js script is introduced to clean up all data associated with a specified organization code and tenant code across multiple PostgreSQL tables, with interactive prompts and transaction management.

Changes

Cohort / File(s) Change Summary
Migration: Additional Foreign Key Handling
src/database/migrations/20250729064710-org-code-fix.js
Modifies the migration script to include disabling and later re-enabling the fk_org_user_invites_org_code foreign key constraint on the organization_user_invites table, following the existing pattern for other foreign keys. No other logic or control flow changes.
Script: Organization Data Cleanup
src/scripts/deleted-org-data-clean-up/clean.js
Introduces a standalone Node.js script that prompts for an organization code and tenant code, summarizes related data across multiple tables, and upon confirmation, deletes all associated data in a transactionally safe order. Uses Sequelize for DB access, cli-table for output, and includes user prompts, error handling, and detailed logging of deletions. No exported entities; script is intended to be run directly.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Script
    participant PostgreSQL

    User->>Script: Start script
    Script->>User: Prompt for organization code and tenant code
    User->>Script: Enter organization code and tenant code
    Script->>PostgreSQL: Query counts of related data across multiple tables
    PostgreSQL-->>Script: Return counts
    Script->>User: Display summary table
    Script->>User: Prompt for deletion confirmation
    User->>Script: Confirm deletion
    Script->>PostgreSQL: Begin transaction
    Script->>PostgreSQL: Delete user organization roles
    Script->>PostgreSQL: Delete user organizations (capture user IDs)
    Script->>PostgreSQL: Delete orphaned users
    Script->>PostgreSQL: Delete organization
    Script->>PostgreSQL: Delete invites, templates, features, registration codes
    Script->>PostgreSQL: Commit transaction
    Script->>User: Log deleted rows and completion
    Script->>PostgreSQL: Close connection
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35 minutes

Possibly related PRs

  • fix organization code #768: Adds foreign key constraint handling logic in migration scripts for organization code fixes, similar to the changes made in the current migration script.

Poem

A bunny with whiskers, so clever and neat,
Hopped through the code with nimble feet.
With foreign keys tamed and data made clean,
Orgs can vanish, like they've never been seen!
"Hop, hop!" says the rabbit, "your database is bright,
Safe, tidy, and ready for flight!"
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 52b1cfd and 7a3d85d.

📒 Files selected for processing (1)
  • src/scripts/deleted-org-data-clean-up/clean.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/scripts/deleted-org-data-clean-up/clean.js
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Support

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

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 generate unit tests to generate unit tests for 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

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

🔭 Outside diff range comments (1)
src/database/migrations/20250729064710-org-code-fix.js (1)

53-62: Missing fk_retainer.push() call for the first constraint.

The code disables the foreign key constraint fk_org_user_invites_organization_id but doesn't add the enable query to fk_retainer array. This means the constraint won't be re-enabled after the migration completes, potentially leaving the database in an inconsistent state.

Add the missing line after line 62:

 await queryInterface.sequelize.query(disableFK(table, fk_name), {
   type: Sequelize.QueryTypes.RAW,
   raw: true,
   transaction,
 })
+fk_retainer.push(enableFK(table, fk_name, fkey, refTable, refKey))
🧹 Nitpick comments (3)
src/scripts/deleted-org-data-clean-up/clean.js (3)

244-244: Remove commented code.

The commented await t.commit() is unnecessary as Sequelize automatically commits the transaction when the callback completes successfully.

-				// await t.commit();

252-252: Enhance error logging for better debugging.

Consider logging the full error stack trace for easier debugging.

-		console.error(`Error executing transaction: ${error}`)
+		console.error('Error executing transaction:', error)

149-151: Consider adding a dry-run mode for safety.

A dry-run option would allow users to see what would be deleted without actually performing the deletion.

Would you like me to help implement a dry-run mode that shows what data would be deleted without executing the actual deletions?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5596b7a and 7f101d7.

📒 Files selected for processing (2)
  • src/database/migrations/20250729064710-org-code-fix.js (1 hunks)
  • src/scripts/deleted-org-data-clean-up/clean.js (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/database/models/entityType.js:38-38
Timestamp: 2025-07-31T08:43:35.971Z
Learning: The migration for converting tenant_code to a primary key in the EntityType model was already handled in a previous PR, not in the current refactoring PR that focuses on organization codes instead of organization IDs.
📚 Learning: the migration for converting tenant_code to a primary key in the entitytype model was already handle...
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/database/models/entityType.js:38-38
Timestamp: 2025-07-31T08:43:35.971Z
Learning: The migration for converting tenant_code to a primary key in the EntityType model was already handled in a previous PR, not in the current refactoring PR that focuses on organization codes instead of organization IDs.

Applied to files:

  • src/database/migrations/20250729064710-org-code-fix.js
🔇 Additional comments (1)
src/database/migrations/20250729064710-org-code-fix.js (1)

63-73: LGTM! Proper handling of the second foreign key constraint.

The added code correctly handles the fk_org_user_invites_org_code constraint by disabling it before updates and scheduling its re-enabling through the fk_retainer array.

@coderabbitai
Copy link

coderabbitai bot commented Aug 4, 2025

✅ Actions performed

Full review triggered.

@ELEVATE-Project ELEVATE-Project deleted a comment from coderabbitai bot Aug 4, 2025
@nevil-mathew
Copy link
Collaborator

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Aug 4, 2025

✅ Actions performed

Full review triggered.

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: 2

♻️ Duplicate comments (2)
src/scripts/deleted-org-data-clean-up/clean.js (2)

3-3: Fix dotenv configuration path.

The relative path to .env file might not work when the script is executed from different directories.


54-136: Critical SQL injection vulnerability in REPORT_QUERY.

Both organizationCode and tenantCode variables are directly interpolated into the SQL query string, creating SQL injection vulnerabilities. User input must never be directly concatenated into SQL queries.

Use parameterized queries with Sequelize's replacements feature. Replace all string interpolations with named parameters:

-    WHERE organization_code = '${organizationCode}' AND tenant_code = '${tenantCode}'
+    WHERE organization_code = :organizationCode AND tenant_code = :tenantCode

Then update the query execution at line 137:

 const report = await sequelize.query(REPORT_QUERY, {
+    replacements: { organizationCode, tenantCode },
     type: Sequelize.QueryTypes.RAW,
     raw: true,
 })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5596b7a and 52b1cfd.

📒 Files selected for processing (2)
  • src/database/migrations/20250729064710-org-code-fix.js (1 hunks)
  • src/scripts/deleted-org-data-clean-up/clean.js (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/database/models/entityType.js:38-38
Timestamp: 2025-07-31T08:43:35.971Z
Learning: The migration for converting tenant_code to a primary key in the EntityType model was already handled in a previous PR, not in the current refactoring PR that focuses on organization codes instead of organization IDs.
📚 Learning: the migration for converting tenant_code to a primary key in the entitytype model was already handle...
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/database/models/entityType.js:38-38
Timestamp: 2025-07-31T08:43:35.971Z
Learning: The migration for converting tenant_code to a primary key in the EntityType model was already handled in a previous PR, not in the current refactoring PR that focuses on organization codes instead of organization IDs.

Applied to files:

  • src/database/migrations/20250729064710-org-code-fix.js
  • src/scripts/deleted-org-data-clean-up/clean.js
📚 Learning: in the elevate-project/user codebase, organizationcode and tenantcode parameters passed to service m...
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.

Applied to files:

  • src/scripts/deleted-org-data-clean-up/clean.js
🧬 Code Graph Analysis (1)
src/scripts/deleted-org-data-clean-up/clean.js (1)
src/scripts/delete-scripts/delete-transactional-data.js (5)
  • DELETE_USER_ORG_ROLES_QUERY (95-95)
  • DELETE_USER_ORGS_QUERY (104-104)
  • userIdsToDelete (90-90)
  • DELETE_USERS_QUERY (113-113)
  • DELETE_ORGS_QUERY (159-159)
🔇 Additional comments (1)
src/database/migrations/20250729064710-org-code-fix.js (1)

63-73: LGTM! Properly handles additional foreign key constraint.

The implementation correctly follows the established pattern for disabling and re-enabling foreign key constraints. The constraint fk_org_user_invites_org_code is appropriately disabled during the migration and scheduled for re-enabling through the fk_retainer array.

@nevil-mathew nevil-mathew merged commit 31c3b7e into ELEVATE-Project:develop Aug 4, 2025
1 check 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