-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Disable unused drafts #409
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
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
164 changes: 164 additions & 0 deletions
164
apps/web/app/api/reply-tracker/disable-unused-auto-draft/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import subDays from "date-fns/subDays"; | ||
| import { withError } from "@/utils/middleware"; | ||
| import prisma from "@/utils/prisma"; | ||
| import { ActionType, SystemType } from "@prisma/client"; | ||
| import { createScopedLogger } from "@/utils/logger"; | ||
| import { hasPostCronSecret } from "@/utils/cron"; | ||
| import { captureException } from "@/utils/error"; | ||
|
|
||
| const logger = createScopedLogger("auto-draft/disable-unused"); | ||
|
|
||
| // Force dynamic to ensure fresh data on each request | ||
| export const dynamic = "force-dynamic"; | ||
| export const maxDuration = 300; | ||
|
|
||
| const MAX_DRAFTS_TO_CHECK = 10; | ||
|
|
||
| /** | ||
| * Disables auto-draft feature for users who haven't used their last 10 drafts | ||
| * Only checks drafts that are more than a day old to give users time to use them | ||
| */ | ||
| async function disableUnusedAutoDrafts() { | ||
| logger.info("Starting to check for unused auto-drafts"); | ||
|
|
||
| const oneDayAgo = subDays(new Date(), 1); | ||
|
|
||
| // TODO: may need to make this more efficient | ||
| // Find all users who have the auto-draft feature enabled (have an Action of type DRAFT_EMAIL) | ||
| const usersWithAutoDraft = await prisma.user.findMany({ | ||
| where: { | ||
| rules: { | ||
| some: { | ||
| systemType: SystemType.TO_REPLY, | ||
| actions: { | ||
| some: { | ||
| type: ActionType.DRAFT_EMAIL, | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| select: { | ||
| id: true, | ||
| rules: { | ||
| where: { | ||
| systemType: SystemType.TO_REPLY, | ||
| }, | ||
| select: { | ||
| id: true, | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| logger.info( | ||
| `Found ${usersWithAutoDraft.length} users with auto-draft enabled`, | ||
| ); | ||
|
|
||
| const results = { | ||
| usersChecked: usersWithAutoDraft.length, | ||
| usersDisabled: 0, | ||
| errors: 0, | ||
| }; | ||
|
|
||
| // Process each user | ||
| for (const user of usersWithAutoDraft) { | ||
| try { | ||
| // Find the last 10 drafts created for the user | ||
| const lastTenDrafts = await prisma.executedAction.findMany({ | ||
| where: { | ||
| executedRule: { | ||
| userId: user.id, | ||
| rule: { | ||
| systemType: SystemType.TO_REPLY, | ||
| }, | ||
| }, | ||
| type: ActionType.DRAFT_EMAIL, | ||
| draftId: { not: null }, | ||
| createdAt: { lt: oneDayAgo }, // Only check drafts older than a day | ||
| }, | ||
| orderBy: { | ||
| createdAt: "desc", | ||
| }, | ||
| take: MAX_DRAFTS_TO_CHECK, | ||
| select: { | ||
| id: true, | ||
| wasDraftSent: true, | ||
| draftSendLog: { | ||
| select: { | ||
| id: true, | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| // Skip if user has fewer than 10 drafts (not enough data to make a decision) | ||
| if (lastTenDrafts.length < MAX_DRAFTS_TO_CHECK) { | ||
| logger.info("Skipping user - only has few drafts", { | ||
| userId: user.id, | ||
| numDrafts: lastTenDrafts.length, | ||
| }); | ||
| continue; | ||
| } | ||
|
|
||
| // Check if any of the drafts were sent | ||
| const anyDraftsSent = lastTenDrafts.some( | ||
| (draft) => draft.wasDraftSent === true || draft.draftSendLog, | ||
| ); | ||
|
|
||
| // If none of the drafts were sent, disable auto-draft | ||
| if (!anyDraftsSent) { | ||
| logger.info("Disabling auto-draft for user - last 10 drafts not used", { | ||
| userId: user.id, | ||
| }); | ||
|
|
||
| // Delete the DRAFT_EMAIL actions from all TO_REPLY rules | ||
| await prisma.action.deleteMany({ | ||
| where: { | ||
| rule: { | ||
| userId: user.id, | ||
| systemType: SystemType.TO_REPLY, | ||
| }, | ||
| type: ActionType.DRAFT_EMAIL, | ||
| content: null, | ||
| }, | ||
| }); | ||
elie222 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| results.usersDisabled++; | ||
| } | ||
| } catch (error) { | ||
| logger.error("Error processing user", { userId: user.id, error }); | ||
| captureException(error); | ||
| results.errors++; | ||
| } | ||
| } | ||
|
|
||
| logger.info("Completed auto-draft usage check", results); | ||
| return results; | ||
| } | ||
|
|
||
| // For easier local testing | ||
| // export const GET = withError(async (request) => { | ||
| // if (!hasCronSecret(request)) { | ||
| // captureException( | ||
| // new Error("Unauthorized request: api/auto-draft/disable-unused"), | ||
| // ); | ||
| // return new Response("Unauthorized", { status: 401 }); | ||
| // } | ||
|
|
||
| // const results = await disableUnusedAutoDrafts(); | ||
| // return NextResponse.json(results); | ||
| // }); | ||
|
|
||
| export const POST = withError(async (request: Request) => { | ||
| if (!(await hasPostCronSecret(request))) { | ||
| captureException( | ||
| new Error("Unauthorized cron request: api/auto-draft/disable-unused"), | ||
| ); | ||
| return new Response("Unauthorized", { status: 401 }); | ||
| } | ||
|
|
||
| const results = await disableUnusedAutoDrafts(); | ||
| return NextResponse.json(results); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
N + 1 queries – fetch drafts in batch instead of per‑user loop
The loop issues one
executedAction.findManyper user. If thousands of users have auto‑draft enabled the route will:You can reduce round‑trips with a single query that groups by
userIdand aggregates the last 10 drafts per user, e.g.:Then process the in‑memory groups.
This will scale linearly with returned rows instead of users.