-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathcommissions.ts
More file actions
615 lines (589 loc) · 19.4 KB
/
Copy pathcommissions.ts
File metadata and controls
615 lines (589 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
import { DATE_RANGE_INTERVAL_PRESETS } from "@/lib/analytics/constants";
import { CommissionStatus, CommissionType } from "@prisma/client";
import * as z from "zod/v4";
import { createCustomerBodySchema, CustomerSchema } from "./customers";
import { LinkSchema } from "./links";
import {
getCursorPaginationQuerySchema,
getPaginationQuerySchema,
} from "./misc";
import { EnrolledPartnerSchema, WebhookPartnerSchema } from "./partners";
import { PayoutSchema } from "./payouts";
import { rewardContextSchema, RewardSchema } from "./rewards";
import { UserSchema } from "./users";
import { centsSchema, parseDateSchema } from "./utils";
export const CommissionSchema = z.object({
id: z.string().describe("The commission's unique ID on Dub.").meta({
example: "cm_1JVR7XRCSR0EDBAF39FZ4PMYE",
}),
type: z.enum(CommissionType).optional(), // Note: Not sure the type will ever be optional
amount: z.number(),
earnings: z.number(),
currency: z.string(),
status: z.enum(CommissionStatus),
invoiceId: z.string().nullable(),
description: z.string().nullable(),
quantity: z.number(),
userId: z
.string()
.nullish()
.describe("The user who created the manual commission."),
createdAt: z.date(),
updatedAt: z.date(),
});
// Represents the commission object used in webhook and API responses (/api/commissions/**)
export const CommissionEnrichedSchema = CommissionSchema.extend({
paidAt: z
.date()
.nullable()
.describe(
"The date the commission was paid out to the partner. Null if not paid yet.",
),
partner: EnrolledPartnerSchema.pick({
id: true,
name: true,
email: true,
image: true,
payoutsEnabledAt: true,
country: true,
groupId: true,
}),
customer: CustomerSchema.nullish(), // customer can be null for click-based / custom commissions
});
// Schema for the commission detail page (GET /api/commissions/:commissionId)
// TODO: Simplify this for OpenAPI and limit extra fields to in-app only – similar to getLinkInfoQuerySchemaExtended logic
export const CommissionDetailSchema = CommissionEnrichedSchema.extend({
user: UserSchema.nullish().describe("The user who created the commission."),
reward: RewardSchema.pick({
event: true,
description: true,
type: true,
amountInCents: true,
amountInPercentage: true,
}).nullish(),
payout: PayoutSchema.pick({
id: true,
paidAt: true,
initiatedAt: true,
})
.extend({
user: UserSchema.nullish().describe("The user who processed the payout."),
})
.nullish(),
holdingPeriodDays: z
.number()
.nullish()
.describe("The holding period days for the partner group."),
});
// "commission.created" webhook event schema
export const CommissionWebhookSchema = CommissionSchema.extend({
partner: WebhookPartnerSchema,
customer: CustomerSchema.nullish(), // customer can be null for click-based / custom commissions
link: LinkSchema.pick({
id: true,
shortLink: true,
domain: true,
key: true,
}).nullable(),
});
export const COMMISSIONS_MAX_PAGE_SIZE = 100;
export const getCommissionsQuerySchema = z
.object({
type: z
.enum(CommissionType)
.optional()
.describe(
"Filter the list of commissions by type. " +
"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +
"Examples: `sale`, `sale,lead`, `-click`.",
),
customerId: z
.string()
.optional()
.describe("Filter the list of commissions by the associated customer."),
payoutId: z
.string()
.optional()
.describe("Filter the list of commissions by the associated payout."),
partnerId: z
.string()
.optional()
.describe(
"Filter the list of commissions by the associated partner. When specified, takes precedence over `tenantId`. " +
"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +
"Examples: `partner_abc`, `partner_abc,partner_xyz`, `-partner_abc`.",
),
tenantId: z
.string()
.optional()
.describe(
"Filter the list of commissions by the associated partner's `tenantId` (their unique ID within your database).",
),
groupId: z
.string()
.optional()
.describe(
"Filter the list of commissions by the associated partner group. " +
"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +
"Examples: `group_abc`, `group_abc,group_xyz`, `-group_abc`.",
),
partnerTagId: z
.string()
.optional()
.describe(
"Filter the list of commissions by the associated partner tag. " +
"Supports advanced filtering: single value, multiple values (comma-separated), or exclusion (prefix with `-`). " +
"Examples: `ptag_abc`, `ptag_abc,ptag_xyz`, `-ptag_abc`.",
),
invoiceId: z
.string()
.optional()
.describe(
"Filter the list of commissions by the associated invoice. Since invoiceId is unique on a per-program basis, this will only return one commission per invoice.",
),
status: z
.enum(CommissionStatus)
.optional()
.describe(
"Filter the list of commissions by their corresponding status.",
),
sortBy: z
.enum(["createdAt", "amount"])
.default("createdAt")
.describe("The field to sort the list of commissions by."),
sortOrder: z
.enum(["asc", "desc"])
.default("desc")
.describe("The sort order for the list of commissions."),
interval: z
.enum(DATE_RANGE_INTERVAL_PRESETS)
.default("all")
.describe("The interval to retrieve commissions for."),
start: parseDateSchema
.optional()
.describe(
"The start date of the date range to filter the commissions by.",
),
end: parseDateSchema
.optional()
.describe("The end date of the date range to filter the commissions by."),
timezone: z.string().optional(),
})
.extend({
...getCursorPaginationQuerySchema({
example: "cm_1KAP4CGN2Z5TPYYQ1W4JEYD56",
}),
...getPaginationQuerySchema({
pageSize: COMMISSIONS_MAX_PAGE_SIZE,
deprecated: true,
}),
});
export const getCommissionsCountQuerySchema = getCommissionsQuerySchema
.omit({
page: true,
pageSize: true,
sortOrder: true,
sortBy: true,
startingAfter: true,
endingBefore: true,
})
.extend({
// Accept raw string to support comma-separated multi-value (e.g. "sale,lead")
type: z.string().optional(),
});
export const commissionPatchStatusSchema = z.enum([
"pending",
"refunded",
"duplicate",
"canceled",
"fraud",
]);
export const updateCommissionSchema = z.object({
earnings: z
.number()
.min(0)
.optional()
.describe(
"The new earnings amount for the commission. Paid commissions cannot be updated. If provided, will override the earnings calculated based on the sale amount and currency.",
),
saleAmount: z
.number()
.min(0)
.optional()
.describe(
"The new absolute amount for the sale. Paid commissions cannot be updated.",
),
modifySaleAmount: z
.number()
.optional()
.describe(
"Modify the current sale amount: use positive values to increase the amount, negative values to decrease it. Takes precedence over `saleAmount`. Paid commissions cannot be updated.",
),
currency: z
.string()
.optional()
.default("usd")
.transform((val) => val.toLowerCase())
.describe(
"The currency of the sale amount to update. Accepts ISO 4217 currency codes.",
),
status: commissionPatchStatusSchema
.optional()
.describe(
"Useful for marking a commission as pending, refunded, duplicate, canceled, or fraudulent. Takes precedence over `saleAmount` and `modifySaleAmount`. When a commission is marked as pending, refunded, duplicate, canceled, or fraudulent, it will be omitted from the payout, and the payout amount will be recalculated accordingly. Paid commissions cannot be updated.",
),
amount: z
.number()
.min(0)
.optional()
.describe("Deprecated. Use `saleAmount` instead.")
.meta({ deprecated: true }),
modifyAmount: z
.number()
.optional()
.describe("Deprecated. Use `modifySaleAmount` instead.")
.meta({ deprecated: true }),
});
export const updateCommissionSchemaExtended = updateCommissionSchema.extend({
updateHistoricalCommissions: z.boolean().optional(),
});
export const bulkUpdateCommissionsSchema = z.object({
commissionIds: z
.array(z.string())
.min(1, "At least one commission ID is required.")
.max(100, "You can only update up to 100 commissions at a time.")
.refine((ids) => new Set(ids).size === ids.length, {
message: "commissionIds must be unique.",
}),
status: commissionPatchStatusSchema.describe(
"The status to apply to every commission in the batch.",
),
});
export const CLAWBACK_REASONS = [
{
value: "order_canceled",
label: "Order Canceled",
description: "Order was canceled or refunded.",
},
{
value: "fraud",
label: "Fraud",
description: "Fraudulent or invalid transaction.",
},
{
value: "terms_violation",
label: "Terms Violation",
description: "Partner broke program rules.",
},
{
value: "tracking_error",
label: "Tracking Error",
description: "Commission was assigned by mistake.",
},
{
value: "payment_failed",
label: "Payment Failed",
description: "Customer payment failed or was reversed.",
},
{
value: "ineligible_partner",
label: "Ineligible Partner",
description: "Partner was not eligible for this reward.",
},
{
value: "duplicate_commission",
label: "Duplicate Commission",
description: "Commission was a duplicate entry.",
},
{
value: "other",
label: "Other",
description: "Other issue not listed.",
},
];
export const CLAWBACK_REASONS_MAP = Object.fromEntries(
CLAWBACK_REASONS.map((r) => [r.value, r]),
);
export const COMMISSION_EXPORT_COLUMNS = [
{ id: "id", label: "ID", type: "string", default: true },
{ id: "type", label: "Type", type: "string", default: true },
{ id: "amount", label: "Amount", type: "money", default: true },
{ id: "earnings", label: "Earnings", type: "money", default: true },
{ id: "currency", label: "Currency", type: "string", default: true },
{ id: "status", label: "Status", type: "string", default: true },
{ id: "invoiceId", label: "Invoice ID", type: "string", default: true },
{ id: "quantity", label: "Quantity", type: "number", default: true },
{ id: "createdAt", label: "Created at", type: "date", default: true },
{ id: "paidAt", label: "Paid at", type: "date", default: false },
{ id: "updatedAt", label: "Updated at", type: "date", default: false },
{ id: "partnerId", label: "Partner ID", type: "string", default: false },
{ id: "partnerName", label: "Partner name", type: "string", default: false },
{
id: "partnerEmail",
label: "Partner email",
type: "string",
default: false,
},
{
id: "partnerTenantId",
label: "Partner tenant ID",
type: "string",
default: false,
},
{ id: "customerId", label: "Customer ID", type: "string", default: false },
{
id: "customerName",
label: "Customer name",
type: "string",
default: false,
},
{
id: "customerEmail",
label: "Customer email",
type: "string",
default: false,
},
{
id: "customerExternalId",
label: "Customer external ID",
type: "string",
default: false,
},
{
id: "stripeCustomerId",
label: "Stripe customer ID",
type: "string",
default: false,
},
] as const;
type CommissionExportColumnId =
(typeof COMMISSION_EXPORT_COLUMNS)[number]["id"];
export const DEFAULT_COMMISSION_EXPORT_COLUMNS =
COMMISSION_EXPORT_COLUMNS.filter((column) => column.default).map(
(column) => column.id,
);
export const commissionsExportQuerySchema = getCommissionsQuerySchema
.omit({
page: true,
pageSize: true,
startingAfter: true,
endingBefore: true,
})
.extend({
columns: z
.string()
.default(DEFAULT_COMMISSION_EXPORT_COLUMNS.join(","))
.transform((v) =>
v
.split(",")
.map((s) => s.trim())
.filter(Boolean),
)
.refine(
(columns): columns is CommissionExportColumnId[] => {
const validColumnIds = COMMISSION_EXPORT_COLUMNS.map((col) => col.id);
return columns.every((column): column is CommissionExportColumnId =>
validColumnIds.includes(column as CommissionExportColumnId),
);
},
{
message:
"Invalid column IDs provided. Please check the available columns.",
},
),
});
export const createPartnerCommissionSchema = z.object({
event: z.enum(CommissionType),
partnerId: z.string(),
programId: z.string(),
linkId: z.string().optional(),
customerId: z.string().optional(),
eventId: z.string().optional(),
invoiceId: z.string().nullish(),
amount: z.number().default(0).optional(),
quantity: z.number().default(1),
currency: z.string().optional(),
description: z.string().nullish(),
createdAt: z.coerce.date().optional(),
status: commissionPatchStatusSchema.optional(), // used for create-manual-commission (import commission as refunded)
userId: z.string().optional(),
context: rewardContextSchema.optional(),
skipWorkflow: z.boolean().default(false).optional(),
isFirstConversion: z.boolean().optional(),
bountySubmissionId: z
.string()
.optional()
.describe(
"The ID of the bounty submission that the commission should be created for.",
),
clickEvent: z
.object({
url: z.string().nullable(),
referer: z.string().nullable(),
})
.optional(),
triggerAggregateDueCommissions: z
.boolean()
.default(false)
.optional()
.describe(
"Whether to trigger the triggerAggregateDueCommissionsCronJob or not.",
),
});
export const createManualCommissionBodySchema = z
.discriminatedUnion("type", [
// Custom commission (negative amount = clawback)
z.object({
type: z.literal("custom"),
partnerId: z
.string()
.describe("The ID of the partner to create the commission for."),
amount: centsSchema
.pipe(
z.number().refine((n) => n !== 0, {
message: "Amount cannot be 0.",
}),
)
.describe(
"The commission amount in cents. Use a negative amount to create a clawback.",
),
date: parseDateSchema
.nullish()
.describe("If not provided, the current date will be used."),
description: z
.string()
.max(190)
.nullish()
.describe(
"The description of the commission. Required for clawbacks (negative `amount`). May be a known clawback reason (`order_canceled`, `fraud`, `terms_violation`, `tracking_error`, `payment_failed`, `ineligible_partner`, `duplicate_commission`, `other`) or any other string.",
),
}),
// Lead commission
z.object({
type: z.literal("lead"),
partnerId: z
.string()
.describe("The ID of the partner to create the commission for."),
customerId: z
.string()
.nullish()
.describe(
"The customer ID to associate the commission with. Useful if the customer was already created in a prior operation and you want to associate the commission with it.",
),
customer: createCustomerBodySchema
.nullish()
.describe(
"The full customer object to associate the commission with. Useful for creating the customer on demand.",
),
linkId: z
.string()
.nullish()
.describe(
"The partner link ID to associate the commission with. If not provided, default to the link with the most revenue.",
),
leadEventDate: parseDateSchema
.nullish()
.describe(
"The date and time of the lead event. If not provided, defaults to the current date and time.",
),
leadEventName: z
.string()
.nullish()
.default("Sign up")
.describe(
"The name of the lead event. If not provided, defaults to 'Sign up'.",
),
}),
// Sale commission
z.object({
type: z.literal("sale"),
partnerId: z
.string()
.describe("The ID of the partner to create the commission for."),
customerId: z
.string()
.nullish()
.describe(
"The customer ID to associate the commission with. Useful if the customer was already created in a prior operation and you want to associate the commission with it.",
),
customer: createCustomerBodySchema
.nullish()
.describe(
"The full customer object to associate the commission with. Useful for creating the customer on demand.",
),
linkId: z
.string()
.nullish()
.describe(
"The partner link ID to associate the commission with. If not provided, default to the link with the most revenue.",
),
importStripeInvoices: z
.boolean()
.nullish()
.default(false)
.describe(
"When `true`, import all unimported paid Stripe invoices for the customer and create a commission for each. When `false`, create a single manual sale event using `saleAmount`.",
),
saleAmount: centsSchema
.pipe(z.number().min(0))
.nullish()
.describe(
"Required when `importStripeInvoices` is `false`. The sale amount in cents for the manual sale event. Ignored when importing from Stripe.",
),
saleEventDate: parseDateSchema
.nullish()
.describe(
"Only used when `importStripeInvoices` is `false`. The date of the manual sale event. Defaults to the current date and time if not provided.",
),
invoiceId: z
.string()
.nullish()
.describe(
"Only used when `importStripeInvoices` is `false`. An optional invoice ID to attach to the generated sale event and commission entry for deduplication.",
),
productId: z
.string()
.nullish()
.describe(
"Only used when `importStripeInvoices` is `false`. An optional product ID stored on the sale event metadata – will also impact commission earnings calculation (if a `Sale` `Product ID` modifier is set).",
),
}),
])
.superRefine((data, ctx) => {
if (data.type === "custom") {
if (data.amount < 0 && !data.description?.trim()) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"`description` is required when creating a clawback (negative amount).",
path: ["description"],
});
}
return;
}
if (data.type === "sale") {
if (data.importStripeInvoices) {
return;
}
if (data.saleAmount == null) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"`saleAmount` is required when `importStripeInvoices` is false.",
path: ["saleAmount"],
});
return;
}
if (data.saleAmount === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Sale amount cannot be 0.",
path: ["saleAmount"],
});
}
}
});
export const createCommissionResponseSchema = z.object({
success: z.boolean(),
message: z.string(),
});