The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
improve fraud review table
Steven Teyd279c54f7d1d
diff --git a/apps/web/lib/api/fraud/hold-processed-commissions.ts b/apps/web/lib/api/fraud/hold-processed-commissions.tsindex 6545153a48..5e93e62492 100644--- a/apps/web/lib/api/fraud/hold-processed-commissions.ts+++ b/apps/web/lib/api/fraud/hold-processed-commissions.ts@@ -107,7 +107,7 @@ export async function holdProcessedCommissions(console.log(`Updated ${updatedCount} commissions to hold`);// updateMany re-checks eligibility, so a commission's status can change between findMany- // and updateMany (i.e. if they're aggregated to a payout). Only log/sync rows we actually held.+ // and updateMany (i.e. if their associated payout is updated). Only log/sync rows we actually held.let heldCommissions = processedCommissions;if (updatedCount < processedCommissions.length) {diff --git a/apps/web/lib/swr/use-fraud-events-paginated.ts b/apps/web/lib/swr/use-fraud-events-paginated.tsindex 532d14f71a..929d7ba469 100644--- a/apps/web/lib/swr/use-fraud-events-paginated.ts+++ b/apps/web/lib/swr/use-fraud-events-paginated.ts@@ -12,7 +12,7 @@ export function useFraudEventsPaginated<T = unknown>({pageSize,});- const { fraudEvents, loading, error, isValidating } = useFraudEvents<T>({+ const { fraudEvents, loading, error } = useFraudEvents<T>({page: pagination.pageIndex,pageSize: pagination.pageSize,});@@ -21,7 +21,7 @@ export function useFraudEventsPaginated<T = unknown>({return {fraudEvents,- loading: loading || isValidating,+ loading,error,pagination,setPagination,diff --git a/apps/web/scripts/migrations/backfill-fraud-hold-commissions.ts b/apps/web/scripts/migrations/backfill-hold-pending-commissions.tssimilarity index 52%rename from apps/web/scripts/migrations/backfill-fraud-hold-commissions.tsrename to apps/web/scripts/migrations/backfill-hold-pending-commissions.tsindex 03cf2266ad..571e386fa3 100644--- a/apps/web/scripts/migrations/backfill-fraud-hold-commissions.ts+++ b/apps/web/scripts/migrations/backfill-hold-pending-commissions.ts@@ -3,8 +3,11 @@ import {PARTNER_LEVEL_FRAUD_RULES,} from "@/lib/api/fraud/constants";import { prisma } from "@/lib/prisma";+import { groupBy } from "@dub/utils";import { CommissionStatus, FraudEventStatus, Prisma } from "@prisma/client";import "dotenv-flow/config";+import { trackCommissionStatusUpdate } from "../../lib/api/commissions/track-commission-update-activity-log";+import { syncTotalCommissions } from "../../lib/api/partners/sync-total-commissions";const BATCH_SIZE = 50;@@ -36,6 +39,7 @@ async function main() {where: {status: FraudEventStatus.pending,program: {+ slug: "acme",workspace: {plan: {in: ["enterprise", "advanced"],@@ -105,17 +109,35 @@ async function main() {}if (commissionWhere.length > 0) {- const commissions = await prisma.commission.findMany({- where: {- OR: commissionWhere,- ...holdEligibleWhere,- },- select: {- id: true,- },- });+ while (true) {+ const commissions = await prisma.commission.findMany({+ where: {+ OR: commissionWhere,+ ...holdEligibleWhere,+ },+ select: {+ id: true,+ amount: true,+ earnings: true,+ status: true,+ programId: true,+ partnerId: true,+ payoutId: true,+ program: {+ select: {+ id: true,+ workspaceId: true,+ },+ },+ },+ take: 250,+ });++ if (commissions.length === 0) {+ console.log("No more commissions to update to hold, breaking...");+ break;+ }- if (commissions.length > 0) {const { count: updatedCount } = await prisma.commission.updateMany({where: {id: {@@ -125,6 +147,7 @@ async function main() {},data: {status: CommissionStatus.hold,+ payoutId: null,},});@@ -132,6 +155,65 @@ async function main() {if (updatedCount > 0) {console.log(`Held ${updatedCount} commissions (total: ${totalHeld})`);++ // updateMany re-checks eligibility, so a commission's status can change between findMany+ // and updateMany (i.e. if they're aggregated to a payout). Only log/sync rows we actually held.+ let heldCommissions = commissions;++ if (updatedCount < commissions.length) {+ const commissionIds = commissions.map((c) => c.id);++ const heldCommissionIds = await prisma.commission.findMany({+ where: {+ id: {+ in: commissionIds,+ },+ status: CommissionStatus.hold,+ },+ select: {+ id: true,+ },+ });++ const heldIds = new Set(heldCommissionIds.map(({ id }) => id));++ heldCommissions = commissions.filter((c) => heldIds.has(c.id));+ }++ // Activity logs are scoped to a workspace + program, so batch by program.+ const commissionsByProgram = groupBy(+ heldCommissions,+ (c) => c.programId,+ );++ for (const commissions of Object.values(commissionsByProgram)) {+ const { id: programId, workspaceId } = commissions[0].program;++ await trackCommissionStatusUpdate({+ workspaceId,+ programId,+ commissions,+ newStatus: CommissionStatus.hold,+ });+ }++ const affectedPairs = [+ ...new Map(+ heldCommissions.map((c) => [+ `${c.programId}:${c.partnerId}`,+ { programId: c.programId, partnerId: c.partnerId },+ ]),+ ).values(),+ ];++ await Promise.all(+ affectedPairs.map(({ programId, partnerId }) =>+ syncTotalCommissions({+ programId,+ partnerId,+ }),+ ),+ );}}}diff --git a/apps/web/scripts/migrations/backfill-hold-processed-commissions.ts b/apps/web/scripts/migrations/backfill-hold-processed-commissions.tsnew file mode 100644index 0000000000..7d4578fe89--- /dev/null+++ b/apps/web/scripts/migrations/backfill-hold-processed-commissions.ts@@ -0,0 +1,251 @@+import {+ CUSTOMER_LEVEL_FRAUD_RULES,+ PARTNER_LEVEL_FRAUD_RULES,+} from "@/lib/api/fraud/constants";+import { prisma } from "@/lib/prisma";+import { groupBy } from "@dub/utils";+import {+ CommissionStatus,+ FraudEventStatus,+ PayoutStatus,+ Prisma,+} from "@prisma/client";+import "dotenv-flow/config";+import { trackCommissionStatusUpdate } from "../../lib/api/commissions/track-commission-update-activity-log";+import { syncTotalCommissions } from "../../lib/api/partners/sync-total-commissions";+import { retallyPayoutsAmount } from "../../lib/payouts/retally-payouts-amount";++const BATCH_SIZE = 50;++type PartnerLevelFraudRule = (typeof PARTNER_LEVEL_FRAUD_RULES)[number];+type CustomerLevelFraudRule = (typeof CUSTOMER_LEVEL_FRAUD_RULES)[number];++const holdEligibleWhere: Prisma.CommissionWhereInput = {+ status: CommissionStatus.processed,+ payout: {+ status: PayoutStatus.pending,+ },+ earnings: {+ gt: 0,+ },+ program: {+ workspace: {+ plan: {+ in: ["enterprise", "advanced"],+ },+ },+ },+};++// One-time backfill: hold processed commissions for partners who already have pending+// fraud groups but were not covered by the new hold-on-fraud-event logic.+async function main() {+ let startingAfter: string | undefined;+ let totalHeld = 0;++ while (true) {+ const riskGroups = await prisma.fraudEventGroup.findMany({+ where: {+ status: FraudEventStatus.pending,+ program: {+ slug: "acme",+ workspace: {+ plan: {+ in: ["enterprise", "advanced"],+ },+ },+ },+ },+ include: {+ fraudEvents: {+ select: {+ customerId: true,+ eventId: true,+ },+ },+ },+ take: BATCH_SIZE,+ orderBy: {+ id: "asc",+ },+ ...(startingAfter && {+ skip: 1,+ cursor: {+ id: startingAfter,+ },+ }),+ });++ console.log(`Found ${riskGroups.length} risk groups`);++ if (riskGroups.length === 0) {+ break;+ }++ const commissionWhere: Prisma.CommissionWhereInput[] = [];++ for (const riskGroup of riskGroups) {+ if (+ PARTNER_LEVEL_FRAUD_RULES.includes(+ riskGroup.type as PartnerLevelFraudRule,+ )+ ) {+ commissionWhere.push({+ programId: riskGroup.programId,+ partnerId: riskGroup.partnerId,+ });++ continue;+ }++ if (+ CUSTOMER_LEVEL_FRAUD_RULES.includes(+ riskGroup.type as CustomerLevelFraudRule,+ )+ ) {+ const customerIds = riskGroup.fraudEvents+ .map((event) => event.customerId)+ .filter((id): id is string => id !== null);++ if (customerIds.length > 0) {+ commissionWhere.push({+ programId: riskGroup.programId,+ partnerId: riskGroup.partnerId,+ customerId: {+ in: customerIds,+ },+ });+ }+ }+ }++ const payoutIdsToRetallySet = new Set<string>();+ if (commissionWhere.length > 0) {+ while (true) {+ const commissions = await prisma.commission.findMany({+ where: {+ OR: commissionWhere,+ ...holdEligibleWhere,+ },+ select: {+ id: true,+ amount: true,+ earnings: true,+ status: true,+ programId: true,+ partnerId: true,+ payoutId: true,+ program: {+ select: {+ id: true,+ workspaceId: true,+ },+ },+ },+ take: 250,+ });++ if (commissions.length === 0) {+ console.log("No more commissions to update to hold, breaking...");+ break;+ }++ // add payout IDs to retally for later+ for (const { payoutId } of commissions) {+ if (payoutId) payoutIdsToRetallySet.add(payoutId);+ }++ const { count: updatedCount } = await prisma.commission.updateMany({+ where: {+ id: {+ in: commissions.map((c) => c.id),+ },+ ...holdEligibleWhere,+ },+ data: {+ status: CommissionStatus.hold,+ payoutId: null,+ },+ });++ totalHeld += updatedCount;++ if (updatedCount > 0) {+ console.log(`Held ${updatedCount} commissions (total: ${totalHeld})`);++ // updateMany re-checks eligibility, so a commission's status can change between findMany+ // and updateMany (i.e. if their associated payout is updated). Only log/sync rows we actually held.+ let heldCommissions = commissions;++ if (updatedCount < commissions.length) {+ const commissionIds = commissions.map((c) => c.id);++ const heldCommissionIds = await prisma.commission.findMany({+ where: {+ id: {+ in: commissionIds,+ },+ status: CommissionStatus.hold,+ },+ select: {+ id: true,+ },+ });++ const heldIds = new Set(heldCommissionIds.map(({ id }) => id));++ heldCommissions = commissions.filter((c) => heldIds.has(c.id));+ }++ // Activity logs are scoped to a workspace + program, so batch by program.+ const commissionsByProgram = groupBy(+ heldCommissions,+ (c) => c.programId,+ );++ for (const commissions of Object.values(commissionsByProgram)) {+ const { id: programId, workspaceId } = commissions[0].program;++ await trackCommissionStatusUpdate({+ workspaceId,+ programId,+ commissions,+ newStatus: CommissionStatus.hold,+ });+ }++ const affectedPairs = [+ ...new Map(+ heldCommissions.map((c) => [+ `${c.programId}:${c.partnerId}`,+ { programId: c.programId, partnerId: c.partnerId },+ ]),+ ).values(),+ ];++ await Promise.all(+ affectedPairs.map(({ programId, partnerId }) =>+ syncTotalCommissions({+ programId,+ partnerId,+ }),+ ),+ );+ }+ }+ }++ // need to retally payouts to ensure the payout amount is correct+ await retallyPayoutsAmount(Array.from(payoutIdsToRetallySet));++ startingAfter = riskGroups[riskGroups.length - 1].id;++ if (riskGroups.length < BATCH_SIZE) {+ break;+ }+ }++ console.log(`Finished backfill. Held ${totalHeld} commissions total.`);+}++main();diff --git a/apps/web/ui/partners/fraud-risks/associated-commissions-table.tsx b/apps/web/ui/partners/fraud-risks/associated-commissions-table.tsxindex de470b5df8..993c7f3caf 100644--- a/apps/web/ui/partners/fraud-risks/associated-commissions-table.tsx+++ b/apps/web/ui/partners/fraud-risks/associated-commissions-table.tsx@@ -89,10 +89,7 @@ export function AssociatedCommissionsTable({header: "Customer",cell: ({ row }) =>row.original.customer ? (- <CustomerRowItem- customer={row.original.customer}- href={`/${slug}/program/customers/${row.original.customer.id}`}- />+ <CustomerRowItem customer={row.original.customer} />) : ("-"),@@ -148,6 +145,10 @@ export function AssociatedCommissionsTable({className: "[&_tr:last-child>td]:border-b-transparent",}),columnPinning: { right: ["menu"] },+ onRowClick: (row) =>+ window.open(`/${slug}/program/commissions/${row.original.id}`, "_blank"),+ onRowAuxClick: (row) =>+ window.open(`/${slug}/program/commissions/${row.original.id}`, "_blank"),thClassName: "border-l-0",tdClassName: "border-l-0",scrollWrapperClassName: "min-h-0",diff --git a/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-matching-customer-email-table.tsx b/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-matching-customer-email-table.tsxindex 79be3a9b3b..05323dcbef 100644--- a/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-matching-customer-email-table.tsx+++ b/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-matching-customer-email-table.tsx@@ -15,6 +15,19 @@ import * as z from "zod/v4";type EventDataProps = z.infer<(typeof fraudEventSchemas)["customerEmailMatch"]>;+function getRowHref(row: EventDataProps, workspaceSlug?: string) {+ if (!row.customer || !workspaceSlug) return null;++ if (+ row.customer.email &&+ row.metadata?.matchType === CustomerEmailMatchType.HISTORICAL_DOMAIN_MATCH+ ) {+ return `/${workspaceSlug}/program/customers?partnerId=${row.partner.id}&search=${extractEmailDomain(row.customer.email)}`;+ }++ return `/${workspaceSlug}/events?event=leads&interval=all&customerId=${row.customer.id}`;+}+const MATCH_TYPE_LABELS: Record<CustomerEmailMatchType, string> = {[CustomerEmailMatchType.EXACT]: "Exact email match",[CustomerEmailMatchType.DOMAIN_MATCH]: "Domain match",@@ -111,19 +124,11 @@ export function FraudMatchingCustomerEmailTable({size: 100,maxSize: 100,cell: ({ row }) => {- if (!row.original.customer) return null;+ const href = getRowHref(row.original, workspaceSlug);+ if (!href) return null;return (- <Link- href={- row.original.customer.email &&- row.original.metadata?.matchType ===- CustomerEmailMatchType.HISTORICAL_DOMAIN_MATCH- ? `/${workspaceSlug}/program/customers?partnerId=${row.original.partner.id}&search=${extractEmailDomain(row.original.customer.email)}`- : `/${workspaceSlug}/events?event=leads&interval=all&customerId=${row.original.customer.id}`- }- target="_blank"- >+ <Link href={href} target="_blank"><Buttonvariant="secondary"text="View"@@ -134,6 +139,14 @@ export function FraudMatchingCustomerEmailTable({},},],+ onRowClick: (row) => {+ const url = getRowHref(row.original, workspaceSlug);+ if (url) window.open(url, "_blank");+ },+ onRowAuxClick: (row) => {+ const url = getRowHref(row.original, workspaceSlug);+ if (url) window.open(url, "_blank");+ },resourceName: (p) => `event${p ? "s" : ""}`,thClassName: "border-l-0",tdClassName: "border-l-0",