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.

wip - initial structure

Pedro Ladeirac577245865b4
diff --git a/apps/web/lib/ai/review-reward-tooltip-schema.ts b/apps/web/lib/ai/review-reward-tooltip-schema.ts
new file mode 100644
index 0000000000..616201c573
--- /dev/null
+++ b/apps/web/lib/ai/review-reward-tooltip-schema.ts
@@ -0,0 +1,87 @@
+import { AI_REWARD_EVENTS } from "@/lib/ai/ai-reward-schema";
+import { CONDITION_OPERATORS } from "@/lib/zod/schemas/rewards";
+import * as z from "zod/v4";
+
+export const TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR = 0.5;
+
+const tooltipSuggestionValueSchema = z.union([
+ z.string(),
+ z.number(),
+ z.array(z.string()),
+ z.array(z.number()),
+]);
+
+const tooltipSuggestionPatchSchema = z.object({
+ operator: z
+ .enum(CONDITION_OPERATORS)
+ .optional()
+ .describe("Replacement operator. Omit to keep the current operator."),
+ value: tooltipSuggestionValueSchema
+ .optional()
+ .describe("Replacement value. Omit to keep the current value."),
+});
+
+const tooltipSuggestionSchema = z.object({
+ modifierIndex: z
+ .number()
+ .int()
+ .nonnegative()
+ .describe("Index of the existing modifier group (0-based)."),
+ conditionIndex: z
+ .number()
+ .int()
+ .nonnegative()
+ .describe("Index of the existing condition within that group (0-based)."),
+ confidence: z
+ .number()
+ .min(0)
+ .max(1)
+ .describe(
+ "0–1 confidence that this condition contradicts the tooltip. Use below 0.5 when the reading is ambiguous.",
+ ),
+ reason: z
+ .string()
+ .min(1)
+ .max(200)
+ .describe("One short sentence explaining the contradiction."),
+ suggested: tooltipSuggestionPatchSchema.describe(
+ "Operator and/or value to write back. Never change entity or attribute.",
+ ),
+});
+
+export const reviewRewardTooltipOutputSchema = z.object({
+ suggestions: z
+ .array(tooltipSuggestionSchema)
+ .describe(
+ "Contradictions on existing conditions. Empty if the tooltip and conditions agree, or if you are unsure.",
+ ),
+});
+
+const reviewRewardTooltipConditionSchema = z.object({
+ entity: z.string(),
+ attribute: z.string(),
+ operator: z.enum(CONDITION_OPERATORS),
+ value: tooltipSuggestionValueSchema,
+ label: z.string().nullish(),
+ metadataField: z.string().optional(),
+});
+
+const reviewRewardTooltipModifierSchema = z.object({
+ operator: z.enum(["AND", "OR"]).default("AND"),
+ conditions: z.array(reviewRewardTooltipConditionSchema).min(1),
+});
+
+export const reviewRewardTooltipInputSchema = z.object({
+ workspaceId: z.string(),
+ event: z.enum(AI_REWARD_EVENTS),
+ tooltip: z.string().min(1).max(4000),
+ modifiers: z.array(reviewRewardTooltipModifierSchema).min(1),
+});
+
+export type TooltipSuggestion = z.infer<typeof tooltipSuggestionSchema>;
+export type TooltipSuggestionPatch = z.infer<
+ typeof tooltipSuggestionPatchSchema
+>;
+export type ReviewRewardTooltipModifier = z.infer<
+ typeof reviewRewardTooltipModifierSchema
+>;
diff --git a/apps/web/lib/ai/review-reward-tooltip.ts b/apps/web/lib/ai/review-reward-tooltip.ts
new file mode 100644
index 0000000000..49ab8fd56e
--- /dev/null
+++ b/apps/web/lib/ai/review-reward-tooltip.ts
@@ -0,0 +1,157 @@
+"use server";
+
+import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";
+import { getSession } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import {
+ filterValidatedTooltipSuggestions,
+ stripRewardTooltipMarkdown,
+} from "@/lib/rewards/validate-tooltip-suggestion";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
+import { CONDITION_OPERATOR_LABELS } from "@/lib/zod/schemas/rewards";
+import { anthropic } from "@ai-sdk/anthropic";
+import { generateText, Output } from "ai";
+import { throwIfNoPermission } from "../actions/throw-if-no-permission";
+import {
+ reviewRewardTooltipInputSchema,
+ reviewRewardTooltipOutputSchema,
+ type ReviewRewardTooltipModifier,
+ type TooltipSuggestion,
+} from "./review-reward-tooltip-schema";
+
+export async function reviewRewardTooltipConsistency(
+ input: unknown,
+): Promise<{ suggestions: TooltipSuggestion[] }> {
+ try {
+ const parsedInput = reviewRewardTooltipInputSchema.safeParse(input);
+ if (!parsedInput.success) {
+ return { suggestions: [] };
+ }
+
+ const session = await getSession();
+ if (!session?.user.id) {
+ return { suggestions: [] };
+ }
+
+ const workspaceId = normalizeWorkspaceId(parsedInput.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) {
+ return { suggestions: [] };
+ }
+
+ throwIfNoPermission({
+ role: workspace.users[0].role,
+ requiredRoles: ["owner", "member"],
+ });
+
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.aiRewardTooltipReview,
+ identifier: [session.user.id, workspaceId],
+ });
+
+ const tooltip = stripRewardTooltipMarkdown(parsedInput.data.tooltip);
+ if (!tooltip) {
+ return { suggestions: [] };
+ }
+
+ const { event, modifiers } = parsedInput.data;
+
+ const { output } = await generateText({
+ model: anthropic("claude-sonnet-4-6"),
+ output: Output.object({
+ schema: reviewRewardTooltipOutputSchema,
+ }),
+ system: buildSystemPrompt(event),
+ prompt: buildUserPrompt({ tooltip, modifiers }),
+ temperature: 0,
+ maxOutputTokens: 1500,
+ });
+
+ const parsedOutput = reviewRewardTooltipOutputSchema.safeParse(output);
+ if (!parsedOutput.success) {
+ return { suggestions: [] };
+ }
+
+ return {
+ suggestions: filterValidatedTooltipSuggestions({
+ event,
+ modifiers,
+ suggestions: parsedOutput.data.suggestions,
+ }),
+ };
+ } catch (error) {
+ console.error("[reviewRewardTooltipConsistency]", error);
+ return { suggestions: [] };
+ }
+}
+
+function buildSystemPrompt(event: string) {
+ return `You review whether partner-facing reward tooltip copy contradicts the structured reward conditions.
+
+Event type: ${event}
+
+Rules:
+- Compare meaning, not wording. The tooltip is marketing copy; the conditions are the eligibility rules.
+- Only flag an EXISTING condition that a partner who only read the tooltip would find surprising.
+- Do not flag extra conditions the tooltip never mentioned.
+- Do not invent new condition rows. Do not change entity or attribute.
+- A suggestion may change operator and/or value only.
+- If you are not sure, return an empty suggestions array. Never guess.
+- confidence is 0–1. Use below 0.5 when the reading is ambiguous or only loosely implied.
+- reason must be one short sentence.
+
+Examples of contradictions:
+- Tooltip says "minimum $20" / "at least $20" but the condition is greater_than 20 (excludes $20).
+- Tooltip says "more than $20" / "over $20" but the condition is greater_than_or_equal 20.
+
+Not contradictions:
+- Tooltip is shorter than the config or omits extra filters (country, product, metadata).
+- Informal wording that does not clearly specify a different operator or threshold.`;
+}
+
+function buildUserPrompt({
+ tooltip,
+ modifiers,
+}: {
+ tooltip: string;
+ modifiers: ReviewRewardTooltipModifier[];
+}) {
+ const serialized = modifiers
+ .map((modifier, modifierIndex) => {
+ const conditions = modifier.conditions
+ .map((condition, conditionIndex) => {
+ const operatorLabel =
+ CONDITION_OPERATOR_LABELS[condition.operator] ?? condition.operator;
+ const value = Array.isArray(condition.value)
+ ? condition.value.join(", ")
+ : String(condition.value);
+ const field = condition.metadataField
+ ? `${condition.entity}.${condition.attribute}.${condition.metadataField}`
+ : `${condition.entity}.${condition.attribute}`;
+
+ return ` [${modifierIndex}][${conditionIndex}] ${field} ${condition.operator} (${operatorLabel}) ${value}`;
+ })
+ .join("\n");
+
+ return `Group ${modifierIndex} (${modifier.operator}):\n${conditions}`;
+ })
+ .join("\n");
+
+ return `Tooltip:
+"""
+${tooltip}
+"""
+
+Conditions:
+${serialized}`;
+}
diff --git a/apps/web/lib/rewards/validate-tooltip-suggestion.ts b/apps/web/lib/rewards/validate-tooltip-suggestion.ts
new file mode 100644
index 0000000000..fbc1b67c74
--- /dev/null
+++ b/apps/web/lib/rewards/validate-tooltip-suggestion.ts
@@ -0,0 +1,307 @@
+import {
+ TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR,
+ type ReviewRewardTooltipModifier,
+ type TooltipSuggestion,
+ type TooltipSuggestionPatch,
+} from "@/lib/ai/review-reward-tooltip-schema";
+import {
+ CONDITION_OPERATORS,
+ DATE_CONDITION_OPERATORS,
+ ENUM_CONDITION_OPERATORS,
+ METADATA_CONDITION_OPERATORS,
+ METADATA_NUMBER_CONDITION_OPERATORS,
+ NUMBER_CONDITION_OPERATORS,
+ REWARD_CONDITIONS,
+ STRING_CONDITION_OPERATORS,
+ type RewardConditionEntityAttribute,
+} from "@/lib/zod/schemas/rewards";
+import { EventType } from "@prisma/client";
+
+type ConditionOperator = (typeof CONDITION_OPERATORS)[number];
+
+export function getRewardConditionAttribute({
+ event,
+ entity,
+ attribute,
+}: {
+ event: EventType;
+ entity?: string;
+ attribute?: string;
+}): RewardConditionEntityAttribute | undefined {
+ if (!entity || !attribute) return undefined;
+
+ return REWARD_CONDITIONS[event].entities
+ .find((entry) => entry.id === entity)
+ ?.attributes.find((entry) => entry.id === attribute);
+}
+
+export function isRewardConditionComplete({
+ event,
+ condition,
+}: {
+ event: EventType;
+ condition?: {
+ entity?: string;
+ attribute?: string;
+ operator?: string;
+ value?: unknown;
+ metadataField?: string;
+ } | null;
+}): boolean {
+ if (
+ !condition?.entity ||
+ !condition.attribute ||
+ !condition.operator ||
+ !getRewardConditionAttribute({
+ event,
+ entity: condition.entity,
+ attribute: condition.attribute,
+ })
+ ) {
+ return false;
+ }
+
+ if (condition.attribute === "metadata" && !condition.metadataField?.trim()) {
+ return false;
+ }
+
+ return isConditionValueFilled(condition.value);
+}
+
+export function applyTooltipSuggestion<
+ T extends { operator?: ConditionOperator; value?: unknown },
+>(condition: T, suggested: TooltipSuggestionPatch): T {
+ return {
+ ...condition,
+ ...(suggested.operator ? { operator: suggested.operator } : {}),
+ ...(suggested.value !== undefined ? { value: suggested.value } : {}),
+ };
+}
+
+export function suggestionTouchesField({
+ field,
+ current,
+ suggested,
+}: {
+ field: "operator" | "value";
+ current: { operator?: ConditionOperator; value?: unknown };
+ suggested: TooltipSuggestionPatch;
+}): boolean {
+ if (field === "operator") {
+ return (
+ suggested.operator != null && suggested.operator !== current.operator
+ );
+ }
+
+ return (
+ suggested.value !== undefined &&
+ !valuesEqual(suggested.value, current.value)
+ );
+}
+
+export function filterValidatedTooltipSuggestions({
+ event,
+ modifiers,
+ suggestions,
+}: {
+ event: EventType;
+ modifiers: ReviewRewardTooltipModifier[];
+ suggestions: TooltipSuggestion[];
+}): TooltipSuggestion[] {
+ const byCondition = new Map<string, TooltipSuggestion>();
+
+ for (const suggestion of suggestions) {
+ if (!isValidTooltipSuggestion({ event, modifiers, suggestion })) {
+ continue;
+ }
+
+ const key = `${suggestion.modifierIndex}:${suggestion.conditionIndex}`;
+ const existing = byCondition.get(key);
+
+ if (!existing || suggestion.confidence > existing.confidence) {
+ byCondition.set(key, suggestion);
+ }
+ }
+
+ return [...byCondition.values()];
+}
+
+function isValidTooltipSuggestion({
+ event,
+ modifiers,
+ suggestion,
+}: {
+ event: EventType;
+ modifiers: ReviewRewardTooltipModifier[];
+ suggestion: TooltipSuggestion;
+}): boolean {
+ if (
+ typeof suggestion.confidence !== "number" ||
+ Number.isNaN(suggestion.confidence) ||
+ suggestion.confidence < TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR
+ ) {
+ return false;
+ }
+
+ if (!suggestion.reason?.trim()) {
+ return false;
+ }
+
+ if (
+ suggestion.suggested.operator == null &&
+ suggestion.suggested.value === undefined
+ ) {
+ return false;
+ }
+
+ const current =
+ modifiers[suggestion.modifierIndex]?.conditions[suggestion.conditionIndex];
+
+ if (!current) {
+ return false;
+ }
+
+ const nextOperator = suggestion.suggested.operator ?? current.operator;
+ const allowedOperators = getAllowedOperators({
+ event,
+ entity: current.entity,
+ attribute: current.attribute,
+ });
+
+ if (!allowedOperators.includes(nextOperator)) {
+ return false;
+ }
+
+ const nextValue =
+ suggestion.suggested.value !== undefined
+ ? suggestion.suggested.value
+ : current.value;
+
+ if (
+ !isValueValidForOperator({
+ event,
+ entity: current.entity,
+ attribute: current.attribute,
+ operator: nextOperator,
+ value: nextValue,
+ })
+ ) {
+ return false;
+ }
+
+ return (
+ nextOperator !== current.operator || !valuesEqual(nextValue, current.value)
+ );
+}
+
+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];
+ }
+
+ if (attributeType === "number" || attributeType === "currency") {
+ return [...NUMBER_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 {
+ if (value == null || value === "") return false;
+ if (Array.isArray(value)) return value.filter(Boolean).length > 0;
+ if (typeof value === "number") return !Number.isNaN(value);
+ return true;
+}
+
+function isValueValidForOperator({
+ event,
+ entity,
+ attribute,
+ operator,
+ value,
+}: {
+ event: EventType;
+ entity: string;
+ attribute: string;
+ operator: ConditionOperator;
+ value: unknown;
+}): boolean {
+ if (!isConditionValueFilled(value)) {
+ return false;
+ }
+
+ if (operator === "in" || operator === "not_in") {
+ return Array.isArray(value);
+ }
+
+ if (Array.isArray(value)) {
+ return false;
+ }
+
+ const attributeType =
+ getRewardConditionAttribute({ event, entity, attribute })?.type ?? "string";
+
+ const numeric =
+ attributeType === "number" ||
+ attributeType === "currency" ||
+ attributeType === "date" ||
+ (attributeType === "metadata" &&
+ METADATA_NUMBER_CONDITION_OPERATORS.includes(operator));
+
+ if (numeric) {
+ return typeof value === "number" && !Number.isNaN(value);
+ }
+
+ return typeof value === "string";
+}
+
+function valuesEqual(left: unknown, right: unknown): boolean {
+ if (Array.isArray(left) && Array.isArray(right)) {
+ return (
+ left.length === right.length &&
+ left.every((item, index) => item === right[index])
+ );
+ }
+
+ return left === right;
+}
+
+export function stripRewardTooltipMarkdown(markdown: string): string {
+ return markdown
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
+ .replace(/\*\*([^*]+)\*\*/g, "$1")
+ .replace(/\*([^*]+)\*/g, "$1")
+ .replace(/__([^_]+)__/g, "$1")
+ .replace(/_([^_]+)_/g, "$1")
+ .replace(/`([^`]+)`/g, "$1")
+ .replace(/#+\s+/g, "")
+ .replace(/\n+/g, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+}
diff --git a/apps/web/lib/upstash/ratelimit-policies.ts b/apps/web/lib/upstash/ratelimit-policies.ts
index 5ef9524a9a..1579a223b4 100644
--- a/apps/web/lib/upstash/ratelimit-policies.ts
+++ b/apps/web/lib/upstash/ratelimit-policies.ts
@@ -96,6 +96,12 @@ export const RATELIMIT_POLICIES = {
keyPrefix: "rl:ai:reward:generate",
},
+ aiRewardTooltipReview: {
+ attempts: 20,
+ window: "1 m",
+ keyPrefix: "rl:ai:reward:tooltip-review",
+ },
+
// Keyed on workspace + user so one actor cannot exhaust the workspace quota
forwardDnsInstructions: {
attempts: 10,
diff --git a/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts b/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
new file mode 100644
index 0000000000..453eeca227
--- /dev/null
+++ b/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
@@ -0,0 +1,255 @@
+import type {
+ ReviewRewardTooltipModifier,
+ TooltipSuggestion,
+} from "@/lib/ai/review-reward-tooltip-schema";
+import {
+ applyTooltipSuggestion,
+ filterValidatedTooltipSuggestions,
+ isRewardConditionComplete,
+ suggestionTouchesField,
+} from "@/lib/rewards/validate-tooltip-suggestion";
+import { describe, expect, test } from "vitest";
+
+const saleAmountModifiers: ReviewRewardTooltipModifier[] = [
+ {
+ operator: "AND",
+ conditions: [
+ {
+ entity: "sale",
+ attribute: "amount",
+ operator: "greater_than",
+ value: 20,
+ },
+ ],
+ },
+];
+
+const minTwentySuggestion: TooltipSuggestion = {
+ modifierIndex: 0,
+ conditionIndex: 0,
+ confidence: 0.9,
+ reason:
+ '"Minimum $20 deposit" implies $20 qualifies, but "is greater than" excludes it.',
+ suggested: {
+ operator: "greater_than_or_equal" as const,
+ },
+};
+
+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);
+ });
+});
+
+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([]);
+ });
+
+ test("rejects a no-op that matches the current condition", () => {
+ expect(
+ accepted({
+ ...minTwentySuggestion,
+ suggested: { operator: "greater_than" },
+ }),
+ ).toEqual([]);
+ });
+
+ test("rejects a value whose shape does not match the operator", () => {
+ expect(
+ accepted({
+ ...minTwentySuggestion,
+ suggested: { operator: "in", value: 20 },
+ }),
+ ).toEqual([]);
+ });
+
+ test("rejects customer.source operator changes", () => {
+ expect(
+ filterValidatedTooltipSuggestions({
+ event: "sale",
+ modifiers: [
+ {
+ operator: "AND",
+ conditions: [
+ {
+ entity: "customer",
+ attribute: "source",
+ operator: "equals_to",
+ value: "tracked",
+ },
+ ],
+ },
+ ],
+ 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 },
+ ],
+ });
+
+ 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("suggestionTouchesField", () => {
+ test("detects operator vs value changes", () => {
+ const current = saleAmountModifiers[0].conditions[0];
+
+ 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 },
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/apps/web/ui/partners/rewards/rewards-logic.tsx b/apps/web/ui/partners/rewards/rewards-logic.tsx
index 86b0bc52fd..a66f843172 100644
--- a/apps/web/ui/partners/rewards/rewards-logic.tsx
+++ b/apps/web/ui/partners/rewards/rewards-logic.tsx
@@ -2,6 +2,10 @@
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
+import {
+ applyTooltipSuggestion,
+ suggestionTouchesField,
+} from "@/lib/rewards/validate-tooltip-suggestion";
import { SUBMITTED_LEADS_ENABLED_PROGRAM_IDS } from "@/lib/submitted-leads/constants";
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
@@ -61,6 +65,12 @@ import {
} from "../../shared/inline-badge-popover";
import { useAddEditRewardForm } from "./add-edit-reward-sheet";
import { RewardIconSquare } from "./reward-icon-square";
+import { SuggestedFixBadge } from "./suggested-fix-popover";
+import {
+ RewardTooltipConsistencyContext,
+ useRewardTooltipConsistency,
+ useRewardTooltipConsistencyContext,
+} from "./use-reward-tooltip-consistency";
export const REWARD_TYPES = [
{
@@ -78,9 +88,33 @@ export function RewardsLogic({
}: {
isDefaultReward: boolean;
}) {
- const { plan } = useWorkspace();
+ const { plan, id: workspaceId } = useWorkspace();
+
+ const { control, getValues, setValue } = useAddEditRewardForm();
+ const [event, tooltipDescription, modifiers] = useWatch({
+ control,
+ name: ["event", "tooltipDescription", "modifiers"],
+ });
- const { control, getValues } = useAddEditRewardForm();
+ const consistency = useRewardTooltipConsistency({
+ workspaceId,
+ event,
+ tooltipDescription,
+ modifiers,
+ onApply: (suggestion) => {
+ const conditionKey =
+ `modifiers.${suggestion.modifierIndex}.conditions.${suggestion.conditionIndex}` as const;
+ const current = getValues(conditionKey);
+
+ if (!current) return;
+
+ setValue(
+ conditionKey,
+ applyTooltipSuggestion(current, suggestion.suggested),
+ { shouldDirty: true },
+ );
+ },
+ });
const {
fields: modifierFields,
@@ -92,57 +126,62 @@ export function RewardsLogic({
});
return (
- <div
- className={cn("flex flex-col gap-2", !!modifierFields.length && "-mt-2")}
- >
- {modifierFields.map((field, index) => (
- <ConditionalGroup
- key={field.id}
- index={index}
- groupCount={modifierFields.length}
- onRemove={() => removeModifier(index)}
+ <RewardTooltipConsistencyContext.Provider value={consistency}>
+ <div
+ className={cn(
+ "flex flex-col gap-2",
+ !!modifierFields.length && "-mt-2",
+ )}
+ >
+ {modifierFields.map((field, index) => (
+ <ConditionalGroup
+ key={field.id}
+ index={index}
+ groupCount={modifierFields.length}
+ onRemove={() => removeModifier(index)}
+ />
+ ))}
+ <Button
+ className="h-8 rounded-lg"
+ icon={<ArrowTurnRight2 className="size-4" />}
+ text={
+ <div className="flex items-center gap-2">
+ <span>Add condition</span>
+ {!getPlanCapabilities(plan).canUseAdvancedRewardLogic && (
+ <div
+ className={cn(
+ "rounded-sm px-1.5 py-1 text-[0.625rem] uppercase leading-none",
+ isDefaultReward
+ ? "bg-violet-500/50 text-violet-200"
+ : "bg-violet-50 text-violet-600",
+ )}
+ >
+ Upgrade required
+ </div>
+ )}
+ </div>
+ }
+ onClick={() => {
+ const type = getValues("type");
+
+ appendModifier({
+ id: uuid(),
+ operator: "AND",
+ conditions: [{}],
+ amountInCents:
+ type === "flat" ? getValues("amountInCents") || 0 : undefined,
+ amountInPercentage:
+ type === "percentage"
+ ? getValues("amountInPercentage") || 0
+ : undefined,
+ type,
+ maxDuration: getValues("maxDuration"),
+ });
+ }}
+ variant={isDefaultReward ? "primary" : "secondary"}
/>
- ))}
- <Button
- className="h-8 rounded-lg"
- icon={<ArrowTurnRight2 className="size-4" />}
- text={
- <div className="flex items-center gap-2">
- <span>Add condition</span>
- {!getPlanCapabilities(plan).canUseAdvancedRewardLogic && (
- <div
- className={cn(
- "rounded-sm px-1.5 py-1 text-[0.625rem] uppercase leading-none",
- isDefaultReward
- ? "bg-violet-500/50 text-violet-200"
- : "bg-violet-50 text-violet-600",
- )}
- >
- Upgrade required
- </div>
- )}
- </div>
- }
- onClick={() => {
- const type = getValues("type");
-
- appendModifier({
- id: uuid(),
- operator: "AND",
- conditions: [{}],
- amountInCents:
- type === "flat" ? getValues("amountInCents") || 0 : undefined,
- amountInPercentage:
- type === "percentage"
- ? getValues("amountInPercentage") || 0
- : undefined,
- type,
- maxDuration: getValues("maxDuration"),
- });
- }}
- variant={isDefaultReward ? "primary" : "secondary"}
- />
- </div>
+ </div>
+ </RewardTooltipConsistencyContext.Provider>
);
}
@@ -385,6 +424,26 @@ function ConditionLogic({
control,
name: ["event", conditionKey, `${modifierKey}.operator`],
});
+ const suggestion = useRewardTooltipConsistencyContext()?.getSuggestion(
+ modifierIndex,
+ conditionIndex,
+ );
+ const highlightOperator = Boolean(
+ suggestion &&
+ suggestionTouchesField({
+ field: "operator",
+ current: condition ?? {},
+ suggested: suggestion.suggested,
+ }),
+ );
+ const highlightValue = Boolean(
+ suggestion &&
+ suggestionTouchesField({
+ field: "value",
+ current: condition ?? {},
+ suggested: suggestion.suggested,
+ }),
+ );
const [displayProductLabel, setDisplayProductLabel] = useState(false);
@@ -586,6 +645,12 @@ function ConditionLogic({
)}
{isCustomerSourceCondition || isSaleTypeCondition ? (
<span className="text-content-emphasis font-medium">is </span>
+ ) : highlightOperator && condition.operator ? (
+ <SuggestedFixBadge
+ text={CONDITION_OPERATOR_LABELS[condition.operator]}
+ modifierIndex={modifierIndex}
+ conditionIndex={conditionIndex}
+ />
) : (
<InlineBadgePopover
text={
@@ -665,7 +730,21 @@ function ConditionLogic({
)}{" "}
{condition.operator && (
<>
- {attributeType === "date" && !isMetadataCondition ? (
+ {highlightValue ? (
+ <SuggestedFixBadge
+ text={
+ formatValue(
+ condition.value,
+ attribute,
+ isMetadataCondition
+ ? condition.operator
+ : undefined,
+ ) ?? "Value"
+ }
+ modifierIndex={modifierIndex}
+ conditionIndex={conditionIndex}
+ />
+ ) : attributeType === "date" && !isMetadataCondition ? (
<DatePicker
value={
condition.value
diff --git a/apps/web/ui/partners/rewards/suggested-fix-popover.tsx b/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
new file mode 100644
index 0000000000..1d1d2d6750
--- /dev/null
+++ b/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
@@ -0,0 +1,295 @@
+"use client";
+
+import type { TooltipSuggestion } from "@/lib/ai/review-reward-tooltip-schema";
+import { formatRewardConditionParts } from "@/lib/rewards/format-reward-condition";
+import {
+ applyTooltipSuggestion,
+ getRewardConditionAttribute,
+ suggestionTouchesField,
+} from "@/lib/rewards/validate-tooltip-suggestion";
+import { RewardCondition } from "@/lib/types";
+import { Button, InvoiceDollar, Popover, useMediaQuery } from "@dub/ui";
+import { Sparkle3 } from "@dub/ui/icons";
+import { cn } from "@dub/utils";
+import { useRef, useState, type ReactNode } from "react";
+import { useWatch } from "react-hook-form";
+import { useAddEditRewardForm } from "./add-edit-reward-sheet";
+import { useRewardTooltipConsistencyContext } from "./use-reward-tooltip-consistency";
+
+export function SuggestedFixBadge({
+ text,
+ modifierIndex,
+ conditionIndex,
+}: {
+ text: string;
+ modifierIndex: number;
+ conditionIndex: number;
+}) {
+ const consistency = useRewardTooltipConsistencyContext();
+ const { isMobile } = useMediaQuery();
+ const [open, setOpen] = useState(false);
+ const closeTimer = useRef<number | undefined>(undefined);
+
+ if (!consistency) return null;
+
+ const {
+ suggestions,
+ activeIndex,
+ setActiveIndex,
+ accept,
+ acceptAll,
+ dismiss,
+ dismissAll,
+ } = consistency;
+
+ const thisIndex = suggestions.findIndex(
+ (suggestion) =>
+ suggestion.modifierIndex === modifierIndex &&
+ suggestion.conditionIndex === conditionIndex,
+ );
+
+ if (thisIndex === -1) return null;
+
+ const clearClose = () => {
+ if (closeTimer.current) window.clearTimeout(closeTimer.current);
+ };
+
+ const scheduleClose = () => {
+ if (isMobile) return;
+ clearClose();
+ closeTimer.current = window.setTimeout(() => setOpen(false), 150);
+ };
+
+ const active = suggestions[activeIndex] ?? suggestions[thisIndex];
+ const isMultiple = suggestions.length > 1;
+
+ return (
+ <Popover
+ openPopover={open}
+ setOpenPopover={setOpen}
+ align="start"
+ sideOffset={8}
+ onOpenAutoFocus={(event) => event.preventDefault()}
+ popoverContentClassName="w-[min(411px,calc(100vw-2rem))] overflow-hidden rounded-xl border-neutral-200 bg-white p-0 drop-shadow-none shadow-[0px_4px_6px_-2px_#0000000D,0px_10px_15px_-3px_#0000001A]"
+ content={
+ <div
+ onMouseEnter={() => {
+ if (!isMobile) {
+ clearClose();
+ setOpen(true);
+ }
+ }}
+ onMouseLeave={scheduleClose}
+ >
+ <SuggestedFixContent
+ suggestion={active}
+ index={Math.max(activeIndex, 0)}
+ total={suggestions.length}
+ onNext={() =>
+ setActiveIndex((activeIndex + 1) % suggestions.length)
+ }
+ onDiscard={() => {
+ if (isMultiple) {
+ dismissAll();
+ } else {
+ dismiss(active);
+ }
+ setOpen(false);
+ }}
+ onAccept={() => {
+ if (isMultiple) {
+ acceptAll();
+ } else {
+ accept(active);
+ }
+ setOpen(false);
+ }}
+ />
+ </div>
+ }
+ >
+ <button
+ type="button"
+ onMouseEnter={() => {
+ if (!isMobile) {
+ clearClose();
+ setActiveIndex(thisIndex);
+ setOpen(true);
+ }
+ }}
+ onMouseLeave={scheduleClose}
+ onClick={() => {
+ if (isMobile) {
+ setOpen((current) => !current);
+ setActiveIndex(thisIndex);
+ }
+ }}
+ className="inline-flex items-center gap-1 rounded bg-[#FFFBEB] px-1.5 text-left text-sm font-semibold text-[#973C00] transition-colors"
+ >
+ <Sparkle3 variant="fill" className="size-3 shrink-0 text-[#E17100]" />
+ {text}
+ </button>
+ </Popover>
+ );
+}
+
+function SuggestedFixContent({
+ suggestion,
+ index,
+ total,
+ onNext,
+ onDiscard,
+ onAccept,
+}: {
+ suggestion: TooltipSuggestion;
+ index: number;
+ total: number;
+ onNext: () => void;
+ onDiscard: () => void;
+ onAccept: () => void;
+}) {
+ const { control } = useAddEditRewardForm();
+ const [event, modifiers] = useWatch({
+ control,
+ name: ["event", "modifiers"],
+ });
+
+ const current =
+ modifiers?.[suggestion.modifierIndex]?.conditions?.[
+ suggestion.conditionIndex
+ ];
+
+ if (!current?.entity || !current.attribute || !current.operator) {
+ return null;
+ }
+
+ const patched = applyTooltipSuggestion(current, suggestion.suggested);
+ const entity = patched.entity ?? current.entity;
+ const attribute = patched.attribute ?? current.attribute;
+ const operator = patched.operator ?? current.operator;
+ const attributeType = getRewardConditionAttribute({
+ event,
+ entity,
+ attribute,
+ })?.type;
+
+ const { entityLabel, attributeLabel, operatorLabel, valueLabel } =
+ formatRewardConditionParts({
+ event,
+ condition: {
+ entity,
+ attribute,
+ operator,
+ value:
+ attributeType === "currency" && typeof patched.value === "number"
+ ? patched.value * 100
+ : patched.value,
+ label: patched.label,
+ metadataField: patched.metadataField,
+ } as RewardCondition,
+ });
+
+ const isMultiple = total > 1;
+
+ return (
+ <div className="flex flex-col">
+ <div className="flex items-center justify-between gap-2 border-b border-neutral-200 p-3">
+ <div className="flex items-center gap-1.5 text-sm font-medium text-neutral-900">
+ <Sparkle3 variant="fill" className="size-3.5" />
+ Suggested fix
+ </div>
+ {isMultiple && (
+ <span className="text-xs text-neutral-500">
+ {index + 1} of {total}
+ </span>
+ )}
+ </div>
+
+ <div className="flex flex-col gap-3 p-3">
+ <div className="rounded-lg bg-neutral-50 px-2.5 py-2">
+ <div className="flex items-start gap-2">
+ <div className="flex size-6 shrink-0 items-center justify-center rounded-md bg-white">
+ <InvoiceDollar className="size-3.5 text-neutral-800" />
+ </div>
+ <p className="min-w-0 text-sm font-medium leading-relaxed text-neutral-800">
+ If <PreviewChip>{entityLabel}</PreviewChip>{" "}
+ <PreviewChip>{attributeLabel}</PreviewChip>{" "}
+ <PreviewChip
+ changed={suggestionTouchesField({
+ field: "operator",
+ current,
+ suggested: suggestion.suggested,
+ })}
+ >
+ {operatorLabel}
+ </PreviewChip>{" "}
+ <PreviewChip
+ changed={suggestionTouchesField({
+ field: "value",
+ current,
+ suggested: suggestion.suggested,
+ })}
+ >
+ {valueLabel}
+ </PreviewChip>
+ </p>
+ </div>
+ </div>
+
+ <p className="text-sm text-neutral-600">{suggestion.reason}</p>
+ </div>
+
+ <div
+ className={cn(
+ "flex items-center gap-2 border-t border-neutral-200 px-3 py-2",
+ isMultiple ? "justify-between" : "justify-end",
+ )}
+ >
+ {isMultiple && (
+ <button
+ type="button"
+ onClick={onNext}
+ className="text-sm font-medium text-neutral-600 hover:text-neutral-900"
+ >
+ Next
+ </button>
+ )}
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ className="h-7 w-fit rounded-lg px-3 py-2"
+ text="Discard"
+ onClick={onDiscard}
+ />
+ <Button
+ type="button"
+ variant="primary"
+ className="h-7 w-fit rounded-lg px-3 py-2"
+ text={isMultiple ? "Accept all changes" : "Accept change"}
+ onClick={onAccept}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function PreviewChip({
+ children,
+ changed,
+}: {
+ children: ReactNode;
+ changed?: boolean;
+}) {
+ return (
+ <span
+ className={cn(
+ "inline-block rounded px-1.5 text-sm font-semibold",
+ changed ? "bg-blue-600 text-white" : "bg-blue-50 text-blue-700",
+ )}
+ >
+ {children}
+ </span>
+ );
+}
diff --git a/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts b/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
new file mode 100644
index 0000000000..1e4920b6be
--- /dev/null
+++ b/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
@@ -0,0 +1,323 @@
+"use client";
+
+import {
+ AI_REWARD_EVENTS,
+ type AIRewardEvent,
+} from "@/lib/ai/ai-reward-schema";
+import { reviewRewardTooltipConsistency } from "@/lib/ai/review-reward-tooltip";
+import type {
+ ReviewRewardTooltipModifier,
+ TooltipSuggestion,
+} from "@/lib/ai/review-reward-tooltip-schema";
+import {
+ getRewardConditionAttribute,
+ isRewardConditionComplete,
+ stripRewardTooltipMarkdown,
+} from "@/lib/rewards/validate-tooltip-suggestion";
+import { EventType } from "@prisma/client";
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+
+const DEBOUNCE_MS = 600;
+const reviewCache = new Map<string, TooltipSuggestion[]>();
+
+type RewardTooltipConsistencyValue = {
+ suggestions: TooltipSuggestion[];
+ activeIndex: number;
+ setActiveIndex: (index: number) => void;
+ getSuggestion: (
+ modifierIndex: number,
+ conditionIndex: number,
+ ) => TooltipSuggestion | undefined;
+ accept: (suggestion: TooltipSuggestion) => void;
+ acceptAll: () => void;
+ dismiss: (suggestion: TooltipSuggestion) => void;
+ dismissAll: () => void;
+};
+
+export const RewardTooltipConsistencyContext =
+ createContext<RewardTooltipConsistencyValue | null>(null);
+
+export function useRewardTooltipConsistencyContext() {
+ return useContext(RewardTooltipConsistencyContext);
+}
+
+export function useRewardTooltipConsistency({
+ workspaceId,
+ event,
+ tooltipDescription,
+ modifiers,
+ onApply,
+}: {
+ workspaceId?: string;
+ event: EventType;
+ tooltipDescription?: string | null;
+ modifiers?: Array<{
+ operator?: "AND" | "OR";
+ conditions?: Array<{
+ entity?: string;
+ attribute?: string;
+ operator?: string;
+ value?: unknown;
+ label?: string | null;
+ metadataField?: string;
+ } | null>;
+ } | null> | null;
+ onApply?: (suggestion: TooltipSuggestion) => void;
+}): RewardTooltipConsistencyValue {
+ const [suggestions, setSuggestions] = useState<TooltipSuggestion[]>([]);
+ const [activeIndex, setActiveIndex] = useState(0);
+ const [dismissedKeys, setDismissedKeys] = useState<string[]>([]);
+ const requestIdRef = useRef(0);
+
+ const tooltip = stripRewardTooltipMarkdown(tooltipDescription ?? "");
+ const serializedModifiers = useMemo(
+ () => serializeModifiersForReview({ event, modifiers }),
+ [event, modifiers],
+ );
+
+ const cacheKey = useMemo(() => {
+ if (
+ !workspaceId ||
+ !isAiRewardEvent(event) ||
+ !tooltip ||
+ !serializedModifiers
+ ) {
+ return null;
+ }
+
+ return JSON.stringify({
+ event,
+ tooltip,
+ modifiers: serializedModifiers,
+ });
+ }, [event, serializedModifiers, tooltip, workspaceId]);
+
+ useEffect(() => {
+ const requestId = ++requestIdRef.current;
+
+ if (!cacheKey || !workspaceId || !isAiRewardEvent(event)) {
+ setSuggestions([]);
+ setActiveIndex(0);
+ return;
+ }
+
+ const cached = reviewCache.get(cacheKey);
+ if (cached) {
+ setSuggestions(cached);
+ setActiveIndex(0);
+ return;
+ }
+
+ setSuggestions([]);
+ setActiveIndex(0);
+ const timeout = window.setTimeout(async () => {
+ try {
+ const result = await reviewRewardTooltipConsistency({
+ workspaceId,
+ event,
+ tooltip,
+ modifiers: serializedModifiers,
+ });
+
+ if (requestId !== requestIdRef.current) {
+ return;
+ }
+
+ const next = result.suggestions ?? [];
+ reviewCache.set(cacheKey, next);
+ setSuggestions(next);
+ setActiveIndex(0);
+ } catch {
+ if (requestId !== requestIdRef.current) {
+ return;
+ }
+
+ setSuggestions([]);
+ setActiveIndex(0);
+ }
+ }, DEBOUNCE_MS);
+
+ return () => {
+ window.clearTimeout(timeout);
+ };
+ }, [cacheKey, event, serializedModifiers, tooltip, workspaceId]);
+
+ const visibleSuggestions = useMemo(() => {
+ if (!serializedModifiers?.length) return [];
+
+ return suggestions.filter((suggestion) => {
+ const current =
+ serializedModifiers[suggestion.modifierIndex]?.conditions[
+ suggestion.conditionIndex
+ ];
+
+ if (!current) return false;
+
+ return !dismissedKeys.includes(dismissalKey(suggestion, current));
+ });
+ }, [dismissedKeys, serializedModifiers, suggestions]);
+
+ useEffect(() => {
+ if (activeIndex >= visibleSuggestions.length) {
+ setActiveIndex(0);
+ }
+ }, [activeIndex, visibleSuggestions.length]);
+
+ const getSuggestion = useCallback(
+ (modifierIndex: number, conditionIndex: number) =>
+ visibleSuggestions.find(
+ (suggestion) =>
+ suggestion.modifierIndex === modifierIndex &&
+ suggestion.conditionIndex === conditionIndex,
+ ),
+ [visibleSuggestions],
+ );
+
+ const dismiss = useCallback(
+ (suggestion: TooltipSuggestion) => {
+ const current =
+ serializedModifiers?.[suggestion.modifierIndex]?.conditions[
+ suggestion.conditionIndex
+ ];
+
+ if (!current) return;
+
+ const key = dismissalKey(suggestion, current);
+ setDismissedKeys((keys) => (keys.includes(key) ? keys : [...keys, key]));
+ },
+ [serializedModifiers],
+ );
+
+ const dismissAll = useCallback(() => {
+ if (!serializedModifiers) return;
+
+ setDismissedKeys((keys) => {
+ const next = new Set(keys);
+
+ for (const suggestion of suggestions) {
+ const current =
+ serializedModifiers[suggestion.modifierIndex]?.conditions[
+ suggestion.conditionIndex
+ ];
+
+ if (current) {
+ next.add(dismissalKey(suggestion, current));
+ }
+ }
+
+ return [...next];
+ });
+ }, [serializedModifiers, suggestions]);
+
+ const accept = useCallback(
+ (suggestion: TooltipSuggestion) => {
+ onApply?.(suggestion);
+ dismiss(suggestion);
+ },
+ [dismiss, onApply],
+ );
+
+ const acceptAll = useCallback(() => {
+ visibleSuggestions.forEach((suggestion) => onApply?.(suggestion));
+ dismissAll();
+ }, [dismissAll, onApply, visibleSuggestions]);
+
+ return {
+ suggestions: visibleSuggestions,
+ activeIndex,
+ setActiveIndex,
+ getSuggestion,
+ accept,
+ acceptAll,
+ dismiss,
+ dismissAll,
+ };
+}
+
+function isAiRewardEvent(event: EventType): event is AIRewardEvent {
+ return (AI_REWARD_EVENTS as readonly string[]).includes(event);
+}
+
+function dismissalKey(
+ suggestion: TooltipSuggestion,
+ current: { operator: string; value: unknown },
+) {
+ return [
+ suggestion.modifierIndex,
+ suggestion.conditionIndex,
+ current.operator,
+ JSON.stringify(current.value),
+ suggestion.suggested.operator ?? "",
+ JSON.stringify(suggestion.suggested.value ?? null),
+ ].join(":");
+}
+
+function serializeModifiersForReview({
+ event,
+ modifiers,
+}: {
+ event: EventType;
+ modifiers?: Array<{
+ operator?: "AND" | "OR";
+ conditions?: Array<{
+ entity?: string;
+ attribute?: string;
+ operator?: string;
+ value?: unknown;
+ label?: string | null;
+ metadataField?: string;
+ } | null>;
+ } | null> | null;
+}): ReviewRewardTooltipModifier[] | null {
+ if (!isAiRewardEvent(event) || !modifiers?.length) return null;
+ if (
+ !modifiers.every(
+ (modifier) =>
+ !!modifier?.conditions?.length &&
+ modifier.conditions.every((condition) =>
+ isRewardConditionComplete({ event, condition }),
+ ),
+ )
+ ) {
+ return null;
+ }
+
+ return (modifiers ?? []).map((modifier) => ({
+ operator: modifier?.operator ?? "AND",
+ conditions: (modifier?.conditions ?? []).map((condition) => {
+ const attribute = getRewardConditionAttribute({
+ event,
+ entity: condition?.entity,
+ attribute: condition?.attribute,
+ });
+
+ let value = condition?.value;
+ if (
+ attribute &&
+ ["number", "currency", "date"].includes(attribute.type) &&
+ !Array.isArray(value)
+ ) {
+ value = Number(value);
+ }
+
+ return {
+ entity: condition!.entity!,
+ attribute: condition!.attribute!,
+ operator: condition!
+ .operator as ReviewRewardTooltipModifier["conditions"][number]["operator"],
+ value:
+ value as ReviewRewardTooltipModifier["conditions"][number]["value"],
+ label: condition?.label,
+ metadataField: condition?.metadataField,
+ };
+ }),
+ }));
+}