The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add `conversions` stats (new sales only)
Steven Tey02704f05e233
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.tsindex c9f3aee54a..50b5875fc4 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts@@ -286,6 +286,12 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {increment: 1,},}),+ // if this is the first sale for the customer, increment conversions+ ...(customer.sales === 0 && {+ conversions: {+ increment: 1,+ },+ }),sales: {increment: 1,},diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.tsindex c8233dd75f..9957ab59a3 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts@@ -139,6 +139,11 @@ export async function invoicePaid(event: Stripe.Event) {id: linkId,},data: {+ ...(customer.sales === 0 && {+ conversions: {+ increment: 1,+ },+ }),sales: {increment: 1,},diff --git a/apps/web/lib/actions/partners/create-commission.ts b/apps/web/lib/actions/partners/create-commission.tsindex 5517a6bad8..6c48e4c569 100644--- a/apps/web/lib/actions/partners/create-commission.ts+++ b/apps/web/lib/actions/partners/create-commission.ts@@ -190,10 +190,7 @@ export const createCommissionAction = authActionClient]);}- // Record sale- const shouldRecordSale = saleAmount;-- if (shouldRecordSale && leadEvent) {+ if (saleAmount && leadEvent) {const saleEventId = nanoid(16);const saleDate = new Date(saleEventDate ?? Date.now());@@ -240,10 +237,16 @@ export const createCommissionAction = authActionClientid: linkId,},data: {- leads: {- increment: 1,- },- ...(shouldRecordSale && {+ // if this is the first sale for the customer, increment leads and conversions+ ...(customer.sales === 0 && {+ leads: {+ increment: 1,+ },+ conversions: {+ increment: 1,+ },+ }),+ ...(saleAmount && {sales: {increment: 1,},@@ -255,7 +258,7 @@ export const createCommissionAction = authActionClient}),// Update customer details / stats- (shouldUpdateCustomer || shouldRecordSale) &&+ (shouldUpdateCustomer || saleAmount) &&prisma.customer.update({where: {id: customerId,@@ -266,7 +269,7 @@ export const createCommissionAction = authActionClientclickId: clickEvent?.click_id,clickedAt: clickEvent?.timestamp,}),- ...(shouldRecordSale && {+ ...(saleAmount && {sales: {increment: 1,},diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.tsindex 48656fb255..d9e4529474 100644--- a/apps/web/lib/api/conversions/track-sale.ts+++ b/apps/web/lib/api/conversions/track-sale.ts@@ -155,12 +155,18 @@ export const trackSale = async ({const [_sale, link] = await Promise.all([recordSale(saleData),- // update link sales count+ // update link conversions, sales, and saleAmountprisma.link.update({where: {id: clickData.link_id,},data: {+ // if this is the first sale for the customer, increment conversions+ ...(customer.sales === 0 && {+ conversions: {+ increment: 1,+ },+ }),sales: {increment: 1,},diff --git a/apps/web/lib/integrations/shopify/create-sale.ts b/apps/web/lib/integrations/shopify/create-sale.tsindex c0486c3490..06e056d595 100644--- a/apps/web/lib/integrations/shopify/create-sale.ts+++ b/apps/web/lib/integrations/shopify/create-sale.ts@@ -61,7 +61,21 @@ export async function createShopifySale({metadata: JSON.stringify(order),};- const [_sale, link, workspace, customer] = await Promise.all([+ const customer = await prisma.customer.update({+ where: {+ id: customerId,+ },+ data: {+ sales: {+ increment: 1,+ },+ saleAmount: {+ increment: amount,+ },+ },+ });++ const [_sale, link, workspace] = await Promise.all([// record salerecordSale(saleData),@@ -71,6 +85,14 @@ export async function createShopifySale({id: linkId,},data: {+ // if this is the first sale for the customer, increment conversions+ // usually we would do customer.sales === 0, but we incremented the sales count above+ // so we need to check if it's 1 instead+ ...(customer.sales === 1 && {+ conversions: {+ increment: 1,+ },+ }),sales: {increment: 1,},@@ -92,21 +114,6 @@ export async function createShopifySale({},},}),-- prisma.customer.update({- where: {- id: customerId,- },- data: {- sales: {- increment: 1,- },- saleAmount: {- increment: amount,- },- },- }),-redis.del(`shopify:checkout:${checkoutToken}`),]);diff --git a/apps/web/lib/partnerstack/import-commissions.ts b/apps/web/lib/partnerstack/import-commissions.tsindex 2d322965d8..a9ab39841e 100644--- a/apps/web/lib/partnerstack/import-commissions.ts+++ b/apps/web/lib/partnerstack/import-commissions.ts@@ -227,6 +227,12 @@ async function createCommission({id: customer.linkId,},data: {+ // if this is the first sale for the customer, increment conversions+ ...(customer.sales === 0 && {+ conversions: {+ increment: 1,+ },+ }),sales: {increment: 1,},diff --git a/apps/web/lib/rewardful/import-commissions.ts b/apps/web/lib/rewardful/import-commissions.tsindex 70f8cd9f33..45cf0d91e7 100644--- a/apps/web/lib/rewardful/import-commissions.ts+++ b/apps/web/lib/rewardful/import-commissions.ts@@ -249,6 +249,12 @@ async function createCommission({prisma.link.update({where: { id: customerFound.linkId },data: {+ // if this is the first sale for the customer, increment conversions+ ...(customerFound.sales === 0 && {+ conversions: {+ increment: 1,+ },+ }),sales: { increment: 1 },saleAmount: { increment: sale.sale_amount_cents },},diff --git a/apps/web/lib/tolt/import-commissions.ts b/apps/web/lib/tolt/import-commissions.tsindex ed937f27f9..66ac81b32d 100644--- a/apps/web/lib/tolt/import-commissions.ts+++ b/apps/web/lib/tolt/import-commissions.ts@@ -257,6 +257,12 @@ async function createCommission({id: customerFound.linkId,},data: {+ // if this is the first sale for the customer, increment conversions+ ...(customerFound.sales === 0 && {+ conversions: {+ increment: 1,+ },+ }),sales: {increment: 1,},diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.tsindex 8cd70e5096..1f665efa29 100644--- a/apps/web/lib/zod/schemas/analytics.ts+++ b/apps/web/lib/zod/schemas/analytics.ts@@ -197,13 +197,6 @@ export const analyticsQuerySchema = z.describe("The full referer URL to retrieve analytics for.").openapi({ example: "https://dub.co/blog" }),url: z.string().optional().describe("The URL to retrieve analytics for."),- tagId: z- .string()- .optional()- .describe(- "Deprecated. Use `tagIds` instead. The tag ID to retrieve analytics for.",- )- .openapi({ deprecated: true }),tagIds: z.union([z.string(), z.array(z.string())]).transform((v) => (Array.isArray(v) ? v : v.split(",")))@@ -215,12 +208,6 @@ export const analyticsQuerySchema = z.describe("The folder ID to retrieve analytics for. If not provided, return analytics for unsorted links.",),- qr: booleanQuerySchema- .optional()- .describe(- "Deprecated. Use the `trigger` field instead. Filter for QR code scans. If true, filter for QR codes only. If false, filter for links only. If undefined, return both.",- )- .openapi({ deprecated: true }),root: booleanQuerySchema.optional().describe(@@ -232,6 +219,20 @@ export const analyticsQuerySchema = z.describe("Filter sales by type: 'new' for first-time purchases, 'recurring' for repeat purchases. If undefined, returns both.",),+ // deprecated fields+ tagId: z+ .string()+ .optional()+ .describe(+ "Deprecated: Use `tagIds` instead. The tag ID to retrieve analytics for.",+ )+ .openapi({ deprecated: true }),+ qr: booleanQuerySchema+ .optional()+ .describe(+ "Deprecated: Use the `trigger` field instead. Filter for QR code scans. If true, filter for QR codes only. If false, filter for links only. If undefined, return both.",+ )+ .openapi({ deprecated: true }),}).merge(utmTagsSchema);diff --git a/apps/web/lib/zod/schemas/deprecated.ts b/apps/web/lib/zod/schemas/deprecated.tsindex c3a24687f4..a1d074cc82 100644--- a/apps/web/lib/zod/schemas/deprecated.ts+++ b/apps/web/lib/zod/schemas/deprecated.ts@@ -3,54 +3,54 @@ import z from "@/lib/zod";export const commonDeprecatedEventFields = z.object({click_id: z.string()- .describe("Deprecated. Use `click.id` instead.")+ .describe("Deprecated: Use `click.id` instead.").openapi({ deprecated: true }),link_id: z.string()- .describe("Deprecated. Use `link.id` instead.")+ .describe("Deprecated: Use `link.id` instead.").openapi({ deprecated: true }),domain: z.string()- .describe("Deprecated. Use `link.domain` instead.")+ .describe("Deprecated: Use `link.domain` instead.").openapi({ deprecated: true }),key: z.string()- .describe("Deprecated. Use `link.key` instead.")+ .describe("Deprecated: Use `link.key` instead.").openapi({ deprecated: true }),url: z.string()- .describe("Deprecated. Use `click.url` instead.")+ .describe("Deprecated: Use `click.url` instead.").openapi({ deprecated: true }),continent: z.string()- .describe("Deprecated. Use `click.continent` instead.")+ .describe("Deprecated: Use `click.continent` instead.").openapi({ deprecated: true }),country: z.string()- .describe("Deprecated. Use `click.country` instead.")+ .describe("Deprecated: Use `click.country` instead.").openapi({ deprecated: true }),city: z.string()- .describe("Deprecated. Use `click.city` instead.")+ .describe("Deprecated: Use `click.city` instead.").openapi({ deprecated: true }),device: z.string()- .describe("Deprecated. Use `click.device` instead.")+ .describe("Deprecated: Use `click.device` instead.").openapi({ deprecated: true }),browser: z.string()- .describe("Deprecated. Use `click.browser` instead.")+ .describe("Deprecated: Use `click.browser` instead.").openapi({ deprecated: true }),os: z.string()- .describe("Deprecated. Use `click.os` instead.")+ .describe("Deprecated: Use `click.os` instead.").openapi({ deprecated: true }),qr: z.number()- .describe("Deprecated. Use `click.qr` instead.")+ .describe("Deprecated: Use `click.qr` instead.").openapi({ deprecated: true }),ip: z.string()- .describe("Deprecated. Use `click.ip` instead.")+ .describe("Deprecated: Use `click.ip` instead.").openapi({ deprecated: true }),});diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.tsindex 51ab8d3ffd..945c9e23aa 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -72,7 +72,7 @@ const LinksQuerySchema = z.object({.string().optional().describe(- "Deprecated. Use `tagIds` instead. The tag ID to filter the links by.",+ "Deprecated: Use `tagIds` instead. The tag ID to filter the links by.",).openapi({ deprecated: true }),tagIds: z@@ -298,20 +298,6 @@ export const createLinkBodySchema = z.object({.describe("Whether the short link is archived. Defaults to `false` if not provided.",),- publicStats: z- .boolean()- .optional()- .describe(- "Deprecated: Use `dashboard` instead. Whether the short link's stats are publicly accessible. Defaults to `false` if not provided.",- )- .openapi({ deprecated: true }),- tagId: z- .string()- .nullish()- .describe(- "The unique ID of the tag assigned to the short link. This field is deprecated – use `tagIds` instead.",- )- .openapi({ deprecated: true }),tagIds: z.union([z.string(), z.array(z.string())]).transform((v) => (Array.isArray(v) ? v : v.split(",")))@@ -454,6 +440,22 @@ export const createLinkBodySchema = z.object({.string().nullish().describe("The date and time when the tests were or will be completed."),++ // deprecated fields+ publicStats: z+ .boolean()+ .optional()+ .describe(+ "Deprecated: Use `dashboard` instead. Whether the short link's stats are publicly accessible. Defaults to `false` if not provided.",+ )+ .openapi({ deprecated: true }),+ tagId: z+ .string()+ .nullish()+ .describe(+ "Deprecated: Use `tagIds` instead. The unique ID of the tag assigned to the short link.",+ )+ .openapi({ deprecated: true }),});export const createLinkBodySchemaAsync = createLinkBodySchema.extend({@@ -627,13 +629,6 @@ export const LinkSchema = z.boolean().default(false).describe("Whether the short link's stats are publicly accessible."),- tagId: z- .string()- .nullable()- .describe(- "The unique ID of the tag assigned to the short link. This field is deprecated – use `tags` instead.",- )- .openapi({ deprecated: true }),tags: TagSchema.array().nullable().describe("The tags assigned to the short link."),@@ -697,34 +692,50 @@ export const LinkSchema = z.number().default(0).describe("The number of clicks on the short link."),- lastClicked: z- .string()- .nullable()- .describe("The date and time when the short link was last clicked."),leads: z.number().default(0)- .describe("The number of leads the short links has generated."),+ .describe("The number of leads the short link has generated."),+ conversions: z+ .number()+ .default(0)+ .describe("The number of leads that converted to paying customers."),sales: z.number().default(0)- .describe("The number of sales the short links has generated."),+ .describe(+ "The total number of sales (includes recurring sales) generated by the short link.",+ ),saleAmount: z.number().default(0).describe(- "The total dollar amount of sales the short links has generated (in cents).",+ "The total dollar value of sales (in cents) generated by the short link.",),++ lastClicked: z+ .string()+ .nullable()+ .describe("The date and time when the short link was last clicked."),createdAt: z.string().describe("The date and time when the short link was created."),updatedAt: z.string().describe("The date and time when the short link was last updated."),++ // deprecated fields+ tagId: z+ .string()+ .nullable()+ .describe(+ "Deprecated: Use `tags` instead. The unique ID of the tag assigned to the short link.",+ )+ .openapi({ deprecated: true }),projectId: z.string().describe(- "The project ID of the short link. This field is deprecated – use `workspaceId` instead.",+ "Deprecated: Use `workspaceId` instead. The project ID of the short link.",).openapi({ deprecated: true }),})diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.tsindex be4f36fffc..8f09394e86 100644--- a/apps/web/lib/zod/schemas/sales.ts+++ b/apps/web/lib/zod/schemas/sales.ts@@ -149,15 +149,16 @@ export const saleEventResponseSchema = z}),saleAmount: z.number()- .describe("Deprecated. Use `sale.amount` instead.")+ .describe("Deprecated: Use `sale.amount` instead.").openapi({ deprecated: true }),invoice_id: z.string()- .describe("Deprecated. Use `sale.invoiceId` instead.")+ .describe("Deprecated: Use `sale.invoiceId` instead.").openapi({ deprecated: true }),payment_processor: z.string()- .describe("Deprecated. Use `sale.paymentProcessor` instead."),+ .describe("Deprecated: Use `sale.paymentProcessor` instead.")+ .openapi({ deprecated: true }),}).merge(commonDeprecatedEventFields).openapi({ ref: "SaleEvent", title: "SaleEvent" });diff --git a/packages/prisma/schema/link.prisma b/packages/prisma/schema/link.prismaindex 5601c2a911..0ee4cca47d 100644--- a/packages/prisma/schema/link.prisma+++ b/packages/prisma/schema/link.prisma@@ -55,10 +55,12 @@ model Link {publicStats Boolean @default(false) // whether to show public stats or notclicks Int @default(0) // number of clicks+ leads Int @default(0) // number of leads+ conversions Int @default(0) // number of leads that converted to sales+ sales Int @default(0) // number of sales (includes recurring sales)+ saleAmount Int @default(0) // Deprecated: drop this column after migration is complete + backwards compatibility is added+lastClicked DateTime? // when the link was last clicked- leads Int @default(0)- sales Int @default(0) // number of sales- saleAmount Int @default(0) // total dollar value of sales (in cents)createdAt DateTime @default(now())updatedAt DateTime @updatedAt@@ -90,4 +92,5 @@ model Link {@@index([domain, createdAt]) // for bulk link deletion workflows (by domain) + deleting old short-lived links@@index(folderId) // used in /api/folders@@index(userId) // for relation to User table, used in /api/cron/cleanup/e2e-tests too+ @@index(sales) // for getting links that have sales recorded – can be removed after migration is complete}