Skip to content

refactor: update organization setup logic and remove subdomain field#144

Merged
carhartlewis merged 2 commits into
mainfrom
lewis/onboarding-workflow
Mar 18, 2025
Merged

refactor: update organization setup logic and remove subdomain field#144
carhartlewis merged 2 commits into
mainfrom
lewis/onboarding-workflow

Conversation

@carhartlewis
Copy link
Copy Markdown
Contributor

@carhartlewis carhartlewis commented Mar 18, 2025

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

Summary by CodeRabbit

  • New Features

    • Redesigned onboarding with a single-step organization creation process that provides real-time feedback and requires selecting a framework.
    • Updated multilingual onboarding texts to better guide users in English, Spanish, French, Norwegian, and Portuguese.
  • Enhancements

    • Streamlined organization setup with improved validations to ensure proper dashboard access.
    • Improved error handling and caching for team management.
  • Chores

    • Refined development scripts and backend tasks.
    • Updated the database structure to replace subdomain tracking with a setup indicator.

- 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.
@vercel
Copy link
Copy Markdown

vercel Bot commented Mar 18, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 18, 2025 7:13pm
comp-portal ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 18, 2025 7:13pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 18, 2025

Walkthrough

This 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

File(s) Change Summary
apps/app/package.json Updated dev script to use npx concurrently to run the Next.js server alongside trigger:dev, with a new trigger:dev script added.
apps/app/src/actions/organization/{check-subdomain-availability.ts, create-organization-action.ts}
apps/app/src/actions/schema.ts
Removed the subdomain availability check, updated createOrganizationAction to drop Vercel/domain logic in favor of frameworks, and modified the organization schema (removed subdomain, added frameworks field, updated website validation, and added type inference).
apps/app/src/app/[locale]/**/{layout.tsx, settings/page.tsx, setup/page.tsx} Enhanced user flow by adding additional organization status checks, caching functions (isOrganizationSetup, organizationDetails, getFrameworks), and updated redirect logic.
apps/app/src/app/api/revalidate/path/route.ts Added a new POST endpoint to handle path revalidation, including secret validation and error handling.
apps/app/src/auth/org.ts Modified createOrganizationAndConnectUser to remove the subdomain parameter and change the user role from "admin" to "owner".
apps/app/src/components/forms/create-organization-form.tsx Refactored the onboarding form by replacing the multi-step process with a single-step submission, adding a RealtimeStatus component for feedback, and updating the function signature to receive frameworks.
apps/app/src/components/settings/team/team-members.tsx Replaced unstable_cache with React’s cache for member and invitation queries and updated query conditions.
apps/app/src/env.mjs Introduced a new environment variable, REVALIDATION_SECRET, in both server and runtime configurations.
apps/app/src/jobs/tasks/organization/{create-default-policies.ts (removed), new-organization.ts (removed), create-organization.ts, setup-org-frameworks.ts} Removed deprecated tasks and added new tasks (createOrganizationTask and setupOrgFrameworksTask) for comprehensive organization setup and framework creation.
apps/app/src/locales/{en,es,fr,no,pt}.ts Updated localization strings—especially in onboarding sections—with refreshed and restructured text for multiple languages.
apps/app/src/types/actions.ts Added a new generic interface, ActionResponse<T = unknown>, for standardized action responses.
packages/db/prisma/{migrations/20250318161548_drop_subdomain_add_setup/migration.sql, schema/schema.prisma} Dropped the unique subdomain field/column and added a new boolean setup field/column (default false) to the Organization model/schema.

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

Possibly related PRs

Poem

I'm just a bunny, hopping to and fro,
Watching subdomains vanish—where did they go?
Frameworks now bloom like carrots in spring,
Tasks and routes in a synchronized swing.
With hops of code and joyful cheer,
My garden of changes grows bright and clear!
🐰💻

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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
Copy Markdown

@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)
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 ts

Length of output: 252


Action Required: Remove Unused Subdomain Schema

Based on the reference search, the only occurrence of subdomainAvailabilitySchema is its own definition in apps/app/src/actions/schema.ts. Since the subdomain field has already been removed from both the Organization model and the organizationSchema, 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: subdomainAvailabilitySchema is 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 isOrganizationSetup function 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.
Aggregating createOrganizationFramework calls 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 default assigneeId will 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 unused useEffect import.

The useEffect import 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 empty frameworks gracefully.

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 the Onboarding vs. OnboardingClient component structure.

Exporting the main component as OnboardingClient and wrapping it in Onboarding could 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 run method and createOrganizationFramework verify 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: Utilize logger instead of console.log.

There are a few leftover console.log calls. For consistent logging and better production insight, replace them with your logger utility.

- console.log({
-   evidenceId,
- });
+ logger.debug("Evidence ID", { evidenceId });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a79238a and f7f685e.

⛔ Files ignored due to path filters (1)
  • apps/app/languine.lock is 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 unknown type 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:

  1. Dropping the unique index first
  2. Removing the subdomain column
  3. 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 concurrently to 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 setup boolean field with default false aligns 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-ignore

Length 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 OrganizationSchema type 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.organizationId ensures 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:

  1. Validates the secret against an environment variable
  2. Checks for the presence of required parameters
  3. Includes comprehensive error handling
  4. 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 js

Length of output: 157


I'll run an additional verification to check the contents of the env.mjs file and verify whether REVALIDATION_SECRET is 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."
fi

Length 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_SECRET is indeed defined in apps/app/src/env.mjs.

  • Verified that REVALIDATION_SECRET is 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 process

The 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 variable

The addition of the REVALIDATION_SECRET environment variable aligns with the PR objectives.


53-53: LGTM: REVALIDATION_SECRET added to runtimeEnv

Correctly 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 function

Good implementation of React's cache function to improve performance when fetching organization details.

Also applies to: 51-62


22-24: LGTM: Simplified organization check

The simplified check for organization ID is cleaner and more direct.


30-32: LGTM: Added null safety with optional chaining

Good 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 function

The 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 db and cache support 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 getFrameworks function 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.
The z.object schema 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: createOrganizationFramework is 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 via usedBy ensures 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 RealtimeStatus component 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 of react-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 frameworks is 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 setupOrgFrameworksTask with 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.

Comment thread apps/app/src/auth/org.ts
create: {
userId: input.userId,
role: "admin",
role: "owner",
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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 ts

Length 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.
  • 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 check checked: role === "admin" and the setter setRole(checked ? "admin" : null)). Ensure these are updated to maintain consistency with the new role designation.

Please update these references accordingly or add appropriate comments if retaining the legacy "admin" value is intentional.

Comment on lines +316 to +319
subdomain: {
label: "Subdomain",
placeholder: "example",
},
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
subdomain: {
label: "Subdomain",
placeholder: "example",
},

Comment on lines +327 to +329
check_availability: "Checking availability",
available: "Available",
unavailable: "Unavailable",
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Suggested change
check_availability: "Checking availability",
available: "Available",
unavailable: "Unavailable",

Comment on lines +16 to +59
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;
}
},
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

@carhartlewis carhartlewis merged commit 085356a into main Mar 18, 2025
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