Skip to content

Related org#794

Closed
praveenKDass wants to merge 4 commits intodevelopfrom
relatedOrg
Closed

Related org#794
praveenKDass wants to merge 4 commits intodevelopfrom
relatedOrg

Conversation

@praveenKDass
Copy link
Collaborator

@praveenKDass praveenKDass commented Aug 12, 2025

Summary by CodeRabbit

  • New Features

    • Organization details can now include related organizations (IDs and codes) where available.
    • Admin views of an organization now surface active registration codes.
  • Chores

    • Improved database setup and seeding scripts with clearer messaging when the database or seed data already exists or creation/seeding encounters issues.

@coderabbitai
Copy link

coderabbitai bot commented Aug 12, 2025

Walkthrough

Adds a self-referential Organization association; augments Organization.findOne query assembly to conditionally include registration codes and related organizations; updates OrganizationsHelper.read to request related org IDs/codes; adjusts npm scripts for DB init and seeding with conditional echo messaging and altered control flow.

Changes

Cohort / File(s) Summary
Model: Organization association
src/database/models/organization.js
Adds self-referential hasMany: Organization.hasMany(models.Organization, { as: 'relatedOrgsDetails', foreignKey: 'id', constraints: false }).
Query: Organization findOne includes
src/database/queries/organization.js
Builds local includes array from options.include; conditionally adds includes for organizationRegistrationCodes (ACTIVE, non-deleted, tenant-scoped) when isAdmin; and relatedOrgsDetails via ANY(Organization.related_orgs) when getRelatedOrgIdAndCode; removes control flags before calling Organization.findOne with nest: true.
Service: OrganizationsHelper.read
src/services/organization.js
Passes { getRelatedOrgIdAndCode: true } to organizationQueries.findOne; adds but comments out mapping of related org details.
Scripts: DB setup and seeding
src/package.json
Changes db:init to "sequelize-cli db:create

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Service as OrganizationsHelper.read
  participant Query as organizationQueries.findOne
  participant ORM as Sequelize Organization
  participant DB

  Client->>Service: read(filter, options)
  Service->>Query: findOne(filter, { ...options, getRelatedOrgIdAndCode: true })
  Query->>Query: Build includes from options.include
  alt options.isAdmin
    Query->>Query: Include organizationRegistrationCodes (ACTIVE, not deleted, tenant_code)
  end
  alt getRelatedOrgIdAndCode
    Query->>Query: Include relatedOrgsDetails via ON id = ANY(Organization.related_orgs)
  end
  Query->>ORM: Organization.findOne({ where: filter, include, nest: true })
  ORM->>DB: SELECT with LEFT JOINs as needed
  DB-->>ORM: Row with nested includes
  ORM-->>Query: Instance
  Query-->>Service: Organization + includes
  Service-->>Client: Response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • nevil-mathew

Poem

A rabbit taps the ORM keys,
Linking orgs like family trees.
Includes hop in, conditions true,
Codes active, related too.
Scripts now chirp when seeds don’t grow—
I twitch my nose and let you know. 🐇✨

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

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ad49496 and cbc1218.

⛔ Files ignored due to path filters (1)
  • README.md is excluded by !**/*.md
📒 Files selected for processing (4)
  • src/database/models/organization.js (1 hunks)
  • src/database/queries/organization.js (1 hunks)
  • src/package.json (1 hunks)
  • src/services/organization.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/database/queries/**

⚙️ CodeRabbit Configuration File

Review database queries for performance. Check for N+1 problems and ensure indexes can be used.

Files:

  • src/database/queries/organization.js
src/services/**

⚙️ CodeRabbit Configuration File

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

Files:

  • src/services/organization.js
🧬 Code Graph Analysis (2)
src/database/models/organization.js (2)
src/database/queries/users.js (1)
  • Organization (3-3)
src/database/queries/tenants.js (1)
  • Organization (3-3)
src/database/queries/organization.js (2)
src/database/models/OrganizationRegistrationCode.js (1)
  • OrganizationRegistrationCode (3-66)
src/database/models/organization.js (1)
  • Organization (3-67)
🔇 Additional comments (8)
src/database/models/organization.js (1)

91-95: Association relatedOrgsDetails is correctly configured; no changes needed

Verified that in src/database/queries/organization.js the include uses

on: sequelize.literal(
  `"relatedOrgsDetails"."id" = ANY("Organization"."related_orgs")`
)

to join the primary key against the integer‐array field. Disabling constraints and specifying foreignKey: 'id' are intentional to support this custom self-referential lookup. No conflicting migrations or other usages were found.

src/package.json (1)

20-20: LGTM!

The fallback echo message for seed failures is properly implemented and will only execute when seeding fails.

src/services/organization.js (1)

413-413: LGTM!

The addition of getRelatedOrgIdAndCode: true option correctly enables the related organization data retrieval feature implemented in the query layer.

src/database/queries/organization.js (5)

55-55: LGTM!

Creating a local copy of the includes array prevents mutation of the original options object, which is a good practice.


56-64: LGTM!

The admin-specific include for registration codes is well-structured with appropriate filtering conditions and uses the correct association alias.


75-76: LGTM!

Properly cleaning up the temporary option flags after processing is good practice to avoid polluting the final query options.


80-80: LGTM!

Using the locally built includes array maintains the intended functionality while avoiding side effects on the original options object.


66-74: Self-association and JOIN condition are correct

The related_orgs column is defined as DataTypes.ARRAY(DataTypes.INTEGER) in both the migration and the model. The self-association

  • uses foreignKey: 'id' and constraints: false to enable a manual ON clause
  • pairs with the query’s on: sequelize.literal('"relatedOrgsDetails"."id" = ANY("Organization"."related_orgs")')

This setup correctly resolves the related organizations by matching each array value to the id of the target rows. No changes are required.

"test:integration": "jest --verbose ./integration-test --config=integrationJest.config.js --runInBand",
"db:init": "sequelize-cli db:create && sequelize-cli db:migrate ",
"db:seed:all": "sequelize-cli db:seed:all"
"db:init": "sequelize-cli db:create || echo 'Database already exists or some issue while creating db, Please check' && sequelize-cli db:migrate ",
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the conditional logic in db:init script.

The current script has incorrect operator precedence. Due to && having higher precedence than ||, migrations will only run when db:create fails, not when it succeeds.

Apply this diff to fix the logic:

-		"db:init": "sequelize-cli db:create || echo 'Database already exists or some issue while creating db, Please check' && sequelize-cli db:migrate ",
+		"db:init": "(sequelize-cli db:create || echo 'Database already exists or some issue while creating db, Please check') && sequelize-cli db:migrate",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"db:init": "sequelize-cli db:create || echo 'Database already exists or some issue while creating db, Please check' && sequelize-cli db:migrate ",
"db:init": "(sequelize-cli db:create || echo 'Database already exists or some issue while creating db, Please check') && sequelize-cli db:migrate",
🤖 Prompt for AI Agents
In src/package.json around line 19, the db:init npm script uses "|| ... &&
sequelize-cli db:migrate" so due to operator precedence migrations only run on
failure; change the script so migrations run regardless by replacing the '&&'
between the echo fallback and the migrate command with a command separator
(e.g., semicolon) or alternatively make the create step always succeed before
migrate (e.g., use '|| true && ...'); update the line accordingly so
sequelize-cli db:migrate is executed whether db:create succeeded or reported an
existing DB.

Comment on lines +423 to +430
// if(organisationDetails.related_orgs && organisationDetails.related_orgs.length >0){
// let orgFilters = {id:{[Op.in]:organisationDetails.related_orgs}}
// const relatedOrgsIdAndCode = await organizationQueries.findAll(orgFilters)
// organisationDetails.relatedOrgsIdAndCode = relatedOrgsIdAndCode.map(eachOrg => ({
// id: eachOrg.id,
// code: eachOrg.code
// }));
// }
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Consider activating the related organizations population logic.

The commented-out block contains logic to populate relatedOrgsIdAndCode from the related_orgs array field. Since the query layer now includes relatedOrgsDetails when getRelatedOrgIdAndCode is true, this logic may be redundant, but it's worth verifying the intended behavior.

Let me check if the query layer's relatedOrgsDetails include provides the same data that this commented code would populate:


🏁 Script executed:

#!/bin/bash
# Description: Verify if the relatedOrgsDetails include in queries provides the same functionality as the commented code

# Check the query implementation for relatedOrgsDetails
rg -A 10 -B 5 "getRelatedOrgIdAndCode"

# Look for any tests that might show expected behavior
fd -e js test | xargs grep -l "relatedOrgs\|related_orgs" | head -3

Length of output: 2752


🏁 Script executed:

#!/bin/bash
# Show context around the commented block in src/services/organization.js
rg -n "related_orgs" -C5 src/services/organization.js

Length of output: 3071


Remove redundant related-orgs population logic

The getRelatedOrgIdAndCode flag in your query already includes a relatedOrgsDetails array (with id and code) on the returned organisationDetails. You can safely delete the commented-out block at lines 423–430 in src/services/organization.js. If the API contract still needs a relatedOrgsIdAndCode field, simply map it from the include:

 const organisationDetails = await organizationQueries.findOne(filter, { getRelatedOrgIdAndCode: true })

-// if(organisationDetails.related_orgs && organisationDetails.related_orgs.length >0){
-//     let orgFilters = {id:{[Op.in]:organisationDetails.related_orgs}}
-//     const relatedOrgsIdAndCode = await organizationQueries.findAll(orgFilters)
-//     organisationDetails.relatedOrgsIdAndCode = relatedOrgsIdAndCode.map(eachOrg => ({
-//         id: eachOrg.id,
-//         code: eachOrg.code
-//       }));
-//}
+// If you still need the old field name, uncomment below:
+// organisationDetails.relatedOrgsIdAndCode = organisationDetails.relatedOrgsDetails

• File: src/services/organization.js
• Remove or replace lines 423–430

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// if(organisationDetails.related_orgs && organisationDetails.related_orgs.length >0){
// let orgFilters = {id:{[Op.in]:organisationDetails.related_orgs}}
// const relatedOrgsIdAndCode = await organizationQueries.findAll(orgFilters)
// organisationDetails.relatedOrgsIdAndCode = relatedOrgsIdAndCode.map(eachOrg => ({
// id: eachOrg.id,
// code: eachOrg.code
// }));
// }
const organisationDetails = await organizationQueries.findOne(filter, { getRelatedOrgIdAndCode: true })
// If you still need the old field name, uncomment below:
// organisationDetails.relatedOrgsIdAndCode = organisationDetails.relatedOrgsDetails
🤖 Prompt for AI Agents
In src/services/organization.js around lines 423 to 430, remove the redundant
commented-out block that manually populated relatedOrgsIdAndCode from
organisationDetails.related_orgs because getRelatedOrgIdAndCode already provides
relatedOrgsDetails; either delete lines 423–430 entirely or, if the API still
requires a relatedOrgsIdAndCode field, add a small mapping from
organisationDetails.relatedOrgsDetails to relatedOrgsIdAndCode (id and code)
instead of the old commented logic.

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.

4 participants