The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
AI-assisted reward builder (#4277)
Pedro Ladeira6417fe75e522
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsxindex 53ce72a642..d98440b830 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx@@ -15,7 +15,6 @@ import {usePartnerPlatformsForm,} from "@/ui/partners/partner-platforms-form";import { CustomToast } from "@/ui/shared/custom-toast";-import { AlertCircleFill } from "@/ui/shared/icons";import {Button,DynamicTooltipWrapper,@@ -253,7 +252,7 @@ function BasicInfoForm({if (error.serverError?.includes("merge your partner accounts")) {toast.custom(() => (- <CustomToast icon={AlertCircleFill}>+ <CustomToast variant="error">Email already in use. Do you want to [merge your partneraccounts](https://d.to/merge-partners) instead?</CustomToast>diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsxindex 98b13212df..1259375c69 100644--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsx+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsx@@ -132,6 +132,7 @@ export function Form() {autoFocus={!isMobile}className="max-w-full"error={errors.name?.message}+ data-testid="onboarding-program-company-name"/><p className="text-content-subtle text-xs">@@ -162,6 +163,7 @@ export function Form() {onChange={({ file }) => handleUpload(file)}content={null}maxFileSizeMB={2}+ data-testid="onboarding-program-logo"/>)}/>@@ -189,6 +191,7 @@ export function Form() {placeholder="https://"className="max-w-full"error={errors.url?.message}+ data-testid="onboarding-program-destination-url"/>)}/>@@ -216,6 +219,7 @@ export function Form() {type="email"className="max-w-full"error={errors.supportEmail?.message}+ data-testid="onboarding-program-support-email"/>)}/>@@ -231,6 +235,7 @@ export function Form() {disabledTooltip={!isLoading ? disabledTooltip : undefined}text="Continue"className="w-full"+ data-testid="onboarding-program-continue"/></form>);diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/reward/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/reward/form.tsxindex 03b07c6f74..ebd60d8cb0 100644--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/reward/form.tsx+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/reward/form.tsx@@ -448,6 +448,7 @@ export function Form() {</span><inputid={rewardAmountInputId}+ data-testid="onboarding-reward-amount"className={cn("block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",type === "flat" ? "pl-6 pr-12" : "pr-7",@@ -479,6 +480,7 @@ export function Form() {loading={isLoading}disabledTooltip={!isLoading ? disabledTooltip : undefined}type="submit"+ data-testid="onboarding-reward-continue"/></form>);diff --git a/apps/web/lib/ai/ai-reward-schema.ts b/apps/web/lib/ai/ai-reward-schema.tsnew file mode 100644index 0000000000..19c67ef43b--- /dev/null+++ b/apps/web/lib/ai/ai-reward-schema.ts@@ -0,0 +1,251 @@+import {+ CONDITION_OPERATORS,+ isOneOffRewardEvent,+ REWARD_CONDITIONS,+} from "@/lib/zod/schemas/rewards";+import { RewardStructure } from "@prisma/client";+import * as z from "zod/v4";++export const AI_REWARD_EVENTS = ["click", "lead", "sale"] as const;+export type AIRewardEvent = (typeof AI_REWARD_EVENTS)[number];++const REWARD_CONDITION_ENTITY_IDS = [+ ...new Set(+ AI_REWARD_EVENTS.flatMap((event) =>+ REWARD_CONDITIONS[event].entities.map((entity) => entity.id),+ ),+ ),+] as [string, ...string[]];++function buildConditionSchema(entityIds: [string, ...string[]]) {+ return z.object({+ entity: z+ .enum(entityIds)+ .describe("The entity to evaluate (customer, partner, sale, or lead)."),+ attribute: z+ .string()+ .describe("The attribute on the entity (e.g. country, amount, source)."),+ operator: z+ .enum(CONDITION_OPERATORS)+ .describe("Comparison operator for the condition."),+ value: z+ .union([z.string(), z.number(), z.array(z.string()), z.array(z.number())])+ .describe(+ "Condition value. For currency attributes use dollars (not cents). For country use ISO country codes (e.g. US). For enums use the option id.",+ ),+ label: z+ .string()+ .nullish()+ .describe(+ "Optional display label for the reward (e.g. product name for productId).",+ ),+ metadataField: z+ .string()+ .optional()+ .describe("Required when attribute is metadata — the metadata key name."),+ });+}++type ConditionSchema = ReturnType<typeof buildConditionSchema>;++/** Plain object shape for model JSON-schema steering (no refinements). */+function buildModifierObjectSchema(conditionSchema: ConditionSchema) {+ return z.object({+ operator: z+ .enum(["AND", "OR"])+ .default("AND")+ .describe("How conditions in this group combine."),+ conditions: z+ .array(conditionSchema)+ .min(1)+ .describe("Conditions that must match for this alternate reward."),+ type: z+ .enum(RewardStructure)+ .optional()+ .describe(+ "Reward structure for this group. Omit to inherit the base reward type.",+ ),+ amount: z+ .number()+ .nonnegative()+ .optional()+ .describe(+ "Reward amount for this group. Flat = dollars; percentage = 0–100. Omit to inherit base amount.",+ ),+ maxDuration: z+ .number()+ .int()+ .nonnegative()+ .nullable()+ .optional()+ .describe(+ "Duration in months for sale rewards. null = lifetime. Omit to inherit base.",+ ),+ });+}++type ModifierObjectSchema = ReturnType<typeof buildModifierObjectSchema>;++function buildRewardObjectSchema(modifierSchema: ModifierObjectSchema) {+ return z.object({+ type: z+ .enum(RewardStructure)+ .describe(+ "Base reward structure. Click and lead rewards must be flat. Sale may be flat or percentage.",+ ),+ amount: z+ .number()+ .nonnegative()+ .describe(+ "Base reward amount. Flat = dollars (e.g. 10 for $10); percentage = 0–100 (e.g. 20 for 20%).",+ ),+ maxDuration: z+ .number()+ .int()+ .nonnegative()+ .nullish()+ .describe(+ "Base duration in months for sale rewards. null = customer's lifetime. One-time sale rewards must be 0, same as click and lead rewards.",+ ),+ modifiers: z+ .array(modifierSchema)+ .optional()+ .describe(+ "Optional conditional reward groups. Omit or use [] when there are no conditions.",+ ),+ });+}++type RewardObjectSchema = ReturnType<typeof buildRewardObjectSchema>;++function withPercentageLimits(schema: RewardObjectSchema) {+ return schema+ .refine((data) => data.type !== "percentage" || data.amount <= 100, {+ message: "Percentage amount must be between 0 and 100.",+ path: ["amount"],+ })+ .refine(+ (data) =>+ (data.modifiers ?? []).every((modifier) => {+ const type = modifier.type ?? data.type;+ return (+ type !== "percentage" ||+ modifier.amount == null ||+ modifier.amount <= 100+ );+ }),+ {+ message: "Percentage amount must be between 0 and 100.",+ path: ["modifiers"],+ },+ );+}++function buildEventRewardObjectSchema(event: AIRewardEvent) {+ const entityIds = REWARD_CONDITIONS[event].entities.map(+ (entity) => entity.id,+ ) as [string, ...string[]];++ return buildRewardObjectSchema(+ buildModifierObjectSchema(buildConditionSchema(entityIds)),+ );+}++const aiRewardSchema = withPercentageLimits(+ buildRewardObjectSchema(+ buildModifierObjectSchema(+ buildConditionSchema(REWARD_CONDITION_ENTITY_IDS),+ ),+ ),+);++export type AIRewardDraft = z.infer<typeof aiRewardSchema>;++/** Event-aware schema for final draft validation. */+export function getAIRewardSchema(event: AIRewardEvent) {+ let schema = withPercentageLimits(buildEventRewardObjectSchema(event));++ if (isOneOffRewardEvent(event)) {+ schema = schema.refine(+ (data) => {+ if (data.type !== "flat") return false;+ if (!(data.maxDuration == null || data.maxDuration === 0)) return false;++ return (data.modifiers ?? []).every(+ (modifier) =>+ (modifier.type == null || modifier.type === "flat") &&+ (modifier.maxDuration == null || modifier.maxDuration === 0),+ );+ },+ { message: "Click and lead rewards must be flat with duration 0." },+ );+ }++ return schema.superRefine((data, ctx) => {+ data.modifiers?.forEach((modifier, modifierIndex) => {+ modifier.conditions.forEach((condition, conditionIndex) => {+ const entity = REWARD_CONDITIONS[event].entities.find(+ (entry) => entry.id === condition.entity,+ );+ const attribute = entity?.attributes.find(+ (entry) => entry.id === condition.attribute,+ );+ const valid =+ attribute != null &&+ (attribute.type !== "metadata" || Boolean(condition.metadataField));++ if (valid) return;++ ctx.addIssue({+ code: "custom",+ message: `Condition uses an entity/attribute not allowed for ${event} rewards.`,+ path: ["modifiers", modifierIndex, "conditions", conditionIndex],+ });+ });+ });+ });+}++/**+ * Model structured-output envelope. Keep this free of app-level refinements so+ * Output.object can stream/parse JSON even when the model picks a bad attribute;+ * validate the reward with getAIRewardSchema after the stream completes.+ */+export function getAIRewardGenerationSchema(event: AIRewardEvent) {+ return z+ .object({+ supported: z+ .boolean()+ .describe(+ "True only if the request can be expressed accurately with the allowed entities/attributes. False if any important part would require guessing, stretching meanings, or inventing fields.",+ ),+ reason: z+ .string()+ .nullish()+ .describe(+ "When supported is false: brief explanation of what is not supported. When supported is true: null or omit.",+ ),+ reward: buildEventRewardObjectSchema(event)+ .nullish()+ .describe(+ "When supported is true: the reward configuration. When supported is false: null or omit.",+ ),+ })+ .superRefine((data, ctx) => {+ if (data.supported && data.reward == null) {+ ctx.addIssue({+ code: "custom",+ message: "Reward is required when supported is true.",+ path: ["reward"],+ });+ }+ });+}++export type AIRewardGenerationOutput = z.infer<+ ReturnType<typeof getAIRewardGenerationSchema>+>;++export function getAIRewardConditionEntityIds() {+ return REWARD_CONDITION_ENTITY_IDS;+}diff --git a/apps/web/lib/ai/generate-partner-network-invite-email.ts b/apps/web/lib/ai/generate-partner-network-invite-email.tsindex b04440c19b..bf6bf96f21 100644--- a/apps/web/lib/ai/generate-partner-network-invite-email.ts+++ b/apps/web/lib/ai/generate-partner-network-invite-email.ts@@ -1,16 +1,15 @@"use server";-import { DubApiError } from "@/lib/api/errors";+import {+ refundAIUsageCredit,+ reserveAIUsageCredit,+} from "@/lib/api/links/usage-checks";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { getProgramPartnerEarningsClaim } from "@/lib/api/programs/get-program-partner-earnings-claim";-import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";-import { exceededLimitError } from "@/lib/exceeded-limit-error";import { getUsableNetworkPartnerName } from "@/lib/network/get-program-network-invite-email-defaults";import { prisma } from "@/lib/prisma";-import { PlanProps } from "@/lib/types";import { emailSchema } from "@/lib/zod/schemas/auth";import { anthropic } from "@ai-sdk/anthropic";-import { PlanPeriod } from "@prisma/client";import { generateText, Output } from "ai";import * as z from "zod/v4";import { authActionClient } from "../actions/safe-action";@@ -86,12 +85,7 @@ export const generatePartnerNetworkInviteEmailAction = authActionClient: null;const partnerGreetingName = partnerName ?? companyName ?? "there";- await reserveAIUsageCredit({- workspaceId: workspace.id,- aiLimit: workspace.aiLimit,- plan: workspace.plan,- planPeriod: workspace.planPeriod,- });+ await reserveAIUsageCredit(workspace);try {const { output } = await generateText({@@ -226,59 +220,3 @@ function getPlatformDescription(metadata: unknown) {? value.trim(): null;}--async function reserveAIUsageCredit({- workspaceId,- aiLimit,- plan,- planPeriod,-}: {- workspaceId: string;- aiLimit: number;- plan: PlanProps;- planPeriod: PlanPeriod | null;-}) {- const { count } = await prisma.project.updateMany({- where: {- id: normalizeWorkspaceId(workspaceId),- aiUsage: {- lt: aiLimit,- },- },- data: {- aiUsage: {- increment: 1,- },- },- });-- if (count === 0) {- throw new DubApiError({- code: "forbidden",- message: exceededLimitError({- plan,- planPeriod,- limit: aiLimit,- type: "AI",- }),- });- }-}--async function refundAIUsageCredit(workspaceId: string) {- // Guard against driving aiUsage negative (e.g. if the monthly cron reset the- // counter to 0 between reserving and refunding the credit).- await prisma.project.updateMany({- where: {- id: normalizeWorkspaceId(workspaceId),- aiUsage: {- gt: 0,- },- },- data: {- aiUsage: {- decrement: 1,- },- },- });-}diff --git a/apps/web/lib/ai/generate-reward.ts b/apps/web/lib/ai/generate-reward.tsnew file mode 100644index 0000000000..66cfd13e3f--- /dev/null+++ b/apps/web/lib/ai/generate-reward.ts@@ -0,0 +1,228 @@+"use server";++import {+ refundAIUsageCredit,+ reserveAIUsageCredit,+} from "@/lib/api/links/usage-checks";+import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";+import { getSession } from "@/lib/auth";+import { prisma } from "@/lib/prisma";+import { PlanProps } from "@/lib/types";+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";+import { REWARD_CONDITIONS } from "@/lib/zod/schemas/rewards";+import { anthropic } from "@ai-sdk/anthropic";+import { createStreamableValue } from "@ai-sdk/rsc";+import { Output, streamText } from "ai";+import * as z from "zod/v4";+import { throwIfNoPermission } from "../actions/throw-if-no-permission";+import {+ AI_REWARD_EVENTS,+ AIRewardGenerationOutput,+ getAIRewardGenerationSchema,+ getAIRewardSchema,+} from "./ai-reward-schema";++const inputSchema = z.object({+ workspaceId: z.string(),+ event: z.enum(AI_REWARD_EVENTS),+ prompt: z.string().min(1).max(2000),+});++function buildSystemPrompt(event: (typeof AI_REWARD_EVENTS)[number]) {+ const entities = REWARD_CONDITIONS[event].entities.map((entity) => {+ const attrs = entity.attributes+ .map((attr) => {+ const options = attr.options+ ? ` options=[${attr.options.map((o) => `${o.id}`).join(", ")}]`+ : "";+ return ` - ${attr.id} (${attr.type}${options})`;+ })+ .join("\n");+ return ` - ${entity.id}:\n${attrs}`;+ });++ return `You are a partner reward structure assistant for Dub. Convert the user's natural-language reward idea into a structured reward configuration.++Event type: ${event}++Rules:+- Output only fields that are clearly requested or strongly implied.+- Flat amounts are in dollars (not cents). Percentage amounts are 0–100. Decimals are allowed for both.+- Currency condition values (sale.amount, partner.totalSaleAmount, partner.totalCommissions) are in dollars.+- Date condition values (e.g. signupDate, subscriptionStartDate) use ISO 8601 strings (e.g. 2024-01-15).+- Country values use ISO 3166-1 alpha-2 codes (e.g. US, GB).+- Condition groups (modifiers) override the base reward when their conditions match. Make sure to set the most generic condition as the base condition.+- If the user describes only a simple base reward with no conditions, omit modifiers or return an empty array.+- Do not invent metadata fields unless the user names them; when using metadata, set metadataField.+- Only use entities and attributes allowed for this event (listed below). Use attribute ids exactly as listed — never invent names (e.g. use signupDate for when a customer joined, not createdAt).++Unsupported requests (important):+- Set supported=false when the request cannot be expressed accurately with the allowed attributes. Set reward to null and explain briefly in reason.+- Do NOT approximate, stretch meanings, or substitute a "close enough" attribute.+- Examples of unsupported: billing interval / plan cadence (yearly vs monthly plans), plan names or tiers not identified via productId or an explicitly named metadata field, or any condition on a field not listed below.+- customer.subscriptionDurationMonths is how long the customer has already been subscribed — it is NOT whether their plan is billed yearly or monthly.+- When supported=true, provide a complete reward object. When supported=false, reward must be null.++Allowed entities and attributes for ${event}:+${entities.join("\n")}`;+}++export async function generateReward(input: z.infer<typeof inputSchema>) {+ const parsed = inputSchema.safeParse(input);+ if (!parsed.success) {+ throw new Error("Invalid request.");+ }++ const { event, prompt } = parsed.data;++ const session = await getSession();+ if (!session?.user.id) {+ throw new Error("Unauthorized: Login required.");+ }++ const workspaceId = normalizeWorkspaceId(parsed.data.workspaceId);++ const workspace = await prisma.project.findUnique({+ where: { id: workspaceId },+ include: {+ users: {+ where: { userId: session.user.id },+ select: { role: true },+ },+ },+ });++ if (!workspace?.users?.length) {+ throw new Error("Workspace not found.");+ }++ const role = workspace.users[0].role;+ throwIfNoPermission({+ role,+ requiredRoles: ["owner", "member"],+ });++ await assertRateLimit({+ policy: RATELIMIT_POLICIES.aiRewardGenerate,+ identifier: [session.user.id, workspaceId],+ });++ await reserveAIUsageCredit({+ id: workspace.id,+ aiLimit: workspace.aiLimit,+ plan: workspace.plan as PlanProps,+ planPeriod: workspace.planPeriod,+ });++ const stream = createStreamableValue();++ (async () => {+ let failed = false;++ const fail = async (cause?: unknown) => {+ if (failed) return;+ failed = true;+ if (cause != null) {+ console.error("[generateReward] failed", cause);+ }+ await refundAIUsageCredit(workspaceId).catch((e) =>+ console.error("Failed to refund AI credit", e),+ );+ stream.error(new Error("Failed to generate reward. Please try again."));+ };++ try {+ const generationSchema = getAIRewardGenerationSchema(event);+ const result = streamText({+ model: anthropic("claude-sonnet-4-6"),+ output: Output.object({ schema: generationSchema }),+ system: buildSystemPrompt(event),+ prompt,+ temperature: 0.3,+ maxOutputTokens: 2000,+ onError: ({ error }) => {+ void fail(error);+ },+ });++ let lastPartial: Partial<AIRewardGenerationOutput> | null = null;+ for await (const partialObject of result.partialOutputStream) {+ if (failed) return;+ if (partialObject) {+ lastPartial = partialObject as Partial<AIRewardGenerationOutput>;+ stream.update(lastPartial);+ }+ }++ if (failed) return;++ if (!lastPartial) {+ try {+ const text = await result.text;+ if (text) {+ lastPartial = JSON.parse(text) as Partial<AIRewardGenerationOutput>;+ }+ } catch (error) {+ let text: string | null = null;+ let finishReason: string | null = null;+ try {+ text = await result.text;+ } catch {+ // ignore+ }+ try {+ finishReason = await result.finishReason;+ } catch {+ // ignore+ }+ await fail({+ reason: "empty_generation_output",+ error,+ text,+ finishReason,+ });+ return;+ }+ }++ const parsed = generationSchema.safeParse(lastPartial);+ if (!parsed.success) {+ await fail({+ reason: "invalid_generation_output",+ lastPartial,+ issues: parsed.error.issues,+ });+ return;+ }++ if (parsed.data.supported) {+ const rewardParsed = getAIRewardSchema(event).safeParse(+ parsed.data.reward,+ );+ if (!rewardParsed.success) {+ console.error("[generateReward] invalid reward draft", {+ lastPartial: parsed.data,+ issues: rewardParsed.error.issues,+ });++ const unsupported: AIRewardGenerationOutput = {+ supported: false,+ reason:+ "Could not map this request to supported reward conditions.",+ reward: null,+ };+ stream.update(unsupported);+ stream.done();+ return;+ }+ }++ stream.done();+ } catch (error) {+ await fail(error);+ }+ })();++ return { object: stream.value };+}diff --git a/apps/web/lib/api/links/usage-checks.ts b/apps/web/lib/api/links/usage-checks.tsindex 1f95ec0017..616eb6e052 100644--- a/apps/web/lib/api/links/usage-checks.ts+++ b/apps/web/lib/api/links/usage-checks.ts@@ -1,4 +1,6 @@+import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";import { exceededLimitError } from "@/lib/exceeded-limit-error";+import { prisma } from "@/lib/prisma";import { WorkspaceWithUsers } from "@/lib/types";import { DubApiError } from "../errors";@@ -48,3 +50,44 @@ export const throwIfAIUsageExceeded = (workspace: WorkspaceWithUsers) => {});}};++export async function reserveAIUsageCredit(+ workspace: Pick<WorkspaceWithUsers, "id" | "aiLimit" | "plan" | "planPeriod">,+) {+ const workspaceId = normalizeWorkspaceId(workspace.id);++ const count = await prisma.$executeRaw`+ UPDATE Project+ SET aiUsage = aiUsage + 1+ WHERE id = ${workspaceId}+ AND aiUsage < aiLimit+ `;++ if (count === 0) {+ throw new DubApiError({+ code: "forbidden",+ message: exceededLimitError({+ plan: workspace.plan,+ planPeriod: workspace.planPeriod,+ limit: workspace.aiLimit,+ type: "AI",+ }),+ });+ }+}++export async function refundAIUsageCredit(workspaceId: string) {+ await prisma.project.updateMany({+ where: {+ id: normalizeWorkspaceId(workspaceId),+ aiUsage: {+ gt: 0,+ },+ },+ data: {+ aiUsage: {+ decrement: 1,+ },+ },+ });+}diff --git a/apps/web/lib/upstash/ratelimit-policies.ts b/apps/web/lib/upstash/ratelimit-policies.tsindex e456d5f9a1..10ba05a3f6 100644--- a/apps/web/lib/upstash/ratelimit-policies.ts+++ b/apps/web/lib/upstash/ratelimit-policies.ts@@ -89,4 +89,10 @@ export const RATELIMIT_POLICIES = {window: "1 h",keyPrefix: "rl:partner-profile:invite",},++ aiRewardGenerate: {+ attempts: 10,+ window: "1 m",+ keyPrefix: "rl:ai:reward:generate",+ },} as const satisfies Record<string, RatelimitPolicy>;diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.tsindex 97d069493c..e72edba86d 100644--- a/apps/web/lib/zod/schemas/rewards.ts+++ b/apps/web/lib/zod/schemas/rewards.ts@@ -8,6 +8,12 @@ import * as z from "zod/v4";import { getPaginationQuerySchema, maxDurationSchema } from "./misc";import { centsSchema } from "./utils";+export function isOneOffRewardEvent(+ event: EventType | "click" | "lead" | "sale" | "referral",+): event is "click" | "lead" {+ return event === "click" || event === "lead";+}+export const COMMISSION_TYPES = [{value: "recurring",@@ -484,9 +490,9 @@ export const createOrUpdateRewardSchema = z.object({export const createRewardSchema = createOrUpdateRewardSchema.superRefine((data) => {- if (data.event === EventType.click || data.event === EventType.lead) {- data.maxDuration = 0;+ if (isOneOffRewardEvent(data.event)) {data.type = "flat";+ data.maxDuration = 0;}},);diff --git a/apps/web/playwright/workspaces/onboarding-dub-partners.spec.ts b/apps/web/playwright/workspaces/onboarding-dub-partners.spec.tsindex c57357132b..3410513b67 100644--- a/apps/web/playwright/workspaces/onboarding-dub-partners.spec.ts+++ b/apps/web/playwright/workspaces/onboarding-dub-partners.spec.ts@@ -121,8 +121,10 @@ test.describe("Dub Partners onboarding", () => {page.getByRole("heading", { name: "Create your partner program" }),).toBeVisible({ timeout: STEP_NAV_TIMEOUT });- await page.getByLabel("Company name").fill(`Test Program ${nanoid(4)}`);- await page.locator('input[type="file"]').setInputFiles({+ await page+ .getByTestId("onboarding-program-company-name")+ .fill(`Test Program ${nanoid(4)}`);+ await page.getByTestId("onboarding-program-logo").setInputFiles({name: "logo.png",mimeType: "image/png",buffer: MINIMAL_PNG,@@ -133,28 +135,31 @@ test.describe("Dub Partners onboarding", () => {}).toBeGreaterThan(0);- await page.getByLabel("Destination URL").fill("https://acme.com");- await page.getByLabel("Support email").fill("[email protected]");+ await page+ .getByTestId("onboarding-program-destination-url")+ .fill("https://acme.com");+ await page+ .getByTestId("onboarding-program-support-email")+ .fill("[email protected]");await Promise.all([expect(page).toHaveURL(/\/onboarding\/program\/reward/, {timeout: STEP_NAV_TIMEOUT,}),- page.getByRole("button", { name: "Continue" }).click(),+ page.getByTestId("onboarding-program-continue").click(),]);// Default reward — keep Sale / recurring / percentage defaults, set 30%await expect(page.getByRole("heading", { name: "Create your default reward" }),).toBeVisible({ timeout: STEP_NAV_TIMEOUT });- const pctInput = page.getByLabel(/Percentage per sale/i);+ const pctInput = page.getByTestId("onboarding-reward-amount");await expect(pctInput).toBeVisible({ timeout: STEP_NAV_TIMEOUT });- await page.waitForTimeout(2000);- await pctInput.fill("30", { force: true });+ await pctInput.fill("30");await Promise.all([expect(page).toHaveURL(/\/onboarding\/plan/, {timeout: STEP_NAV_TIMEOUT,}),- page.getByRole("button", { name: "Continue" }).click(),+ page.getByTestId("onboarding-reward-continue").click(),]);// Plan step — mocked checkout trial (no Stripe)diff --git a/apps/web/tests/misc/ai-reward-schema.test.ts b/apps/web/tests/misc/ai-reward-schema.test.tsnew file mode 100644index 0000000000..e1abbb3de4--- /dev/null+++ b/apps/web/tests/misc/ai-reward-schema.test.ts@@ -0,0 +1,301 @@+import {+ AI_REWARD_EVENTS,+ getAIRewardConditionEntityIds,+ getAIRewardGenerationSchema,+ getAIRewardSchema,+ type AIRewardEvent,+} from "@/lib/ai/ai-reward-schema";+import {+ createRewardSchema,+ REWARD_CONDITIONS,+} from "@/lib/zod/schemas/rewards";+import { describe, expect, it } from "vitest";++function sampleValueForAttribute(attribute: {+ id: string;+ type: string;+ options?: { id: string }[];+}): string | number {+ if (attribute.options?.length) {+ return attribute.options[0].id;+ }++ switch (attribute.type) {+ case "number":+ case "currency":+ return 10;+ case "date":+ return "2024-01-01";+ case "metadata":+ return "value";+ default:+ return attribute.id === "country" ? "US" : "example";+ }+}++function draftWithCondition(+ event: AIRewardEvent,+ entityId: string,+ attribute: { id: string; type: string; options?: { id: string }[] },+) {+ return {+ type: "flat" as const,+ amount: 5,+ maxDuration: event === "sale" ? 12 : 0,+ modifiers: [+ {+ operator: "AND" as const,+ conditions: [+ {+ entity: entityId,+ attribute: attribute.id,+ operator: "equals_to" as const,+ value: sampleValueForAttribute(attribute),+ ...(attribute.type === "metadata" ? { metadataField: "plan" } : {}),+ },+ ],+ type: "flat" as const,+ amount: 10,+ maxDuration: event === "sale" ? 12 : 0,+ },+ ],+ };+}++describe("getAIRewardSchema — REWARD_CONDITIONS sync", () => {+ it("accepts every entity id from REWARD_CONDITIONS (non-referral)", () => {+ const derived = new Set(getAIRewardConditionEntityIds());+ const fromConditions = new Set(+ AI_REWARD_EVENTS.flatMap((event) =>+ REWARD_CONDITIONS[event].entities.map((entity) => entity.id),+ ),+ );++ expect(derived).toEqual(fromConditions);+ });++ it("builds a schema that accepts every entity id from REWARD_CONDITIONS", () => {+ for (const event of AI_REWARD_EVENTS) {+ const schema = getAIRewardSchema(event);+ for (const entity of REWARD_CONDITIONS[event].entities) {+ const attribute = entity.attributes[0];+ const result = schema.safeParse(+ draftWithCondition(event, entity.id, attribute),+ );+ expect(result.success, `${event}/${entity.id}`).toBe(true);+ }+ }+ });+});++describe.each(AI_REWARD_EVENTS)("getAIRewardSchema(%s)", (event) => {+ const schema = getAIRewardSchema(event);+ const entities = REWARD_CONDITIONS[event].entities;++ it("accepts a valid draft for every entity/attribute pair", () => {+ for (const entity of entities) {+ for (const attribute of entity.attributes) {+ const result = schema.safeParse(+ draftWithCondition(event, entity.id, attribute),+ );+ expect(+ result.success,+ `${event}/${entity.id}.${attribute.id}: ${result.success ? "" : JSON.stringify(result.error.issues)}`,+ ).toBe(true);+ }+ }+ });++ it("rejects an unknown entity", () => {+ const result = schema.safeParse(+ draftWithCondition(event, "unknown_entity", {+ id: "country",+ type: "enum",+ }),+ );+ expect(result.success).toBe(false);+ });++ it("rejects an unknown attribute for a known entity", () => {+ const entity = entities[0];+ const result = schema.safeParse(+ draftWithCondition(event, entity.id, {+ id: "not_a_real_attribute",+ type: "string",+ }),+ );+ expect(result.success).toBe(false);+ });++ const metadataCases = entities.flatMap((entity) =>+ entity.attributes+ .filter((attribute) => attribute.type === "metadata")+ .map((attribute) => ({ entityId: entity.id, attribute })),+ );++ if (metadataCases.length > 0) {+ it("rejects metadata without metadataField", () => {+ for (const { entityId, attribute } of metadataCases) {+ const draft = draftWithCondition(event, entityId, attribute);+ delete (draft.modifiers[0].conditions[0] as { metadataField?: string })+ .metadataField;++ const result = schema.safeParse(draft);+ expect(result.success, `${entityId}.metadata`).toBe(false);+ }+ });+ }+});++describe("getAIRewardSchema — click/lead one-off rules", () => {+ for (const event of ["click", "lead"] as const) {+ const schema = getAIRewardSchema(event);++ it(`${event}: rejects percentage type`, () => {+ const result = schema.safeParse({+ type: "percentage",+ amount: 10,+ maxDuration: 0,+ });+ expect(result.success).toBe(false);+ });++ it(`${event}: accepts omitted maxDuration`, () => {+ const result = schema.safeParse({+ type: "flat",+ amount: 5,+ });+ expect(result.success).toBe(true);+ });++ it(`${event}: accepts maxDuration 0`, () => {+ const result = schema.safeParse({+ type: "flat",+ amount: 5,+ maxDuration: 0,+ });+ expect(result.success).toBe(true);+ });++ it(`${event}: rejects nonzero maxDuration`, () => {+ const result = schema.safeParse({+ type: "flat",+ amount: 5,+ maxDuration: 12,+ });+ expect(result.success).toBe(false);+ });+ }+});++describe("getAIRewardSchema — sale percentage", () => {+ const schema = getAIRewardSchema("sale");++ it("accepts percentage amount <= 100", () => {+ const result = schema.safeParse({+ type: "percentage",+ amount: 20,+ maxDuration: 12,+ });+ expect(result.success).toBe(true);+ });++ it("rejects percentage amount > 100", () => {+ const result = schema.safeParse({+ type: "percentage",+ amount: 150,+ maxDuration: 12,+ });+ expect(result.success).toBe(false);+ });+});++describe("createRewardSchema — one-off coerce", () => {+ const base = {+ workspaceId: "ws_test",+ groupId: "grp_test",+ amountInCents: 500,+ };++ for (const event of ["click", "lead"] as const) {+ it(`${event}: coerces percentage + nonzero duration to flat / 0`, () => {+ const result = createRewardSchema.safeParse({+ ...base,+ event,+ type: "percentage",+ amountInPercentage: 20,+ maxDuration: 12,+ });++ expect(result.success).toBe(true);+ if (!result.success) return;+ expect(result.data.type).toBe("flat");+ expect(result.data.maxDuration).toBe(0);+ });+ }++ it("sale: does not coerce type or maxDuration", () => {+ const result = createRewardSchema.safeParse({+ ...base,+ event: "sale",+ type: "percentage",+ amountInPercentage: 20,+ maxDuration: 12,+ });++ expect(result.success).toBe(true);+ if (!result.success) return;+ expect(result.data.type).toBe("percentage");+ expect(result.data.maxDuration).toBe(12);+ });+});++describe("getAIRewardGenerationSchema — unsupported refusal", () => {+ const schema = getAIRewardGenerationSchema("sale");++ it("accepts supported=true with a valid reward", () => {+ const result = schema.safeParse({+ supported: true,+ reward: {+ type: "percentage",+ amount: 20,+ maxDuration: 12,+ },+ });+ expect(result.success).toBe(true);+ });++ it("rejects supported=true without a reward", () => {+ const result = schema.safeParse({+ supported: true,+ reward: null,+ });+ expect(result.success).toBe(false);+ });++ it("accepts supported=false with a reason and no reward", () => {+ const result = schema.safeParse({+ supported: false,+ reason: "Yearly vs monthly billing interval is not supported.",+ reward: null,+ });+ expect(result.success).toBe(true);+ });++ it("defers app validation to getAIRewardSchema (not generation envelope)", () => {+ const clickSchema = getAIRewardGenerationSchema("click");+ const result = clickSchema.safeParse({+ supported: true,+ reward: {+ type: "percentage",+ amount: 20,+ maxDuration: 0,+ },+ });++ expect(result.success).toBe(true);+ expect(+ getAIRewardSchema("click").safeParse(result.data?.reward).success,+ ).toBe(false);+ });+});diff --git a/apps/web/ui/modals/add-discount-code-modal.tsx b/apps/web/ui/modals/add-discount-code-modal.tsxindex bbdf5ac6b8..7c7750be0e 100644--- a/apps/web/ui/modals/add-discount-code-modal.tsx+++ b/apps/web/ui/modals/add-discount-code-modal.tsx@@ -19,7 +19,7 @@ import { useDebounce } from "use-debounce";import * as z from "zod/v4";import { ERROR_MAP } from "../partners/constants";import { CustomToast } from "../shared/custom-toast";-import { AlertCircleFill, X } from "../shared/icons";+import { X } from "../shared/icons";import { UpgradeRequiredToast } from "../shared/upgrade-required-toast";type FormData = z.infer<typeof createDiscountCodeSchema>;@@ -107,7 +107,7 @@ const AddDiscountCodeModal = ({return;} else if (error.includes("already in use")) {toast.custom(() => (- <CustomToast icon={AlertCircleFill}>{error}</CustomToast>+ <CustomToast variant="error">{error}</CustomToast>));} else {toast.error(error);diff --git a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsxindex 13d907282f..d727d647c6 100644--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx@@ -26,16 +26,13 @@ import {import { DurationPopoverContent } from "@/ui/shared/duration-popover-content";import { X } from "@/ui/shared/icons";import {- BookOpen,Button,Gift,- Grid,MoneyBills2,Pen2,Sheet,Tooltip,TooltipContent,- useLocalStorage,useRouterStuff,} from "@dub/ui";import { capitalize, cn, currencyFormatter, pluralize } from "@dub/utils";@@ -44,6 +41,7 @@ import { motion } from "motion/react";import { useAction } from "next-safe-action/hooks";import {Dispatch,+ MutableRefObject,PropsWithChildren,ReactNode,SetStateAction,@@ -66,8 +64,12 @@ import {InlineBadgePopoverRichTextArea,} from "../../shared/inline-badge-popover";import { RewardDiscountPartnersCard } from "../groups/reward-discount-partners-card";+import {+ AIRewardInput,+ AIRewardPreviewFrame,+ useAIRewardBuilder,+} from "./ai-reward-builder";import { PartnerReferralRewardBuilder } from "./partner-referral-reward-builder";-import { REWARD_EVENT_DESCRIPTIONS } from "./reward-event-descriptions";import { RewardIconSquare } from "./reward-icon-square";import { RewardPreviewCard } from "./reward-preview-card";import { REWARD_TYPES, RewardsLogic } from "./rewards-logic";@@ -203,7 +205,10 @@ function RewardSheetContent({event,reward,defaultRewardValues,-}: RewardSheetProps) {+ hasPendingChangesRef,+}: RewardSheetProps & {+ hasPendingChangesRef: MutableRefObject<boolean>;+}) {const { group, mutateGroup } = useGroup();const { partnersCount, loading, isValidating } = usePartnersCount<number | undefined@@ -215,12 +220,18 @@ function RewardSheetContent({group?.id && !loading && !isValidating ? partnersCount : undefined;const { openConfirmRewardChangeModal, ConfirmRewardChangeModal } =useConfirmRewardChangeModal();+const {id: workspaceId,slug: workspaceSlug,defaultProgramId,plan,- } = useWorkspace();+ } = useWorkspace({+ swrOpts: {+ revalidateOnFocus: true, // revalidate on focus in case user upgrades their plan in another tab+ },+ });+const formRef = useRef<HTMLFormElement>(null);const { mutate: mutateProgram } = useProgram();const { queryParams } = useRouterStuff();@@ -286,7 +297,15 @@ function RewardSheetContent({},});- const { handleSubmit, watch, setValue, setError } = form;+ const {+ handleSubmit,+ watch,+ setValue,+ setError,+ getValues,+ reset,+ formState: { isDirty },+ } = form;const [selectedEvent,@@ -319,6 +338,16 @@ function RewardSheetContent({canSetRewardSpendLimit,canUseAdvancedRewardLogic,} = getPlanCapabilities(plan);++ const aiEvent = selectedEvent === "referral" ? "sale" : selectedEvent;+ const aiBuilder = useAIRewardBuilder({+ event: aiEvent,+ getValues: () => getValues() as Record<string, unknown>,+ reset: (values, options) => reset(values as FormData, options),+ });++ hasPendingChangesRef.current = isDirty || aiBuilder.isReviewing;+const spendLimitEnabled =canSetRewardSpendLimit && spendLimitInterval != null;const hasIncompleteMainSpendLimit =@@ -330,6 +359,7 @@ function RewardSheetContent({createRewardAction,{onSuccess: async () => {+ hasPendingChangesRef.current = false;setIsOpen(false);toast.success("Reward created!");await mutateProgram();@@ -345,6 +375,7 @@ function RewardSheetContent({updateRewardAction,{onSuccess: async () => {+ hasPendingChangesRef.current = false;queryParams({ del: "rewardId" });toast.success("Reward updated!");await mutateProgram();@@ -360,6 +391,7 @@ function RewardSheetContent({deleteRewardAction,{onSuccess: async () => {+ hasPendingChangesRef.current = false;setIsOpen(false);toast.success("Reward deleted!");await mutate(`/api/programs/${defaultProgramId}`);@@ -470,293 +502,411 @@ function RewardSheetContent({<Sheet.Title className="text-lg font-semibold">{reward ? "Edit" : "Create"} {selectedEvent} reward</Sheet.Title>- <Sheet.Close asChild>- <Button- variant="outline"- icon={<X className="size-5" />}- className="h-auto w-fit p-1"- />- </Sheet.Close>+ <Button+ variant="outline"+ icon={<X className="size-5" />}+ className="h-auto w-fit p-1"+ onClick={() => setIsOpen(false)}+ /></div><div className="flex flex-1 flex-col overflow-y-auto p-6">- {!reward && <RewardHelperBlock event={event} />}- <RewardSheetCard- title={- <div className="w-full">- <div className="flex min-w-0 items-center justify-between">- <div className="flex min-w-0 items-center gap-2.5">- <RewardIconSquare icon={MoneyBills2} />- {selectedEvent === "referral" ? (- <PartnerReferralRewardBuilder />- ) : (- <span className="leading-relaxed">- Pay{" "}- {selectedEvent === "sale" && (- <>- a{" "}- <InlineBadgePopover text={capitalize(type)}>- <InlineBadgePopoverMenu- selectedValue={type}- onSelect={(value) =>- setValue("type", value as RewardStructure, {- shouldDirty: true,- })- }- items={REWARD_TYPES}- />- </InlineBadgePopover>{" "}- {type === "percentage" && "of "}- </>- )}- <InlineBadgePopover- text={- amount != null && !isNaN(amount)- ? constructRewardAmount({- type,- maxDuration,- amountInCents:- type === "flat"- ? amount * 100- : undefined,- amountInPercentage:- type === "percentage"- ? amount- : undefined,- })- : "amount"- }- invalid={amount == null || isNaN(amount)}- >- <AmountInput />- </InlineBadgePopover>{" "}- per {selectedEvent}- {selectedEvent === "sale" && (- <>- {" "}- <InlineBadgePopover- text={- maxDuration === 0- ? "one time"- : maxDuration === Infinity- ? "for the customer's lifetime"- : `for ${maxDuration} ${pluralize("month", Number(maxDuration))}`- }- >- <DurationPopoverContent- value={Number(maxDuration)}- onChange={(value) =>- setValue("maxDuration", value, {- shouldDirty: true,- })- }- presetDurations={RECURRING_MAX_DURATIONS.filter(- (v) => v !== 0 && v !== 1, // filter out one-time and 1-month intervals (we only use 1-month for discounts)- )}- />- </InlineBadgePopover>- </>- )}- {modifiers?.length ? (- <> for all other {selectedEvent}s</>- ) : null}- {canSetRewardSpendLimit ? (- <>- {", "}with{" "}- <InlineBadgePopover- text={- spendLimitEnabled- ? "a spend limit of"- : "no spend limit"- }- >- <InlineBadgePopoverMenu- selectedValue={- spendLimitEnabled ? "limit" : "none"- }- onSelect={(value) => {- if (value === "none") {- setValue("spendLimitAmount", null, {- shouldDirty: true,- });- setValue("spendLimitInterval", null, {- shouldDirty: true,- });- } else {+ {selectedEvent !== "referral" && (+ <AIRewardInput event={selectedEvent} builder={aiBuilder} />+ )}+ {selectedEvent !== "referral" ? (+ <AIRewardPreviewFrame builder={aiBuilder}>+ <RewardSheetCard+ title={+ <div className="w-full">+ <div className="flex min-w-0 items-center justify-between">+ <div className="flex min-w-0 items-center gap-2.5">+ <RewardIconSquare icon={MoneyBills2} />+ <span className="leading-relaxed">+ Pay{" "}+ {selectedEvent === "sale" && (+ <>+ a{" "}+ <InlineBadgePopover text={capitalize(type)}>+ <InlineBadgePopoverMenu+ selectedValue={type}+ onSelect={(value) =>setValue(- "spendLimitInterval",- spendLimitInterval ?? "allTime",+ "type",+ value as RewardStructure,{shouldDirty: true,},- );- }- }}- items={[- { text: "no spend limit", value: "none" },- {- text: "a spend limit of",- value: "limit",- },- ]}- />- </InlineBadgePopover>{" "}- {spendLimitEnabled ? (- <>- <InlineBadgePopover- text={- spendLimitAmount != null &&- !isNaN(spendLimitAmount)- ? currencyFormatter(- spendLimitAmount * 100,- {- trailingZeroDisplay:- "stripIfInteger",- },- )- : "amount"+ )}- invalid={- spendLimitAmount == null ||- isNaN(spendLimitAmount)+ items={REWARD_TYPES}+ />+ </InlineBadgePopover>{" "}+ {type === "percentage" && "of "}+ </>+ )}+ <InlineBadgePopover+ text={+ amount != null && !isNaN(amount)+ ? constructRewardAmount({+ type,+ maxDuration,+ amountInCents:+ type === "flat"+ ? amount * 100+ : undefined,+ amountInPercentage:+ type === "percentage"+ ? amount+ : undefined,+ })+ : "amount"+ }+ invalid={amount == null || isNaN(amount)}+ >+ <AmountInput />+ </InlineBadgePopover>{" "}+ per {selectedEvent}+ {selectedEvent === "sale" && (+ <>+ {" "}+ <InlineBadgePopover+ text={+ maxDuration === 0+ ? "one time"+ : maxDuration === Infinity+ ? "for the customer's lifetime"+ : `for ${maxDuration} ${pluralize("month", Number(maxDuration))}`+ }+ >+ <DurationPopoverContent+ value={Number(maxDuration)}+ onChange={(value) =>+ setValue("maxDuration", value, {+ shouldDirty: true,+ })}- >- <SpendLimitAmountInput />- </InlineBadgePopover>{" "}- <InlineBadgePopover- text={- spendLimitInterval === "allTime"- ? "all-time"- : `per ${spendLimitInterval}`+ presetDurations={RECURRING_MAX_DURATIONS.filter(+ (v) => v !== 0 && v !== 1,+ )}+ />+ </InlineBadgePopover>+ </>+ )}+ {modifiers?.length ? (+ <> for all other {selectedEvent}s</>+ ) : null}+ {canSetRewardSpendLimit ? (+ <>+ {", "}with{" "}+ <InlineBadgePopover+ text={+ spendLimitEnabled+ ? "a spend limit of"+ : "no spend limit"+ }+ >+ <InlineBadgePopoverMenu+ selectedValue={+ spendLimitEnabled ? "limit" : "none"}- >- <InlineBadgePopoverMenu- selectedValue={- spendLimitInterval ?? "allTime"- }- onSelect={(value) =>+ onSelect={(value) => {+ if (value === "none") {+ setValue("spendLimitAmount", null, {+ shouldDirty: true,+ });+ setValue("spendLimitInterval", null, {+ shouldDirty: true,+ });+ } else {setValue("spendLimitInterval",- value as any,+ spendLimitInterval ?? "allTime",{shouldDirty: true,},- )+ );}- items={[- { text: "all-time", value: "allTime" },- { text: "per day", value: "day" },- { text: "per week", value: "week" },- { text: "per month", value: "month" },- ]}- />- </InlineBadgePopover>- </>- ) : null}- </>- ) : null}- </span>- )}- </div>- <Tooltip- content={"Add a custom reward description"}- disabled={description !== null}- >- <div className="shrink-0">- <Button- variant="secondary"- className={cn(- "size-7 p-0",- description !== null && "text-blue-600",- )}- icon={<Pen2 className="size-3.5" />}- onClick={() =>- setValue(- "description",- description === null ? "" : null,- { shouldDirty: true },- )- }- />- </div>- </Tooltip>- </div>- <motion.div- initial={false}- transition={{ ease: "easeInOut", duration: 0.2 }}- animate={{- height: description !== null ? "auto" : 0,- opacity: description !== null ? 1 : 0,- }}- className="-mx-2.5 overflow-hidden"- >- <div className="pt-2.5">- <div className="border-border-subtle flex min-w-0 items-center gap-2.5 border-t px-2.5 pt-2.5">- <RewardIconSquare icon={Gift} />- <span className="min-w-0 grow leading-relaxed">- Shown as{" "}- <InlineBadgePopover- text={description || "Reward description"}- invalid={!description}- >- <InlineBadgePopoverInput- value={description ?? ""}- onChange={(e) =>+ }}+ items={[+ {+ text: "no spend limit",+ value: "none",+ },+ {+ text: "a spend limit of",+ value: "limit",+ },+ ]}+ />+ </InlineBadgePopover>{" "}+ {spendLimitEnabled ? (+ <>+ <InlineBadgePopover+ text={+ spendLimitAmount != null &&+ !isNaN(spendLimitAmount)+ ? currencyFormatter(+ spendLimitAmount * 100,+ {+ trailingZeroDisplay:+ "stripIfInteger",+ },+ )+ : "amount"+ }+ invalid={+ spendLimitAmount == null ||+ isNaN(spendLimitAmount)+ }+ >+ <SpendLimitAmountInput />+ </InlineBadgePopover>{" "}+ <InlineBadgePopover+ text={+ spendLimitInterval === "allTime"+ ? "all-time"+ : `per ${spendLimitInterval}`+ }+ >+ <InlineBadgePopoverMenu+ selectedValue={+ spendLimitInterval ?? "allTime"+ }+ onSelect={(value) =>+ setValue(+ "spendLimitInterval",+ value as any,+ {+ shouldDirty: true,+ },+ )+ }+ items={[+ {+ text: "all-time",+ value: "allTime",+ },+ { text: "per day", value: "day" },+ { text: "per week", value: "week" },+ {+ text: "per month",+ value: "month",+ },+ ]}+ />+ </InlineBadgePopover>+ </>+ ) : null}+ </>+ ) : null}+ </span>+ </div>+ <Tooltip+ content={"Add a custom reward description"}+ disabled={description !== null}+ >+ <div className="shrink-0">+ <Button+ variant="secondary"+ className={cn(+ "size-7 p-0",+ description !== null && "text-blue-600",+ )}+ icon={<Pen2 className="size-3.5" />}+ onClick={() =>setValue("description",- (e.target as HTMLInputElement).value,- {- shouldDirty: true,- },+ description === null ? "" : null,+ { shouldDirty: true },)}- className="sm:w-80"- maxLength={REWARD_DESCRIPTION_MAX_LENGTH}/>- </InlineBadgePopover>{" "}- with the tooltip{" "}- <InlineBadgePopover- text={tooltipDescription || "Reward tooltip"}- showOptional={!tooltipDescription}- buttonClassName="min-w-0 max-w-full"- contentClassName="truncate"- >- <InlineBadgePopoverRichTextArea- value={tooltipDescription ?? ""}- onChange={(value) =>- setValue("tooltipDescription", value, {+ </div>+ </Tooltip>+ </div>+ <motion.div+ initial={false}+ transition={{ ease: "easeInOut", duration: 0.2 }}+ animate={{+ height: description !== null ? "auto" : 0,+ opacity: description !== null ? 1 : 0,+ }}+ className="-mx-2.5 overflow-hidden"+ >+ <div className="pt-2.5">+ <div className="border-border-subtle flex min-w-0 items-center gap-2.5 border-t px-2.5 pt-2.5">+ <RewardIconSquare icon={Gift} />+ <span className="min-w-0 grow leading-relaxed">+ Shown as{" "}+ <InlineBadgePopover+ text={description || "Reward description"}+ invalid={!description}+ >+ <InlineBadgePopoverInput+ value={description ?? ""}+ onChange={(e) =>+ setValue(+ "description",+ (e.target as HTMLInputElement).value,+ {+ shouldDirty: true,+ },+ )+ }+ className="sm:w-80"+ maxLength={REWARD_DESCRIPTION_MAX_LENGTH}+ />+ </InlineBadgePopover>{" "}+ with the tooltip{" "}+ <InlineBadgePopover+ text={tooltipDescription || "Reward tooltip"}+ showOptional={!tooltipDescription}+ buttonClassName="min-w-0 max-w-full"+ contentClassName="truncate"+ >+ <InlineBadgePopoverRichTextArea+ value={tooltipDescription ?? ""}+ onChange={(value) =>+ setValue("tooltipDescription", value, {+ shouldDirty: true,+ })+ }+ className="sm:w-80"+ maxLength={+ REWARD_TOOLTIP_DESCRIPTION_MAX_LENGTH+ }+ />+ </InlineBadgePopover>+ </span>+ <Button+ variant="outline"+ className="size-6 shrink-0 p-0"+ icon={<X className="size-3" strokeWidth={2} />}+ onClick={() => {+ setValue("description", null, {shouldDirty: true,- })- }- className="sm:w-80"- maxLength={REWARD_TOOLTIP_DESCRIPTION_MAX_LENGTH}+ });+ setValue("tooltipDescription", null, {+ shouldDirty: true,+ });+ }}/>- </InlineBadgePopover>- </span>- <Button- variant="outline"- className="size-6 shrink-0 p-0"- icon={<X className="size-3" strokeWidth={2} />}- onClick={() => {- setValue("description", null, {- shouldDirty: true,- });- setValue("tooltipDescription", null, {- shouldDirty: true,- });- }}- />+ </div>+ </div>+ </motion.div>+ </div>+ }+ content={<RewardsLogic isDefaultReward={false} />}+ />+ </AIRewardPreviewFrame>+ ) : (+ <RewardSheetCard+ title={+ <div className="w-full">+ <div className="flex min-w-0 items-center justify-between">+ <div className="flex min-w-0 items-center gap-2.5">+ <RewardIconSquare icon={MoneyBills2} />+ <PartnerReferralRewardBuilder /></div>+ <Tooltip+ content={"Add a custom reward description"}+ disabled={description !== null}+ >+ <div className="shrink-0">+ <Button+ variant="secondary"+ className={cn(+ "size-7 p-0",+ description !== null && "text-blue-600",+ )}+ icon={<Pen2 className="size-3.5" />}+ onClick={() =>+ setValue(+ "description",+ description === null ? "" : null,+ { shouldDirty: true },+ )+ }+ />+ </div>+ </Tooltip></div>- </motion.div>- </div>- }- content={- selectedEvent === "referral" ? null : (- <RewardsLogic isDefaultReward={false} />- )- }- />+ <motion.div+ initial={false}+ transition={{ ease: "easeInOut", duration: 0.2 }}+ animate={{+ height: description !== null ? "auto" : 0,+ opacity: description !== null ? 1 : 0,+ }}+ className="-mx-2.5 overflow-hidden"+ >+ <div className="pt-2.5">+ <div className="border-border-subtle flex min-w-0 items-center gap-2.5 border-t px-2.5 pt-2.5">+ <RewardIconSquare icon={Gift} />+ <span className="min-w-0 grow leading-relaxed">+ Shown as{" "}+ <InlineBadgePopover+ text={description || "Reward description"}+ invalid={!description}+ >+ <InlineBadgePopoverInput+ value={description ?? ""}+ onChange={(e) =>+ setValue(+ "description",+ (e.target as HTMLInputElement).value,+ {+ shouldDirty: true,+ },+ )+ }+ className="sm:w-80"+ maxLength={REWARD_DESCRIPTION_MAX_LENGTH}+ />+ </InlineBadgePopover>{" "}+ with the tooltip{" "}+ <InlineBadgePopover+ text={tooltipDescription || "Reward tooltip"}+ showOptional={!tooltipDescription}+ buttonClassName="min-w-0 max-w-full"+ contentClassName="truncate"+ >+ <InlineBadgePopoverRichTextArea+ value={tooltipDescription ?? ""}+ onChange={(value) =>+ setValue("tooltipDescription", value, {+ shouldDirty: true,+ })+ }+ className="sm:w-80"+ maxLength={+ REWARD_TOOLTIP_DESCRIPTION_MAX_LENGTH+ }+ />+ </InlineBadgePopover>+ </span>+ <Button+ variant="outline"+ className="size-6 shrink-0 p-0"+ icon={<X className="size-3" strokeWidth={2} />}+ onClick={() => {+ setValue("description", null, {+ shouldDirty: true,+ });+ setValue("tooltipDescription", null, {+ shouldDirty: true,+ });+ }}+ />+ </div>+ </div>+ </motion.div>+ </div>+ }+ content={null}+ />+ )}<VerticalLine /><RewardPreviewCard />@@ -805,7 +955,8 @@ function RewardSheetContent({hasIncompleteMainSpendLimit ||isDeleting ||isCreating ||- isUpdating+ isUpdating ||+ (selectedEvent !== "referral" && aiBuilder.isReviewing)}disabledTooltip={showReferralUpsell ? (@@ -822,6 +973,8 @@ function RewardSheetContent({href={`/${workspaceSlug}/upgrade?plan=advanced&showAdvancedUpsellModal=true`}target="_blank"/>+ ) : selectedEvent !== "referral" && aiBuilder.isReviewing ? (+ "Accept or discard the generated reward before saving.") : undefined}/>@@ -833,81 +986,22 @@ function RewardSheetContent({);}-function RewardHelperBlock({ event }: { event: EventType }) {- const [dismissed, setDismissed] = useLocalStorage<boolean>(- `reward-helper-${event}-dismissed`,- false,- );-- const {- icon: Icon,- title,- description,- bestFor,- learnMoreHref,- } = REWARD_EVENT_DESCRIPTIONS[event];-- return (- <motion.div- animate={- dismissed- ? { opacity: 0, height: 0, marginBottom: 0 }- : { opacity: 1, height: "auto", marginBottom: 16 }- }- initial={false}- className="overflow-hidden"- inert={dismissed}- >- <div className="relative overflow-hidden rounded-xl bg-neutral-100 p-4">- <div className="absolute right-0 top-0 flex h-full w-1/2 items-start justify-end opacity-30 mix-blend-hard-light blur-[50px] [mask-image:linear-gradient(90deg,transparent,black)] [transform:translateZ(0)]">- <div className="h-32 w-80 -translate-y-4 translate-x-4 bg-[conic-gradient(from_220deg_at_50%_50%,#FF0000_0%,#EAB308_17%,#1E00FF_31%,#5CFF80_46%,#855AFC_60%,#3A8BFD_78%,#FF0000_100%)]" />- </div>- <Grid- cellSize={60}- patternOffset={[33, 28]}- className="inset-[unset] right-0 top-0 h-full w-1/2 text-neutral-300 [mask-image:linear-gradient(90deg,transparent,black)]"- />-- <div className="relative flex flex-col gap-2">- <Icon className="size-5 text-neutral-600" />- <div className="flex flex-col pt-2">- <span className="text-sm font-medium text-neutral-900">- {title}- </span>- <span className="text-sm text-neutral-500">- {description}. Best for {bestFor}.- </span>- </div>- <div className="mt-1 flex items-center gap-2">- <a href={learnMoreHref} target="_blank" rel="noopener noreferrer">- <Button- type="button"- variant="secondary"- text="Learn more"- icon={<BookOpen className="size-3.5" />}- className="h-8 w-fit px-3"- />- </a>- <Button- type="button"- variant="outline"- text="Dismiss"- className="h-8 w-fit px-3"- onClick={() => setDismissed(true)}- />- </div>- </div>- </div>- </motion.div>- );-}-function RewardSheetCard({title,content,-}: PropsWithChildren<{ title: ReactNode; content: ReactNode }>) {+ className,+}: PropsWithChildren<{+ title: ReactNode;+ content: ReactNode;+ className?: string;+}>) {return (- <div className="border-border-subtle rounded-xl border bg-white text-sm shadow-sm">+ <div+ className={cn(+ "border-border-subtle rounded-xl border bg-white text-sm shadow-sm",+ className,+ )}+ ><div className="text-content-emphasis flex items-center gap-2.5 p-2.5 font-medium">{title}</div>@@ -1010,15 +1104,60 @@ export function RewardSheet({nested?: boolean;}) {const { queryParams } = useRouterStuff();+ const hasPendingChangesRef = useRef(false);++ const setIsOpen: RewardSheetProps["setIsOpen"] = (value) => {+ const nextOpen = typeof value === "function" ? value(isOpen) : value;++ if (+ !nextOpen &&+ hasPendingChangesRef.current &&+ !window.confirm(+ "You have unsaved changes. Are you sure you want to exit the reward builder?",+ )+ ) {+ return;+ }++ rest.setIsOpen(value);++ if (!nextOpen) {+ queryParams({ del: "rewardId" });+ }+ };return (<Sheetopen={isOpen}- onOpenChange={rest.setIsOpen}+ onOpenChange={setIsOpen}nested={nested}- onClose={() => queryParams({ del: "rewardId" })}+ contentProps={{+ onPointerDownOutside: (e) => {+ if (+ e.target instanceof Element &&+ e.target.closest("[data-sonner-toast]")+ ) {+ return;+ }++ if (hasPendingChangesRef.current) {+ e.preventDefault();+ setIsOpen(false);+ }+ },+ onEscapeKeyDown: (e) => {+ if (hasPendingChangesRef.current) {+ e.preventDefault();+ setIsOpen(false);+ }+ },+ }}>- <RewardSheetContent {...rest} />+ <RewardSheetContent+ {...rest}+ setIsOpen={setIsOpen}+ hasPendingChangesRef={hasPendingChangesRef}+ /></Sheet>);}diff --git a/apps/web/ui/partners/rewards/ai-reward-builder.tsx b/apps/web/ui/partners/rewards/ai-reward-builder.tsxnew file mode 100644index 0000000000..015d4811b7--- /dev/null+++ b/apps/web/ui/partners/rewards/ai-reward-builder.tsx@@ -0,0 +1,973 @@+"use client";++import {+ AIRewardDraft,+ AIRewardGenerationOutput,+ getAIRewardSchema,+} from "@/lib/ai/ai-reward-schema";+import { generateReward } from "@/lib/ai/generate-reward";+import useWorkspace from "@/lib/swr/use-workspace";+import { REWARD_CONDITION_ATTRIBUTES } from "@/lib/zod/schemas/rewards";+import { CustomToast } from "@/ui/shared/custom-toast";+import { readStreamableValue } from "@ai-sdk/rsc";+import { AnimatedSizeContainer, Button } from "@dub/ui";+import { ArrowTurnRight2, Sparkle3 } from "@dub/ui/icons";+import { cn } from "@dub/utils";+import { EventType, RewardStructure } from "@prisma/client";+import { AnimatePresence, motion, useReducedMotion } from "motion/react";+import {+ type CSSProperties,+ type PropsWithChildren,+ type ReactNode,+ type TransitionEvent,+ useCallback,+ useEffect,+ useRef,+ useState,+} from "react";+import TextareaAutosize from "react-textarea-autosize";+import { toast } from "sonner";+import { v4 as uuid } from "uuid";+import { REWARD_PRESETS } from "./reward-presets";++const EASE_OUT = [0.23, 1, 0.32, 1] as const;+const EASE_OUT_CSS = "cubic-bezier(0.23, 1, 0.32, 1)";+const EASE_CHROME = "cubic-bezier(0.32, 0.72, 0, 1)";+const CHROME_ENTER_MS = 240;++type BuilderPhase = "idle" | "streaming" | "review" | "error";++function buildRewardFormValuesFromDraft({+ draft,+ event,+ current,+ finalize = false,+}: {+ draft: AIRewardDraft | Partial<AIRewardDraft>;+ event: Exclude<EventType, "referral">;+ current: Record<string, unknown>;+ finalize?: boolean;+}): Record<string, unknown> | null {+ if (draft.type == null || draft.amount == null) return null;++ const isOneOffEvent = event === "click" || event === "lead";+ const type: RewardStructure = isOneOffEvent ? "flat" : draft.type;+ const maxDuration = isOneOffEvent+ ? 0+ : draft.maxDuration === undefined+ ? undefined+ : draft.maxDuration == null+ ? Infinity+ : draft.maxDuration;++ const next: Record<string, unknown> = {+ ...current,+ type,+ };++ if (type === "flat") {+ next.amountInCents = draft.amount;+ next.amountInPercentage = undefined;+ } else {+ next.amountInPercentage = draft.amount;+ next.amountInCents = undefined;+ }++ if (maxDuration !== undefined) {+ next.maxDuration = maxDuration;+ }++ const modifiers = draft.modifiers?.filter((m) => m.conditions?.length);+ if (!modifiers?.length) {+ // Only clear stale conditions on the final draft so partial streams do not wipe them.+ if (finalize) {+ next.modifiers = undefined;+ }+ return next;+ }++ const resolvedMaxDuration =+ maxDuration === undefined ? (isOneOffEvent ? 0 : Infinity) : maxDuration;++ next.modifiers = modifiers.map((modifier) => {+ const modifierType = modifier.type === undefined ? type : modifier.type;+ const modifierAmount = modifier.amount ?? draft.amount;+ const modifierMaxDuration =+ modifier.maxDuration === undefined+ ? resolvedMaxDuration+ : modifier.maxDuration == null+ ? Infinity+ : modifier.maxDuration;++ return {+ id: uuid(),+ operator: modifier.operator ?? "AND",+ conditions: modifier.conditions.map((condition) => {+ const value = condition.value;+ const attrType = REWARD_CONDITION_ATTRIBUTES.find(+ (a) => a.id === condition.attribute,+ )?.type;++ if (attrType !== "date" || value == null || Array.isArray(value)) {+ return condition;+ }++ const ms =+ typeof value === "number" ? value : Number(new Date(String(value)));++ return {+ ...condition,+ value: Number.isNaN(ms) ? value : ms,+ };+ }),+ type: modifierType,+ amountInCents: modifierType === "flat" ? modifierAmount : undefined,+ amountInPercentage:+ modifierType === "percentage" ? modifierAmount : undefined,+ maxDuration: event === "sale" ? modifierMaxDuration : undefined,+ };+ });++ return next;+}++export function useAIRewardBuilder({+ event,+ getValues,+ reset,+}: {+ event: Exclude<EventType, "referral">;+ getValues: () => Record<string, unknown>;+ reset: (+ values: Record<string, unknown>,+ options?: { keepDefaultValues?: boolean },+ ) => void;+}) {+ const {+ id: workspaceId,+ slug: workspaceSlug,+ mutate: mutateWorkspace,+ } = useWorkspace();++ const [prompt, setPrompt] = useState("");+ const [phase, setPhase] = useState<BuilderPhase>("idle");+ const [error, setError] = useState<string | null>(null);+ const [hasPreviewContent, setHasPreviewContent] = useState(false);+ const snapshotRef = useRef<Record<string, unknown> | null>(null);+ const presetTimeoutRef = useRef<number | null>(null);+ const generationIdRef = useRef(0);+ const streamingRef = useRef(false);++ const presets = REWARD_PRESETS[event] ?? [];+ const isReviewing =+ phase === "streaming" || phase === "review" || phase === "error";++ const clearPresetTimeout = useCallback(() => {+ if (presetTimeoutRef.current != null) {+ window.clearTimeout(presetTimeoutRef.current);+ presetTimeoutRef.current = null;+ }+ }, []);++ const ensureSnapshot = useCallback(() => {+ if (!snapshotRef.current) {+ snapshotRef.current = structuredClone(getValues());+ }+ }, [getValues]);++ const applyDraft = useCallback(+ (+ draft: AIRewardDraft | Partial<AIRewardDraft>,+ finalize: boolean = false,+ ) => {+ const next = buildRewardFormValuesFromDraft({+ draft,+ event,+ current: getValues(),+ finalize,+ });+ if (!next) return;+ reset(next, { keepDefaultValues: true });+ setHasPreviewContent(true);+ },+ [event, getValues, reset],+ );++ const exitReview = useCallback(() => {+ clearPresetTimeout();+ generationIdRef.current += 1;+ streamingRef.current = false;+ snapshotRef.current = null;+ setHasPreviewContent(false);+ setPhase("idle");+ setError(null);+ }, [clearPresetTimeout]);++ const discard = useCallback(+ ({ keepPrompt = false }: { keepPrompt?: boolean } = {}) => {+ if (snapshotRef.current) {+ reset(snapshotRef.current, { keepDefaultValues: true });+ }+ exitReview();+ if (!keepPrompt) {+ setPrompt("");+ }+ },+ [exitReview, reset],+ );++ const accept = useCallback(() => {+ exitReview();+ setPrompt("");+ toast.success("Reward applied — review and save when ready.");+ }, [exitReview]);++ const selectPreset = useCallback(+ (draft: AIRewardDraft) => {+ if (streamingRef.current) return;++ clearPresetTimeout();+ const generationId = ++generationIdRef.current;+ streamingRef.current = true;+ ensureSnapshot();+ setPrompt("");+ setHasPreviewContent(false);+ setPhase("streaming");+ setError(null);++ presetTimeoutRef.current = window.setTimeout(() => {+ presetTimeoutRef.current = null;+ if (generationId !== generationIdRef.current) return;+ applyDraft(draft, true);+ setPhase("review");+ streamingRef.current = false;+ }, 1500);+ },+ [applyDraft, clearPresetTimeout, ensureSnapshot],+ );++ const generate = useCallback(async () => {+ if (!workspaceId || !prompt.trim() || streamingRef.current) {+ return;+ }++ clearPresetTimeout();+ const generationId = ++generationIdRef.current;+ streamingRef.current = true;+ ensureSnapshot();+ setHasPreviewContent(false);+ setPhase("streaming");+ setError(null);++ try {+ const { object } = await generateReward({+ workspaceId,+ event,+ prompt: prompt.trim(),+ });++ if (generationId !== generationIdRef.current) return;++ let lastPartial: Partial<AIRewardGenerationOutput> | null = null;+ for await (const partialObject of readStreamableValue(object)) {+ if (generationId !== generationIdRef.current) return;+ if (partialObject) {+ lastPartial = partialObject;+ if (partialObject.supported === true && partialObject.reward) {+ applyDraft(partialObject.reward, false);+ }+ }+ }++ if (generationId !== generationIdRef.current) return;++ if (!lastPartial) {+ setPhase("error");+ setError("Couldn't generate a reward. Try rephrasing your request.");+ return;+ }++ if (lastPartial.supported === false) {+ discard({ keepPrompt: true });+ toast.custom(() => (+ <CustomToast variant="error">+ This reward setup isn't supported yet. [Reach out to+ support](https://dub.co/support) if you need help configuring this.+ </CustomToast>+ ));+ void mutateWorkspace();+ return;+ }++ const parsed = getAIRewardSchema(event).safeParse(lastPartial.reward);+ if (!parsed.success) {+ setPhase("error");+ setError("Generated reward was incomplete. Try a clearer description.");+ return;+ }++ applyDraft(parsed.data, true);+ setPhase("review");+ void mutateWorkspace();+ } catch (err) {+ if (generationId !== generationIdRef.current) return;+ setPhase("error");+ setError(+ err instanceof Error+ ? err.message+ : "Failed to generate reward. Please try again.",+ );+ } finally {+ if (generationId === generationIdRef.current) {+ streamingRef.current = false;+ }+ }+ }, [+ applyDraft,+ clearPresetTimeout,+ discard,+ ensureSnapshot,+ event,+ mutateWorkspace,+ prompt,+ workspaceId,+ ]);++ useEffect(() => {+ return () => {+ generationIdRef.current += 1;+ streamingRef.current = false;+ clearPresetTimeout();+ };+ }, [clearPresetTimeout]);++ return {+ event,+ prompt,+ setPrompt,+ phase,+ error,+ presets,+ isReviewing,+ hasPreviewContent,+ workspaceSlug,+ generate,+ selectPreset,+ accept,+ discard,+ };+}++type AIRewardBuilderState = ReturnType<typeof useAIRewardBuilder>;++function chromeEnterStyle(+ open: boolean,+ reduced: boolean | null,+): CSSProperties | undefined {+ if (reduced) return undefined;+ return {+ transitionDuration: open ? `${CHROME_ENTER_MS}ms` : "150ms",+ transitionDelay: open ? "40ms" : "0ms",+ transitionTimingFunction: open ? EASE_CHROME : EASE_OUT_CSS,+ };+}++function creatingInStyle(+ delayMs: number,+ reduced: boolean | null,+): CSSProperties | undefined {+ if (reduced) return undefined;+ return {+ animation: `ai-creating-in ${CHROME_ENTER_MS}ms ${EASE_CHROME} both`,+ animationDelay: `${delayMs}ms`,+ };+}++export function AIRewardInput({+ event,+ builder,+}: {+ event: Exclude<EventType, "referral">;+ builder: AIRewardBuilderState;+}) {+ const shouldReduceMotion = useReducedMotion();+ const [focused, setFocused] = useState(false);++ const { prompt, setPrompt, presets, workspaceSlug, generate, selectPreset } =+ builder;++ return (+ <div className="relative">+ <AnimatePresence initial={false} mode="popLayout">+ {!builder.isReviewing && (+ <motion.div+ key="ai-reward-input"+ initial={false}+ animate={+ shouldReduceMotion+ ? { opacity: 1 }+ : { opacity: 1, transform: "translateY(0px) scale(1)" }+ }+ exit={+ shouldReduceMotion+ ? { opacity: 0, transition: { duration: 0.1 } }+ : {+ opacity: 0,+ transform: "translateY(-6px) scale(0.98)",+ filter: "blur(2px)",+ transition: {+ duration: 0.18,+ ease: EASE_OUT,+ },+ }+ }+ className="mb-4 origin-top"+ >+ <div+ className="border-border-subtle rounded-xl border bg-white text-sm shadow-sm"+ onFocus={() => {+ setFocused(true);+ }}+ >+ <div className="flex items-start gap-2.5 p-2.5">+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">+ <Sparkle3 className="size-4 text-neutral-800" />+ </div>+ <TextareaAutosize+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ onKeyDown={(e) => {+ if (+ e.key === "Enter" &&+ !e.shiftKey &&+ !e.nativeEvent.isComposing+ ) {+ e.preventDefault();+ void generate();+ setFocused(false);+ }+ }}+ placeholder={`Describe your ${event} reward...`}+ minRows={1}+ maxRows={2}+ className={cn(+ "block min-w-0 flex-1 resize-none border-0 bg-transparent p-0 pt-1 text-sm font-normal leading-5 text-neutral-900 shadow-none",+ "placeholder-neutral-400",+ "focus:outline-none focus:ring-0",+ "disabled:opacity-60",+ )}+ />+ </div>++ <AnimatedSizeContainer+ height+ transition={{ duration: 0.2, ease: EASE_OUT }}+ >+ {focused && (+ <div className="border-border-subtle -mx-px rounded-xl border-x border-t bg-neutral-100 px-2.5 py-2">+ <div className="flex items-center justify-between gap-2">+ <div className="flex min-w-0 flex-wrap gap-1.5">+ {presets.map((preset) => (+ <button+ key={preset.id}+ type="button"+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => selectPreset(preset.draft)}+ className={cn(+ "text-content-emphasis inline-flex h-7 w-fit items-center gap-1.5 rounded-lg bg-neutral-200/80 px-2.5 py-2 text-sm font-medium",+ "transition-[transform,background-color] duration-150 ease-out",+ "hover:bg-neutral-200 active:scale-[0.97]",+ "disabled:cursor-not-allowed disabled:opacity-50",+ )}+ >+ <Sparkle3+ variant="fill"+ className="size-3.5 shrink-0"+ />+ {preset.label}+ </button>+ ))}+ </div>++ <Button+ type="button"+ variant="secondary"+ text="Generate"+ className="h-7 w-fit shrink-0 rounded-lg px-2.5 py-2 text-sm active:scale-[0.97]"+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => void generate()}+ disabled={!prompt.trim()}+ />+ </div>+ </div>+ )}+ </AnimatedSizeContainer>+ </div>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ );+}++const PIXEL_DELAYS = Array.from({ length: 9 }, (_, i) => {+ const row = Math.floor(i / 3);+ const col = i % 3;+ return (col + Math.abs(row - 1)) * 90;+});++function GeneratingStyles() {+ return (+ <style href="ai-generating" precedence="default">{`+ @keyframes ai-pixel-on {+ 0%,+ 100% {+ opacity: 0.15;+ }+ 40%,+ 60% {+ opacity: 1;+ }+ }+ @keyframes ai-shimmer-text {+ 0% {+ background-position: 100% 0;+ }+ 100% {+ background-position: -100% 0;+ }+ }+ @keyframes ai-creating-in {+ from {+ opacity: 0;+ transform: translateY(4px) scale(0.98);+ }+ to {+ opacity: 1;+ transform: translateY(0) scale(1);+ }+ }+ @media (prefers-reduced-motion: reduce) {+ .ai-pixel-on {+ animation: none !important;+ opacity: 0.35 !important;+ }+ .ai-shimmer-text {+ animation: none !important;+ background: none !important;+ color: #737373 !important;+ }+ .ai-creating-in {+ animation: none !important;+ }+ }+ `}</style>+ );+}++function GeneratingStatus() {+ const shouldReduceMotion = useReducedMotion();++ return (+ <div+ className="flex w-fit items-center gap-2.5"+ role="status"+ aria-live="polite"+ aria-label="Generating reward"+ >+ <GeneratingStyles />+ <span aria-hidden className="grid grid-cols-3 gap-[1.5px]">+ {PIXEL_DELAYS.map((delayMs, i) => (+ <span+ key={i}+ className="ai-pixel-on size-1 rounded-[1px] bg-neutral-500"+ style={+ shouldReduceMotion+ ? { opacity: 0.35 }+ : {+ opacity: 0.15,+ animation: `ai-pixel-on 650ms ease-in-out ${delayMs}ms infinite`,+ }+ }+ />+ ))}+ </span>+ <span+ aria-hidden+ className={cn(+ "text-[13px] font-medium",+ shouldReduceMotion+ ? "text-neutral-500"+ : "ai-shimmer-text bg-clip-text text-transparent",+ )}+ style={+ shouldReduceMotion+ ? undefined+ : {+ backgroundImage:+ "linear-gradient(90deg, #a3a3a3 35%, #171717 50%, #a3a3a3 65%)",+ backgroundSize: "200% 100%",+ animation: "ai-shimmer-text 1.4s linear infinite",+ }+ }+ >+ Generating+ </span>+ </div>+ );+}++function ChromeAction({+ open,+ delayClassName,+ children,+}: {+ open: boolean;+ delayClassName: string;+ children: ReactNode;+}) {+ const shouldReduceMotion = useReducedMotion();++ return (+ <div+ className={cn(+ !shouldReduceMotion &&+ "transition-[opacity,transform] will-change-[opacity,transform]",+ open+ ? cn("translate-y-0 opacity-100 duration-200", delayClassName)+ : "translate-y-1 opacity-0 delay-0 duration-100",+ )}+ style={+ shouldReduceMotion+ ? undefined+ : {+ transitionTimingFunction: open ? EASE_CHROME : EASE_OUT_CSS,+ }+ }+ >+ {children}+ </div>+ );+}++function ChromeHeaderTitle({ isCreating }: { isCreating: boolean }) {+ const shouldReduceMotion = useReducedMotion();++ return (+ <motion.div+ className="absolute bottom-1.5 top-0.5 flex items-center"+ initial={false}+ animate={isCreating ? { left: "50%", x: "-50%" } : { left: 8, x: 0 }}+ transition={+ shouldReduceMotion ? { duration: 0 } : { duration: 0.3, ease: EASE_OUT }+ }+ >+ <div className="grid grid-cols-1 grid-rows-1 items-center">+ <AnimatePresence initial={false}>+ {isCreating ? (+ <motion.div+ key="generating"+ className="col-start-1 row-start-1"+ initial={+ shouldReduceMotion ? false : { opacity: 0, y: 4, scale: 0.98 }+ }+ animate={{ opacity: 1, y: 0, scale: 1 }}+ exit={+ shouldReduceMotion+ ? { opacity: 0 }+ : { opacity: 0, transition: { duration: 0.12 } }+ }+ transition={{ duration: 0.2, ease: EASE_OUT }}+ >+ <GeneratingStatus />+ </motion.div>+ ) : (+ <motion.div+ key="generated"+ className="col-start-1 row-start-1"+ initial={shouldReduceMotion ? false : { opacity: 0 }}+ animate={{ opacity: 1 }}+ transition={{+ duration: shouldReduceMotion ? 0 : 0.2,+ delay: shouldReduceMotion ? 0 : 0.06,+ ease: EASE_OUT,+ }}+ >+ <span className="text-content-emphasis text-sm font-medium leading-none">+ Generated reward+ </span>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ </motion.div>+ );+}++export function AIRewardPreviewFrame({+ builder,+ children,+}: PropsWithChildren<{+ builder: AIRewardBuilderState;+}>) {+ const shouldReduceMotion = useReducedMotion();+ const {+ isReviewing,+ phase,+ error,+ accept,+ discard,+ hasPreviewContent,+ event,+ } = builder;++ const [chromeMounted, setChromeMounted] = useState(false);+ const [chromeOpen, setChromeOpen] = useState(false);+ const [exitKind, setExitKind] = useState<+ "accept" | "discard" | "retry" | null+ >(null);+ const exitKindRef = useRef<"accept" | "discard" | "retry" | null>(null);++ useEffect(() => {+ if (!isReviewing) {+ if (exitKindRef.current) return;+ setChromeOpen(false);+ setChromeMounted(false);+ return;+ }++ setChromeMounted(true);+ exitKindRef.current = null;+ setExitKind(null);++ if (shouldReduceMotion) {+ setChromeOpen(true);+ return;+ }++ setChromeOpen(false);+ let inner = 0;+ const outer = requestAnimationFrame(() => {+ inner = requestAnimationFrame(() => setChromeOpen(true));+ });+ return () => {+ cancelAnimationFrame(outer);+ cancelAnimationFrame(inner);+ };+ }, [isReviewing, shouldReduceMotion]);++ const finishExit = useCallback(() => {+ const kind = exitKindRef.current;+ exitKindRef.current = null;+ setExitKind(null);+ setChromeMounted(false);++ if (kind === "accept") accept();+ else if (kind === "discard") discard();+ else if (kind === "retry") discard({ keepPrompt: true });+ }, [accept, discard]);++ const requestExit = (kind: "accept" | "discard" | "retry") => {+ if (exitKindRef.current || phase === "streaming") return;++ if (shouldReduceMotion) {+ exitKindRef.current = kind;+ finishExit();+ return;+ }++ exitKindRef.current = kind;+ setExitKind(kind);+ setChromeOpen(false);++ window.setTimeout(() => {+ if (exitKindRef.current === kind) finishExit();+ }, 180);+ };++ const onChromeTransitionEnd = (e: TransitionEvent<HTMLDivElement>) => {+ if (e.target !== e.currentTarget) return;+ if (e.propertyName !== "opacity") return;+ if (chromeOpen || !exitKindRef.current) return;+ finishExit();+ };++ const showSkeletons = phase === "streaming" && !hasPreviewContent;+ const showError = phase === "error" && Boolean(error);+ const isCreating = phase === "streaming";++ return (+ <div+ className={cn(+ "relative flex flex-col rounded-[14px]",+ chromeMounted && "max-h-[min(70vh,calc(100dvh-14rem))] p-1",+ )}+ >+ {chromeMounted && (+ <div+ aria-hidden+ onTransitionEnd={onChromeTransitionEnd}+ className={cn(+ "pointer-events-none absolute inset-0 origin-top rounded-[14px] bg-amber-100",+ !shouldReduceMotion &&+ "transition-[opacity,transform] will-change-[opacity,transform]",+ chromeOpen+ ? "translate-y-0 scale-100 opacity-100"+ : cn(+ "opacity-0",+ exitKind === "accept" && "-translate-y-1 scale-[0.99]",+ (exitKind === "discard" || exitKind === "retry") &&+ "translate-y-1 scale-[0.98]",+ exitKind == null && "scale-[0.98]",+ ),+ )}+ style={chromeEnterStyle(chromeOpen, shouldReduceMotion)}+ />+ )}++ <div+ className={cn(+ "relative z-10 flex min-h-0 flex-1 flex-col",+ chromeMounted && "overflow-hidden",+ )}+ >+ {chromeMounted && (+ <div+ className={cn(+ "relative flex h-9 shrink-0 items-center pb-1.5 pl-2 pr-[6px] pt-0.5",+ !shouldReduceMotion &&+ "transition-[opacity,transform] will-change-[opacity,transform]",+ chromeOpen+ ? "translate-y-0 opacity-100"+ : "-translate-y-1 opacity-0",+ )}+ style={chromeEnterStyle(chromeOpen, shouldReduceMotion)}+ >+ <ChromeHeaderTitle isCreating={isCreating} />++ {phase !== "error" && (+ <div+ className="ml-auto flex items-center gap-1.5"+ inert={isCreating || undefined}+ >+ <ChromeAction+ open={chromeOpen && !isCreating}+ delayClassName="delay-75"+ >+ <Button+ type="button"+ variant="secondary"+ text="Discard"+ className="h-7 w-fit rounded-lg px-3 active:scale-[0.97]"+ disabled={isCreating || exitKind != null}+ onClick={() => requestExit("discard")}+ />+ </ChromeAction>+ <ChromeAction+ open={chromeOpen && !isCreating && phase === "review"}+ delayClassName="delay-100"+ >+ <Button+ type="button"+ variant="primary"+ text="Accept"+ className="h-7 w-fit rounded-lg px-3 active:scale-[0.97]"+ disabled={+ isCreating || phase !== "review" || exitKind != null+ }+ onClick={() => requestExit("accept")}+ />+ </ChromeAction>+ </div>+ )}+ </div>+ )}++ {showError ? (+ <div className="space-y-2 rounded-[12px] border border-neutral-200 bg-white p-3">+ <p className="text-sm text-red-600">{error}</p>+ <Button+ type="button"+ variant="secondary"+ text="Try again"+ className="h-8 w-fit rounded-lg px-3 active:scale-[0.97]"+ disabled={exitKind != null}+ onClick={() => requestExit("retry")}+ />+ </div>+ ) : showSkeletons ? (+ <div+ className={cn(!shouldReduceMotion && "ai-creating-in")}+ style={creatingInStyle(80, shouldReduceMotion)}+ >+ <ReviewSkeletons event={event} />+ </div>+ ) : (+ <div+ className={cn("min-h-0", chromeMounted && "flex-1 overflow-y-auto")}+ >+ <div+ className={cn(isCreating && "pointer-events-none select-none")}+ inert={isCreating || undefined}+ >+ {children}+ </div>+ </div>+ )}+ </div>+ </div>+ );+}++function SkeletonPill({ className }: { className?: string }) {+ return (+ <span+ className={cn(+ "inline-block h-6 animate-pulse rounded-md bg-neutral-100",+ className,+ )}+ />+ );+}++function ReviewSkeletons({ event }: { event: Exclude<EventType, "referral"> }) {+ return (+ <div className="border-border-subtle rounded-xl border bg-white text-sm shadow-sm">+ <div className="flex items-start gap-2.5 p-2.5">+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md bg-neutral-100">+ <div className="size-4 animate-pulse rounded-sm bg-neutral-200" />+ </div>+ <p className="flex min-w-0 flex-1 flex-wrap items-center gap-x-1.5 gap-y-1.5 text-sm leading-relaxed text-neutral-400">+ <span>Pay</span>+ {event === "sale" ? (+ <>+ <span>a</span>+ <SkeletonPill className="w-14" />+ <span>of</span>+ <SkeletonPill className="w-12" />+ <span>per sale</span>+ <SkeletonPill className="w-16" />+ </>+ ) : (+ <>+ <SkeletonPill className="w-12" />+ <span>per {event}</span>+ </>+ )}+ <span>, with</span>+ <SkeletonPill className="w-20" />+ </p>+ </div>+ <div className="border-border-subtle -mx-px rounded-xl border-x border-t bg-neutral-50 p-2.5">+ <Button+ type="button"+ variant="secondary"+ className="h-8 rounded-lg"+ icon={<ArrowTurnRight2 className="size-4" />}+ text="Add condition"+ disabled+ />+ </div>+ </div>+ );+}diff --git a/apps/web/ui/partners/rewards/reward-presets.ts b/apps/web/ui/partners/rewards/reward-presets.tsnew file mode 100644index 0000000000..70e9fa8779--- /dev/null+++ b/apps/web/ui/partners/rewards/reward-presets.ts@@ -0,0 +1,103 @@+import { AIRewardDraft } from "@/lib/ai/ai-reward-schema";+import { EventType } from "@prisma/client";++export type RewardPreset = {+ id: string;+ label: string;+ draft: AIRewardDraft;+};++export const REWARD_PRESETS: Partial<+ Record<Exclude<EventType, "referral">, RewardPreset[]>+> = {+ sale: [+ {+ id: "sale-30-12-months",+ label: "30% for 12 months",+ draft: {+ type: "percentage",+ amount: 30,+ maxDuration: 12,+ },+ },+ {+ id: "sale-100-cpa",+ label: "$100 CPA",+ draft: {+ type: "flat",+ amount: 100,+ maxDuration: 0,+ },+ },+ ],+ lead: [+ {+ id: "lead-10-flat",+ label: "$10 per lead",+ draft: {+ type: "flat",+ amount: 10,+ maxDuration: 0,+ },+ },+ {+ id: "lead-trial-25",+ label: "$25 for trial leads",+ draft: {+ type: "flat",+ amount: 10,+ maxDuration: 0,+ modifiers: [+ {+ operator: "AND",+ conditions: [+ {+ entity: "customer",+ attribute: "source",+ operator: "equals_to",+ value: "trial",+ },+ ],+ type: "flat",+ amount: 25,+ },+ ],+ },+ },+ ],+ click: [+ {+ id: "click-050",+ label: "$0.50 per click",+ draft: {+ type: "flat",+ amount: 0.5,+ maxDuration: 0,+ },+ },+ {+ id: "click-non-us",+ label: "$1 for non-US traffic",+ draft: {+ type: "flat",+ amount: 0.5,+ maxDuration: 0,+ modifiers: [+ {+ operator: "AND",+ conditions: [+ {+ entity: "customer",+ attribute: "country",+ operator: "not_equals",+ value: "US",+ },+ ],+ type: "flat",+ amount: 1,+ },+ ],+ },+ },+ ],+};diff --git a/apps/web/ui/shared/custom-toast.tsx b/apps/web/ui/shared/custom-toast.tsxindex 5666c6d6d9..427e2e2f04 100644--- a/apps/web/ui/shared/custom-toast.tsx+++ b/apps/web/ui/shared/custom-toast.tsx@@ -1,15 +1,17 @@+import { AlertCircleFill, CheckCircleFill } from "./icons";import { MarkdownDescription } from "./markdown-description";export function CustomToast({- icon: Icon,+ variant,children,}: {- icon?: React.ComponentType<{ className?: string }>;+ variant?: "success" | "error";children: string;}) {+ const Icon = variant === "error" ? AlertCircleFill : CheckCircleFill;return (- <div className="flex items-center gap-1.5 rounded-lg bg-white p-4 text-sm shadow-[0_4px_12px_#0000001a]">- {Icon && <Icon className="size-[18px] shrink-0 text-black" />}+ <div className="flex items-start gap-1.5 rounded-lg bg-white p-4 text-sm shadow-[0_4px_12px_#0000001a]">+ <Icon className="mt-0.5 size-[18px] shrink-0 text-black" /><MarkdownDescription className="text-[13px] font-medium text-neutral-900">{children}</MarkdownDescription>diff --git a/packages/ui/src/date-picker/date-picker.tsx b/packages/ui/src/date-picker/date-picker.tsxindex 95f132ad4c..78135495a5 100644--- a/packages/ui/src/date-picker/date-picker.tsx+++ b/packages/ui/src/date-picker/date-picker.tsx@@ -70,6 +70,7 @@ export function DatePicker({onSelect={onSelect}locale={locale}{...props}+ defaultMonth={selected}/>);diff --git a/packages/ui/src/file-upload.tsx b/packages/ui/src/file-upload.tsxindex 693d559dcb..4965450886 100644--- a/packages/ui/src/file-upload.tsx+++ b/packages/ui/src/file-upload.tsx@@ -143,6 +143,8 @@ export type FileUploadProps = FileUploadReadFileProps & {accessibilityLabel?: string;disabled?: boolean;++ "data-testid"?: string;} & VariantProps<typeof imageUploadVariants>;export function FileUpload({@@ -165,6 +167,7 @@ export function FileUpload({targetResolution,accessibilityLabel = "File upload",disabled = false,+ "data-testid": dataTestId,}: FileUploadProps) {const [dragActive, setDragActive] = useState(false);const [fileName, setFileName] = useState<string | null>(null);@@ -330,6 +333,7 @@ export function FileUpload({accept={acceptFileTypes[accept].types.join(",")}onChange={onFileChange}disabled={disabled}+ data-testid={dataTestId}/></div>)}diff --git a/packages/ui/src/icons/nucleo/sparkle3.tsx b/packages/ui/src/icons/nucleo/sparkle3.tsxindex 0d3fd7cdc8..99c1d2b55c 100644--- a/packages/ui/src/icons/nucleo/sparkle3.tsx+++ b/packages/ui/src/icons/nucleo/sparkle3.tsx@@ -1,6 +1,9 @@import { SVGProps } from "react";-export function Sparkle3(props: SVGProps<SVGSVGElement>) {+export function Sparkle3({+ variant = "outline",+ ...props+}: SVGProps<SVGSVGElement> & { variant?: "outline" | "fill" }) {return (<svgheight="18"@@ -15,14 +18,22 @@ export function Sparkle3(props: SVGProps<SVGSVGElement>) {fill="currentColor"stroke="none"/>- <polygon- fill="none"- points="9.5 2.75 11.412 7.587 16.25 9.5 11.412 11.413 9.5 16.25 7.587 11.413 2.75 9.5 7.587 7.587 9.5 2.75"- stroke="currentColor"- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth="1.5"- />+ {variant === "fill" ? (+ <polygon+ fill="currentColor"+ points="9.5 2.75 11.412 7.587 16.25 9.5 11.412 11.413 9.5 16.25 7.587 11.413 2.75 9.5 7.587 7.587 9.5 2.75"+ stroke="none"+ />+ ) : (+ <polygon+ fill="none"+ points="9.5 2.75 11.412 7.587 16.25 9.5 11.412 11.413 9.5 16.25 7.587 11.413 2.75 9.5 7.587 7.587 9.5 2.75"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ />+ )}</g></svg>);