Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@steven-tey
Copy link
Collaborator

@steven-tey steven-tey commented Jun 2, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new automated welcome email workflow that sends a welcome message and subscribes new users to relevant mailing lists 15 minutes after account creation.
    • Added a script to identify users who are partners but not workspace owners.
  • Improvements

    • Users are now subscribed to appropriate mailing audiences based on their role (partner or workspace owner).
    • Email subscription logic is more flexible, supporting multiple audience types.
    • Welcome email sending is now handled asynchronously for improved reliability and user experience.
    • Post-creation processes for workspaces and partners now include concurrent email subscription steps for better onboarding.
  • Bug Fixes

    • Improved error handling and response messaging for email workflows.

@steven-tey steven-tey requested review from Copilot and devkiran June 2, 2025 02:45
@vercel
Copy link
Contributor

vercel bot commented Jun 2, 2025

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

Name Status Preview Updated (UTC)
dub ✅ Ready (Inspect) Visit Preview Jun 2, 2025 3:03am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 2, 2025

Walkthrough

A new API route for sending delayed welcome emails and managing user subscriptions was introduced. Several modules were refactored to centralize and defer welcome email logic, utilize audience mappings, and run post-processing tasks concurrently. Email subscription logic now supports multiple audiences, and a script was added to query partner users without projects.

Changes

File(s) Change Summary
apps/web/app/(ee)/api/cron/welcome-user/route.ts Added a POST API route for delayed welcome email and audience subscription, triggered by QStash.
apps/web/app/api/workspaces/route.ts Refactored post-creation logic to run user updates and subscriptions concurrently via Promise.allSettled.
apps/web/lib/actions/partners/onboard-partner.ts Now concurrently completes applications and subscribes partners to email audience after onboarding.
apps/web/lib/auth/options.ts Replaced inline welcome email/subscription with scheduled QStash workflow; removed direct email logic.
apps/web/scripts/update-subscribers.ts New script to log users who are partners but not workspace owners.
packages/email/src/resend/index.ts Added and exported RESEND_AUDIENCES mapping for audience IDs.
packages/email/src/resend/subscribe.ts subscribe() now takes an optional audience key, uses RESEND_AUDIENCES for audience ID resolution.
packages/email/src/resend/unsubscribe.ts Now uses RESEND_AUDIENCES for audience ID; checks for resend client, updated error handling and comments.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AuthSystem
    participant QStash
    participant WelcomeAPI
    participant DB
    participant EmailService

    User->>AuthSystem: Sign up
    AuthSystem->>QStash: Schedule welcome workflow (15 min delay)
    QStash-->>WelcomeAPI: POST /api/cron/welcome-user (after delay)
    WelcomeAPI->>DB: Fetch user details
    alt User found and has email
        WelcomeAPI->>EmailService: Subscribe user to audience(s)
        alt User is workspace owner
            WelcomeAPI->>EmailService: Send welcome email
        end
    end
    WelcomeAPI-->>QStash: 200 OK (confirmation or skip)
Loading

Suggested reviewers

  • TWilson023

Poem

A hop, a skip, a welcome cheer,
New users join, their path is clear!
With QStash’s help, the mail will flow,
To partners, owners—let them know.
Subscriptions mapped, the code’s refined,
This bunny’s proud of what you’ll find!
🐇✨


📜 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 c6b3714 and 8bd993e.

📒 Files selected for processing (1)
  • apps/web/app/(ee)/api/cron/welcome-user/route.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/(ee)/api/cron/welcome-user/route.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai 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
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR updates the Resend audience setup to support multiple audiences by introducing the RESEND_AUDIENCES constant, and refactors the subscribe and unsubscribe flows accordingly. Key changes include:

  • Importing and utilizing the RESEND_AUDIENCES constant in both subscribe and unsubscribe modules.
  • Adding support for selecting the appropriate audience in subscribe functions.
  • Updating various API endpoints and partner onboarding flows to use the new setup.

Reviewed Changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
packages/email/src/resend/unsubscribe.ts Updated unsubscribe logic to use RESEND_AUDIENCES and a revised error check.
packages/email/src/resend/subscribe.ts Refactored subscribe method to accept an audience parameter and use RESEND_AUDIENCES.
packages/email/src/resend/index.ts Introduced the RESEND_AUDIENCES constant.
apps/web/scripts/update-subscribers.ts Minor updates importing dotenv-flow; no major functional change.
apps/web/lib/auth/options.ts Updated the welcome flow, replacing direct subscribe/sendEmail calls with qstash publishing.
apps/web/lib/actions/partners/onboard-partner.ts Added a subscribe call for partners when onboarding.
apps/web/app/api/workspaces/route.ts Integrated subscribe to assign default workspaces; updated Promise.allSettled usage.
apps/web/app/(ee)/api/cron/welcome-user/route.ts Enhanced the welcome-user API to subscribe users based on their account type.
Comments suppressed due to low confidence (1)

apps/web/app/api/workspaces/route.ts:147

  • [nitpick] Using the '&&' operator directly within the array passed to Promise.allSettled may reduce code clarity by introducing non-promise values. Consider restructuring this logic to explicitly create promises based on conditionals for better readability.
session.user["defaultWorkspace"] === null && prisma.user.update({

Copy link
Contributor

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

🧹 Nitpick comments (3)
packages/email/src/resend/index.ts (1)

52-55: Good centralization of audience management.

The RESEND_AUDIENCES constant centralizes audience ID management, which improves maintainability. However, consider making these audience IDs configurable via environment variables for better flexibility across different environments.

Consider this approach for environment-based configuration:

export const RESEND_AUDIENCES = {
-  "app.dub.co": "f5ff0661-4234-43f6-b0ca-a3f3682934e3",
-  "partners.dub.co": "6caf6898-941a-45b6-a59f-d0780c3004ac",
+  "app.dub.co": process.env.RESEND_APP_AUDIENCE_ID || "f5ff0661-4234-43f6-b0ca-a3f3682934e3",
+  "partners.dub.co": process.env.RESEND_PARTNERS_AUDIENCE_ID || "6caf6898-941a-45b6-a59f-d0780c3004ac",
};
apps/web/scripts/update-subscribers.ts (1)

2-2: Clarify the purpose of commented-out imports.

The commented-out imports suggest this script might be intended for future batch subscription operations. Consider adding a comment explaining the script's intended purpose or implementing the functionality if it's needed.

Would you like me to help implement the batch subscription functionality using the commented-out imports, or should these be removed if not needed?

apps/web/lib/auth/options.ts (1)

529-529: Consider adding error handling for QStash publish operation.

While the operation is wrapped in waitUntil and Promise.allSettled, consider adding specific error handling for the QStash publish operation to ensure failed welcome email scheduling is logged appropriately.

              qstash.publishJSON({
                url: `${APP_DOMAIN_WITH_NGROK}/api/cron/welcome-user`,
                // trigger welcome workflow 15 minutes after the user signed up
                delay: 15 * 60,
                body: { userId: user.id },
-              }),
+              }).catch((error) => {
+                console.error('Failed to schedule welcome email:', error);
+              }),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 54d006b and 7f16759.

📒 Files selected for processing (8)
  • apps/web/app/(ee)/api/cron/welcome-user/route.ts (1 hunks)
  • apps/web/app/api/workspaces/route.ts (2 hunks)
  • apps/web/lib/actions/partners/onboard-partner.ts (3 hunks)
  • apps/web/lib/auth/options.ts (2 hunks)
  • apps/web/scripts/update-subscribers.ts (1 hunks)
  • packages/email/src/resend/index.ts (1 hunks)
  • packages/email/src/resend/subscribe.ts (1 hunks)
  • packages/email/src/resend/unsubscribe.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
apps/web/app/api/workspaces/route.ts (1)
packages/email/src/resend/subscribe.ts (1)
  • subscribe (3-27)
packages/email/src/resend/unsubscribe.ts (1)
packages/email/src/resend/index.ts (2)
  • resend (4-6)
  • RESEND_AUDIENCES (52-55)
packages/email/src/resend/subscribe.ts (1)
packages/email/src/resend/index.ts (2)
  • RESEND_AUDIENCES (52-55)
  • resend (4-6)
apps/web/lib/auth/options.ts (1)
packages/utils/src/constants/main.ts (1)
  • APP_DOMAIN_WITH_NGROK (20-25)
apps/web/lib/actions/partners/onboard-partner.ts (2)
apps/web/lib/partners/complete-program-applications.ts (1)
  • completeProgramApplications (11-130)
packages/email/src/resend/subscribe.ts (1)
  • subscribe (3-27)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (20)
packages/email/src/resend/unsubscribe.ts (2)

1-1: Good alignment with centralized audience management.

The import of RESEND_AUDIENCES aligns well with the centralized approach introduced in the index file.


12-15:

Details

✅ Verification successful

Verify removal of optional chaining is safe.

The optional chaining operator was removed from resend.contacts.remove(). Ensure that resend is guaranteed to be non-null at this point, given the check at line 4.


🏁 Script executed:

#!/bin/bash
# Description: Verify usage patterns of the unsubscribe function to ensure resend is always available
# Expected: All calls to unsubscribe should be after resend availability checks

rg -A 10 -B 5 "unsubscribe\(" --type ts

Length of output: 6908


Optional chaining removal is safe

The unsubscribe function includes an early-return guard (if (!resend) return;), so by the time we reach resend.contacts.remove(...), resend is guaranteed non-null. No further changes are needed.

apps/web/lib/auth/options.ts (2)

20-22: Good addition of required imports for deferred processing.

The imports for APP_DOMAIN_WITH_NGROK and qstash are appropriate for the new deferred welcome email approach.


528-534:

Details

✅ Verification successful

Excellent architectural improvement with deferred welcome emails.

The shift from immediate to deferred welcome email processing using QStash is a good architectural decision that:

  • Prevents blocking the sign-in flow
  • Allows for more sophisticated welcome workflows
  • Provides better error isolation

The 15-minute delay seems reasonable for onboarding workflows.

Verify that the /api/cron/welcome-user endpoint exists and properly handles the payload:


🏁 Script executed:

#!/bin/bash
# Description: Verify the welcome-user API route exists and check its implementation
# Expected: Should find the route file and verify it handles the userId payload

fd "welcome-user" --type f --extension ts --extension js
ast-grep --pattern 'export async function POST($_) { $$$ }'

Length of output: 68965


Verified /api/cron/welcome-user endpoint and payload handling

  • Confirmed in apps/web/app/api/cron/welcome-user/route.ts
    • Exports POST(req: Request)
    • Calls verifyQstashSignature, parses rawBody, and extracts userId
    • Fetches the user and early-returns on missing user or email
    • Triggers partner and workspace Owner welcome emails based on user data

All verification steps pass—no further action required.

packages/email/src/resend/subscribe.ts (4)

1-1: LGTM: Clean import of new dependencies

The import statements correctly bring in the resend client and RESEND_AUDIENCES mapping needed for the refactored subscription logic.


6-10: LGTM: Well-typed audience parameter with sensible default

The function signature enhancement is well-designed:

  • Optional audience parameter with good default value
  • Proper TypeScript typing using keyof typeof RESEND_AUDIENCES
  • Maintains backward compatibility for existing callers

12-15: LGTM: Improved error checking logic

The error checking has been appropriately updated to check for the resend client existence rather than the environment variable. This is more accurate since the client encapsulates the API key dependency.


17-26: LGTM: Clean audience ID resolution

The audience ID resolution using the mapping is clean and the contact creation logic remains unchanged, ensuring consistency with the existing behavior.

apps/web/app/api/workspaces/route.ts (2)

9-9: LGTM: Appropriate import for subscription functionality

The import correctly brings in the updated subscribe function needed for user subscription logic.


146-165: LGTM: Well-structured concurrent post-creation operations

The implementation is excellent:

  • Uses waitUntil appropriately for non-blocking async operations
  • Promise.allSettled ensures both operations run concurrently without failing if one errors
  • Conditional logic for default workspace update makes sense
  • Subscription to "app.dub.co" audience is appropriate for workspace owners
  • Proper parameter passing with graceful handling of null name

The approach aligns well with the overall refactoring to centralize subscription logic.

apps/web/lib/actions/partners/onboard-partner.ts (3)

7-7: LGTM: Appropriate import for subscription functionality

The import correctly brings in the updated subscribe function for partner subscription logic.


68-93: LGTM: Maintains existing partner creation logic

The partner creation/update logic remains unchanged, which is appropriate since this change focuses on post-creation subscription handling.


95-106: LGTM: Well-implemented concurrent post-onboarding operations

The implementation follows the same excellent pattern as the workspace route:

  • Uses waitUntil for non-blocking async operations
  • Promise.allSettled ensures both operations run concurrently
  • Maintains existing program application completion logic
  • Adds appropriate subscription to "partners.dub.co" audience
  • Smart name resolution using user.name || partner.name || undefined

The approach is consistent with the overall refactoring strategy.

apps/web/app/(ee)/api/cron/welcome-user/route.ts (7)

1-8: LGTM: Appropriate imports and configuration

The imports are correct for the cron job functionality, and dynamic = "force-dynamic" is appropriate for a cron endpoint that should not be cached.


10-13: LGTM: Clear documentation of route purpose

The comment clearly explains the route's purpose and timing, which is helpful for maintainability.


14-31: LGTM: Proper request handling and user lookup

The implementation correctly:

  • Verifies QStash signature for security
  • Parses the request body to extract userId
  • Fetches user with appropriate related data (partners, projects)
  • Selects only needed fields for efficiency

33-40: LGTM: Appropriate early returns for missing data

The early returns for missing user or email are appropriate and use 200 status codes since these are expected scenarios that shouldn't be retried.


42-43: LGTM: Clear role determination logic

The boolean flags for user roles are clear and easy to understand.


45-70: LGTM: Well-structured subscription and email logic

The implementation is excellent:

  • Uses Promise.all for concurrent operations
  • Conditional subscriptions based on user roles
  • Appropriate audience selection for each role
  • Proper email template usage
  • Good parameter passing with fallback handling

The TODO comment for partners welcome email is noted and reasonable.


73-76: LGTM: Proper error handling

The error handling uses the centralized error handler, which is consistent with the application's error handling patterns.

@steven-tey steven-tey merged commit a89c581 into main Jun 2, 2025
8 checks passed
@steven-tey steven-tey deleted the resend-audience branch June 2, 2025 04:55
This was referenced Jun 2, 2025
@coderabbitai coderabbitai bot mentioned this pull request Jun 9, 2025
@coderabbitai coderabbitai bot mentioned this pull request Sep 4, 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.

3 participants