Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

code improvements

Pedro Ladeira7e5f45e93293
diff --git a/apps/web/lib/ai/review-reward-tooltip-schema.ts b/apps/web/lib/ai/review-reward-tooltip-schema.ts
index ba1c34f9b2..e4ec2480f0 100644
--- a/apps/web/lib/ai/review-reward-tooltip-schema.ts
+++ b/apps/web/lib/ai/review-reward-tooltip-schema.ts
@@ -1,5 +1,8 @@
import { AI_REWARD_EVENTS } from "@/lib/ai/ai-reward-schema";
-import { CONDITION_OPERATORS } from "@/lib/zod/schemas/rewards";
+import {
+ CONDITION_OPERATORS,
+ REWARD_DESCRIPTION_MAX_LENGTH,
+} from "@/lib/zod/schemas/rewards";
import * as z from "zod/v4";
export const TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR = 0.5;
@@ -119,12 +122,17 @@ export const reviewRewardTooltipOutputSchema = z.object({
});
const reviewRewardTooltipConditionSchema = z.object({
- entity: z.string(),
- attribute: z.string(),
+ entity: z.string().max(100),
+ attribute: z.string().max(100),
operator: z.enum(CONDITION_OPERATORS),
- value: tooltipSuggestionValueSchema,
- label: z.string().nullish(),
- metadataField: z.string().optional(),
+ value: z.union([
+ z.string().max(500),
+ z.number(),
+ z.array(z.string().max(500)).max(300),
+ z.array(z.number()).max(300),
+ ]),
+ label: z.string().max(200).nullish(),
+ metadataField: z.string().max(100).optional(),
});
const rewardPayoutSchema = z.object({
@@ -135,7 +143,7 @@ const rewardPayoutSchema = z.object({
const reviewRewardTooltipModifierSchema = z.object({
operator: z.enum(["AND", "OR"]).default("AND"),
- conditions: z.array(reviewRewardTooltipConditionSchema).min(1),
+ conditions: z.array(reviewRewardTooltipConditionSchema).min(1).max(20),
payout: rewardPayoutSchema,
});
@@ -143,9 +151,9 @@ export const reviewRewardTooltipInputSchema = z.object({
workspaceId: z.string(),
event: z.enum(AI_REWARD_EVENTS),
tooltip: z.string().min(1).max(4000),
- description: z.string().nullish(),
+ description: z.string().max(REWARD_DESCRIPTION_MAX_LENGTH).nullish(),
basePayout: rewardPayoutSchema,
- modifiers: z.array(reviewRewardTooltipModifierSchema),
+ modifiers: z.array(reviewRewardTooltipModifierSchema).max(20),
});
export type TooltipSuggestion = z.infer<typeof tooltipSuggestionSchema>;
diff --git a/apps/web/lib/ai/review-reward-tooltip.ts b/apps/web/lib/ai/review-reward-tooltip.ts
index 59f4e23679..2dd205bb25 100644
--- a/apps/web/lib/ai/review-reward-tooltip.ts
+++ b/apps/web/lib/ai/review-reward-tooltip.ts
@@ -4,6 +4,7 @@ import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
+ filterPayoutFixes,
filterValidatedTooltipSuggestions,
getRewardConditionAttribute,
stripRewardTooltipMarkdown,
@@ -15,6 +16,7 @@ import {
REWARD_CONDITIONS,
} from "@/lib/zod/schemas/rewards";
import { anthropic } from "@ai-sdk/anthropic";
+import { formatDateTime } from "@dub/utils";
import { type EventType } from "@prisma/client";
import { experimental_evaluate as evaluate, generateText, Output } from "ai";
import { throwIfNoPermission } from "../actions/throw-if-no-permission";
@@ -210,6 +212,10 @@ async function authorizeRewardTooltipReview(input: unknown) {
requiredRoles: ["owner", "member"],
});
+ if (workspace.aiUsage >= workspace.aiLimit) {
+ return null;
+ }
+
return {
userId: session.user.id,
workspaceId,
@@ -315,62 +321,6 @@ function formatPayout(payout: RewardPayout) {
return `${amount}, ${duration}`;
}
-function filterPayoutFixes({
- basePayout,
- modifiers,
- fixes,
-}: {
- basePayout: RewardPayout;
- modifiers: ReviewRewardTooltipModifier[];
- fixes: PayoutFix[];
-}): PayoutFix[] {
- const byTarget = new Map<string, PayoutFix>();
-
- for (const fix of fixes) {
- if (
- typeof fix.confidence !== "number" ||
- fix.confidence < TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR ||
- !fix.reason?.trim()
- ) {
- continue;
- }
-
- const current =
- fix.scope === "default"
- ? basePayout
- : modifiers[fix.modifierIndex ?? -1]?.payout;
-
- if (!current) continue;
- if (fix.scope === "group" && typeof fix.modifierIndex !== "number") {
- continue;
- }
-
- const nextDuration =
- fix.maxDuration === undefined ? current.maxDuration : fix.maxDuration;
- const amountChanges =
- typeof fix.amount === "number" && fix.amount !== current.amount;
- const durationChanges =
- fix.maxDuration !== undefined && nextDuration !== current.maxDuration;
-
- if (!amountChanges && !durationChanges) continue;
-
- const key =
- fix.scope === "default" ? "default" : `group:${fix.modifierIndex}`;
- const existing = byTarget.get(key);
-
- if (!existing || fix.confidence > existing.confidence) {
- byTarget.set(key, {
- ...fix,
- reason: fix.reason.trim(),
- amount: amountChanges ? fix.amount : null,
- maxDuration: durationChanges ? nextDuration : undefined,
- });
- }
- }
-
- return [...byTarget.values()];
-}
-
function formatCondition(
event: EventType,
condition: ReviewRewardTooltipModifier["conditions"][number],
@@ -408,5 +358,12 @@ function formatConditionValue(
return `$${value}`;
}
+ if (type === "date" && typeof value === "number" && Number.isFinite(value)) {
+ return formatDateTime(new Date(value), {
+ timeZone: "UTC",
+ timeZoneName: "short",
+ });
+ }
+
return String(value);
}
diff --git a/apps/web/lib/rewards/validate-tooltip-suggestion.ts b/apps/web/lib/rewards/validate-tooltip-suggestion.ts
index e68b90665f..793115ae9a 100644
--- a/apps/web/lib/rewards/validate-tooltip-suggestion.ts
+++ b/apps/web/lib/rewards/validate-tooltip-suggestion.ts
@@ -1,6 +1,8 @@
import {
TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR,
+ type PayoutFix,
type ReviewRewardTooltipModifier,
+ type RewardPayout,
type TooltipSuggestion,
type TooltipSuggestionPatch,
} from "@/lib/ai/review-reward-tooltip-schema";
@@ -81,7 +83,7 @@ export function applyTooltipSuggestion<
export type TooltipSuggestionField = "operator" | "value";
-export type TooltipSuggestionPage = {
+type TooltipSuggestionPage = {
suggestion: TooltipSuggestion;
field: TooltipSuggestionField;
};
@@ -177,6 +179,66 @@ export function filterValidatedTooltipSuggestions({
return [...byCondition.values()];
}
+export function filterPayoutFixes({
+ basePayout,
+ modifiers,
+ fixes,
+}: {
+ basePayout: RewardPayout;
+ modifiers: ReviewRewardTooltipModifier[];
+ fixes: PayoutFix[];
+}): PayoutFix[] {
+ const byTarget = new Map<string, PayoutFix>();
+
+ for (const fix of fixes) {
+ if (
+ typeof fix.confidence !== "number" ||
+ fix.confidence < TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR ||
+ !fix.reason?.trim()
+ ) {
+ continue;
+ }
+
+ const current =
+ fix.scope === "default"
+ ? basePayout
+ : modifiers[fix.modifierIndex ?? -1]?.payout;
+
+ if (!current) continue;
+ if (fix.scope === "group" && typeof fix.modifierIndex !== "number") {
+ continue;
+ }
+
+ // Amounts are in dollars; these mirror the save schema limits.
+ const maxAmount = current.type === "percentage" ? 100 : 999_999.99;
+ if (typeof fix.amount === "number" && fix.amount > maxAmount) continue;
+
+ const nextDuration =
+ fix.maxDuration === undefined ? current.maxDuration : fix.maxDuration;
+ const amountChanges =
+ typeof fix.amount === "number" && fix.amount !== current.amount;
+ const durationChanges =
+ fix.maxDuration !== undefined && nextDuration !== current.maxDuration;
+
+ if (!amountChanges && !durationChanges) continue;
+
+ const key =
+ fix.scope === "default" ? "default" : `group:${fix.modifierIndex}`;
+ const existing = byTarget.get(key);
+
+ if (!existing || fix.confidence > existing.confidence) {
+ byTarget.set(key, {
+ ...fix,
+ reason: fix.reason.trim(),
+ amount: amountChanges ? fix.amount : null,
+ maxDuration: durationChanges ? nextDuration : undefined,
+ });
+ }
+ }
+
+ return [...byTarget.values()];
+}
+
function isValidTooltipSuggestion({
event,
modifiers,
@@ -213,11 +275,18 @@ function isValidTooltipSuggestion({
}
const nextOperator = suggestion.suggested.operator ?? current.operator;
- const allowedOperators = getAllowedOperators({
- event,
- entity: current.entity,
- attribute: current.attribute,
- });
+ const isFixedOperator =
+ (current.entity === "customer" && current.attribute === "source") ||
+ (current.entity === "sale" && current.attribute === "type");
+ const allowedOperators: ConditionOperator[] = isFixedOperator
+ ? ["equals_to"]
+ : getConditionOperators(
+ getRewardConditionAttribute({
+ event,
+ entity: current.entity,
+ attribute: current.attribute,
+ })?.type ?? "string",
+ );
if (!allowedOperators.includes(nextOperator)) {
return false;
@@ -245,42 +314,16 @@ function isValidTooltipSuggestion({
);
}
-function getAllowedOperators({
- event,
- entity,
- attribute,
-}: {
- event: EventType;
- entity?: string;
- attribute?: string;
-}): ConditionOperator[] {
- if (
- (entity === "customer" && attribute === "source") ||
- (entity === "sale" && attribute === "type")
- ) {
- return ["equals_to"];
- }
-
- const attributeType =
- getRewardConditionAttribute({ event, entity, attribute })?.type ?? "string";
-
- if (attributeType === "metadata") {
- return [...METADATA_CONDITION_OPERATORS];
- }
-
+export function getConditionOperators(
+ attributeType: string,
+): ConditionOperator[] {
+ if (attributeType === "metadata") return METADATA_CONDITION_OPERATORS;
if (attributeType === "number" || attributeType === "currency") {
- return [...NUMBER_CONDITION_OPERATORS];
+ return NUMBER_CONDITION_OPERATORS;
}
-
- if (attributeType === "enum") {
- return [...ENUM_CONDITION_OPERATORS];
- }
-
- if (attributeType === "date") {
- return [...DATE_CONDITION_OPERATORS];
- }
-
- return [...STRING_CONDITION_OPERATORS];
+ if (attributeType === "enum") return ENUM_CONDITION_OPERATORS;
+ if (attributeType === "date") return DATE_CONDITION_OPERATORS;
+ return STRING_CONDITION_OPERATORS;
}
function isConditionValueFilled(value: unknown): boolean {
diff --git a/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts b/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
index 19bef35255..98c15eff06 100644
--- a/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
+++ b/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
@@ -1,13 +1,15 @@
-import type {
- ReviewRewardTooltipModifier,
- TooltipSuggestion,
+import {
+ reviewRewardTooltipInputSchema,
+ type PayoutFix,
+ type ReviewRewardTooltipModifier,
+ type RewardPayout,
+ type TooltipSuggestion,
} from "@/lib/ai/review-reward-tooltip-schema";
import {
- applyTooltipSuggestion,
+ filterPayoutFixes,
filterValidatedTooltipSuggestions,
getTooltipSuggestionPages,
isRewardConditionComplete,
- suggestionTouchesField,
} from "@/lib/rewards/validate-tooltip-suggestion";
import { describe, expect, test } from "vitest";
@@ -32,147 +34,95 @@ const minTwentySuggestion: TooltipSuggestion = {
confidence: 0.9,
reason:
'"Minimum $20 deposit" implies $20 qualifies, but "is greater than" excludes it.',
- suggested: {
- operator: "greater_than_or_equal" as const,
- },
+ suggested: { operator: "greater_than_or_equal" },
};
-function accepted(suggestion: TooltipSuggestion = minTwentySuggestion) {
- return filterValidatedTooltipSuggestions({
- event: "sale",
- modifiers: saleAmountModifiers,
- suggestions: [suggestion],
- });
-}
-
describe("isRewardConditionComplete", () => {
- test("requires entity, attribute, operator, and value", () => {
- expect(
- isRewardConditionComplete({
- event: "sale",
- condition: {
- entity: "sale",
- attribute: "amount",
- operator: "greater_than",
- },
- }),
- ).toBe(false);
-
- expect(
- isRewardConditionComplete({
- event: "sale",
- condition: {
- entity: "sale",
- attribute: "amount",
- operator: "greater_than",
- value: 20,
- },
- }),
- ).toBe(true);
- });
-
- test("requires a metadata field name", () => {
- expect(
- isRewardConditionComplete({
- event: "sale",
- condition: {
- entity: "sale",
- attribute: "metadata",
- operator: "equals_to",
- value: "enterprise",
- },
- }),
- ).toBe(false);
-
- expect(
- isRewardConditionComplete({
- event: "sale",
- condition: {
- entity: "sale",
- attribute: "metadata",
- operator: "equals_to",
- value: "enterprise",
- metadataField: "plan",
- },
- }),
- ).toBe(true);
- });
-
- test("rejects empty arrays and NaN", () => {
- expect(
- isRewardConditionComplete({
- event: "sale",
- condition: {
- entity: "customer",
- attribute: "country",
- operator: "in",
- value: [],
- },
- }),
- ).toBe(false);
-
- expect(
- isRewardConditionComplete({
- event: "sale",
- condition: {
- entity: "sale",
- attribute: "amount",
- operator: "greater_than",
- value: Number.NaN,
- },
- }),
- ).toBe(false);
+ test.each([
+ [{ entity: "sale", attribute: "amount", operator: "greater_than" }, false],
+ [
+ {
+ entity: "sale",
+ attribute: "amount",
+ operator: "greater_than",
+ value: 20,
+ },
+ true,
+ ],
+ [
+ {
+ entity: "sale",
+ attribute: "metadata",
+ operator: "equals_to",
+ value: "enterprise",
+ },
+ false,
+ ],
+ [
+ {
+ entity: "sale",
+ attribute: "metadata",
+ operator: "equals_to",
+ value: "enterprise",
+ metadataField: "plan",
+ },
+ true,
+ ],
+ [
+ { entity: "customer", attribute: "country", operator: "in", value: [] },
+ false,
+ ],
+ [
+ {
+ entity: "sale",
+ attribute: "amount",
+ operator: "greater_than",
+ value: Number.NaN,
+ },
+ false,
+ ],
+ ])("%o -> %s", (condition, expected) => {
+ expect(isRewardConditionComplete({ event: "sale", condition })).toBe(
+ expected,
+ );
});
});
describe("filterValidatedTooltipSuggestions", () => {
- test("accepts a high-confidence operator fix on an existing condition", () => {
- expect(accepted()).toEqual([minTwentySuggestion]);
- });
-
- test("rejects confidence below the 0.5 floor", () => {
- expect(accepted({ ...minTwentySuggestion, confidence: 0.49 })).toEqual([]);
- });
-
- test("rejects unknown condition indexes", () => {
- expect(accepted({ ...minTwentySuggestion, conditionIndex: 1 })).toEqual([]);
- });
-
- test("rejects operators that are not allowed for the attribute", () => {
- expect(
- accepted({
- ...minTwentySuggestion,
- suggested: { operator: "contains" },
- }),
- ).toEqual([]);
- });
+ const filter = (
+ suggestions: TooltipSuggestion[],
+ modifiers = saleAmountModifiers,
+ ) =>
+ filterValidatedTooltipSuggestions({
+ event: "sale",
+ modifiers,
+ suggestions,
+ });
- test("rejects a no-op that matches the current condition", () => {
- expect(
- accepted({
- ...minTwentySuggestion,
- suggested: { operator: "greater_than" },
- }),
- ).toEqual([]);
+ test("accepts a high-confidence fix on an existing condition", () => {
+ expect(filter([minTwentySuggestion])).toEqual([minTwentySuggestion]);
});
- test("rejects a value whose shape does not match the operator", () => {
- expect(
- accepted({
- ...minTwentySuggestion,
- suggested: { operator: "in", value: 20 },
- }),
- ).toEqual([]);
+ test.each<[string, Partial<TooltipSuggestion>]>([
+ ["low confidence", { confidence: 0.49 }],
+ ["unknown condition index", { conditionIndex: 1 }],
+ [
+ "operator not allowed for the attribute",
+ { suggested: { operator: "contains" } },
+ ],
+ ["no-op", { suggested: { operator: "greater_than" } }],
+ ["value shape mismatch", { suggested: { operator: "in", value: 20 } }],
+ ])("rejects %s", (_, override) => {
+ expect(filter([{ ...minTwentySuggestion, ...override }])).toEqual([]);
});
- test("rejects customer.source operator changes", () => {
+ test("rejects operator changes on customer.source", () => {
expect(
- filterValidatedTooltipSuggestions({
- event: "sale",
- modifiers: [
+ filter(
+ [{ ...minTwentySuggestion, suggested: { operator: "not_equals" } }],
+ [
{
- operator: "AND",
- payout: { type: "flat", amount: 10, maxDuration: 0 },
+ ...saleAmountModifiers[0],
conditions: [
{
entity: "customer",
@@ -183,101 +133,94 @@ describe("filterValidatedTooltipSuggestions", () => {
],
},
],
- suggestions: [
- {
- ...minTwentySuggestion,
- suggested: { operator: "not_equals" },
- },
- ],
- }),
+ ),
).toEqual([]);
});
test("keeps the higher-confidence suggestion per condition", () => {
- const result = filterValidatedTooltipSuggestions({
- event: "sale",
- modifiers: saleAmountModifiers,
- suggestions: [
- { ...minTwentySuggestion, confidence: 0.6 },
- {
- ...minTwentySuggestion,
- confidence: 0.95,
- suggested: { operator: "greater_than_or_equal", value: 20 },
- },
- { ...minTwentySuggestion, confidence: 0.2 },
- ],
- });
+ const result = filter([
+ { ...minTwentySuggestion, confidence: 0.6 },
+ {
+ ...minTwentySuggestion,
+ confidence: 0.95,
+ suggested: { operator: "greater_than_or_equal", value: 25 },
+ },
+ ]);
expect(result).toHaveLength(1);
expect(result[0].confidence).toBe(0.95);
- expect(result[0].suggested.value).toBe(20);
- });
-});
-
-describe("applyTooltipSuggestion", () => {
- test("writes only the patched fields", () => {
- expect(
- applyTooltipSuggestion(saleAmountModifiers[0].conditions[0], {
- operator: "greater_than_or_equal",
- }),
- ).toEqual({
- entity: "sale",
- attribute: "amount",
- operator: "greater_than_or_equal",
- value: 20,
- });
});
});
describe("getTooltipSuggestionPages", () => {
- test("splits one suggestion that changes operator and value into two pages", () => {
- const pages = getTooltipSuggestionPages({
- modifiers: saleAmountModifiers,
- suggestions: [
- {
- ...minTwentySuggestion,
- suggested: { operator: "greater_than_or_equal", value: 25 },
- },
- ],
- });
+ test("creates one page per changed field", () => {
+ const pages = (suggested: TooltipSuggestion["suggested"]) =>
+ getTooltipSuggestionPages({
+ modifiers: saleAmountModifiers,
+ suggestions: [{ ...minTwentySuggestion, suggested }],
+ }).map((page) => page.field);
- expect(pages.map((page) => page.field)).toEqual(["operator", "value"]);
+ expect(pages({ operator: "greater_than_or_equal" })).toEqual(["operator"]);
+ expect(pages({ operator: "greater_than_or_equal", value: 25 })).toEqual([
+ "operator",
+ "value",
+ ]);
});
+});
- test("keeps one page when only the operator changes", () => {
+describe("filterPayoutFixes", () => {
+ const flatBase: RewardPayout = { type: "flat", amount: 10, maxDuration: 0 };
+ const percentageGroup: ReviewRewardTooltipModifier[] = [
+ {
+ ...saleAmountModifiers[0],
+ payout: { type: "percentage", amount: 20, maxDuration: null },
+ },
+ ];
+ const fix: PayoutFix = {
+ scope: "default",
+ amount: 300,
+ confidence: 0.9,
+ reason: 'Copy says "earn $300" but the payout is $10.',
+ };
+
+ test("keeps a valid fix", () => {
expect(
- getTooltipSuggestionPages({
- modifiers: saleAmountModifiers,
- suggestions: [minTwentySuggestion],
- }),
+ filterPayoutFixes({ basePayout: flatBase, modifiers: [], fixes: [fix] }),
).toHaveLength(1);
});
-});
-
-describe("suggestionTouchesField", () => {
- test("detects operator vs value changes", () => {
- const current = saleAmountModifiers[0].conditions[0];
+ test.each<[string, PayoutFix]>([
+ ["a no-op", { ...fix, amount: 10 }],
+ ["a flat amount over the save limit", { ...fix, amount: 1_000_000 }],
+ [
+ "a percentage over 100",
+ { ...fix, scope: "group", modifierIndex: 0, amount: 150 },
+ ],
+ ])("drops %s", (_, payoutFix) => {
expect(
- suggestionTouchesField({
- field: "operator",
- current,
- suggested: { operator: "greater_than_or_equal" },
- }),
- ).toBe(true);
- expect(
- suggestionTouchesField({
- field: "value",
- current,
- suggested: { operator: "greater_than_or_equal" },
- }),
- ).toBe(false);
- expect(
- suggestionTouchesField({
- field: "value",
- current,
- suggested: { value: 25 },
+ filterPayoutFixes({
+ basePayout: flatBase,
+ modifiers: percentageGroup,
+ fixes: [payoutFix],
}),
- ).toBe(true);
+ ).toEqual([]);
});
});
+
+test("reviewRewardTooltipInputSchema rejects more than 20 modifiers", () => {
+ const input = {
+ workspaceId: "ws_123",
+ event: "sale",
+ tooltip: "Earn $10 on every sale over $20",
+ basePayout: { type: "flat", amount: 10, maxDuration: 0 },
+ modifiers: saleAmountModifiers,
+ };
+
+ expect(reviewRewardTooltipInputSchema.safeParse(input).success).toBe(true);
+ expect(
+ reviewRewardTooltipInputSchema.safeParse({
+ ...input,
+ modifiers: Array(21).fill(saleAmountModifiers[0]),
+ }).success,
+ ).toBe(false);
+});
diff --git a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
index a0a298047d..370b207157 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -898,37 +898,26 @@ function RewardSheetContent({
/>
</InlineBadgePopover>{" "}
with the tooltip{" "}
- {consistency.status === "reviewing" ||
- consistency.note ||
- (consistency.payoutFixes?.length ?? 0) > 0 ? (
- <ReviewingSuggestedFixBadge
- text={
- tooltipDescription || "Reward 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,
+ })
}
- />
- ) : (
- <InlineBadgePopover
- text={
- tooltipDescription || "Reward tooltip"
+ className="sm:w-80"
+ maxLength={
+ REWARD_TOOLTIP_DESCRIPTION_MAX_LENGTH
}
- 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>
- )}
+ />
+ </InlineBadgePopover>{" "}
+ <ReviewingSuggestedFixBadge text="Suggested fix" />
</span>
<Button
variant="outline"
diff --git a/apps/web/ui/partners/rewards/rewards-logic.tsx b/apps/web/ui/partners/rewards/rewards-logic.tsx
index 6bc1da08c3..04ae18aa9c 100644
--- a/apps/web/ui/partners/rewards/rewards-logic.tsx
+++ b/apps/web/ui/partners/rewards/rewards-logic.tsx
@@ -4,6 +4,7 @@ import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { getCustomerSourceAvailability } from "@/lib/rewards/get-customer-source-availability";
import {
+ getConditionOperators,
isRewardConditionComplete,
suggestionTouchesField,
} from "@/lib/rewards/validate-tooltip-suggestion";
@@ -14,15 +15,11 @@ import { RECURRING_MAX_DURATIONS } from "@/lib/zod/schemas/misc";
import {
CONDITION_OPERATOR_LABELS,
CONDITION_OPERATORS,
- DATE_CONDITION_OPERATORS,
- ENUM_CONDITION_OPERATORS,
METADATA_CONDITION_OPERATORS,
METADATA_NUMBER_CONDITION_OPERATORS,
METADATA_TEXT_CONDITION_OPERATORS,
- NUMBER_CONDITION_OPERATORS,
REWARD_CONDITIONS,
RewardConditionEntityAttribute,
- STRING_CONDITION_OPERATORS,
} from "@/lib/zod/schemas/rewards";
import { CountryFlag } from "@/ui/shared/country-flag";
import { DurationPopoverContent } from "@/ui/shared/duration-popover-content";
@@ -476,16 +473,7 @@ function ConditionLogic({
const isSaleTypeCondition =
condition?.entity === "sale" && condition?.attribute === "type";
- const availableConditionOperators: (typeof CONDITION_OPERATORS)[number][] =
- attributeType === "metadata"
- ? METADATA_CONDITION_OPERATORS
- : ["number", "currency"].includes(attributeType)
- ? NUMBER_CONDITION_OPERATORS
- : attributeType === "enum"
- ? ENUM_CONDITION_OPERATORS
- : attributeType === "date"
- ? DATE_CONDITION_OPERATORS
- : STRING_CONDITION_OPERATORS;
+ const availableConditionOperators = getConditionOperators(attributeType);
useEffect(() => {
if (
diff --git a/apps/web/ui/partners/rewards/suggested-fix-popover.tsx b/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
index 4bd80c3e06..117fef87be 100644
--- a/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
+++ b/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
@@ -173,114 +173,66 @@ export function SuggestedFixBadge({
export function ReviewingSuggestedFixBadge({ text }: { text: string }) {
const consistency = useRewardTooltipConsistencyContext();
- const { isMobile } = useMediaQuery();
- const closeTimerRef = useRef<number | undefined>(undefined);
- const [open, setOpen] = useState(false);
- const reviewing = consistency?.status === "reviewing";
- const payoutFixes = reviewing ? [] : consistency?.payoutFixes ?? [];
- const note = reviewing || payoutFixes.length ? null : consistency?.note;
+ if (!consistency) return null;
- if (!consistency || (!reviewing && !note && !payoutFixes.length)) return null;
+ const { reviewing, payoutFixes, note, dismissNote, acceptPayouts } =
+ consistency;
- const cancelHide = () => {
- if (closeTimerRef.current) {
- window.clearTimeout(closeTimerRef.current);
- closeTimerRef.current = undefined;
- }
- };
-
- const scheduleHide = () => {
- cancelHide();
- closeTimerRef.current = window.setTimeout(() => {
- setOpen(false);
- }, 300);
- };
+ if (!reviewing && !note && !payoutFixes.length) return null;
return (
- <Popover
- openPopover={open}
- setOpenPopover={setOpen}
- align="start"
- sideOffset={8}
- onOpenAutoFocus={(event) => event.preventDefault()}
- popoverContentClassName={POPOVER_CONTENT_CLASS_NAME}
- content={
- <div onMouseEnter={cancelHide} onMouseLeave={scheduleHide}>
- <div className="flex items-center gap-1.5 border-b border-neutral-200 p-3 text-sm font-medium text-neutral-900">
- <Sparkle3 variant="fill" className="size-3.5" />
- Suggested fix
+ <HoverFixPopover text={text}>
+ {(close) =>
+ reviewing ? (
+ <div className="flex flex-col gap-3 p-3">
+ <div className="h-16 animate-pulse rounded-[10px] bg-neutral-100" />
+ <div className="h-3 w-4/5 animate-pulse rounded bg-neutral-200" />
+ <div className="h-3 w-2/3 animate-pulse rounded bg-neutral-200" />
</div>
- {reviewing ? (
+ ) : (
+ <>
<div className="flex flex-col gap-3 p-3">
- <div className="h-16 animate-pulse rounded-[10px] bg-neutral-100" />
- <div className="h-3 w-4/5 animate-pulse rounded bg-neutral-200" />
- <div className="h-3 w-2/3 animate-pulse rounded bg-neutral-200" />
+ {payoutFixes.length ? (
+ <PayoutFixPreview fixes={payoutFixes} />
+ ) : (
+ <p className="text-sm leading-relaxed text-neutral-600">
+ {note}
+ </p>
+ )}
</div>
- ) : (
- <>
- <div className="flex flex-col gap-3 p-3">
- {payoutFixes.length ? (
- <PayoutFixPreview fixes={payoutFixes} />
- ) : (
- <p className="text-sm leading-relaxed text-neutral-600">
- {note}
- </p>
- )}
- </div>
- <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-3 py-2">
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-3 py-2">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Discard"
+ className="h-7 w-fit rounded-lg px-3 py-2"
+ onClick={() => {
+ dismissNote();
+ close();
+ }}
+ />
+ {payoutFixes.length > 0 && (
<Button
type="button"
- variant="secondary"
- text="Discard"
+ variant="primary"
+ text={
+ payoutFixes.length > 1
+ ? "Accept all changes"
+ : "Accept change"
+ }
className="h-7 w-fit rounded-lg px-3 py-2"
onClick={() => {
- consistency.dismissNote();
- setOpen(false);
+ acceptPayouts();
+ close();
}}
/>
- {payoutFixes.length > 0 && (
- <Button
- type="button"
- variant="primary"
- text={
- payoutFixes.length > 1
- ? "Accept all changes"
- : "Accept change"
- }
- className="h-7 w-fit rounded-lg px-3 py-2"
- onClick={() => {
- consistency.acceptPayouts();
- setOpen(false);
- }}
- />
- )}
- </div>
- </>
- )}
- </div>
+ )}
+ </div>
+ </>
+ )
}
- >
- <button
- type="button"
- onMouseEnter={() => {
- if (isMobile) return;
- cancelHide();
- setOpen(true);
- }}
- onMouseLeave={() => {
- if (!isMobile) scheduleHide();
- }}
- onClick={() => {
- if (!isMobile) return;
- setOpen((current) => !current);
- }}
- className={SUGGESTED_FIX_BADGE_CLASS_NAME}
- >
- <Sparkle3 variant="fill" className="size-3 shrink-0 text-[#E17100]" />
- <span className="min-w-0 truncate">{text}</span>
- </button>
- </Popover>
+ </HoverFixPopover>
);
}
@@ -292,6 +244,40 @@ export function SuggestedFixNoticeBadge({
text: string;
message: string;
onDiscard: () => void;
+}) {
+ return (
+ <HoverFixPopover text={text}>
+ {(close) => (
+ <>
+ <div className="p-3">
+ <p className="text-sm leading-relaxed text-neutral-600">
+ {message}
+ </p>
+ </div>
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-3 py-2">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Discard"
+ className="h-7 w-fit rounded-lg px-3 py-2"
+ onClick={() => {
+ onDiscard();
+ close();
+ }}
+ />
+ </div>
+ </>
+ )}
+ </HoverFixPopover>
+ );
+}
+
+function HoverFixPopover({
+ text,
+ children,
+}: {
+ text: string;
+ children: (close: () => void) => ReactNode;
}) {
const { isMobile } = useMediaQuery();
const closeTimerRef = useRef<number | undefined>(undefined);
@@ -331,23 +317,7 @@ export function SuggestedFixNoticeBadge({
<Sparkle3 variant="fill" className="size-3.5" />
Suggested fix
</div>
- <div className="p-3">
- <p className="text-sm leading-relaxed text-neutral-600">
- {message}
- </p>
- </div>
- <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-3 py-2">
- <Button
- type="button"
- variant="secondary"
- text="Discard"
- className="h-7 w-fit rounded-lg px-3 py-2"
- onClick={() => {
- onDiscard();
- setOpen(false);
- }}
- />
- </div>
+ {children(() => setOpen(false))}
</div>
}
>
diff --git a/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts b/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
index bd7e9f9d1f..8bcb01ae47 100644
--- a/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
+++ b/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
@@ -1,9 +1,6 @@
"use client";
-import {
- AI_REWARD_EVENTS,
- type AIRewardEvent,
-} from "@/lib/ai/ai-reward-schema";
+import { AI_REWARD_EVENTS } from "@/lib/ai/ai-reward-schema";
import {
reviewRewardTooltipConsistency,
screenRewardTooltipContradiction,
@@ -20,7 +17,6 @@ import {
isRewardConditionComplete,
stripRewardTooltipMarkdown,
type TooltipSuggestionField,
- type TooltipSuggestionPage,
} from "@/lib/rewards/validate-tooltip-suggestion";
import { EventType } from "@prisma/client";
import {
@@ -31,23 +27,23 @@ import {
useMemo,
useRef,
useState,
- type MutableRefObject,
} from "react";
-const DEBOUNCE_MS = 200;
+const DEBOUNCE_MS = 700;
const HIDE_MS = 300;
-const REVIEW_CACHE_VERSION = 2;
-
-type TooltipReviewStatus = "idle" | "reviewing";
type ReviewCacheEntry = {
- v: typeof REVIEW_CACHE_VERSION;
- flagged: boolean;
suggestions: TooltipSuggestion[];
payoutFixes: PayoutFix[];
note: string | null;
};
+const EMPTY_REVIEW: ReviewCacheEntry = {
+ suggestions: [],
+ payoutFixes: [],
+ note: null,
+};
+
const reviewCache = new Map<string, ReviewCacheEntry>();
export function tooltipSuggestionPageKey({
@@ -62,42 +58,9 @@ export function tooltipSuggestionPageKey({
return `${modifierIndex}:${conditionIndex}:${field}`;
}
-type RewardTooltipConsistencyValue = {
- status: TooltipReviewStatus;
- suggestions: TooltipSuggestion[];
- pages: TooltipSuggestionPage[];
- activeIndex: number;
- open: boolean;
- activeAnchorRef: MutableRefObject<HTMLElement | null>;
- registerBadge: (key: string, element: HTMLElement | null) => void;
- popoverContentRef: MutableRefObject<HTMLDivElement | null>;
- showPage: (index: number) => void;
- focusPopoverContent: () => void;
- handlePopoverCloseAutoFocus: (event: Event) => void;
- scheduleHide: () => void;
- cancelHide: () => void;
- hide: () => void;
- getSuggestion: (
- modifierIndex: number,
- conditionIndex: number,
- ) => TooltipSuggestion | undefined;
- getPageIndex: (
- modifierIndex: number,
- conditionIndex: number,
- field: TooltipSuggestionField,
- ) => number;
- accept: (suggestion: TooltipSuggestion) => void;
- acceptAll: () => void;
- dismiss: (suggestion: TooltipSuggestion) => void;
- dismissAll: () => void;
- note: string | null;
- payoutFixes: PayoutFix[];
- acceptPayouts: () => void;
- dismissNote: () => void;
-};
-
-export const RewardTooltipConsistencyContext =
- createContext<RewardTooltipConsistencyValue | null>(null);
+export const RewardTooltipConsistencyContext = createContext<ReturnType<
+ typeof useRewardTooltipConsistency
+> | null>(null);
export function useRewardTooltipConsistencyContext() {
return useContext(RewardTooltipConsistencyContext);
@@ -139,11 +102,11 @@ export function useRewardTooltipConsistency({
} | null> | null;
onApply?: (suggestion: TooltipSuggestion) => void;
onApplyPayout?: (fixes: PayoutFix[]) => void;
-}): RewardTooltipConsistencyValue {
+}) {
const [suggestions, setSuggestions] = useState<TooltipSuggestion[]>([]);
const [payoutFixes, setPayoutFixes] = useState<PayoutFix[]>([]);
const [note, setNote] = useState<string | null>(null);
- const [status, setStatus] = useState<TooltipReviewStatus>("idle");
+ const [reviewing, setReviewing] = useState(false);
const [activeIndex, setActiveIndex] = useState(0);
const [open, setOpen] = useState(false);
const [dismissedKeys, setDismissedKeys] = useState<string[]>([]);
@@ -155,173 +118,72 @@ export function useRewardTooltipConsistency({
const returnFocusOnCloseRef = useRef(false);
const tooltip = stripRewardTooltipMarkdown(tooltipDescription ?? "");
- const serializedReward = useMemo(
- () =>
- serializeRewardForReview({
- event,
- description,
- baseReward,
- modifiers,
- }),
- [baseReward, description, event, modifiers],
- );
+ const serializedReward = serializeRewardForReview({
+ event,
+ description,
+ baseReward,
+ modifiers,
+ });
const serializedModifiers = serializedReward?.modifiers ?? null;
-
- const cacheKey = useMemo(() => {
- if (
- !workspaceId ||
- !isAiRewardEvent(event) ||
- !tooltip ||
- !serializedReward
- ) {
- return null;
- }
-
- return JSON.stringify({
- event,
- tooltip,
- reward: serializedReward,
- });
- }, [event, serializedReward, tooltip, workspaceId]);
+ const cacheKey =
+ workspaceId && tooltip && serializedReward
+ ? JSON.stringify({ event, tooltip, reward: serializedReward })
+ : null;
const serializedRewardRef = useRef(serializedReward);
serializedRewardRef.current = serializedReward;
useEffect(() => {
const requestId = ++requestIdRef.current;
-
const reward = serializedRewardRef.current;
- if (!cacheKey || !workspaceId || !isAiRewardEvent(event) || !reward) {
- setSuggestions([]);
- setPayoutFixes([]);
- setNote(null);
- setStatus("idle");
- setActiveIndex(0);
- return;
- }
-
- const cached = reviewCache.get(cacheKey);
- if (cached?.v === REVIEW_CACHE_VERSION) {
- setSuggestions(cached.suggestions);
- setPayoutFixes(cached.payoutFixes);
- setNote(cached.note);
- setStatus("idle");
+ const show = (entry: ReviewCacheEntry) => {
+ setSuggestions(entry.suggestions);
+ setPayoutFixes(entry.payoutFixes);
+ setNote(entry.note);
+ setReviewing(false);
setActiveIndex(0);
- return;
- }
+ };
- setSuggestions([]);
- setPayoutFixes([]);
- setNote(null);
- setStatus("idle");
- setActiveIndex(0);
- const timeout = window.setTimeout(async () => {
- let flagged: boolean | null = null;
-
- try {
- const screen = await screenRewardTooltipContradiction({
- workspaceId,
- event,
- tooltip,
- description: reward.description,
- basePayout: reward.basePayout,
- modifiers: reward.modifiers,
- });
+ const cached = cacheKey ? reviewCache.get(cacheKey) : undefined;
+ show(cached ?? EMPTY_REVIEW);
- if (requestId !== requestIdRef.current) {
- return;
- }
+ if (!cacheKey || !reward || cached) return;
- flagged = screen.flagged;
- } catch {
- if (requestId !== requestIdRef.current) {
- return;
- }
+ const input = { workspaceId, event, tooltip, ...reward };
+ const timeout = window.setTimeout(async () => {
+ const { flagged } = await screenRewardTooltipContradiction(input).catch(
+ () => ({ flagged: null }),
+ );
- flagged = null;
- }
+ if (requestId !== requestIdRef.current || flagged === null) return;
- if (flagged === false) {
- reviewCache.set(cacheKey, {
- v: REVIEW_CACHE_VERSION,
- flagged: false,
- suggestions: [],
- payoutFixes: [],
- note: null,
- });
- setSuggestions([]);
- setPayoutFixes([]);
- setNote(null);
- setStatus("idle");
- setActiveIndex(0);
+ if (!flagged) {
+ reviewCache.set(cacheKey, EMPTY_REVIEW);
return;
}
- if (flagged === true) {
- setStatus("reviewing");
- }
+ setReviewing(true);
- try {
- const result = await reviewRewardTooltipConsistency({
- workspaceId,
- event,
- tooltip,
- description: reward.description,
- basePayout: reward.basePayout,
- modifiers: reward.modifiers,
- });
+ const result = await reviewRewardTooltipConsistency(input).catch(
+ () => null,
+ );
- if (requestId !== requestIdRef.current) {
- return;
- }
+ if (requestId !== requestIdRef.current) return;
- const next = result.suggestions ?? [];
- const nextPayoutFixes = result.payoutFixes ?? [];
- const nextNote = noteForFlaggedReward({
- flagged,
- suggestions: next,
- payoutFixes: nextPayoutFixes,
- note: result.note,
- });
- reviewCache.set(cacheKey, {
- v: REVIEW_CACHE_VERSION,
- flagged: flagged === true,
- suggestions: next,
- payoutFixes: nextPayoutFixes,
- note: nextNote,
- });
- setSuggestions(next);
- setPayoutFixes(nextPayoutFixes);
- setNote(nextNote);
- setStatus("idle");
- setActiveIndex(0);
- } catch {
- if (requestId !== requestIdRef.current) {
- return;
- }
+ const suggestions = result?.suggestions ?? [];
+ const payoutFixes = result?.payoutFixes ?? [];
+ const entry = {
+ suggestions,
+ payoutFixes,
+ note:
+ suggestions.length || payoutFixes.length
+ ? null
+ : result?.note || "This copy doesn't match the reward payout.",
+ };
- const nextNote = noteForFlaggedReward({
- flagged,
- suggestions: [],
- payoutFixes: [],
- note: null,
- });
- if (nextNote) {
- reviewCache.set(cacheKey, {
- v: REVIEW_CACHE_VERSION,
- flagged: flagged === true,
- suggestions: [],
- payoutFixes: [],
- note: nextNote,
- });
- }
- setSuggestions([]);
- setPayoutFixes([]);
- setNote(nextNote);
- setStatus("idle");
- setActiveIndex(0);
- }
+ reviewCache.set(cacheKey, entry);
+ show(entry);
}, DEBOUNCE_MS);
return () => {
@@ -475,13 +337,32 @@ export function useRewardTooltipConsistency({
const key = dismissalKey(suggestion, current);
setDismissedKeys((keys) => (keys.includes(key) ? keys : [...keys, key]));
+
+ const cached = cacheKey ? reviewCache.get(cacheKey) : undefined;
+ if (cacheKey && cached) {
+ reviewCache.set(cacheKey, {
+ ...cached,
+ suggestions: cached.suggestions.filter(
+ (entry) =>
+ entry.modifierIndex !== suggestion.modifierIndex ||
+ entry.conditionIndex !== suggestion.conditionIndex,
+ ),
+ });
+ }
+
+ hide();
},
- [serializedModifiers],
+ [cacheKey, hide, serializedModifiers],
);
const dismissAll = useCallback(() => {
if (!serializedModifiers) return;
+ const cached = cacheKey ? reviewCache.get(cacheKey) : undefined;
+ if (cacheKey && cached) {
+ reviewCache.set(cacheKey, { ...cached, suggestions: [] });
+ }
+
setDismissedKeys((keys) => {
const next = new Set(keys);
@@ -498,35 +379,22 @@ export function useRewardTooltipConsistency({
return [...next];
});
- }, [serializedModifiers, suggestions]);
+
+ hide();
+ }, [cacheKey, hide, serializedModifiers, suggestions]);
const accept = useCallback(
(suggestion: TooltipSuggestion) => {
onApply?.(suggestion);
dismiss(suggestion);
- hide();
},
- [dismiss, hide, onApply],
+ [dismiss, onApply],
);
const acceptAll = useCallback(() => {
visibleSuggestions.forEach((suggestion) => onApply?.(suggestion));
dismissAll();
- hide();
- }, [dismissAll, hide, onApply, visibleSuggestions]);
-
- const dismissAndHide = useCallback(
- (suggestion: TooltipSuggestion) => {
- dismiss(suggestion);
- hide();
- },
- [dismiss, hide],
- );
-
- const dismissAllAndHide = useCallback(() => {
- dismissAll();
- hide();
- }, [dismissAll, hide]);
+ }, [dismissAll, onApply, visibleSuggestions]);
const dismissNote = useCallback(() => {
setNote(null);
@@ -550,8 +418,7 @@ export function useRewardTooltipConsistency({
}, [dismissNote, onApplyPayout, payoutFixes]);
return {
- status,
- suggestions: visibleSuggestions,
+ reviewing,
pages,
activeIndex,
open,
@@ -568,8 +435,8 @@ export function useRewardTooltipConsistency({
getPageIndex,
accept,
acceptAll,
- dismiss: dismissAndHide,
- dismissAll: dismissAllAndHide,
+ dismiss,
+ dismissAll,
note,
payoutFixes,
acceptPayouts,
@@ -577,30 +444,6 @@ export function useRewardTooltipConsistency({
};
}
-function isAiRewardEvent(event: EventType): event is AIRewardEvent {
- return (AI_REWARD_EVENTS as readonly string[]).includes(event);
-}
-
-function noteForFlaggedReward({
- flagged,
- suggestions,
- payoutFixes,
- note,
-}: {
- flagged: boolean | null;
- suggestions: TooltipSuggestion[];
- payoutFixes: PayoutFix[];
- note?: string | null;
-}) {
- if (suggestions.length || payoutFixes.length) return null;
-
- const trimmed = note?.trim();
- if (trimmed) return trimmed;
- if (flagged === true) return "This copy doesn't match the reward payout.";
-
- return null;
-}
-
function dismissalKey(
suggestion: TooltipSuggestion,
current: { operator: string; value: unknown },
@@ -651,7 +494,7 @@ function serializeRewardForReview({
if (baseReward?.type !== "flat" && baseReward?.type !== "percentage") {
return null;
}
- if (!isAiRewardEvent(event)) return null;
+ if (!(AI_REWARD_EVENTS as readonly string[]).includes(event)) return null;
const reviewModifiers = modifiers ?? [];
if (
!reviewModifiers.every(