Skip to content

Conversation

@nevil-mathew
Copy link
Collaborator

@nevil-mathew nevil-mathew commented Jul 31, 2025

Summary by CodeRabbit

  • New Features

    • Added support for organization codes in entity and entity type management, allowing more flexible organization identification.
    • Enhanced validation for entity queries, requiring either an ID or both value and entity type ID.
  • Bug Fixes

    • Improved data integrity by enforcing stricter validation and unique constraints on entities and entity types.
    • Updated localization message to clarify restrictions for users from the default organization.
  • Refactor

    • Shifted from organization ID to organization code throughout the platform for more consistent organization handling.
    • Streamlined entity and entity type service and controller logic to align with new organization code usage.
    • Updated password verification to use asynchronous comparison for improved performance and security.
    • Improved error logging and internal method calls for better maintainability.
    • Modified default organization handling to use dynamic organization codes instead of static environment variables.
  • Database

    • Added new columns and constraints to support organization codes and ensure referential integrity.
    • Updated database indexes and foreign key relationships for improved data consistency.
  • Validation

    • Restricted allowed model names for entity types to 'User' only.
    • Improved query parameter validation for entity endpoints.

@coderabbitai
Copy link

coderabbitai bot commented Jul 31, 2025

Walkthrough

The changes refactor the codebase to shift from using organization IDs to organization codes for identifying organizations across controllers, services, database models, queries, and migrations. This includes updating method signatures, query filters, associations, and validation logic. Database migrations add and enforce new organization code fields and constraints, while validation rules are updated for stricter parameter requirements.

Changes

Cohort / File(s) Change Summary
Controllers: Organization Code Refactor
src/controllers/v1/entity-type.js, src/controllers/v1/entity.js, src/controllers/v1/user.js, src/controllers/v1/org-admin.js
Controller methods updated to pass organization_code (and tenant_code) instead of organization_id or user-centric identifiers to service methods. Argument order and presence adjusted. Asynchronous calls and additional parameters added in org-admin controller.
Database Migrations: Organization Code & Constraints
src/database/migrations/20250717071710-add-organization-code-to-entities-and-entity-types.js, src/database/migrations/20250723183753-add-entity-types-constraints.js
Migrations add organization_code columns, backfill and enforce non-null constraints, update unique indexes, and add composite foreign key and unique constraints between entities and entity_types. Down migrations reverse these changes.
Database Models: Organization Code & Associations
src/database/models/entities.js, src/database/models/entityType.js
Models updated to add required organization_code fields, remove organization_id as primary key, adjust associations, and update primary key composition for tenant_code.
Database Queries: Organization Code Filtering
src/database/queries/entities.js, src/database/queries/entityType.js
Query methods refactored to use organization_code and tenant_code for filtering, updating, and deleting. Method signatures and implementation updated. Joins and associations leveraged for optimized queries.
Services: Organization Code Propagation & Logic Updates
src/services/account.js, src/services/entities.js, src/services/entityType.js, src/services/tenant.js, src/services/user.js, src/services/org-admin.js
Service methods updated to propagate organization_code throughout entity and entity type operations. Method signatures, query calls, and filtering logic refactored. Password verification made asynchronous in account service. Org-admin service logic updated to use organization codes and improved error handling.
Validators: Parameter and Value Restrictions
src/validators/v1/entity-type.js, src/validators/v1/entity.js
Validation logic updated: entity-type now only allows 'User' as a model name; entity validator enforces presence of either id or both value and entity_type_id, and adds stricter parameter checks.
Localization
src/locales/en.json
Updated message for key USER_IS_FROM_DEFAULT_ORG to a more explicit user-facing string.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller
    participant Service
    participant Query
    participant DB

    Client->>Controller: Request (with decodedToken.organization_code)
    Controller->>Service: Method call (organization_code, tenant_code, ...)
    Service->>Query: Query (organization_code, tenant_code, ...)
    Query->>DB: SQL (filter by organization_code, tenant_code)
    DB-->>Query: Result
    Query-->>Service: Data
    Service-->>Controller: Response data
    Controller-->>Client: API Response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

In fields of code where queries hop,
The rabbits swapped IDs for codes non-stop.
With migrations and models all in a row,
Constraints and keys now properly flow.
Validators stricter, services neat—
Our patch is complete, a carrot-sweet treat!
🥕🐇

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 b7d11d5 and c5a8d3f.

📒 Files selected for processing (1)
  • src/database/migrations/20250723183753-add-entity-types-constraints.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/database/migrations/20250723183753-add-entity-types-constraints.js
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/verify-entity-type-flow

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

@coderabbitai coderabbitai bot changed the title @coderabbitai Refactor codebase to use organization codes instead of organization IDs Jul 31, 2025
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: 7

🔭 Outside diff range comments (3)
src/database/queries/entityType.js (2)

36-36: Incorrect error handling - should throw instead of return.

The error is being returned instead of thrown, which breaks the error handling pattern used throughout the class.

Apply this diff:

-return error
+throw error

156-157: Incorrect error handling pattern in findAllEntityTypesAndEntities.

Similar to other methods, errors should be thrown instead of returned.

Apply this diff:

-return error
+throw error
src/services/entityType.js (1)

83-89: Fix incorrect error message for UniqueConstraintError.

The error message "ENTITY_TYPE_ALREADY_DELETED" doesn't make sense for a UniqueConstraintError during an update operation. This should indicate a duplicate value issue.

 		} catch (error) {
 			if (error instanceof UniqueConstraintError) {
 				return responses.failureResponse({
-					message: 'ENTITY_TYPE_ALREADY_DELETED',
+					message: 'ENTITY_TYPE_ALREADY_EXISTS',
 					statusCode: httpStatusCode.bad_request,
 					responseCode: 'CLIENT_ERROR',
 				})
 			}
♻️ Duplicate comments (1)
src/services/user.js (1)

466-466: Consistent pattern with removeDefaultOrgEntityTypes.

Similar to the read method, this call to removeDefaultOrgEntityTypes uses organization ID while the rest of the method uses organization codes, indicating the utility function may require organization ID.

🧹 Nitpick comments (7)
src/database/migrations/20250717071710-add-organization-code-to-entities-and-entity-types.js (3)

75-75: Remove console.log statements from production migration.

Console logging in database migrations can clutter production logs and may not be captured properly in all deployment environments.

Consider removing these console.log statements or replacing them with proper migration logging if your framework supports it.

Also applies to: 117-117, 120-120


98-99: Clarify the strategy for removing organization_id column.

The removal of organization_id from entity_types table is commented out, which suggests a phased migration approach. This should be documented or tracked.

Would you like me to create a follow-up issue to track the completion of this migration by uncommenting and executing the organization_id removal in a future release?


184-184: Inconsistent error message format in rollback.

The error message uses err.message while the up migration uses the full err object.

Apply this diff for consistency:

-console.error('❌ Migration rollback failed:', err.message)
+console.error('❌ Migration rollback failed:', err)
src/database/queries/entityType.js (1)

161-174: Inconsistent module export pattern.

The file uses a class-based export pattern but then adds a standalone function export at line 161. This mixing of patterns can be confusing.

Consider moving the hardDelete function inside the class as a static method for consistency:

-exports.hardDelete = async (id) => {
+static async hardDelete(id) {
 	try {
 		await EntityType.destroy({
 			where: {
 				id,
 			},
 			force: true,
 		})
 		return { success: true }
 	} catch (error) {
 		console.error(error)
-		return error
+		throw error
 	}
 }
src/services/account.js (1)

637-637: Remove console.log statements.

Multiple console.log statements are present throughout the file which should be replaced with proper logging mechanism.

Replace console.log with a proper logger:

-console.log(error)
+logger.error('Error in [method_name]:', error)

Also applies to: 823-823, 1100-1100, 1520-1520, 1672-1672, 1819-1819, 1910-1910, 2009-2009

src/services/entityType.js (2)

20-25: Add parameter validation for organization identifiers.

The method correctly incorporates both organizationCode and organizationId parameters, but consider adding validation to ensure these parameters are provided and valid before setting them on bodyData.

 static async create(bodyData, id, organizationCode, organizationId, tenantCode) {
+	if (!organizationCode || !organizationId || !tenantCode) {
+		throw new Error('Missing required organization or tenant identifiers')
+	}
 	bodyData.created_by = id
 	bodyData.updated_by = id
 	bodyData.organization_code = organizationCode
 	bodyData.organization_id = organizationId
 	bodyData.tenant_code = tenantCode

56-56: Improve readability by avoiding comma operator.

The comma operator usage makes the code less readable. Consider using separate statements for clarity.

-	;(bodyData.updated_by = loggedInUserId), (bodyData.organization_code = organizationCode)
+	bodyData.updated_by = loggedInUserId
+	bodyData.organization_code = organizationCode
📜 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 7378387.

📒 Files selected for processing (16)
  • src/controllers/v1/entity-type.js (4 hunks)
  • src/controllers/v1/entity.js (4 hunks)
  • src/controllers/v1/user.js (2 hunks)
  • src/database/migrations/20250717071710-add-organization-code-to-entities-and-entity-types.js (1 hunks)
  • src/database/migrations/20250723183753-add-entity-types-constraints.js (1 hunks)
  • src/database/models/entities.js (1 hunks)
  • src/database/models/entityType.js (2 hunks)
  • src/database/queries/entities.js (4 hunks)
  • src/database/queries/entityType.js (4 hunks)
  • src/services/account.js (4 hunks)
  • src/services/entities.js (7 hunks)
  • src/services/entityType.js (5 hunks)
  • src/services/tenant.js (3 hunks)
  • src/services/user.js (6 hunks)
  • src/validators/v1/entity-type.js (1 hunks)
  • src/validators/v1/entity.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
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/user.js
  • src/controllers/v1/entity-type.js
  • src/controllers/v1/entity.js
src/validators/**

⚙️ CodeRabbit Configuration File

Validate all incoming data thoroughly. Check for missing or incomplete validation rules.

Files:

  • src/validators/v1/entity.js
  • src/validators/v1/entity-type.js
src/services/**

⚙️ CodeRabbit Configuration File

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

Files:

  • src/services/tenant.js
  • src/services/user.js
  • src/services/account.js
  • src/services/entityType.js
  • src/services/entities.js
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/entities.js
  • src/database/queries/entityType.js
🧬 Code Graph Analysis (5)
src/database/models/entityType.js (2)
src/database/queries/entities.js (1)
  • EntityType (3-3)
src/database/queries/entityType.js (1)
  • EntityType (1-1)
src/services/tenant.js (6)
src/services/user.js (5)
  • defaultOrganizationCode (61-61)
  • defaultOrganizationCode (349-349)
  • defaultOrganizationCode (454-454)
  • defaultOrganizationCode (533-533)
  • entityTypeQueries (15-15)
src/services/account.js (3)
  • defaultOrganizationCode (351-351)
  • defaultOrganizationCode (1478-1478)
  • entityTypeQueries (24-24)
src/services/org-admin.js (2)
  • defaultOrgId (477-480)
  • entityTypeQueries (19-19)
src/services/entityType.js (2)
  • entityTypeQueries (4-4)
  • entityType (27-27)
src/services/public.js (1)
  • entityTypeQueries (8-8)
src/controllers/v1/entity-type.js (1)
  • entityTypeService (2-2)
src/database/queries/entities.js (3)
src/database/models/entityType.js (1)
  • EntityType (3-42)
src/database/queries/entityType.js (2)
  • EntityType (1-1)
  • Entity (2-2)
src/database/models/entities.js (1)
  • Entity (3-29)
src/services/account.js (3)
src/services/user.js (18)
  • userQueries (11-11)
  • defaultOrganizationCode (61-61)
  • defaultOrganizationCode (349-349)
  • defaultOrganizationCode (454-454)
  • defaultOrganizationCode (533-533)
  • validationData (71-71)
  • validationData (353-360)
  • validationData (458-465)
  • entityTypeQueries (15-15)
  • user (48-51)
  • user (319-319)
  • user (440-440)
  • user (490-490)
  • user (525-525)
  • prunedEntities (72-72)
  • prunedEntities (361-361)
  • prunedEntities (466-466)
  • prunedEntities (544-544)
src/generics/utils.js (2)
  • bcryptJs (8-8)
  • removeDefaultOrgEntityTypes (835-842)
src/database/queries/users.js (1)
  • user (224-269)
src/services/entities.js (5)
src/database/queries/entities.js (1)
  • require (2-2)
src/services/entityType.js (11)
  • require (5-5)
  • require (7-7)
  • require (8-8)
  • entityTypeQueries (4-4)
  • responses (9-9)
  • updateCount (58-67)
  • filter (127-134)
  • entities (98-104)
  • entities (136-136)
  • deleteCount (161-161)
  • attributes (96-96)
src/helpers/responses.js (1)
  • error (28-28)
src/controllers/v1/entity.js (2)
  • updatedEntity (44-50)
  • updatedEntity (85-89)
src/database/queries/entityType.js (1)
  • entities (141-145)
🔇 Additional comments (39)
src/controllers/v1/user.js (1)

27-27: LGTM! Clean refactoring from organization_id to organization_code.

The changes consistently update token property access to use organization_code instead of organization_id while maintaining the same authentication pattern and service method signatures.

Also applies to: 121-121

src/validators/v1/entity-type.js (1)

38-38: Verify impact of restricting model_names to only 'User'

The validator in src/validators/v1/entity-type.js now only permits model_names = ['User'] (create at line 38; update at line 75). Our code search did not uncover any references to the previously allowed values (Session, MentorExtension, UserExtension) in entity-type logic or migrations.

• src/validators/v1/entity-type.js – line 38 (create)
• src/validators/v1/entity-type.js – line 75 (update)

Please confirm:

  • No existing entity_types records in the database use any other model_names.
  • No external services or integrations rely on the old values.
src/database/models/entities.js (2)

21-24: LGTM! Proper addition of organization_code field.

The new organization_code field is correctly defined as a required string, aligning with the PR's objective to shift from organization IDs to organization codes.


31-40: Good association improvements.

The uncommented association method properly defines the relationship with explicit targetKey: 'id' and includes a scope to filter out deleted records, which is a best practice for maintaining data integrity.

src/validators/v1/entity.js (2)

78-78: Good fix for validation chain order.

Moving .trim() after .optional() prevents potential errors when the field is undefined, which is the correct validation chain order.

Also applies to: 86-86


92-110: Excellent addition of entity_type_id validation and custom logic.

The new validation for entity_type_id includes proper trimming, emptiness, and numeric checks. The custom validator ensuring either id OR (value + entity_type_id) is provided adds robust input validation that prevents invalid parameter combinations.

src/database/models/entityType.js (1)

43-51: Good association implementation.

The hasMany association with Entity is properly scoped to exclude deleted records, which maintains data integrity and follows best practices.

src/services/tenant.js (5)

145-145: Good improvement: Dynamic organization code extraction.

Extracting the organization code from the creation response ensures consistency between the created organization and subsequent operations, replacing the previous reliance on static environment variables.


152-154: Consistent usage of dynamic organization code.

The update to use defaultOrganizationCode in the findAllEntityTypes call is consistent with the broader refactor from static environment variables to dynamic organization codes.


161-161: Correct implementation of organization code parameter.

The usage of defaultOrganizationCode in the readUserEntityTypes call follows the established pattern of using dynamic organization codes instead of static environment variables.


189-189: Proper organization code parameter usage.

The entityTypeService.create call correctly uses the dynamic defaultOrganizationCode parameter, maintaining consistency with the broader refactor.


221-227: Correct multi-tenant parameter usage.

The EntityHelper.create call properly includes both defaultOrganizationCode and tenantCode parameters, aligning with the multi-tenant architecture and the organization code refactor.

src/controllers/v1/entity-type.js (3)

15-21: Correct organization code parameter usage.

The create method correctly uses req.decodedToken.organization_code and maintains both organization code and ID parameters for backward compatibility during the transition period.


37-43: Clean organization code implementation.

The update method cleanly uses req.decodedToken.organization_code without the legacy organization_id parameter, indicating a complete migration to organization codes for this operation.


85-91: Clean and simplified delete method.

The delete method correctly uses req.decodedToken.organization_code with a simplified parameter set, demonstrating a complete migration to organization codes for delete operations.

src/controllers/v1/entity.js (4)

22-28: Correct implementation of organizational identifiers.

The create method properly uses req.decodedToken.tenant_code and req.decodedToken.organization_code, replacing user-centric identifiers with organizational ones as part of the broader refactor.


44-51: Consistent organizational identifier usage.

The update method correctly implements the organizational identifier pattern with req.decodedToken.organization_code and req.decodedToken.tenant_code parameters.


65-73: Simplified read method with tenant scoping.

The read method uses only req.decodedToken.tenant_code for scoping. Ensure that tenant-level scoping provides sufficient access control for entity read operations.


85-89: Comprehensive organizational scoping for delete operations.

The delete method correctly implements both req.decodedToken.organization_code and req.decodedToken.tenant_code parameters, providing proper multi-level scoping for delete operations.

src/services/user.js (7)

38-38: Correct method signature update.

The method signature properly changes from orgId to orgCode parameter, aligning with the organization code refactor.


65-66: Proper query filter update.

The query filter correctly uses organization_code field with the orgCode parameter, replacing the previous organization_id usage.


349-356: Consistent organization code implementation.

The changes correctly implement organization code usage with proper variable extraction from user.organizations[0].code and updated query filters using organization_code.


454-461: Correct organization code pattern implementation.

The method properly implements the organization code pattern with consistent variable naming and query filter usage.


522-522: Updated method signature for organization code.

The method signature correctly changes to use organizationCode parameter, maintaining consistency with the broader refactor.


538-538: Consistent query filter implementation.

The query filter properly uses organization_code with the organizational identifier pattern.


361-361: Ignore mixed ID/code concern for removeDefaultOrgEntityTypes
The utility’s signature in src/generics/utils.js expects an organization ID (as seen on line 835), while the Sequelize query in src/services/user.js uses the organization code to filter by organization_code. Passing user.organizations[0].id into removeDefaultOrgEntityTypes is therefore correct and consistent with its implementation. No changes required.

Likely an incorrect or invalid review comment.

src/database/queries/entities.js (4)

3-3: Required import for new functionality.

The EntityType import is correctly added to support the new findEntityWithOrgCheck method that includes EntityType associations.


26-32: Correct implementation of organizational scoping.

The updateOneEntity method correctly transitions from user-based filtering to organizational identifiers (organizationCode and tenantCode), providing proper multi-tenant scoping for entity updates.


41-47: Consistent organizational scoping for delete operations.

The deleteOneEntity method follows the same correct pattern as the update method, using organizational identifiers for proper access control and multi-tenant scoping.


94-112: Ignore naming inconsistency warning for findEntityWithOrgCheck

The findEntityWithOrgCheck(id, tenantCode, organizationID) method is correctly using organizationID to filter on the organization_id column in the EntityType model. The codebase still relies on organization_id (numeric ID) in this context, and numerous other queries and the model definition itself use organization_id. No change is required.

Likely an incorrect or invalid review comment.

src/database/migrations/20250717071710-add-organization-code-to-entities-and-entity-types.js (1)

106-114: Verify the unique constraint covers all necessary columns.

The new unique index on entities includes value, entity_type_id, organization_code, and tenant_code. This is a significant change from the previous constraint on just value.

Ensure that:

  1. This constraint aligns with your business logic (allowing duplicate entity values across different organizations/tenants)
  2. Application code is updated to handle potential unique constraint violations with the new composite key
  3. Performance impact of the new index has been considered
src/database/migrations/20250723183753-add-entity-types-constraints.js (1)

43-43: Verify CASCADE delete behavior is intended.

The foreign key constraint uses CASCADE on delete, which means deleting an entity_type will automatically delete all associated entities. This could lead to unintended data loss.

Confirm that:

  1. This cascading delete behavior is intentional and documented
  2. Application code properly handles or prevents entity_type deletions when entities exist
  3. Soft deletes (deleted_at) are preferred over hard deletes in your system
src/database/queries/entityType.js (1)

39-66: Excellent query optimization using Sequelize associations.

The refactoring to use Sequelize's include mechanism with proper LEFT JOIN and tenant isolation is a significant improvement over the previous implementation. The error handling has also been enhanced with specific error messages.

src/services/entities.js (1)

184-216: Good use of pagination in list method.

The list method correctly uses pagination parameters and handles empty results appropriately.

src/services/account.js (2)

351-360: Good implementation of organization code validation and filtering.

The error handling for missing organization codes and the logic for collecting organization codes from user data is well implemented. The use of the default organization code as a fallback is appropriate.

Also applies to: 786-799


357-364: Consistent and correct implementation of entity type filtering.

The entity type queries consistently use organization codes with the Op.in operator, properly including both user-specific and default organization codes. This ensures users have access to both their organization-specific and system-wide entity types.

Also applies to: 789-796, 1481-1488

src/services/entityType.js (3)

94-122: LGTM! Well-structured organization code migration.

The method correctly handles the transition by:

  • Querying both default and specific organization codes
  • Using organizationId for the pruning logic (maintaining backward compatibility)
  • Properly handling empty result sets

The implementation maintains functionality while supporting the new organization code structure.


124-150: Excellent multi-tenant isolation and error handling improvements.

The updates demonstrate good practices:

  • Added tenant_code filtering for proper tenant isolation
  • Clear comments explaining the deduplication logic
  • Enhanced error logging for better debuggability
  • Proper use of Sequelize Op.in for organization code filtering

The method correctly handles the migration while maintaining security through tenant isolation.


159-177: LGTM! Clean and straightforward organization code integration.

The delete method properly incorporates the organizationCode parameter and passes it to the query layer. The error handling remains appropriate for the not found scenario.

@nevil-mathew
Copy link
Collaborator Author

@coderabbitai help

@coderabbitai

This comment was marked as resolved.

@nevil-mathew nevil-mathew merged commit 21c0aa2 into develop Aug 1, 2025
1 of 2 checks passed
@nevil-mathew
Copy link
Collaborator Author

@coderabbitai Can you help me to generate the changelog that I can share with QA for this PR ?

@coderabbitai
Copy link

coderabbitai bot commented Aug 1, 2025

Tip

For best results, initiate chat on the files or code changes.

@nevil-mathew: I'll generate a comprehensive changelog for QA testing based on the changes in this PR. Let me organize this by the types of changes that impact testing:

Changelog for PR #776: Refactor Organization IDs to Organization Codes

🔄 API Parameter Changes

Impact: All API endpoints now use organization_code instead of organization_id

Controllers Updated:

  • Entity Type Controller (/src/controllers/v1/entity-type.js)

    • All methods now use req.decodedToken.organization_code instead of organization_id
    • Methods affected: create, update, read, delete
  • Entity Controller (/src/controllers/v1/entity.js)

    • create: Now includes organization_code as additional parameter
    • update: Uses organization_code and tenant_code instead of roles
    • read: Uses tenant_code instead of user id, removed fallback to readAll
    • delete: Now takes organization_code and tenant_code
  • User Controller (/src/controllers/v1/user.js)

    • update and setLanguagePreference: Now use organization_code
  • Org Admin Controller (/src/controllers/v1/org-admin.js)

    • inheritEntityType: Now includes organization_code parameter

🗄️ Database Schema Changes

Impact: New columns added, constraints updated

New Migrations:

  1. 20250717071710-add-organization-code-to-entities-and-entity-types.js

    • Adds organization_code column to entities and entity_types tables
    • Backfills data from existing organization_id references
    • Updates unique constraints on entities table
    • ⚠️ Breaking: Old unique index removed, new composite unique index created
  2. 20250723183753-add-entity-types-constraints.js

    • Adds foreign key constraints between entities and entity_types
    • Creates partial unique index on entity_types
    • ⚠️ Breaking: Enforces referential integrity

Model Changes:

  • EntityType Model:
    • organization_id no longer primary key
    • tenant_code now primary key
    • New required field: organization_code
  • Entity Model:
    • New required field: organization_code
    • Updated associations with EntityType

🔧 Validation Changes

Impact: Request validation updated

  • Entity Type Validator: model_names now restricted to only 'User' (previously allowed ['Session', 'MentorExtension', 'UserExtension'])
  • Entity Validator: New optional parameter entity_type_id in read operations with custom validation logic

🏢 Business Logic Changes

Impact: Organization handling and entity inheritance

  • Account Service:

    • User creation now uses organization codes directly
    • Password verification changed to async
    • Entity type filtering uses organization codes
  • Entity/EntityType Services:

    • All CRUD operations now scope by organization code + tenant code
    • Inheritance logic updated for organization codes
    • ⚠️ Breaking: Method signatures changed across service layer
  • Org Admin Service:

    • Entity type inheritance now prevents default org users
    • Uses organization codes for inheritance logic

📝 User-Facing Changes

  • Error Message: Updated "User is from default org" to "Users from the default organization are not permitted to proceed with this action"

🧪 QA Testing Focus Areas

High Priority Testing:

  1. Entity CRUD Operations: Verify all create, read, update, delete operations work with new organization code logic
  2. Entity Type Management: Test entity type inheritance, especially restrictions for default organization users
  3. User Authentication: Verify login/registration flows with new organization code handling
  4. Data Integrity: Confirm entities and entity types are properly scoped to organization codes
  5. Migration Verification: Ensure existing data was properly migrated to use organization codes

API Testing:

  • Test all endpoints that previously used organization_id now work with organization_code
  • Verify proper error handling for invalid organization codes
  • Test entity validation with new entity_type_id parameter requirements

Edge Cases:

  • Default organization user restrictions in inheritEntityType
  • Entity lookups with both id and value/entity_type_id combinations
  • Constraint enforcement on duplicate entity types per organization

Regression Testing:

  • User profile operations
  • Language preference settings
  • Entity filtering and search functionality
  • Organization-specific data isolation

This refactoring maintains the same business functionality while changing the underlying organization identification system from numeric IDs to string codes.


🧠 Learnings used
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.

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