Skip to content
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

Sync Updates #192

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open

Sync Updates #192

wants to merge 5 commits into from

Conversation

rupamkairi
Copy link
Contributor

@rupamkairi rupamkairi commented Feb 14, 2025

Site Sync Updates

  • Added filter for the allowDonations
  • Added Syncing for the Users.
  • Added name_flags (NEW_, UPDATE_ on name fields) for verification purpose.
  • origin ttc is added
  • isMonitored false is handled on dissociation

@sagararyal

Summary by CodeRabbit

  • New Features

    • Enhanced synchronization capabilities for remote operations, enabling automated updates and clear differentiation of new and updated user, project, and site records.
    • Improved error handling and logging to boost data integrity during the synchronization process.
  • Chores

    • Updated repository management by excluding temporary project files from version control for cleaner release workflows.

- Added filter for the allowDonations
- Added Syncing for the Users.
- Added name_flags (NEW_, UPDATE_ on name fields) for verification purpose.
- origin ttc is added
- isMonitored false is handled on dissociation
Copy link

vercel bot commented Feb 14, 2025

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

Name Status Preview Updated (UTC)
fire-alert ✅ Ready (Inspect) Visit Preview Feb 17, 2025 1:22pm

Copy link

coderabbitai bot commented Feb 14, 2025

Walkthrough

This pull request updates the RO user synchronization process in several areas. The syncROUsers function has been modified to filter projects based on the allowDonations property, aggregate unique RO users, and manage new user creation with error logging. Additionally, projects and sites are updated with specific prefixes, and sites can be disassociated. The .gitignore file is updated to ignore projects.json. A new API endpoint in syncROs.ts has been introduced to handle RO data synchronization, utilizing comparison functions for projects and sites along with utility methods for database operations and cleanup.

Changes

File(s) Change Summary
apps/server/src/pages/api/cron/sync-ro-users.ts Updates to the syncROUsers function including filtering projects by allowDonations, aggregating unique RO users, creating new users (with error handling), and updating projects/sites with prefixes.
apps/server/src/pages/api/cron/sync/.gitignore Added projects.json to the ignore list to prevent tracking of this file in version control.
apps/server/src/pages/api/cron/sync/syncROs.ts New file implementing the syncROs API endpoint. It verifies a CRON key, fetches project data, uses dedicated functions to compare and prepare database operations for projects and sites, and includes cleanup logic.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant DB
    Note over API: syncROUsers updates
    Client->>API: Request to sync RO users
    API->>API: Filter projects by allowDonations
    API->>API: Aggregate unique RO users into Map
    API->>DB: Create new users (with error handling)
    API->>DB: Fetch existing RO users, update mapping
    API->>DB: Insert/Update projects and sites (prefix NEW_/UPDATE_)
    API->>DB: Disassociate sites not in PP API
    API-->>Client: Return response
Loading
sequenceDiagram
    participant Client
    participant SyncEndpoint
    participant FS as FileSystem
    participant DB
    Note over SyncEndpoint: New syncROs endpoint flow
    Client->>SyncEndpoint: Call syncROs (with CRON key)
    SyncEndpoint->>FS: Read projects.json data
    SyncEndpoint->>DB: Fetch existing RO users, projects, sites
    SyncEndpoint->>SyncEndpoint: Compare projects (compareProjects)
    SyncEndpoint->>SyncEndpoint: Compare sites (compareSites)
    SyncEndpoint->>DB: Execute create/update/delete operations (commented out)
    SyncEndpoint->>SyncEndpoint: Run cleanup (cleanUps)
    SyncEndpoint-->>Client: Return success response with project info
Loading

Poem

I’m a rabbit in a digital glen,
Hopping through code again and again.
Syncing users with a twitch of my nose,
New projects bloom where logic flows.
With each commit, my whiskers beam –
A playful hop in a coder’s dream!
🐰💻


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 76f51ea and f6f4dc7.

📒 Files selected for processing (1)
  • apps/server/src/pages/api/cron/sync-ro-users.ts (11 hunks)
🔇 Additional comments (6)
apps/server/src/pages/api/cron/sync-ro-users.ts (6)

6-6: LGTM! Import changes improve type safety.

The addition of the User type from @prisma/client enhances type checking for user-related operations.

Also applies to: 12-12


30-48: Remove temporary name flags.

The "NEW_" prefix was added for verification purposes and should be removed before merging.

Apply this diff to remove the temporary prefix:

-                name: "NEW_" + project.tpo.name,
+                name: project.tpo.name,

50-86: LGTM! Robust user creation implementation.

The implementation follows best practices:

  • Efficiently checks for existing users using Set
  • Uses bulk operations for better performance
  • Includes proper error handling and logging

166-166: Remove all temporary name flags.

The "NEW_" and "UPDATE_" prefixes were added for verification purposes and should be removed from all occurrences.

Apply these diffs to remove the temporary prefixes:

-                name: "NEW_" + projectName,
+                name: projectName,
-                name: "NEW_" + siteName,
+                name: siteName,
-                            name:  "UPDATE_" + projectNameFormPP,
+                            name: projectNameFormPP,
-                                        name: "NEW_" + siteName,
+                                        name: siteName,
-                                        name:  "UPDATE_" + siteName,
+                                        name: siteName,

Also applies to: 200-200, 321-321, 353-353, 372-372


283-295: LGTM! Good addition of isMonitored flag update.

Setting isMonitored to false during site dissociation is a good practice to ensure consistent state.


406-407: Remove redundant console.log statement.

The error is already being logged using the logger utility.

Apply this diff to remove the redundant logging:

-        console.log(error);
         logger(`Error in transaction: ${error}`, "error");
✨ 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.

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

@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: 0

🧹 Nitpick comments (5)
apps/server/src/pages/api/cron/sync-ro-users.ts (4)

54-67: Consider using upsert instead of skipDuplicates
Using skipDuplicates: true only avoids inserting exact duplicate data but does not update any partially matching user fields. If fields like name or email can change, consider an upsert-based approach or a separate update step to keep user data current.


302-302: Avoid repeatedly prefixing project names with "UPDATE_"
Appending "UPDATE_" on every change can lead to names like "UPDATE_UPDATE_*". Consider storing a version field or a separate flag to distinguish new vs. updated projects, rather than continually manipulating the name.

- name:  "UPDATE_" + projectNameFormPP,
+ name: projectNameFormPP,
+ // Optionally store a version or set an "isUpdated" flag if needed

334-335: Ensure "NEW_" prefix is truly needed
Prefixing newly created sites with "NEW_" can be helpful for debugging, but confirm you won’t unintentionally retain this prefix in production. Handle edge cases (e.g., empty or undefined siteName) gracefully.


353-353: Avoid duplicative "UPDATE_" prefix for site names
Similar to projects, repeatedly prepending "UPDATE_" can produce unwieldy names. Track updates with a timestamp or separate flag instead of chaining prefixes.

apps/server/src/pages/api/cron/sync/syncROs.ts (1)

1-220: Complete or remove commented logic and add testing
Most synchronization routines here are commented out, making the file appear like a prototype. Unclear code can cause confusion and lead to maintenance challenges. Consider:

  1. Activating or removing sections of commented code.
  2. Adding tests to validate each step in the sync flow (e.g., compareProjects, compareSites, etc.).
  3. Ensuring that reading from projects.json is intentional, especially if you plan to fetch data from external services later.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dc1477b and d33f8da.

📒 Files selected for processing (3)
  • apps/server/src/pages/api/cron/sync-ro-users.ts (9 hunks)
  • apps/server/src/pages/api/cron/sync/.gitignore (1 hunks)
  • apps/server/src/pages/api/cron/sync/syncROs.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/server/src/pages/api/cron/sync/.gitignore
🔇 Additional comments (3)
apps/server/src/pages/api/cron/sync-ro-users.ts (3)

30-31: Validate data availability and structure before filtering
Ensure that fetchAllProjectsWithSites() consistently returns an array of objects containing allowDonations. If it can sometimes return undefined or an unexpected structure, consider adding guard clauses or fallback logic to prevent runtime errors.


33-52: Confirm project.tpo reliably exists
This block robustly extracts RO users, but it depends on project.tpo and project.tpo.id. If any project objects lack those fields, they will be skipped. Verify that this scenario is acceptable or handle it explicitly to avoid missing users. Also confirm prefixing names with "NEW_" fits your naming requirements long-term.


264-265: Verify the necessity of setting isMonitored to false
When disassociating sites, forcing isMonitored to false might be desired, but confirm there is no condition under which a site should remain monitored after being removed from the PP API.

if (!uniqueUsers.has(project.tpo.id)) {
uniqueUsers.set(project.tpo.id, {
remoteId: project.tpo.id,
name: "NEW_" + project.tpo.name,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

These "NEW_" & "UPDATE_" name flags I have just added for checking Purposes. So If I ran it few passes, I'd be able to check what's change & etc. It will be removed.

@@ -141,6 +178,8 @@ export default async function syncROUsers(req: NextApiRequest, res: NextApiRespo
// Add the new site to the array for bulk creation
newSiteData.push({
remoteId: remoteId_PP,
name: "NEW_" + siteName,
origin: "ttc",
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Here are 2 things.
name: siteName was not being used here, not sure why. Added it just to keep it uniform.
origin: 'ttc' was not anywhere. Existing Imported Projects have their origin "ttc" so I added.

@@ -0,0 +1,220 @@
// Organizing the Sync Flow
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ignore this File entirely.
I was trying to rewrite to refactoring the CRON.

added check for user with remoteId before adding it to users, prevents creating multiple user with same remoteId. Checked by grouping by remoteId.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
apps/server/src/pages/api/cron/sync-ro-users.ts (1)

51-86: Consider adding batch size for user creation.

When creating multiple users, consider adding a batch size to prevent potential performance issues with large datasets.

         if (newUsersToCreate.length > 0) {
             const result = await prisma.user.createMany({
                 data: newUsersToCreate,
+                skipDuplicates: true,
             });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d33f8da and 1895a79.

📒 Files selected for processing (2)
  • apps/server/src/pages/api/cron/sync-ro-users.ts (11 hunks)
  • apps/server/src/pages/api/cron/sync/syncROs.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/server/src/pages/api/cron/sync/syncROs.ts
🔇 Additional comments (3)
apps/server/src/pages/api/cron/sync-ro-users.ts (3)

30-31: LGTM! Good filtering of projects based on allowDonations.

The filtering ensures that only projects allowing donations are synchronized, which aligns with the PR objectives.


201-201: LGTM! Origin field added for consistency.

Based on your previous comment, adding origin: 'ttc' maintains consistency with existing imported projects.

Also applies to: 354-354


283-295: LGTM! Improved site dissociation logic.

Setting isMonitored to false when dissociating sites aligns with the PR objectives and ensures proper cleanup.

Comment on lines +406 to 407
console.log(error);
logger(`Error in transaction: ${error}`, "error");
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove console.log statement.

The error is already being logged using the logger utility. Remove the redundant console.log statement.

-        console.log(error);
         logger(`Error in transaction: ${error}`, "error");
📝 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
console.log(error);
logger(`Error in transaction: ${error}`, "error");
logger(`Error in transaction: ${error}`, "error");

if (!uniqueUsers.has(project.tpo.id)) {
uniqueUsers.set(project.tpo.id, {
remoteId: project.tpo.id,
name: "NEW_" + project.tpo.name,
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Remove temporary name flags after verification.

Based on your previous comment, these "NEW_" and "UPDATE_" name flags were added for verification purposes and should be removed.

Also applies to: 166-166, 200-200, 321-321, 353-353, 372-372


🏁 Script executed:

#!/bin/bash
# Description: Find all occurrences of temporary name flags.
rg -A 1 'name: "(NEW|UPDATE)_"'

Length of output: 820


ACTION REQUIRED: Remove Temporary Debug Flags

Our verification confirms that temporary prefixes (e.g., "NEW_") are still present in the file. Please remove these prefixes from all occurrences in apps/server/src/pages/api/cron/sync-ro-users.ts. Specifically:

  • Line 40: Remove the prefix from name: "NEW_" + project.tpo.name
  • Line 166: Remove the prefix from name: "NEW_" + projectName
  • Line 321 & 353: Remove the prefixes from both occurrences of name: "NEW_" + siteName

Additionally, check any other flagged lines (e.g., lines 200, 372) to ensure that no temporary flags remain in the code. These prefixes were only used for verification purposes and should be removed before merging.

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: 0

🧹 Nitpick comments (1)
apps/server/src/pages/api/cron/sync-ro-users.ts (1)

43-43: Simplify the boolean literal in the ternary expression.

The ternary expression can be simplified by directly using the condition result.

-isPlanetRO: project.tpo.id.startsWith("tpo_") ? true : false,
+isPlanetRO: project.tpo.id.startsWith("tpo_"),
🧰 Tools
🪛 Biome (1.9.4)

[error] 43-43: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1895a79 and 76f51ea.

📒 Files selected for processing (1)
  • apps/server/src/pages/api/cron/sync-ro-users.ts (11 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
apps/server/src/pages/api/cron/sync-ro-users.ts

[error] 43-43: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

🔇 Additional comments (6)
apps/server/src/pages/api/cron/sync-ro-users.ts (6)

6-8: LGTM! Type imports are properly optimized.

The use of the type keyword for imports helps reduce bundle size by ensuring types are not included in the runtime code.


41-41: Remove temporary name prefix.

As previously discussed, the "NEW_" prefix was added for verification purposes and should be removed.

-name: "NEW_" + project.tpo.name,
+name: project.tpo.name,

167-167: Remove temporary name prefix.

The "NEW_" prefix should be removed as it was only used for verification purposes.

-name: "NEW_" + projectName,
+name: projectName,

284-296: LGTM! Proper handling of isMonitored flag during site dissociation.

Setting isMonitored to false when dissociating a site ensures consistent state management.


407-407: Remove console.log statement.

The error is already being logged using the logger utility.

-console.log(error);

321-322: Remove all temporary name prefixes.

Remove the "NEW_" and "UPDATE_" prefixes from all site names as they were only used for verification purposes.

-name:  "UPDATE_" + projectNameFormPP,
+name: projectNameFormPP,

-name: "NEW_" + siteName,
+name: siteName,

-name:  "UPDATE_" + siteName,
+name: siteName,

Also applies to: 353-354, 372-373

remoteId: project.tpo.id,
name: "NEW_" + project.tpo.name,
email: project.tpo.email,
isPlanetRO: project.tpo.id.startsWith("tpo_") ? true : false,
Copy link
Contributor Author

@rupamkairi rupamkairi Feb 17, 2025

Choose a reason for hiding this comment

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

Does this seem right? All profiles (prf_) would be false & tpo_ are in fact RO so only they will be true.

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.

1 participant