-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Add bulk ban UI #3158
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
Add bulk ban UI #3158
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
04aa78f
Add `POST /partners/ban` API
steven-tey 14795da
Merge branch 'main' into ban-api
steven-tey db91cf6
Add bulk ban UI
devkiran dfa193a
fix the ban API response
devkiran b3e402b
Add bulk ban functionality to FraudEventGroupsTable and update API er…
devkiran bd35934
Update route.ts
devkiran 5c5b487
Update route.ts
devkiran a9fb9cf
Enhance error handling in ban partner API by introducing DubApiError …
devkiran 4b1d7ec
Update route.ts
devkiran f55dc36
Delete route.ts
devkiran fa9dab9
Update partners-table.tsx
devkiran de0bfd2
Merge branch 'main' into ban-ui
steven-tey 76456a1
add deduplicationId
steven-tey 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
71 changes: 71 additions & 0 deletions
71
apps/web/app/(ee)/api/cron/partners/ban/process/cancel-commissions.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,71 @@ | ||
| import { prisma } from "@dub/prisma"; | ||
|
|
||
| // Mark the commissions as cancelled | ||
| export async function cancelCommissions({ | ||
| programId, | ||
| partnerId, | ||
| }: { | ||
| programId: string; | ||
| partnerId: string; | ||
| }) { | ||
| let canceledCommissions = 0; | ||
| let failedBatches = 0; | ||
| const maxRetries = 3; | ||
|
|
||
| while (true) { | ||
| try { | ||
| const commissions = await prisma.commission.findMany({ | ||
| where: { | ||
| programId, | ||
| partnerId, | ||
| status: "pending", | ||
| }, | ||
| select: { | ||
| id: true, | ||
| }, | ||
| orderBy: { | ||
| id: "asc", | ||
| }, | ||
| take: 500, | ||
| }); | ||
|
|
||
| if (commissions.length === 0) { | ||
| break; | ||
| } | ||
|
|
||
| const { count } = await prisma.commission.updateMany({ | ||
| where: { | ||
| id: { | ||
| in: commissions.map((c) => c.id), | ||
| }, | ||
| }, | ||
| data: { | ||
| status: "canceled", | ||
| }, | ||
| }); | ||
|
|
||
| canceledCommissions += count; | ||
| } catch (error) { | ||
| failedBatches++; | ||
|
|
||
| // If we've failed too many times, break to avoid infinite loop | ||
| if (failedBatches >= maxRetries) { | ||
| console.error( | ||
| `Failed to cancel commissions after ${maxRetries} attempts. Stopping batch processing.`, | ||
| ); | ||
| break; | ||
| } | ||
|
|
||
| // Wait a bit before retrying the same batch | ||
| await new Promise((resolve) => setTimeout(resolve, 1000)); | ||
| } | ||
| } | ||
|
|
||
| if (failedBatches > 0) { | ||
| console.warn( | ||
| `Cancelled ${canceledCommissions} commissions with ${failedBatches} failed batch(es).`, | ||
| ); | ||
| } else { | ||
| console.info(`Cancelled ${canceledCommissions} commissions.`); | ||
| } | ||
| } | ||
229 changes: 229 additions & 0 deletions
229
apps/web/app/(ee)/api/cron/partners/ban/process/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,229 @@ | ||
| import { queueDiscountCodeDeletion } from "@/lib/api/discounts/queue-discount-code-deletion"; | ||
| import { handleAndReturnErrorResponse } from "@/lib/api/errors"; | ||
| import { createFraudEvents } from "@/lib/api/fraud/create-fraud-events"; | ||
| import { resolveFraudEvents } from "@/lib/api/fraud/resolve-fraud-events"; | ||
| import { linkCache } from "@/lib/api/links/cache"; | ||
| import { includeTags } from "@/lib/api/links/include-tags"; | ||
| import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions"; | ||
| import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw"; | ||
| import { verifyQstashSignature } from "@/lib/cron/verify-qstash"; | ||
| import { recordLink } from "@/lib/tinybird"; | ||
| import { BAN_PARTNER_REASONS } from "@/lib/zod/schemas/partners"; | ||
| import { sendEmail } from "@dub/email"; | ||
| import PartnerBanned from "@dub/email/templates/partner-banned"; | ||
| import { prisma } from "@dub/prisma"; | ||
| import { log } from "@dub/utils"; | ||
| import { z } from "zod"; | ||
| import { logAndRespond } from "../../../utils"; | ||
| import { cancelCommissions } from "./cancel-commissions"; | ||
|
|
||
| const schema = z.object({ | ||
| programId: z.string(), | ||
| partnerId: z.string(), | ||
| userId: z.string(), | ||
| }); | ||
|
|
||
| // POST /api/cron/partners/ban/process - do the post-ban processing | ||
| export async function POST(req: Request) { | ||
| try { | ||
| const rawBody = await req.text(); | ||
|
|
||
| await verifyQstashSignature({ | ||
| req, | ||
| rawBody, | ||
| }); | ||
|
|
||
| const { programId, partnerId, userId } = schema.parse(JSON.parse(rawBody)); | ||
|
|
||
| console.info(`Banning partner ${partnerId} from program ${programId}...`); | ||
|
|
||
| const { partner, links, ...programEnrollment } = | ||
| await getProgramEnrollmentOrThrow({ | ||
| partnerId, | ||
| programId, | ||
| include: { | ||
| partner: true, | ||
| links: { | ||
| include: { | ||
| ...includeTags, | ||
| discountCode: true, | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| if (programEnrollment.status !== "banned") { | ||
| return logAndRespond( | ||
| `Partner ${programEnrollment.partnerId} is not banned from program ${programEnrollment.programId}.`, | ||
| ); | ||
| } | ||
steven-tey marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| const commonWhere = { | ||
| programId, | ||
| partnerId, | ||
| }; | ||
|
|
||
| const [linksUpdated, bountySubmissions, discountCodes, payouts] = | ||
| await prisma.$transaction([ | ||
| // Disable links | ||
| prisma.link.updateMany({ | ||
| where: { | ||
| ...commonWhere, | ||
| }, | ||
| data: { | ||
| disabledAt: new Date(), | ||
| expiresAt: new Date(), | ||
| }, | ||
| }), | ||
|
|
||
| // Reject bounty submissions | ||
| prisma.bountySubmission.updateMany({ | ||
| where: { | ||
| ...commonWhere, | ||
| status: { | ||
| not: "approved", | ||
| }, | ||
| }, | ||
| data: { | ||
| status: "rejected", | ||
| }, | ||
| }), | ||
|
|
||
| // Remove discount codes | ||
| prisma.discountCode.updateMany({ | ||
| where: { | ||
| ...commonWhere, | ||
| }, | ||
| data: { | ||
| discountId: null, | ||
| }, | ||
| }), | ||
|
|
||
| // Cancel payouts | ||
| prisma.payout.updateMany({ | ||
| where: { | ||
| ...commonWhere, | ||
| status: "pending", | ||
| }, | ||
| data: { | ||
| status: "canceled", | ||
| }, | ||
| }), | ||
| ]); | ||
|
|
||
| console.info(`Disabled ${linksUpdated.count} links.`); | ||
| console.info(`Rejected ${bountySubmissions.count} bounty submissions.`); | ||
| console.info(`Removed ${discountCodes.count} discount codes.`); | ||
| console.info(`Cancelled ${payouts.count} payouts.`); | ||
|
|
||
| // Mark the commissions as cancelled | ||
| await cancelCommissions({ | ||
| programId, | ||
| partnerId, | ||
| }); | ||
|
|
||
| await Promise.all([ | ||
| // Sync total commissions | ||
| syncTotalCommissions({ | ||
| programId, | ||
| partnerId, | ||
| }), | ||
|
|
||
| // Expire links from cache | ||
| linkCache.expireMany(links), | ||
|
|
||
| // Delete links from Tinybird links metadata | ||
| recordLink(links, { deleted: true }), | ||
|
|
||
| // Queue discount code deletions | ||
| queueDiscountCodeDeletion( | ||
| links | ||
| .map((link) => link.discountCode?.id) | ||
| .filter((id): id is string => id !== undefined), | ||
| ), | ||
| ]); | ||
|
|
||
| // Find other programs where this partner is enrolled and approved | ||
| const programEnrollments = await prisma.programEnrollment.findMany({ | ||
| where: { | ||
| partnerId, | ||
| programId: { | ||
| not: programId, | ||
| }, | ||
| status: { | ||
| in: ["approved"], | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| await Promise.all([ | ||
| // Automatically resolve all pending fraud events for this partner in the current program | ||
| resolveFraudEvents({ | ||
| where: { | ||
| ...commonWhere, | ||
| }, | ||
| userId, | ||
| resolutionReason: | ||
| "Resolved automatically because the partner was banned.", | ||
| }), | ||
|
|
||
| // Create partnerCrossProgramBan fraud events for other programs where this partner | ||
| // is enrolled and approved, to flag potential cross-program fraud risk | ||
| createFraudEvents( | ||
| programEnrollments.map(({ programId }) => ({ | ||
| programId, | ||
| partnerId, | ||
| type: "partnerCrossProgramBan", | ||
| })), | ||
| ), | ||
| ]); | ||
|
|
||
| // Send email | ||
| if (partner.email) { | ||
| const program = await prisma.program.findUniqueOrThrow({ | ||
| where: { | ||
| id: programId, | ||
| }, | ||
| select: { | ||
| name: true, | ||
| slug: true, | ||
| supportEmail: true, | ||
| }, | ||
| }); | ||
|
|
||
| try { | ||
| await sendEmail({ | ||
| to: partner.email, | ||
| subject: `You've been banned from the ${program.name} Partner Program`, | ||
| variant: "notifications", | ||
| replyTo: program.supportEmail || "noreply", | ||
| react: PartnerBanned({ | ||
| partner: { | ||
| name: partner.name, | ||
| email: partner.email, | ||
| }, | ||
| program: { | ||
| name: program.name, | ||
| slug: program.slug, | ||
| }, | ||
| // A reason is always present because we validate the schema | ||
| bannedReason: programEnrollment.bannedReason | ||
| ? BAN_PARTNER_REASONS[programEnrollment.bannedReason!] | ||
| : "", | ||
| }), | ||
| }); | ||
| } catch {} | ||
| } | ||
|
|
||
| return logAndRespond( | ||
| `Partner ${partnerId} banned from the program ${programId}.`, | ||
| ); | ||
| } catch (error) { | ||
| await log({ | ||
| message: `Error banning partner /api/cron/partners/ban/process: ${error instanceof Error ? error.message : String(error)}`, | ||
| type: "cron", | ||
| }); | ||
|
|
||
| return handleAndReturnErrorResponse(error); | ||
| } | ||
| } | ||
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
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.
Retry counter is cumulative across batches instead of per-batch.
The
failedBatchescounter accumulates across all batches. If batch 1 fails twice then succeeds (failedBatches = 2), and batch 2 fails once (failedBatches = 3), the loop exits even though each batch hasn't exhausted its retries. This reduces resilience for large commission sets.🤖 Prompt for AI Agents