Skip to content

Campaign creation bug fix#26

Merged
dcodesdev merged 5 commits intomainfrom
dev
May 30, 2025
Merged

Campaign creation bug fix#26
dcodesdev merged 5 commits intomainfrom
dev

Conversation

@dcodesdev
Copy link
Owner

@dcodesdev dcodesdev commented May 30, 2025

Summary by CodeRabbit

  • New Features

    • Added the ability to retry individual messages independently of the overall campaign status.
  • Bug Fixes

    • Fixed campaign creation to ensure only subscribers from selected lists are targeted.
    • Resolved an issue where campaign cancellation did not affect all pending messages.
  • User Interface

    • Extended the cancel button to campaigns in "CREATING" and "SCHEDULED" states.
  • Chores

    • Updated release notes and incremented the version to 0.9.1.

@vercel
Copy link

vercel bot commented May 30, 2025

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

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
letter-space-docs ⬜️ Ignored (Inspect) Visit Preview May 30, 2025 5:26am
letter-space-landing-page ⬜️ Ignored (Inspect) Visit Preview May 30, 2025 5:26am

@coderabbitai
Copy link

coderabbitai bot commented May 30, 2025

Walkthrough

The changes introduce improved campaign cancellation and subscriber targeting logic. Campaigns can now be cancelled in additional states, and cancellation atomically updates all pending messages to a new "CANCELLED" status. Subscriber selection for campaigns is now strictly filtered by associated lists. Release notes and UI elements have been updated accordingly.

Changes

File(s) Change Summary
RELEASE_NOTES.md Updated to specify new features and detailed bug fixes; removed generic entries.
apps/backend/prisma/schema.prisma, apps/backend/prisma/migrations/20250530052056_message_status_update/migration.sql Added CANCELLED status to MessageStatus enum via schema and migration script.
apps/backend/src/campaign/mutation.ts, apps/backend/src/campaign/router.ts Renamed cancel to cancelCampaign; expanded cancellation logic to more states; atomic update of campaign and messages to CANCELLED.
apps/backend/src/cron/processQueuedCampaigns.ts Subscriber queries now filter by selected list IDs; function signature updated.
apps/backend/src/cron/sendMessages.ts Message sending decoupled from campaign status; includes CANCELLED in campaign completion logic.
apps/backend/src/index.ts On startup, connects to DB and migrates message statuses for cancelled campaigns before serving.
apps/web/src/pages/dashboard/campaigns/[id]/campaign-actions.tsx Cancel button now appears for campaigns in "CREATING" and "SCHEDULED" states as well as "SENDING".
package.json Version bumped from 0.9.0 to 0.9.1.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant WebApp
    participant Backend
    participant DB

    User->>WebApp: Click "Cancel" on campaign (CREATING/SENDING/SCHEDULED)
    WebApp->>Backend: cancelCampaign(campaignId)
    Backend->>DB: Begin transaction
    Backend->>DB: Update campaign status to CANCELLED
    Backend->>DB: Update all related messages (QUEUED/PENDING/RETRYING) to CANCELLED
    DB-->>Backend: Transaction committed
    Backend-->>WebApp: Success response
    WebApp-->>User: UI updates to show cancellation
Loading
sequenceDiagram
    participant CronJob
    participant DB

    CronJob->>DB: Get campaigns with status QUEUED
    CronJob->>DB: For each campaign, get associated list IDs
    CronJob->>DB: Fetch subscribers filtered by selected list IDs
    DB-->>CronJob: Return filtered subscribers
    CronJob->>DB: Create messages only for filtered subscribers
Loading

Poem

A bunny hops and taps its paw,
Campaigns now cancel with perfect law.
Subscribers filtered, lists precise,
Messages cancelled in a trice.
With status clear and logic tight,
The dashboard’s buttons feel just right.
Version bumped—release in sight! 🐇✨


📜 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 d96c91f and e527bf0.

📒 Files selected for processing (1)
  • apps/backend/src/cron/processQueuedCampaigns.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/backend/src/cron/processQueuedCampaigns.ts
✨ 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.
    • 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

@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 (2)
apps/backend/src/index.ts (1)

13-34: Good migration logic, but consider adding error handling.

The migration logic correctly ensures backwards compatibility by updating message statuses for already cancelled campaigns. The approach is sound and idempotent.

Consider adding error handling for the database connection and migration:

-prisma.$connect().then(async () => {
+prisma.$connect().then(async () => {
   console.log("Connected to database")
 
   // For backwards compatibility, set all messages that have campaign status === "CANCELLED" to "CANCELLED"
-  await prisma.message.updateMany({
+  try {
+    await prisma.message.updateMany({
       where: {
         Campaign: {
           status: "CANCELLED",
         },
         status: {
           in: ["QUEUED", "PENDING", "RETRYING"],
         },
       },
       data: {
         status: "CANCELLED",
       },
-    })
+    })
+    console.log("Migration completed successfully")
+  } catch (error) {
+    console.error("Migration failed:", error)
+    process.exit(1)
+  }
 
   app.listen(PORT, () => {
     console.log(`Server is running on port ${PORT}`)
   })
+}).catch((error) => {
+  console.error("Failed to connect to database:", error)
+  process.exit(1)
 })
apps/backend/src/cron/processQueuedCampaigns.ts (1)

122-132: Consider optimizing the database query structure.

While the logic is correct, fetching campaign lists in a separate query could be optimized by including the CampaignLists relation in the main campaign query earlier in the function.

Consider this optimization to reduce database calls:

const queuedCampaigns = await prisma.campaign.findMany({
  where: {
    status: "CREATING",
  },
  include: {
+   CampaignLists: {
+     select: { listId: true },
+   },
    Organization: {
      include: {
        GeneralSettings: true,
        SmtpSettings: true,
      },
    },
    Template: true,
  },
})

Then replace lines 122-132 with:

- const campaignLists = await prisma.campaign.findUnique({
-   where: { id: campaign.id },
-   select: {
-     CampaignLists: {
-       select: { listId: true },
-     },
-   },
- })
- 
- const selectedListIds =
-   campaignLists?.CampaignLists.map((cl) => cl.listId) || []
+ const selectedListIds = campaign.CampaignLists.map((cl) => cl.listId)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bafb4fd and eee5c36.

📒 Files selected for processing (9)
  • RELEASE_NOTES.md (1 hunks)
  • apps/backend/prisma/schema.prisma (1 hunks)
  • apps/backend/src/campaign/mutation.ts (3 hunks)
  • apps/backend/src/campaign/router.ts (2 hunks)
  • apps/backend/src/cron/processQueuedCampaigns.ts (3 hunks)
  • apps/backend/src/cron/sendMessages.ts (3 hunks)
  • apps/backend/src/index.ts (1 hunks)
  • apps/web/src/pages/dashboard/campaigns/[id]/campaign-actions.tsx (1 hunks)
  • package.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
apps/backend/src/campaign/router.ts (1)
apps/backend/src/campaign/mutation.ts (1)
  • cancelCampaign (391-443)
apps/backend/src/index.ts (2)
apps/backend/src/utils/prisma.ts (1)
  • prisma (3-28)
apps/backend/src/app.ts (1)
  • app (38-38)
apps/backend/src/cron/sendMessages.ts (1)
apps/backend/src/utils/prisma.ts (1)
  • prisma (3-28)
apps/backend/src/campaign/mutation.ts (1)
apps/backend/src/utils/prisma.ts (1)
  • prisma (3-28)
apps/backend/src/cron/processQueuedCampaigns.ts (1)
apps/backend/src/utils/prisma.ts (1)
  • prisma (3-28)
🪛 LanguageTool
RELEASE_NOTES.md

[uncategorized] ~7-~7: You might be missing the article “the” here.
Context: ...es - Fixed campaign creation targeting wrong subscribers (now filters by selected li...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

🔇 Additional comments (17)
apps/backend/prisma/schema.prisma (1)

201-201: LGTM! Enum extension correctly implements cancellation status.

The addition of CANCELLED to the MessageStatus enum properly supports the new campaign cancellation workflow. This change is backwards compatible and aligns with the transaction logic that updates both campaign and message statuses atomically.

package.json (1)

2-2: Appropriate version bump for bug fix release.

The patch version increment from "0.9.0" to "0.9.1" correctly follows semantic versioning for this bug fix release.

apps/backend/src/campaign/router.ts (1)

7-7: LGTM! Naming consistency fix aligns router with implementation.

The import and router mapping changes correctly align with the actual cancelCampaign function name shown in the mutation implementation. This ensures consistent naming throughout the codebase.

Also applies to: 20-20

apps/web/src/pages/dashboard/campaigns/[id]/campaign-actions.tsx (1)

203-205: LGTM! UI correctly extends cancellation to additional campaign states.

The addition of "CREATING" and "SCHEDULED" cases properly extends the cancel button functionality to match the backend capabilities. The fall-through behavior efficiently reuses the existing cancel button implementation, and this aligns with the backend mutation logic that supports cancelling campaigns in these states.

RELEASE_NOTES.md (1)

3-8: LGTM! Clear and informative release notes.

The release notes effectively document the new features and bug fixes. The static analysis hint about the missing "the" article is a false positive - the current phrasing is grammatically correct and appropriate for technical documentation.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~7-~7: You might be missing the article “the” here.
Context: ...es - Fixed campaign creation targeting wrong subscribers (now filters by selected li...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

apps/backend/src/cron/sendMessages.ts (3)

53-70: LGTM! Excellent implementation of message status independence.

The decoupling of message status from campaign status is well-implemented:

  • Clear comments explain the rationale
  • Proper organization filtering ensures security
  • Logic correctly allows retrying individual messages regardless of campaign state

This change enables the feature mentioned in the release notes where individual messages can be retried independently.


89-92: Good addition of organization filter for consistency.

Adding the organization filter to the retrying messages count query maintains consistency with the main message filtering logic and ensures proper security isolation.


103-103: Correct inclusion of CANCELLED status in completion logic.

Adding "CANCELLED" to the list of statuses that mark a campaign as completed is necessary for proper campaign lifecycle management with the new cancellation behavior.

apps/backend/src/campaign/mutation.ts (4)

201-201: Helpful comment about cascade behavior.

The comment clarifies the delete behavior, which is useful for understanding the data relationships.


391-391: Good function rename for clarity.

Renaming cancel to cancelCampaign is more descriptive and follows better naming conventions, especially in a file that contains multiple mutation functions.


413-418: Excellent expansion of cancellable states.

Allowing cancellation of campaigns in "CREATING", "SENDING", and "SCHEDULED" states provides much better user experience and covers all logical scenarios where cancellation should be possible.


420-440: Outstanding implementation of atomic cancellation.

The transaction-based approach ensures data consistency by atomically updating both the campaign status and all related message statuses. This prevents partial updates and race conditions.

Key benefits:

  • Atomicity ensures either all updates succeed or none do
  • Proper filtering of message statuses prevents overwriting already processed messages
  • Consistent state management across campaign and messages

This is a significant improvement over the previous non-atomic approach.

apps/backend/src/cron/processQueuedCampaigns.ts (5)

15-17: Good enhancement to function signature for list-based filtering.

The addition of the selectedListIds parameter properly restricts subscriber selection to specific lists, which aligns with the campaign creation bug fix objective.


19-21: Excellent defensive programming with early return.

The early return for empty selectedListIds prevents unnecessary database queries and correctly returns an empty result when no lists are selected.


28-28: Proper implementation of list-based filtering.

The query correctly filters subscribers to only include those belonging to the specified lists using the in operator.


134-137: Function call correctly updated with new parameter.

The function call properly passes the selectedListIds parameter, maintaining consistency with the updated function signature.


258-258: Consistent filtering logic applied to count query.

The count query correctly uses the same selectedListIds filtering logic as the main subscriber query, ensuring consistency between subscriber fetching and counting operations.

@dcodesdev dcodesdev merged commit f168e9a into main May 30, 2025
4 checks passed
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

Comments