Skip to content

Add Default Organization Creation on API Startup #3232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

khushipatil1523
Copy link

@khushipatil1523 khushipatil1523 commented Feb 17, 2025

What kind of change does this PR introduce?
Added a check on API startup to create a default organization if none exists.

Issue Number:
#3168

Snapshots/Videos:
Screenshot 2025-02-17 112229
Screenshot 2025-02-17 112733

Does this PR introduce a breaking change?
No

Summary by CodeRabbit

  • New Features
    • Made the organization record creation process more flexible by allowing an identifier to be optionally provided.
    • Enhanced the initial data seeding process to verify organization address details and create a default organization when none with valid address information exists.
  • Chores
    • Improved error logging during organization setup to better capture and report issues.

Copy link

coderabbitai bot commented Feb 17, 2025

Walkthrough

This pull request updates the organization-related functionality in two areas. In the organizations table schema, an optional id field is added to the insert schema, allowing record insertions without providing an id. In the seed initial data script, the process now verifies if an organization with a valid address exists. If not found, it creates a default organization named "Unity Foundation USA" and adds a corresponding organization membership for the administrator user. The changes also include new imports and enhanced error logging specific to the organization creation workflow.

Changes

File Change Description
src/drizzle/.../organizations.ts Added an optional id field to organizationsTableInsertSchema by including id: (schema) => schema.optional(), modifying the validation logic for record insertion.
src/plugins/.../seedInitialData.ts Added new imports for organization tables. Extended the seeding process to check for an organization with a valid address; if not found, creates a default "Unity Foundation USA" organization and an associated organization membership, with enhanced error logging.

Sequence Diagram(s)

sequenceDiagram
    participant SeedScript
    participant Database
    participant Logger
    participant AdminQuery

    SeedScript->>Database: Query organization with valid address
    alt Organization Exists
        Database-->>SeedScript: Return organization record
        SeedScript->>Logger: Log "Creation skipped"
    else No Organization Found
        Database-->>SeedScript: Return no record
        SeedScript->>AdminQuery: Query for administrator user
        AdminQuery-->>SeedScript: Return admin user ID
        SeedScript->>Database: Begin transaction: Insert default organization ("Unity Foundation USA")
        Database-->>SeedScript: Organization inserted
        SeedScript->>Database: Insert organization membership for admin user
        Database-->>SeedScript: Membership record inserted
        SeedScript->>Logger: Log success or encountered errors
    end
Loading

Possibly related PRs

Suggested reviewers

  • palisadoes

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3e0bf44 and 76c8e34.

📒 Files selected for processing (1)
  • src/plugins/seedInitialData.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (8)
src/plugins/seedInitialData.ts (8)

2-2: No concerns regarding the new import statement.
It aligns well with the subsequent usage of logical operators and SQL fragments.


11-15: Newly introduced imports look appropriate.
Importing organizationMembershipsTable, organizationsTable, and organizationsTableInsertSchema cleanly integrates organization logic into the seeding process.


182-183: Clear and concise logging.
The log statement effectively communicates the upcoming organization validity check to developers.


199-203: Early return upon finding a valid organization is correct.
This logic prevents redundant insertion of a default organization if one already exists.


205-208: Information log is sufficiently descriptive.
The message clarifies why a default organization is being created if none exists.


210-217: Properly locating the admin user.
Verifying the administrator user exists before creating the organization is a crucial prerequisite.


219-221: Immediate error thrown for missing admin user.
This guard ensures that the default organization will not be created without a defined administrator.


255-263: Strong error handling and logging.
Capturing error details and rethrowing a descriptive message aids in diagnostic clarity.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Congratulations on making your first PR! 🎊 If you haven't already, check out our Contributing Guidelines and PR Reporting Guidelines to ensure that you are following our guidelines for contributing and creating PR.

Copy link

codecov bot commented Feb 17, 2025

Codecov Report

Attention: Patch coverage is 29.72973% with 52 lines in your changes missing coverage. Please review.

Project coverage is 45.44%. Comparing base (e3c51e8) to head (86856d0).
Report is 48 commits behind head on develop-postgres.

Files with missing lines Patch % Lines
src/plugins/seedInitialData.ts 28.76% 52 Missing ⚠️
Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #3232      +/-   ##
====================================================
- Coverage             45.48%   45.44%   -0.04%     
====================================================
  Files                   455      455              
  Lines                 33935    34008      +73     
  Branches                757      759       +2     
====================================================
+ Hits                  15435    15456      +21     
- Misses                18496    18548      +52     
  Partials                  4        4              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e3c51e8 and d329a89.

📒 Files selected for processing (3)
  • .devcontainer/devcontainer.json (1 hunks)
  • src/drizzle/tables/organizations.ts (1 hunks)
  • src/plugins/seedInitialData.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (2)
src/drizzle/tables/organizations.ts (1)

214-214: Change looks good.
Making the id an optional field aligns with the UUID default generation in the table definition and allows more flexibility when inserting records.

.devcontainer/devcontainer.json (1)

70-70: Confirm wsl usage for cross-platform compatibility.
Using wsl cp may not work in non-WSL environments. If you intend to support developers on other platforms, consider a more generic approach or confirm this command is strictly for WSL-based workflows.

Comment on lines +221 to +248
await fastify.drizzleClient.transaction(async (tx) => {
const organizationId = uuidv7();

const defaultOrganization = organizationsTableInsertSchema.parse({
id: organizationId,
name: "Unity Foundation USA",
description: "Service to the Community",
addressLine1: "1268 Finwood Road",
addressLine2: "Suite 200",
city: "Dodge City",
postalCode: "67801",
state: "Kansas",
avatarName: null,
countryCode: "us",
createdAt: new Date(),
creatorId: adminUser.id,
});

await tx.insert(organizationsTable).values(defaultOrganization);

await tx.insert(organizationMembershipsTable).values({
memberId: adminUser.id,
organizationId,
role: "administrator",
creatorId: adminUser.id,
createdAt: new Date(),
});

Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Address potential concurrency.
The check and insertion logic runs outside a strict upsert pattern. If multiple instances of the seeding logic run simultaneously, it can lead to multiple default organizations. Consider adding more robust constraints or an upsert-like transaction to ensure only one default is created.

Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

  1. Please make coderabbit.ai approves your work.
  2. Make sure all tests pass and are valid.
  3. Ensure the test code coverage for your patch reaches as close to 100% as possible.

Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

See comment

Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

@khushipatil1523
Copy link
Author

  1. Please make coderabbit.ai approves your work.
  2. Make sure all tests pass and are valid.
  3. Ensure the test code coverage for your patch reaches as close to 100% as possible.

Got it sir! I'll make sure coderabbit.ai approves the work, and I'll ensure all tests pass with near 100% coverage.

Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

@palisadoes palisadoes added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Feb 17, 2025
Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

@khushipatil1523
Copy link
Author

  1. Please make coderabbit.ai approves your work.
  2. Make sure all tests pass and are valid.
  3. Ensure the test code coverage for your patch reaches as close to 100% as possible.

Got it sir! I'll make sure coderabbit.ai approves the work, and I'll ensure all tests pass with near 100% coverage.

Should I create a new file to write test cases?

@palisadoes
Copy link
Contributor

Yes we need tests. We can't afford to have this feature fail

@khushipatil1523
Copy link
Author

Yes we need tests. We can't afford to have this feature fail
Absolutely sir i complete it ASAP

Copy link

This pull request did not get any activity in the past 10 days and will be closed in 180 days if no update occurs. Please verify it has no conflicts with the develop branch and rebase if needed. Mention it now if you need help or give permission to other people to finish your work.

@github-actions github-actions bot added the no-pr-activity No pull request activity label Feb 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files no-pr-activity No pull request activity
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants