refactor: update organization setup logic and remove subdomain field#144
Conversation
- Modified the `create-organization-action` to include framework handling and organization setup. - Introduced a new task `create-organization` for better organization creation management. - Removed the `subdomain` field from the `Organization` model and added a `setup` boolean field. - Updated environment variables in `env.mjs` to include `REVALIDATION_SECRET`. - Enhanced the onboarding process to check organization setup status. - Refactored various components and actions to improve type safety and organization management.
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThis pull request updates various aspects of the codebase. The development scripts in the package configuration now run multiple processes concurrently. Functionality related to subdomains has been removed in favor of framework-based organization creation, affecting both API actions and schema validations. Several pages now include additional checks and caching related to organization setup. A new revalidation API endpoint has been introduced along with changes to authentication and onboarding flows. Database migrations remove the subdomain column in favor of a new setup flag, and new tasks have been added to handle organization creation and framework setup. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant OnboardingForm
participant API_Server
participant OrgTask
User->>OnboardingForm: Fill & submit organization form
OnboardingForm->>API_Server: Call createOrganization action
API_Server->>OrgTask: Trigger createOrganizationTask
OrgTask-->>API_Server: Return runId & publicAccessToken
API_Server-->>OnboardingForm: Respond with run details
OnboardingForm->>User: Display real-time status via RealtimeStatus
sequenceDiagram
participant Client
participant RevalidateAPI
participant Database
Client->>RevalidateAPI: POST /api/revalidate with path, type, and secret
RevalidateAPI->>RevalidateAPI: Validate secret and parse request body
RevalidateAPI->>Database: Execute revalidatePath(path)
Database-->>RevalidateAPI: Acknowledge revalidation
RevalidateAPI-->>Client: Return JSON success response
Possibly related PRs
Poem
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 4
🔭 Outside diff range comments (1)
apps/app/src/actions/schema.ts (1)
31-40: 💡 Verification agent🧩 Analysis chain
Verify if subdomainAvailabilitySchema is still needed.
Since the subdomain field has been removed from the Organization model and the organizationSchema, this schema might no longer be necessary. If the application no longer uses subdomains, consider removing this schema as well.
🏁 Script executed:
#!/bin/bash # Check if there are any remaining references to the subdomainAvailabilitySchema echo "Checking for references to subdomainAvailabilitySchema..." rg "subdomainAvailabilitySchema" --type tsLength of output: 252
Action Required: Remove Unused Subdomain Schema
Based on the reference search, the only occurrence of
subdomainAvailabilitySchemais its own definition inapps/app/src/actions/schema.ts. Since the subdomain field has already been removed from both the Organization model and theorganizationSchema, this schema appears to be orphaned. Unless there’s a specific plan to reintroduce subdomain functionality, it’s advisable to remove this unused schema.
- File:
apps/app/src/actions/schema.ts(lines 31–40)- Observation:
subdomainAvailabilitySchemais defined but not referenced elsewhere.- Recommendation: Remove the schema if subdomains are no longer part of the application’s requirements.
🧹 Nitpick comments (11)
apps/app/src/actions/organization/create-organization-action.ts (1)
25-28: Consider validating frameworks in addition to name and website.While the validation checks for name and website, it doesn't explicitly validate frameworks, which is now required according to the schema.
-if (!name || !website) { - console.log("Invalid input detected:", { name, website }); - throw new Error("Invalid user input"); -} +if (!name || !website || !frameworks || frameworks.length === 0) { + console.log("Invalid input detected:", { name, website, frameworks }); + throw new Error("Invalid user input"); +}apps/app/src/app/[locale]/(app)/setup/page.tsx (1)
41-50: Implemented cached organization setup status check.The
isOrganizationSetupfunction efficiently checks and caches the organization's setup status, preventing redundant database queries during page rendering.Consider adding error handling to this function for robustness against database errors.
const isOrganizationSetup = cache(async (organizationId: string) => { - const organization = await db.organization.findUnique({ - where: { id: organizationId }, - select: { - setup: true, - }, - }); - - return organization?.setup; + try { + const organization = await db.organization.findUnique({ + where: { id: organizationId }, + select: { + setup: true, + }, + }); + + return organization?.setup; + } catch (error) { + console.error("Error checking organization setup status:", error); + return false; // Default to not set up if there's an error + } });apps/app/src/jobs/tasks/organization/create-organization.ts (3)
76-97: Framework setup logic is well-distributed.
AggregatingcreateOrganizationFrameworkcalls and the follow-up functions is neat. Might consider re-checking concurrency if multiple frameworks are processed in parallel.
231-257: Category creation for frameworks is straightforward.
Creating new categories by mapping framework categories is a clear approach, possibly double-check if duplicate names are handled gracefully.
348-387: Evidence creation is well-structured.
Assigning the user as defaultassigneeIdwill help maintain accountability for initial tasks. Confirm if we need finer-grained assignment logic.apps/app/src/components/forms/create-organization-form.tsx (4)
4-29: Remove unuseduseEffectimport.The
useEffectimport on line 20 is never used in this file. Removing unused imports helps maintain code clarity and avoid confusion.-import { useState, useEffect } from "react"; +import { useState } from "react";
75-119: Consider handling emptyframeworksgracefully.If no frameworks are passed in, the form might proceed with an empty array. For completeness, consider showing an appropriate message or disabling form submission to avoid confusion.
121-135: Use consistent heading hierarchy and accessibility labels.The heading and paragraph elements are semantically appropriate. For improved accessibility, consider adding descriptive
aria-labels where needed, such as for important content or structural landmarks.
249-269: Simplify theOnboardingvs.OnboardingClientcomponent structure.Exporting the main component as
OnboardingClientand wrapping it inOnboardingcould be folded into a single component unless there's a strong motivation to keep them separate. This minor consolidation can simplify the codebase.apps/app/src/jobs/tasks/organization/setup-org-frameworks.ts (2)
62-142: Reduce repeated organization checks for efficiency.Both the main
runmethod andcreateOrganizationFrameworkverify the organization’s existence. Avoid fetching the same data multiple times if you already have a reference to it, unless you need up-to-date data from separate calls.
303-343: Utilizeloggerinstead ofconsole.log.There are a few leftover
console.logcalls. For consistent logging and better production insight, replace them with yourloggerutility.- console.log({ - evidenceId, - }); + logger.debug("Evidence ID", { evidenceId });
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
apps/app/languine.lockis excluded by!**/*.lock
📒 Files selected for processing (24)
apps/app/package.json(1 hunks)apps/app/src/actions/organization/check-subdomain-availability.ts(0 hunks)apps/app/src/actions/organization/create-organization-action.ts(1 hunks)apps/app/src/actions/schema.ts(1 hunks)apps/app/src/app/[locale]/(app)/(dashboard)/layout.tsx(3 hunks)apps/app/src/app/[locale]/(app)/(dashboard)/settings/page.tsx(3 hunks)apps/app/src/app/[locale]/(app)/setup/page.tsx(2 hunks)apps/app/src/app/api/revalidate/path/route.ts(1 hunks)apps/app/src/auth/org.ts(1 hunks)apps/app/src/components/forms/create-organization-form.tsx(3 hunks)apps/app/src/components/settings/team/team-members.tsx(2 hunks)apps/app/src/env.mjs(1 hunks)apps/app/src/jobs/tasks/organization/create-default-policies.ts(0 hunks)apps/app/src/jobs/tasks/organization/create-organization.ts(1 hunks)apps/app/src/jobs/tasks/organization/new-organization.ts(0 hunks)apps/app/src/jobs/tasks/organization/setup-org-frameworks.ts(1 hunks)apps/app/src/locales/en.ts(1 hunks)apps/app/src/locales/es.ts(2 hunks)apps/app/src/locales/fr.ts(2 hunks)apps/app/src/locales/no.ts(2 hunks)apps/app/src/locales/pt.ts(2 hunks)apps/app/src/types/actions.ts(1 hunks)packages/db/prisma/migrations/20250318161548_drop_subdomain_add_setup/migration.sql(1 hunks)packages/db/prisma/schema/schema.prisma(1 hunks)
💤 Files with no reviewable changes (3)
- apps/app/src/jobs/tasks/organization/new-organization.ts
- apps/app/src/actions/organization/check-subdomain-availability.ts
- apps/app/src/jobs/tasks/organization/create-default-policies.ts
🧰 Additional context used
🧬 Code Definitions (3)
apps/app/src/actions/organization/create-organization-action.ts (3)
apps/app/src/actions/schema.ts (1) (1)
organizationSchema(13:20)apps/app/src/auth/org.ts (1) (1)
createOrganizationAndConnectUser(25:78)apps/app/src/jobs/tasks/organization/create-organization.ts (1) (1)
createOrganizationTask(8:105)
apps/app/src/app/[locale]/(app)/setup/page.tsx (1)
apps/app/src/components/forms/create-organization-form.tsx (1) (1)
Onboarding(266:268)
apps/app/src/components/forms/create-organization-form.tsx (2)
apps/app/src/actions/organization/create-organization-action.ts (1) (1)
createOrganizationAction(12:73)apps/app/src/actions/schema.ts (1) (1)
organizationSchema(13:20)
🔇 Additional comments (61)
apps/app/src/types/actions.ts (1)
1-5: Good addition of a standard action response interface.This generic interface provides a consistent structure for action responses throughout the application, making error handling and success states more predictable. The default
unknowntype for the data is a sensible choice to ensure type safety when the response type isn't specified.packages/db/prisma/migrations/20250318161548_drop_subdomain_add_setup/migration.sql (1)
1-12: Schema migration looks correct for subdomain removal and setup field addition.The migration properly handles:
- Dropping the unique index first
- Removing the subdomain column
- Adding the new setup boolean field with a default value of false
The warning about data loss for the subdomain column is appropriate.
apps/app/package.json (1)
6-7: Improved development workflow with concurrent processes.Using
concurrentlyto run both the Next.js dev server and Trigger.dev is a good approach for a better development experience. This allows developers to work with both servers running simultaneously without needing multiple terminal instances.packages/db/prisma/schema/schema.prisma (2)
80-80: Correctly added setup field to Organization model.The new
setupboolean field with defaultfalsealigns with the database migration and supports the improved organization setup process mentioned in the PR objectives.
76-120:Details
❓ Verification inconclusive
Verify impact of subdomain removal on organization identification.
The removal of the subdomain field (previously present in this model) shifts how organizations are identified and accessed. Make sure all references to organization identification throughout the codebase have been updated to accommodate this change.
🏁 Script executed:
#!/bin/bash # Check for any remaining references to the Organization.subdomain field in the codebase echo "Searching for references to subdomain in the codebase..." rg -t ts -t tsx "organization.*subdomain|subdomain.*organization" --no-ignoreLength of output: 230
Subdomain References Verification – Action Required
The Prisma schema now correctly omits the subdomain field. However, since our initial search command failed due to an unrecognized file type error for TSX files, please rerun the search on all TypeScript files using the updated command below to ensure no lingering references to "subdomain" exist:
#!/bin/bash echo "Searching for references to subdomain in the codebase..." rg -g "*.ts" -g "*.tsx" "organization.*subdomain|subdomain.*organization" --no-ignore
- Verify that this search produces no output.
- Confirm that all parts of the codebase referencing organization identification now correctly reflect the intended changes from the Prisma schema update.
apps/app/src/actions/schema.ts (2)
15-20: Good enhancement of the organization schema to support framework selection.The changes to the organization schema now require at least one framework to be selected, which aligns with the PR objective to incorporate framework handling in the organization setup process. The website field now correctly accepts empty strings as valid input.
22-22: Type definition improves code safety.Adding the
OrganizationSchematype using Zod's infer method is a good practice that enhances type safety throughout the codebase.apps/app/src/app/[locale]/(app)/(dashboard)/layout.tsx (3)
23-23: Improved session validation.The additional check for
session.user.organizationIdensures users without an organization are properly redirected to the authentication page.
27-31: Enhanced onboarding flow with organization setup check.This check ensures users are directed to the setup page if their organization isn't fully configured, improving the user onboarding experience.
47-58: Well-implemented organization setup verification.The cached function is a good approach to efficiently check the organization setup status while preventing redundant database queries.
apps/app/src/auth/org.ts (1)
25-28: Simplified function signature by removing subdomain parameter.The removal of the subdomain parameter from the function signature aligns with the PR objective of removing the subdomain field from the Organization model.
apps/app/src/app/api/revalidate/path/route.ts (1)
1-30:Details
✅ Verification successful
Well-implemented revalidation API with proper security checks.
This new endpoint correctly implements path revalidation with appropriate security measures:
- Validates the secret against an environment variable
- Checks for the presence of required parameters
- Includes comprehensive error handling
- Returns appropriate status codes
Ensure that the REVALIDATION_SECRET environment variable is properly set in all environments where this code will run.
🏁 Script executed:
#!/bin/bash # Check if REVALIDATION_SECRET is defined in env.mjs echo "Checking if REVALIDATION_SECRET is defined in env.mjs..." rg "REVALIDATION_SECRET" --type jsLength of output: 157
I'll run an additional verification to check the contents of the
env.mjsfile and verify whetherREVALIDATION_SECRETis defined as expected. This will help us confirm that the security check in your revalidation API is correctly configured.
🏁 Script executed:
#!/bin/bash # Locate and print the first few lines of env.mjs to inspect if REVALIDATION_SECRET is defined env_file=$(fd -e mjs -p "env\.mjs" | head -n1) if [ -n "$env_file" ]; then echo "Found env.mjs at: $env_file" echo "Printing first 50 lines of $env_file:" head -n 50 "$env_file" echo "---------" echo "Searching for REVALIDATION_SECRET in $env_file:" grep "REVALIDATION_SECRET" "$env_file" || echo "REVALIDATION_SECRET not found in $env_file" else echo "env.mjs file not found." fiLength of output: 2420
Revalidation API Verified and Approved
The updated endpoint correctly validates the secret against the environment variable and ensures the required parameters are provided, with comprehensive error handling and proper status codes. Additionally, our checks confirm that the
REVALIDATION_SECRETis indeed defined inapps/app/src/env.mjs.
- Verified that
REVALIDATION_SECRETis declared and mapped to the process environment.- Security checks and error handling are appropriately implemented.
Please ensure that this environment variable is correctly set in all deployment environments.
apps/app/src/locales/en.ts (1)
295-305: Update onboarding language for new setup processThe onboarding process has been reworked to include checks for organization setup status, but some of the strings might need updates to reflect the new workflow.
Please verify that these strings align with the current UI flow in the organization creation process.
apps/app/src/env.mjs (2)
20-20: LGTM: New REVALIDATION_SECRET environment variableThe addition of the REVALIDATION_SECRET environment variable aligns with the PR objectives.
53-53: LGTM: REVALIDATION_SECRET added to runtimeEnvCorrectly added to runtimeEnv to make it available at runtime.
apps/app/src/app/[locale]/(app)/(dashboard)/settings/page.tsx (3)
10-10: LGTM: Improved data fetching with React's cache functionGood implementation of React's cache function to improve performance when fetching organization details.
Also applies to: 51-62
22-24: LGTM: Simplified organization checkThe simplified check for organization ID is cleaner and more direct.
30-32: LGTM: Added null safety with optional chainingGood use of optional chaining and nullish coalescing to prevent potential runtime errors.
apps/app/src/components/settings/team/team-members.tsx (1)
9-9: LGTM: Updated caching with React's cache functionThe switch from unstable_cache to React's cache function is a good stability improvement. The updated query conditions for organization members properly handle the new model without the subdomain field.
Also applies to: 54-71, 73-85
apps/app/src/actions/organization/create-organization-action.ts (7)
8-10: Updated imports align with new task-based approach.The imports correctly include the required task libraries and types for the new asynchronous organization creation process.
12-20: Function metadata properly configured for tracking organization creation.The metadata configuration is well-structured, with appropriate naming and tracking event information.
22-22: Replaced subdomain with frameworks in input destructuring.This change aligns with the schema update that now requires frameworks instead of subdomains, following the PR objective to remove the subdomain field.
30-35: User organization connection maintained correctly.The organization creation logic properly maintains the user connection flow while removing the subdomain parameter from the function call.
51-61: Implemented task-based organization creation with framework handling.The code now triggers an asynchronous task for organization creation, passing the frameworks array instead of dealing with subdomains. This approach improves separation of concerns and allows for better error handling and status tracking.
63-67: Enhanced response with task tracking information.The response now includes task tracking details (runId and publicAccessToken), which will improve client-side handling of the asynchronous organization creation process.
68-72: Error handling properly implemented.The error handling catches any issues during the task creation process and provides appropriate error messaging.
apps/app/src/app/[locale]/(app)/setup/page.tsx (6)
3-3: Added necessary imports for database access and caching.The imports for
dbandcachesupport the new database queries and caching mechanisms needed for the organization setup status check and framework retrieval.Also applies to: 6-6
19-21: Simplified organization check logic.The logic has been simplified to only check for the absence of an organization ID, which is cleaner and more focused.
23-24: Added organization setup check and framework retrieval.These function calls retrieve critical information needed for the onboarding process: the organization's setup status and available frameworks.
26-28: Added redirect for already set up organizations.This check ensures users who have already completed the organization setup are redirected to the home page, preventing duplicate setup processes.
30-30: Updated component rendering with frameworks data.The Onboarding component now receives frameworks data, allowing users to select frameworks during the setup process.
33-39: Implemented cached framework retrieval.The
getFrameworksfunction efficiently retrieves and caches framework data from the database, improving performance by preventing redundant database queries.apps/app/src/locales/es.ts (2)
256-257: Updated welcome message and description to include frameworks.The Spanish localization now properly welcomes users to Comp AI and requests information about frameworks, aligning with the new onboarding flow.
280-289: Added organization creation workflow strings.New localization strings have been added to support the user feedback during the organization creation process, including waiting, creation, completion, and error states.
apps/app/src/locales/fr.ts (2)
256-257: Updated welcome message and description to include frameworks.The French localization now properly welcomes users to Comp AI and requests information about frameworks, aligning with the new onboarding flow.
280-289: Added organization creation workflow strings.New localization strings have been added to support the user feedback during the organization creation process, including waiting, creation, completion, and error states.
apps/app/src/locales/pt.ts (4)
256-257: Looks good for clearer messaging.
The updated messages more accurately guide the user through the onboarding process.
280-281: Translation updated successfully.
These new strings help clarify availability status and submission flow.
282-288: Good addition for user feedback.
Introducing detailed status steps (title, creating, completed, etc.) improves the user experience.
289-289: Progress indicator.
This string concisely communicates that the system is setting up the organization.apps/app/src/locales/no.ts (4)
256-257: Welcoming introduction.
Shifting from a generic setup prompt to a welcoming message aligns well with the updated onboarding experience.
280-281: Clearer user flow.
Explicitly labeling the availability and setup completion button clarifies next steps for Norwegian users.
282-288: Detailed progress states.
Providing step-by-step feedback (title, creating, completed, error) ensures a transparent organization creation process.
289-289: Concise creation feedback.
This string effectively informs the user that the system is currently busy creating the organization.apps/app/src/jobs/tasks/organization/create-organization.ts (11)
1-7: Imports look appropriate.
All required modules and types for database, logging, and schema validation appear logically grouped.
8-17: Schema validation is neatly defined.
Thez.objectschema ensures that all required parameters for organization creation are present.
18-25: Sufficient logging on initialization.
Logging the parameters helps with tracing and debugging potential setup issues.
27-36: Organization accessibility check.
Verifying that the user is part of the organization helps prevent unauthorized or invalid creation attempts.
38-40: Explicit handling of a missing organization.
Throwing an error when the organization is not found prevents silent failures.
42-67: Transactional upsert pattern looks solid.
The transaction ensures atomic updates to the organization record and user onboarding status. Consider verifying if partial updates would require a rollback scenario in edge cases.Would you like a script to search for usage or check if a rollback is triggered in nested transactions?
68-75: Category creation step.
Creating organization categories first is an important prerequisite for subsequent tasks. This sequencing helps maintain data integrity.
98-105: Error logging & rethrowing.
Capturing the error and rethrowing ensures the transaction is rolled back and the failure is clearly reported, preventing partial state commits.
107-185:createOrganizationFrameworkis thorough.
It checks both the organization and the framework existence, logs appropriately, and creates category controls. No obvious issues.
189-229: Selective policy creation.
Filtering policies viausedByensures that only relevant policies are assigned to the organization based on framework usage. This is a solid approach.
259-346: Control requirements mapping is cohesive.
Associating each control with the corresponding organization policy or evidence is correct. Logging statements help debug mismatches.apps/app/src/components/forms/create-organization-form.tsx (2)
31-72: Well-structured real-time feedback component.The
RealtimeStatuscomponent correctly handles in-progress, completed, and error states. The code is clean, and the UI feedback is intuitive for users. No concerns here.
139-247: Great use ofreact-hook-form& modular fields.The form fields are clearly defined with Zod validation, making the onboarding process straightforward. The approach to dynamic checkbox handling for
frameworksis concise and readable. Good job!apps/app/src/jobs/tasks/organization/setup-org-frameworks.ts (4)
1-15: Good use of schema validation and task definition.Defining
setupOrgFrameworksTaskwith a Zod schema clarifies the required inputs for this process. This approach helps maintain type safety and ensures data integrity.
144-184: Efficiently filter policies based on frameworks.The loop identifies policies relevant to provided
frameworkIds. This is logically sound. If performance becomes an issue with large policy sets, consider a more direct query (e.g., with a relationship table or composite indexes).
186-212: Comprehensive category creation logic.Creating organization categories in bulk is performant. The code is straightforward and well-structured for extension if additional fields are needed later.
214-301:Details
❓ Verification inconclusive
Validate final control states more robustly.
The logic for mapping controls to requirements and policies is correct. Consider verifying that each required policy or piece of evidence exists in the final assignment to avoid storing incomplete references.
You can run a script to confirm there are no orphan references:
(Adjust to your code structure as needed.)
🏁 Script executed:
#!/bin/bash # Checking for organizationControlRequirements with missing references ast-grep --pattern $'db.organizationControlRequirement.createMany({ data: $$... })'Length of output: 84
Please manually verify the completeness of control reference assignments.
The mapping logic between controls, requirements, and their linked organization policies and evidences is implemented correctly. However, to avoid inserting any incomplete or orphaned records, ensure that for every control requirement being created via
createMany, the corresponding organization policy or evidence exists when it’s expected.
- File:
apps/app/src/jobs/tasks/organization/setup-org-frameworks.ts(lines 214–301)- Verify that every policy- or evidence-type requirement correctly maps to an existing organization policy or evidence.
- The automated check using the provided script did not return conclusive output—please perform a manual review of the final state to catch any orphaned references.
| create: { | ||
| userId: input.userId, | ||
| role: "admin", | ||
| role: "owner", |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Role designation changed from "admin" to "owner".
Changing the user's role from "admin" to "owner" represents a semantic improvement in the role assignment. However, ensure that all authorization checks throughout the application have been updated to handle this new role designation properly.
🏁 Script executed:
#!/bin/bash
# Check for places in the codebase that might be affected by the role change
echo "Checking for references to admin role in authorization contexts..."
rg -A 3 -B 3 "role\s*(===|==|!==|!=)\s*['\"]admin['\"]" --type tsLength of output: 1598
Action Required: Update Authorization Checks to Reflect New Ownership Role
The change in apps/app/src/auth/org.ts from "admin" to "owner" is a positive improvement. However, our search revealed that other parts of the codebase still reference "admin" in authorization logic. Please review the following locations:
-
apps/app/src/components/settings/team/member-actions.tsx
- The condition
const canChangeRole = currentUserRole === "owner" || member.role !== "admin";still uses"admin". Confirm if this logic should now exclusively rely on"owner"or if additional role distinctions are necessary.
- The condition
-
apps/app/src/app/[locale]/(app)/(dashboard)/people/components/table/components/filterCategories.tsx
- The UI filter still presents
"Admin"as a label and"admin"as its value (including in the checkchecked: role === "admin"and the settersetRole(checked ? "admin" : null)). Ensure these are updated to maintain consistency with the new role designation.
- The UI filter still presents
Please update these references accordingly or add appropriate comments if retaining the legacy "admin" value is intentional.
| subdomain: { | ||
| label: "Subdomain", | ||
| placeholder: "example", | ||
| }, |
There was a problem hiding this comment.
Remove unused subdomain field references
The subdomain field still appears in the onboarding localization strings, but according to the PR objectives, this field has been removed from the Organization model.
Remove or update these strings to align with the new organization setup approach:
- subdomain: {
- label: "Subdomain",
- placeholder: "example",
- },📝 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.
| subdomain: { | |
| label: "Subdomain", | |
| placeholder: "example", | |
| }, |
| check_availability: "Checking availability", | ||
| available: "Available", | ||
| unavailable: "Unavailable", |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Remove unused availability check references
These strings are related to the subdomain availability check, which should no longer be needed after removing the subdomain field.
- check_availability: "Checking availability",
- available: "Available",
- unavailable: "Unavailable",📝 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.
| check_availability: "Checking availability", | |
| available: "Available", | |
| unavailable: "Unavailable", |
| logger.info("Setting up organization frameworks", { | ||
| organizationId, | ||
| frameworkIds, | ||
| }); | ||
|
|
||
| const organization = await db.organization.findFirst({ | ||
| where: { | ||
| id: organizationId, | ||
| }, | ||
| }); | ||
|
|
||
| if (!organization) { | ||
| throw new Error("Organization not found"); | ||
| } | ||
|
|
||
| try { | ||
| await createOrganizationCategories(organizationId, frameworkIds); | ||
|
|
||
| const organizationFrameworks = await Promise.all( | ||
| frameworkIds.map((frameworkId) => | ||
| createOrganizationFramework(organizationId, frameworkId), | ||
| ), | ||
| ); | ||
|
|
||
| await createOrganizationPolicy(organizationId, frameworkIds); | ||
|
|
||
| await createOrganizationControlRequirements( | ||
| organizationId, | ||
| organizationFrameworks.map((framework) => framework.id), | ||
| ); | ||
|
|
||
| await createOrganizationEvidence(organizationId, frameworkIds, userId); | ||
|
|
||
| return { | ||
| success: true, | ||
| }; | ||
| } catch (error) { | ||
| logger.error("Error setting up organization frameworks", { | ||
| error, | ||
| }); | ||
|
|
||
| throw error; | ||
| } | ||
| }, |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider wrapping the entire setup in a transaction.
Multiple subsections (categories, frameworks, policies, etc.) are created step by step. If a partial failure occurs, the organization could be left in an inconsistent state. Using a single transaction (or partial rollbacks if partial success is not desirable) could improve atomicity.
create-organization-actionto include framework handling and organization setup.create-organizationfor better organization creation management.subdomainfield from theOrganizationmodel and added asetupboolean field.env.mjsto includeREVALIDATION_SECRET.Summary by CodeRabbit
New Features
Enhancements
Chores