Skip to content

Comments

feat: add 'Delete All Spam' button on /mail/spam route (#886)#888

Closed
giteshsarvaiya wants to merge 3 commits intoMail-0:stagingfrom
giteshsarvaiya:feat/spam-delete-all-button-886
Closed

feat: add 'Delete All Spam' button on /mail/spam route (#886)#888
giteshsarvaiya wants to merge 3 commits intoMail-0:stagingfrom
giteshsarvaiya:feat/spam-delete-all-button-886

Conversation

@giteshsarvaiya
Copy link
Contributor

@giteshsarvaiya giteshsarvaiya commented May 6, 2025

Description

This PR (address #886):

  • adds a new function deleteAllSpamMails to delete all the spam mails
  • adds a new function checkSpamEMails to check if spam mails are present to do conditional rendering in components.
  • creates a button "Delete All Spam" in "/mail/spam" route that invokes onDeleteAllSpam (this function calls deleteAllSpam and also mutatesThreads and stats. then raises a toast to show the success/failure"

Type of Change

Please delete options that are not relevant.

  • ✨ New feature (non-breaking change which adds functionality)

Areas Affected

Please check all that apply:

  • Email Integration (Gmail, IMAP, etc.)
  • User Interface/Experience
  • Authentication/Authorization
  • Data Storage/Management
  • API Endpoints
  • Documentation
  • Testing Infrastructure
  • Development Workflow
  • Deployment/Infrastructure

Testing Done

Describe the tests you've done:

  • Manual testing is done.
  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed
  • Cross-browser testing (if UI changes)
  • Mobile responsiveness verified (if UI changes)

Security Considerations

For changes involving data or authentication:

  • No sensitive data is exposed
  • Authentication checks are in place
  • Input validation is implemented
  • Rate limiting is considered (if applicable)

Checklist

  • I have read the CONTRIBUTING document
  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in complex areas
  • I have updated the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix/feature works
  • All tests pass locally
  • Any dependent changes are merged and published

Screenshots/Recordings

Loom [Link]


By submitting this pull request, I confirm that my contribution is made under the terms of the project's license.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added detection of spam emails and a "Delete All Spam" button in the spam folder for bulk deletion.
  • UI Improvements

    • Enhanced styling of bulk action buttons for consistent size and color.
  • Chores

    • Updated Docker scripts to use the modern docker compose command.
  • Database

    • Added default user settings for new accounts.
    • Updated database schema snapshot and migration journal for consistency and tracking.

@vercel
Copy link

vercel bot commented May 6, 2025

@giteshsarvaiya is attempting to deploy a commit to the Zero Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 6, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The updates introduce spam management functions to the mail application, enabling detection and deletion of all spam emails via new asynchronous actions and UI elements. Database migrations set default user settings and update the migration snapshot and journal. Docker-related npm scripts are revised to use the modern docker compose command.

Changes

File(s) Change Summary
apps/mail/actions/mail.ts Added checkSpamEmails and deleteAllSpamEmails async functions for spam detection and deletion, using the mail driver's API.
apps/mail/components/mail/mail.tsx Integrated spam check/delete actions, added UI state and button for deleting all spam, and refined button styling and category tab state.
package.json Updated Docker scripts to use docker compose instead of docker-compose.
packages/db/migrations/0025_salty_the_fallen.sql Set default JSONB value for the settings column in mail0_user_settings table.
packages/db/migrations/meta/0025_snapshot.json Added migration snapshot defining schema for all mail-related tables, including new defaults and constraints.
packages/db/migrations/meta/_journal.json Appended new migration entry for "0025_salty_the_fallen" with version, timestamp, and breakpoints flag.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MailUI
    participant Actions
    participant Driver

    User->>MailUI: Navigate to Spam folder
    MailUI->>Actions: checkSpamEmails()
    Actions->>Driver: list('SPAM')
    Driver-->>Actions: Return spam emails
    Actions-->>MailUI: { hasEmails, count }
    MailUI->>User: Show "Delete All Spam" button if hasEmails

    User->>MailUI: Click "Delete All Spam"
    MailUI->>Actions: deleteAllSpamEmails()
    Actions->>Driver: list('SPAM')
    Driver-->>Actions: Return spam emails
    Actions->>Driver: modifyLabels(emailIds, add=['TRASH'])
    Driver-->>Actions: Success
    Actions-->>MailUI: { success, message }
    MailUI->>User: Show toast notification
Loading

Possibly related PRs

Suggested labels

design

Suggested reviewers

  • MrgSub

Poem

In the warren of code, we sweep the spam away,
With buttons and scripts, our inboxes we sway.
Docker commands now fresh as dew,
And default settings, shiny and new.
A hop, a skip, migrations run—
The mail is tidied, the work is done!
🐇📬✨


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.

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

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

🧹 Nitpick comments (4)
apps/mail/actions/mail.ts (3)

193-209: Use optional chaining for cleaner null checking.

The function follows the existing error handling pattern but could use optional chaining for cleaner code.

-  return { 
-    hasEmails: !!(spamEmails && spamEmails.threads && spamEmails.threads.length > 0),
-    count: spamEmails?.threads?.length || 0
-  };
+  return { 
+    hasEmails: !!spamEmails?.threads?.length,
+    count: spamEmails?.threads?.length || 0
+  };
🧰 Tools
🪛 Biome (1.9.4)

[error] 202-202: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


211-236: Consider reusing existing bulkDeleteThread function.

The deleteAllSpamEmails function duplicates logic from the existing bulkDeleteThread function. Consider reusing it for better maintainability.

export const deleteAllSpamEmails = async () => {
  try {
    const driver = await getActiveDriver();
    
    // Get all emails from spam folder
    const spamEmails = await driver.list("spam");
    console.log(spamEmails);
    if (!spamEmails || spamEmails.threads.length === 0) {
      return { success: true, message: 'No spam emails to delete' };
    }
    
    // Extract email IDs
    const emailIds = spamEmails.threads.map((thread) => thread.id);
    
-    // Use bulkDeleteThread to move them to trash
-    await driver.modifyLabels(emailIds, { addLabels: ['TRASH'], removeLabels: [] });
+    // Use existing bulkDeleteThread function
+    await bulkDeleteThread({ ids: emailIds });
    
    return { 
      success: true, 
      message: `Successfully deleted ${emailIds.length} email(s) from spam folder` 
    };
  } catch (error) {
    console.error('Error deleting all spam emails:', error);
    throw error;
  }
};

216-218: Remove debug logging in production code.

The console.log(spamEmails) statement is likely for debugging and should be removed before production.

// Get all emails from spam folder
const spamEmails = await driver.list("spam");
-console.log(spamEmails);
if (!spamEmails || spamEmails.threads.length === 0) {
packages/db/migrations/meta/0025_snapshot.json (1)

90-111: Add indexes on foreign-key and frequently filtered columns
Every table that declares a foreign key (e.g., mail0_account.user_id, mail0_connection.user_id, mail0_note.user_id, mail0_writing_style_matrix.connectionId, etc.) currently has an empty indexes block. Without explicit indexes on these columns, join and lookup performance will degrade under load. Please add single-column indexes for each foreign-key column and any other columns frequently used in WHERE clauses (e.g., thread_id, connection_id).

Also applies to: 189-191, 263-265, 343-345, 418-420, 502-503, 570-571, 614-615, 672-673, 743-744, 781-782

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d73ebfa and b6e9e3f.

📒 Files selected for processing (6)
  • apps/mail/actions/mail.ts (1 hunks)
  • apps/mail/components/mail/mail.tsx (8 hunks)
  • package.json (1 hunks)
  • packages/db/migrations/0025_salty_the_fallen.sql (1 hunks)
  • packages/db/migrations/meta/0025_snapshot.json (1 hunks)
  • packages/db/migrations/meta/_journal.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/mail/actions/mail.ts (2)
apps/mail/app/api/driver/google.ts (1)
  • driver (183-1109)
apps/mail/actions/utils.ts (1)
  • getActiveDriver (33-63)
🪛 Biome (1.9.4)
apps/mail/actions/mail.ts

[error] 202-202: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (8)
package.json (1)

16-18: Use Docker Compose V2 CLI commands
The scripts have been correctly updated from the legacy docker-compose to the modern docker compose syntax.

packages/db/migrations/meta/_journal.json (1)

179-186: Clean migration journal entry added.

The new migration entry for "0025_salty_the_fallen" is properly structured and follows the existing pattern in the journal.

packages/db/migrations/0025_salty_the_fallen.sql (1)

1-1: Well-structured default settings configuration.

The migration properly sets default user preferences as a JSONB value for the "settings" column, ensuring new users have consistent initial configuration.

apps/mail/components/mail/mail.tsx (5)

82-82: Good state initialization for spam emails detection.

The state variable for tracking spam emails is correctly initialized as false by default.


139-157: Well-structured promise handling with appropriate user feedback.

The onDeleteAllSpam function properly handles the promise lifecycle with toast notifications for success/error states and triggers the necessary data refreshes.


184-198: Properly implemented effect hook for spam email detection.

The effect correctly checks for spam emails when in the spam folder and handles errors appropriately.


260-272: Well-implemented conditional UI for the Delete All Spam button.

The button is only rendered when in the spam folder and when spam emails are present, with appropriate styling that matches the rest of the application.


732-735: Simplified CategorySelect component initialization.

The component now properly uses useQueryState with a default value of 'Important'.

Comment on lines +751 to +780
"public.mail0_writing_style_matrix": {
"name": "mail0_writing_style_matrix",
"schema": "",
"columns": {
"connectionId": {
"name": "connectionId",
"type": "text",
"primaryKey": false,
"notNull": true
},
"numMessages": {
"name": "numMessages",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"style": {
"name": "style",
"type": "jsonb",
"primaryKey": false,
"notNull": true
},
"updatedAt": {
"name": "updatedAt",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Inconsistent column naming: use snake_case
The mail0_writing_style_matrix table defines columns connectionId and updatedAt in camelCase, while all other tables and columns use snake_case. For consistency and to avoid confusion (especially in SQL queries), these should be renamed to connection_id and updated_at.

@hiheyhello123
Copy link
Contributor

I think you provided the wrong demo link... Please double check.

@giteshsarvaiya
Copy link
Contributor Author

giteshsarvaiya commented May 6, 2025

I think you provided the wrong demo link... Please double check.

hey needle, thanks for pointing out, i had pasted a wrong link there, now the link has been updated

@MrgSub MrgSub changed the base branch from main to staging May 6, 2025 18:56
const driver = await getActiveDriver();

// Get all emails from spam folder
const spamEmails = await driver.list('spam');
Copy link
Collaborator

Choose a reason for hiding this comment

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

this deletes the default count of list which is 20 threads in the spam folder, which is the number of threads on the user's page, it doesn't delete all

Copy link
Collaborator

Choose a reason for hiding this comment

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

please use trpc

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Okay!

Copy link
Contributor Author

@giteshsarvaiya giteshsarvaiya May 6, 2025

Choose a reason for hiding this comment

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

oh yess, I see that the maxResult is set to 20 by default and can go upto 500(as per the gmail api provider). so yes, tRPC would be a better approach.

my next commit will have tRPC

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@MrgSub pls check now

Copy link
Contributor Author

Choose a reason for hiding this comment

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

what if we introduced pagination(to fetch all spams with maxResult 500) and implemented it with the same logic as of previous commit, i.e. without tRPC ? is there a specific reason we chose tRPC over server action ?

@BlankParticle
Copy link
Contributor

BlankParticle commented May 7, 2025

there was already trpc setup, why did you reimplement a 2nd TRPC client??

Edit: looks like your PR is based on main and not staging, the TRPC stuff has not been merged to main yet. Please rebase your PR on latest staging and using the existing TRPC code

@giteshsarvaiya
Copy link
Contributor Author

giteshsarvaiya commented May 7, 2025

hey @BlankParticle, yes, there is no tRPC in the main branch yet.
I just saw that staging branch has tRPC setup done already,will use this branch for raising PR

edit: thanks for the clarification

@MrgSub MrgSub closed this May 9, 2025
@giteshsarvaiya giteshsarvaiya deleted the feat/spam-delete-all-button-886 branch May 12, 2025 19:15
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.

4 participants