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.

improve jev checker

Pedro Ladeiraa266df2623e2
diff --git a/apps/web/lib/ai/review-reward-tooltip-schema.ts b/apps/web/lib/ai/review-reward-tooltip-schema.ts
index 480dece0f0..a2031878e8 100644
--- a/apps/web/lib/ai/review-reward-tooltip-schema.ts
+++ b/apps/web/lib/ai/review-reward-tooltip-schema.ts
@@ -51,11 +51,70 @@ const tooltipSuggestionSchema = z.object({
),
});
+const payoutFixSchema = z.object({
+ scope: z
+ .enum(["default", "group"])
+ .describe(
+ "default is the payout when no condition matches. group is one condition group's payout.",
+ ),
+ modifierIndex: z
+ .number()
+ .int()
+ .nonnegative()
+ .nullish()
+ .describe(
+ "Required when scope is group. The condition group's modifierIndex.",
+ ),
+ amount: z
+ .number()
+ .nonnegative()
+ .nullish()
+ .describe(
+ "New amount in dollars for a flat payout, or percent for a percentage payout. Omit to keep the current amount.",
+ ),
+ maxDuration: z
+ .number()
+ .int()
+ .min(0)
+ .max(600)
+ .nullable()
+ .optional()
+ .describe(
+ "0 = one time, null = for the customer's lifetime, a positive integer = that many months. Omit to keep the current duration.",
+ ),
+ confidence: z
+ .number()
+ .min(0)
+ .max(1)
+ .describe(
+ "0–1 confidence that the copy states this amount or duration. Use below 0.5 when the reading is ambiguous.",
+ ),
+ reason: z
+ .string()
+ .min(1)
+ .max(300)
+ .describe(
+ "One short sentence quoting the copy and the payout it disagrees with. Never use raw field names.",
+ ),
+});
+
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.",
+ "Condition operator or value fixes. Empty when no existing condition should change.",
+ ),
+ payoutFixes: z
+ .array(payoutFixSchema)
+ .describe(
+ "Amount or duration changes so a payout matches the partner copy. One entry per payout that disagrees. Empty when every payout already matches, or when you cannot name the replacement amount or duration.",
+ ),
+ note: z
+ .string()
+ .max(300)
+ .nullish()
+ .describe(
+ "One sentence when the copy disagrees with a payout and you cannot name the replacement amount or duration. Null when suggestions or payoutFixes is non-empty.",
),
});
@@ -68,15 +127,24 @@ const reviewRewardTooltipConditionSchema = z.object({
metadataField: z.string().optional(),
});
+const rewardPayoutSchema = z.object({
+ type: z.enum(["flat", "percentage"]),
+ amount: z.number().nullish(),
+ maxDuration: z.number().int().nonnegative().nullish(),
+});
+
const reviewRewardTooltipModifierSchema = z.object({
operator: z.enum(["AND", "OR"]).default("AND"),
conditions: z.array(reviewRewardTooltipConditionSchema).min(1),
+ payout: rewardPayoutSchema,
});
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(),
+ basePayout: rewardPayoutSchema,
modifiers: z.array(reviewRewardTooltipModifierSchema).min(1),
});
@@ -84,6 +152,8 @@ export type TooltipSuggestion = z.infer<typeof tooltipSuggestionSchema>;
export type TooltipSuggestionPatch = z.infer<
typeof tooltipSuggestionPatchSchema
>;
+export type PayoutFix = z.infer<typeof payoutFixSchema>;
export type ReviewRewardTooltipModifier = z.infer<
typeof reviewRewardTooltipModifierSchema
>;
+export type RewardPayout = z.infer<typeof rewardPayoutSchema>;
diff --git a/apps/web/lib/ai/review-reward-tooltip.ts b/apps/web/lib/ai/review-reward-tooltip.ts
index 93428c9983..fb0cc29949 100644
--- a/apps/web/lib/ai/review-reward-tooltip.ts
+++ b/apps/web/lib/ai/review-reward-tooltip.ts
@@ -5,19 +5,26 @@ import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
filterValidatedTooltipSuggestions,
+ getRewardConditionAttribute,
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 {
+ CONDITION_OPERATOR_LABELS,
+ REWARD_CONDITIONS,
+} from "@/lib/zod/schemas/rewards";
import { anthropic } from "@ai-sdk/anthropic";
+import { type EventType } from "@prisma/client";
import { experimental_evaluate as evaluate, generateText, Output } from "ai";
import { throwIfNoPermission } from "../actions/throw-if-no-permission";
import {
reviewRewardTooltipInputSchema,
reviewRewardTooltipOutputSchema,
TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR,
+ type PayoutFix,
type ReviewRewardTooltipModifier,
+ type RewardPayout,
type TooltipSuggestion,
} from "./review-reward-tooltip-schema";
@@ -27,11 +34,17 @@ export async function screenRewardTooltipContradiction(
try {
const authorized = await authorizeRewardTooltipReview(input);
if (!authorized) {
+ console.log("[screenRewardTooltipContradiction] skipped", {
+ reason: "unauthorized",
+ });
return { flagged: false };
}
const tooltip = stripRewardTooltipMarkdown(authorized.data.tooltip);
if (!tooltip) {
+ console.log("[screenRewardTooltipContradiction] skipped", {
+ reason: "empty tooltip",
+ });
return { flagged: false };
}
@@ -40,36 +53,37 @@ export async function screenRewardTooltipContradiction(
identifier: [authorized.userId, authorized.workspaceId],
});
- const { event, modifiers } = authorized.data;
+ const reward = describeReward({
+ ...authorized.data,
+ tooltip,
+ });
const result = await evaluate({
model: "typesafe-ai/jev",
- state: {
- event,
- tooltip,
- conditions: serializeConditions(modifiers),
- },
+ state: reward,
questions: {
contradicts: {
type: "boolean",
instructions:
- "Would a partner who only read the tooltip be surprised by an existing condition?",
+ "Would a partner who read the shown-as text or the tooltip be surprised by this reward?",
criteria: {
true: {
meaning:
- "Yes only when an existing condition clearly contradicts the tooltip. One strong mismatch is enough. Use a low probability when unsure.",
+ "Yes when the partner copy states an amount, a duration, or an eligibility rule that the payout or a condition does not match. One strong mismatch is enough. Use a low probability when unsure.",
matches_any: [
- "The tooltip says minimum, at least, or that a threshold qualifies, but the condition uses a strict greater-than or less-than that excludes that boundary.",
- "The tooltip says more than, over, or above, but the condition includes the boundary.",
- "The tooltip names a different operator or threshold than an existing condition, clearly enough that a partner would expect a different eligibility rule.",
+ "The copy says every month, every N months, monthly, recurring, lifetime, or one time, and that is not the payout duration.",
+ "The copy states a dollar or percent amount that is not what the default payout or the matching condition group pays.",
+ "The copy says minimum, at least, or that a threshold qualifies, but the condition uses a strict greater-than or less-than that excludes that boundary.",
+ "The copy says more than, over, or above, but the condition includes the boundary.",
+ "The copy names a different operator or threshold than an existing condition.",
],
},
false: {
meaning:
- "No when the tooltip and the existing conditions agree, or when the reading is ambiguous.",
+ "No when the copy agrees with the payout and the conditions, or when it does not clearly state a conflicting amount, duration, operator, or threshold.",
even_if: [
- "The tooltip is shorter than the config or omits extra filters such as country, product, or metadata.",
- "The wording is informal and does not clearly specify a different operator or threshold.",
- "The tooltip never mentions a condition that still exists in the config.",
+ "The copy is shorter than the config or omits extra filters such as country, product, or metadata.",
+ "The copy never mentions a condition that still exists, and it also does not state a conflicting amount or duration.",
+ "The wording is informal and does not clearly name a different amount, duration, operator, or threshold.",
],
},
},
@@ -84,27 +98,42 @@ export async function screenRewardTooltipContradiction(
const answer = result.answers.contradicts;
if (answer?.type !== "boolean") {
+ console.log("[screenRewardTooltipContradiction] jev result", {
+ reward,
+ answer,
+ flagged: null,
+ });
return { flagged: null };
}
- return {
- flagged:
- Number.isFinite(answer.probability) &&
- answer.probability > TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR,
- };
+ const flagged =
+ Number.isFinite(answer.probability) &&
+ answer.probability > TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR;
+
+ console.log("[screenRewardTooltipContradiction] jev result", {
+ reward,
+ probability: answer.probability,
+ flagged,
+ });
+
+ return { flagged };
} catch (error) {
console.error("[screenRewardTooltipContradiction]", error);
return { flagged: null };
}
}
-export async function reviewRewardTooltipConsistency(
- input: unknown,
-): Promise<{ suggestions: TooltipSuggestion[] }> {
+export async function reviewRewardTooltipConsistency(input: unknown): Promise<{
+ suggestions: TooltipSuggestion[];
+ payoutFixes: PayoutFix[];
+ note: string | null;
+}> {
+ const empty = { suggestions: [], payoutFixes: [], note: null };
+
try {
const authorized = await authorizeRewardTooltipReview(input);
if (!authorized) {
- return { suggestions: [] };
+ return empty;
}
await assertRateLimit({
@@ -114,10 +143,14 @@ export async function reviewRewardTooltipConsistency(
const tooltip = stripRewardTooltipMarkdown(authorized.data.tooltip);
if (!tooltip) {
- return { suggestions: [] };
+ return empty;
}
- const { event, modifiers } = authorized.data;
+ const { event, modifiers, basePayout } = authorized.data;
+ const reward = describeReward({
+ ...authorized.data,
+ tooltip,
+ });
const { output } = await generateText({
model: anthropic("claude-haiku-4-5"),
@@ -125,26 +158,38 @@ export async function reviewRewardTooltipConsistency(
schema: reviewRewardTooltipOutputSchema,
}),
system: buildSystemPrompt(event),
- prompt: buildUserPrompt({ tooltip, modifiers }),
+ prompt: buildUserPrompt(reward),
temperature: 0,
- maxOutputTokens: 600,
+ maxOutputTokens: 900,
});
const parsedOutput = reviewRewardTooltipOutputSchema.safeParse(output);
if (!parsedOutput.success) {
- return { suggestions: [] };
+ return empty;
}
+ const suggestions = filterValidatedTooltipSuggestions({
+ event,
+ modifiers,
+ suggestions: parsedOutput.data.suggestions,
+ });
+ const payoutFixes = filterPayoutFixes({
+ basePayout,
+ modifiers,
+ fixes: parsedOutput.data.payoutFixes,
+ });
+
return {
- suggestions: filterValidatedTooltipSuggestions({
- event,
- modifiers,
- suggestions: parsedOutput.data.suggestions,
- }),
+ suggestions,
+ payoutFixes,
+ note:
+ suggestions.length || payoutFixes.length
+ ? null
+ : parsedOutput.data.note?.trim() || null,
};
} catch (error) {
console.error("[reviewRewardTooltipConsistency]", error);
- return { suggestions: [] };
+ return empty;
}
}
@@ -187,72 +232,204 @@ async function authorizeRewardTooltipReview(input: unknown) {
}
function buildSystemPrompt(event: string) {
- return `You review whether partner-facing reward tooltip copy contradicts the structured reward conditions.
+ return `You review whether partner-facing reward copy contradicts the structured reward.
Event type: ${event}
+The reward has partner copy (shown-as text and tooltip), a default payout, and condition groups. Each group pays its own amount and duration when its conditions match. The default payout applies when no group matches. Amounts are dollars for flat payouts and percents for percentage payouts. Duration is "one time", "for N months", or "for the customer's lifetime".
+
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.
+- Compare meaning, not wording.
+- Only flag an EXISTING condition that a partner who read the copy would find surprising.
+- Do not flag extra conditions the copy 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.
+- When the copy states an amount or duration that a payout does not match, return a payoutFix for each payout that disagrees. Set amount and/or maxDuration to what the copy says. Omit a field that already matches.
+- "no money", "$0", "free", or "earn nothing" means amount 0.
+- "no month", "one time", or "not monthly" means maxDuration 0.
+- "every month" or "monthly" means maxDuration 1. "every N months" means maxDuration N. "lifetime" means maxDuration null.
+- If you return a condition suggestion or a payoutFix, set note to null.
+- Use note only when the copy disagrees and you cannot name the replacement amount, duration, operator, or threshold.
+- If you are not sure, return suggestions: [], payoutFixes: [], and note: null. 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 a program manager can understand.
+- reason and note must be one short sentence a program manager can understand.
- Use the human operator labels (e.g. "is greater than"), never raw IDs like greater_than or field paths like sale.amount.
-- Wrap the tooltip phrase and the conflicting condition wording in double quotes.
-- Do not explain inclusive/exclusive in parentheses. Say what a partner would expect vs what the condition does.
+- Wrap the copy phrase and the conflicting wording in double quotes.
+- Do not explain inclusive/exclusive in parentheses. Say what a partner would expect vs what the reward does.
Good reason: "Minimum $20 deposit" implies $20 qualifies, but "is greater than" excludes it.
Bad reason: Tooltip says "min $20" (at least $20, inclusive) but the condition uses greater_than 20 (excludes $20).
-Examples of contradictions:
-- Tooltip says "minimum $20" / "at least $20" but the condition is "is greater than" $20 (excludes $20).
-- Tooltip says "more than $20" / "over $20" but the condition is "is greater than or equal to" $20.
+Condition contradictions:
+- Copy says "minimum $20" / "at least $20" but the condition is "is greater than" $20 (excludes $20).
+- Copy says "more than $20" / "over $20" but the condition is "is greater than or equal to" $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.`;
-}
+Payout fixes, not a note:
+- Copy says "earn no money" and "no month", but the default payout is $10 one time and a condition group pays $30 one time. Return two payoutFixes with amount 0. Omit maxDuration because it is already one time.
+- Copy says "every 3 months" but the payout duration is "one time". Return maxDuration 3 and omit amount if it already matches.
+- Copy says "earn $300" but the payout is a flat $10. Return amount 300 and omit maxDuration if it already matches.
-function serializeConditions(modifiers: ReviewRewardTooltipModifier[]) {
- return 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");
+Not contradictions:
+- Copy is shorter than the config or omits extra filters (country, product, metadata).
+- Informal wording that does not clearly specify a different amount, duration, operator, or threshold.`;
}
-function buildUserPrompt({
+function describeReward({
+ event,
tooltip,
+ description,
+ basePayout,
modifiers,
}: {
+ event: EventType;
tooltip: string;
+ description?: string | null;
+ basePayout: RewardPayout;
modifiers: ReviewRewardTooltipModifier[];
}) {
- return `Tooltip:
-"""
-${tooltip}
-"""
+ const shownAs = stripRewardTooltipMarkdown(description ?? "");
+
+ return {
+ event,
+ partnerCopy: {
+ shownAs: shownAs || null,
+ tooltip,
+ },
+ defaultPayout: {
+ pays: formatPayout(basePayout),
+ appliesWhen: "no condition group matches",
+ },
+ conditionGroups: modifiers.map((modifier, modifierIndex) => ({
+ modifierIndex,
+ match:
+ modifier.operator === "OR"
+ ? "any condition (OR)"
+ : "every condition (AND)",
+ when: modifier.conditions.map((condition, conditionIndex) => ({
+ conditionIndex,
+ rule: formatCondition(event, condition),
+ })),
+ thenPays: formatPayout(modifier.payout),
+ })),
+ };
+}
+
+function formatPayout(payout: RewardPayout) {
+ const amount =
+ payout.type === "percentage"
+ ? `${payout.amount ?? 0}% of the sale`
+ : `$${payout.amount ?? 0} flat`;
+ const duration =
+ payout.maxDuration == null
+ ? "for the customer's lifetime"
+ : payout.maxDuration === 0
+ ? "one time"
+ : `for ${payout.maxDuration} month${payout.maxDuration === 1 ? "" : "s"}`;
+
+ 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 nextAmount =
+ typeof fix.amount === "number" ? fix.amount : current.amount;
+ 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],
+) {
+ const attribute = getRewardConditionAttribute({
+ event,
+ entity: condition.entity,
+ attribute: condition.attribute,
+ });
+ const entity = REWARD_CONDITIONS[event].entities.find(
+ (entry) => entry.id === condition.entity,
+ );
+ const operator =
+ CONDITION_OPERATOR_LABELS[condition.operator] ?? condition.operator;
+ const field = condition.metadataField
+ ? `${attribute?.label ?? condition.attribute} (${condition.metadataField})`
+ : attribute?.label ?? condition.attribute;
+
+ return `${entity?.label ?? condition.entity} ${field} ${operator} ${formatConditionValue(attribute?.type, condition.value)}`;
+}
+
+function formatConditionValue(
+ type: string | undefined,
+ value: unknown,
+): string {
+ if (Array.isArray(value)) {
+ return value.map((item) => formatConditionValue(type, item)).join(", ");
+ }
+
+ if (
+ type === "currency" &&
+ typeof value === "number" &&
+ Number.isFinite(value)
+ ) {
+ return `$${value}`;
+ }
+
+ return String(value);
+}
-Conditions:
-${serializeConditions(modifiers)}
+function buildUserPrompt(reward: ReturnType<typeof describeReward>) {
+ return `Partner copy and the reward it must match:
+${JSON.stringify(reward, null, 2)}
-Write the reason for a non-technical user. Use the operator labels in parentheses, not the raw operator keys.`;
+Use modifierIndex and conditionIndex from conditionGroups when a condition should change. Write the reason for a non-technical user.`;
}
diff --git a/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts b/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
index 006ff5d15c..19bef35255 100644
--- a/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
+++ b/apps/web/tests/rewards/validate-tooltip-suggestion.test.ts
@@ -14,6 +14,7 @@ import { describe, expect, test } from "vitest";
const saleAmountModifiers: ReviewRewardTooltipModifier[] = [
{
operator: "AND",
+ payout: { type: "flat", amount: 10, maxDuration: 0 },
conditions: [
{
entity: "sale",
@@ -171,6 +172,7 @@ describe("filterValidatedTooltipSuggestions", () => {
modifiers: [
{
operator: "AND",
+ payout: { type: "flat", amount: 10, maxDuration: 0 },
conditions: [
{
entity: "customer",
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 d610d5bb57..a0a298047d 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -31,7 +31,6 @@ import { X } from "@/ui/shared/icons";
import {
Button,
Gift,
- LoadingSpinner,
MoneyBills2,
Pen2,
Sheet,
@@ -78,6 +77,7 @@ import { PartnerReferralRewardBuilder } from "./partner-referral-reward-builder"
import { RewardIconSquare } from "./reward-icon-square";
import { RewardPreviewCard } from "./reward-preview-card";
import { REWARD_TYPES, RewardsLogic } from "./rewards-logic";
+import { ReviewingSuggestedFixBadge } from "./suggested-fix-popover";
import {
RewardTooltipConsistencyContext,
useRewardTooltipConsistency,
@@ -388,6 +388,12 @@ function RewardSheetContent({
workspaceId,
event: selectedEvent,
tooltipDescription,
+ description,
+ baseReward: {
+ type,
+ amount,
+ maxDuration,
+ },
modifiers,
onApply: (suggestion) => {
const conditionKey =
@@ -402,6 +408,53 @@ function RewardSheetContent({
{ shouldDirty: true },
);
},
+ onApplyPayout: (fixes) => {
+ for (const fix of fixes) {
+ if (fix.scope === "default") {
+ if (typeof fix.amount === "number") {
+ setValue(
+ type === "percentage" ? "amountInPercentage" : "amountInCents",
+ fix.amount,
+ { shouldDirty: true },
+ );
+ }
+
+ if (fix.maxDuration !== undefined) {
+ setValue(
+ "maxDuration",
+ fix.maxDuration === null ? Infinity : fix.maxDuration,
+ { shouldDirty: true },
+ );
+ }
+
+ continue;
+ }
+
+ if (typeof fix.modifierIndex !== "number") continue;
+
+ const modifierKey = `modifiers.${fix.modifierIndex}` as const;
+ const modifier = getValues(modifierKey);
+ const payoutType = modifier?.type || type;
+
+ if (typeof fix.amount === "number") {
+ setValue(
+ payoutType === "percentage"
+ ? `${modifierKey}.amountInPercentage`
+ : `${modifierKey}.amountInCents`,
+ fix.amount,
+ { shouldDirty: true },
+ );
+ }
+
+ if (fix.maxDuration !== undefined) {
+ setValue(
+ `${modifierKey}.maxDuration`,
+ fix.maxDuration === null ? Infinity : fix.maxDuration,
+ { shouldDirty: true },
+ );
+ }
+ }
+ },
});
const isAiRewardEvent =
@@ -845,30 +898,36 @@ function RewardSheetContent({
/>
</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
+ {consistency.status === "reviewing" ||
+ consistency.note ||
+ (consistency.payoutFixes?.length ?? 0) > 0 ? (
+ <ReviewingSuggestedFixBadge
+ text={
+ tooltipDescription || "Reward tooltip"
}
/>
- </InlineBadgePopover>
- {consistency.status === "reviewing" && (
- <span className="ml-1.5 inline-flex items-center gap-1 align-middle text-xs font-medium text-neutral-500">
- <LoadingSpinner className="size-3" />
- Reviewing
- </span>
+ ) : (
+ <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
diff --git a/apps/web/ui/partners/rewards/suggested-fix-popover.tsx b/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
index 1230f1689f..4355abf1b8 100644
--- a/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
+++ b/apps/web/ui/partners/rewards/suggested-fix-popover.tsx
@@ -1,6 +1,9 @@
"use client";
-import type { TooltipSuggestion } from "@/lib/ai/review-reward-tooltip-schema";
+import type {
+ PayoutFix,
+ TooltipSuggestion,
+} from "@/lib/ai/review-reward-tooltip-schema";
import { formatRewardConditionParts } from "@/lib/rewards/format-reward-condition";
import {
applyTooltipSuggestion,
@@ -11,7 +14,7 @@ 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 { type ReactNode } from "react";
+import { type ReactNode, useRef, useState } from "react";
import { useWatch } from "react-hook-form";
import { useAddEditRewardForm } from "./add-edit-reward-sheet";
import {
@@ -22,6 +25,9 @@ import {
const POPOVER_CONTENT_CLASS_NAME =
"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]";
+const SUGGESTED_FIX_BADGE_CLASS_NAME =
+ "inline-flex max-w-full items-center gap-1 rounded bg-[#FFFBEB] px-1.5 text-left text-sm font-semibold leading-5 text-[#973C00] transition-colors";
+
export function SuggestedFixPopoverHost() {
const consistency = useRewardTooltipConsistencyContext();
@@ -145,19 +151,218 @@ export function SuggestedFixBadge({
consistency.showPage(thisIndex);
}}
- className="inline-block rounded bg-[#FFFBEB] px-1.5 text-left text-sm font-semibold text-[#973C00] transition-colors"
+ className={SUGGESTED_FIX_BADGE_CLASS_NAME}
>
- <span>
- <Sparkle3
- variant="fill"
- className="mr-1 inline-block size-3 align-middle text-[#E17100]"
- />
- {text}
- </span>
+ <Sparkle3 variant="fill" className="size-3 shrink-0 text-[#E17100]" />
+ <span className="min-w-0 truncate">{text}</span>
</button>
);
}
+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 || (!reviewing && !note && !payoutFixes.length)) return null;
+
+ const cancelHide = () => {
+ if (closeTimerRef.current) {
+ window.clearTimeout(closeTimerRef.current);
+ closeTimerRef.current = undefined;
+ }
+ };
+
+ const scheduleHide = () => {
+ cancelHide();
+ closeTimerRef.current = window.setTimeout(() => {
+ setOpen(false);
+ }, 300);
+ };
+
+ 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
+ </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" />
+ </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">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Discard"
+ className="h-7 w-fit rounded-lg px-3 py-2"
+ onClick={() => {
+ consistency.dismissNote();
+ setOpen(false);
+ }}
+ />
+ {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>
+ }
+ >
+ <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>
+ );
+}
+
+function PayoutFixPreview({ fixes }: { fixes: PayoutFix[] }) {
+ const { control } = useAddEditRewardForm();
+ const [
+ event,
+ type,
+ amountInCents,
+ amountInPercentage,
+ maxDuration,
+ modifiers,
+ ] = useWatch({
+ control,
+ name: [
+ "event",
+ "type",
+ "amountInCents",
+ "amountInPercentage",
+ "maxDuration",
+ "modifiers",
+ ],
+ });
+ const reason = fixes[0]?.reason;
+
+ return (
+ <>
+ <div className="flex min-h-16 w-full flex-col gap-2 rounded-[10px] border border-neutral-200 bg-white p-2.5 shadow-[0px_2px_4px_0px_#00000008]">
+ {fixes.map((fix) => {
+ const group =
+ fix.scope === "group" && typeof fix.modifierIndex === "number";
+ const modifier = group ? modifiers?.[fix.modifierIndex!] : null;
+ const payoutType =
+ (group ? modifier?.type || type : type) === "percentage"
+ ? "percentage"
+ : "flat";
+ const currentAmount =
+ payoutType === "percentage"
+ ? group
+ ? modifier?.amountInPercentage
+ : amountInPercentage
+ : group
+ ? modifier?.amountInCents
+ : amountInCents;
+ const currentDuration = group
+ ? modifier?.maxDuration === undefined
+ ? maxDuration
+ : modifier?.maxDuration
+ : maxDuration;
+ const nextAmount =
+ typeof fix.amount === "number" ? fix.amount : currentAmount;
+ const nextDuration =
+ fix.maxDuration === undefined ? currentDuration : fix.maxDuration;
+
+ return (
+ <p
+ key={group ? `group-${fix.modifierIndex}` : "default"}
+ className="min-w-0 text-sm font-medium leading-relaxed text-neutral-800"
+ >
+ {group ? "Then pay a" : "Pay a"}{" "}
+ <PreviewChip changed={typeof fix.amount === "number"}>
+ {formatPayoutAmount(payoutType, nextAmount)}
+ </PreviewChip>{" "}
+ per {event}{" "}
+ <PreviewChip changed={fix.maxDuration !== undefined}>
+ {formatPayoutDuration(nextDuration)}
+ </PreviewChip>
+ </p>
+ );
+ })}
+ </div>
+ {reason && <SuggestedFixReason reason={reason} />}
+ </>
+ );
+}
+
+function formatPayoutAmount(
+ type: "flat" | "percentage",
+ amount: number | null | undefined,
+) {
+ if (amount == null || Number.isNaN(amount)) return "amount";
+ return type === "percentage" ? `${amount}%` : `$${amount}`;
+}
+
+function formatPayoutDuration(maxDuration: number | null | undefined) {
+ if (maxDuration == null || !Number.isFinite(maxDuration)) {
+ return "for the customer's lifetime";
+ }
+
+ if (maxDuration === 0) return "one time";
+
+ return `for ${maxDuration} month${maxDuration === 1 ? "" : "s"}`;
+}
+
function SuggestedFixContent({
suggestion,
field,
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 c843e3913a..cd88bc6428 100644
--- a/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
+++ b/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
@@ -9,7 +9,9 @@ import {
screenRewardTooltipContradiction,
} from "@/lib/ai/review-reward-tooltip";
import type {
+ PayoutFix,
ReviewRewardTooltipModifier,
+ RewardPayout,
TooltipSuggestion,
} from "@/lib/ai/review-reward-tooltip-schema";
import {
@@ -34,13 +36,20 @@ import {
const DEBOUNCE_MS = 200;
const HIDE_MS = 300;
+const REVIEW_CACHE_VERSION = 2;
+const PAYOUT_MISMATCH_NOTE = "This copy doesn't match the reward payout.";
type TooltipReviewStatus = "idle" | "reviewing";
-const reviewCache = new Map<
- string,
- { flagged: boolean; suggestions: TooltipSuggestion[] }
->();
+type ReviewCacheEntry = {
+ v: typeof REVIEW_CACHE_VERSION;
+ flagged: boolean;
+ suggestions: TooltipSuggestion[];
+ payoutFixes: PayoutFix[];
+ note: string | null;
+};
+
+const reviewCache = new Map<string, ReviewCacheEntry>();
export function tooltipSuggestionPageKey({
modifierIndex,
@@ -79,6 +88,10 @@ type RewardTooltipConsistencyValue = {
acceptAll: () => void;
dismiss: (suggestion: TooltipSuggestion) => void;
dismissAll: () => void;
+ note: string | null;
+ payoutFixes: PayoutFix[];
+ acceptPayouts: () => void;
+ dismissNote: () => void;
};
export const RewardTooltipConsistencyContext =
@@ -92,14 +105,27 @@ export function useRewardTooltipConsistency({
workspaceId,
event,
tooltipDescription,
+ description,
+ baseReward,
modifiers,
onApply,
+ onApplyPayout,
}: {
workspaceId?: string;
event: EventType;
tooltipDescription?: string | null;
+ description?: string | null;
+ baseReward?: {
+ type?: string | null;
+ amount?: number | null;
+ maxDuration?: number | null;
+ } | null;
modifiers?: Array<{
operator?: "AND" | "OR";
+ type?: string | null;
+ amountInCents?: number | null;
+ amountInPercentage?: number | null;
+ maxDuration?: number | null;
conditions?: Array<{
entity?: string;
attribute?: string;
@@ -110,8 +136,11 @@ export function useRewardTooltipConsistency({
} | null>;
} | 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 [activeIndex, setActiveIndex] = useState(0);
const [open, setOpen] = useState(false);
@@ -122,17 +151,24 @@ export function useRewardTooltipConsistency({
const activeAnchorRef = useRef<HTMLElement | null>(null);
const tooltip = stripRewardTooltipMarkdown(tooltipDescription ?? "");
- const serializedModifiers = useMemo(
- () => serializeModifiersForReview({ event, modifiers }),
- [event, modifiers],
+ const serializedReward = useMemo(
+ () =>
+ serializeRewardForReview({
+ event,
+ description,
+ baseReward,
+ modifiers,
+ }),
+ [baseReward, description, event, modifiers],
);
+ const serializedModifiers = serializedReward?.modifiers ?? null;
const cacheKey = useMemo(() => {
if (
!workspaceId ||
!isAiRewardEvent(event) ||
!tooltip ||
- !serializedModifiers
+ !serializedReward
) {
return null;
}
@@ -140,29 +176,53 @@ export function useRewardTooltipConsistency({
return JSON.stringify({
event,
tooltip,
- modifiers: serializedModifiers,
+ reward: serializedReward,
});
- }, [event, serializedModifiers, tooltip, workspaceId]);
+ }, [event, serializedReward, tooltip, workspaceId]);
+
+ const serializedRewardRef = useRef(serializedReward);
+ serializedRewardRef.current = serializedReward;
useEffect(() => {
const requestId = ++requestIdRef.current;
- if (!cacheKey || !workspaceId || !isAiRewardEvent(event)) {
+ const reward = serializedRewardRef.current;
+
+ if (!cacheKey || !workspaceId || !isAiRewardEvent(event) || !reward) {
+ console.log("[reward-tooltip-review] skipped", {
+ workspaceId: workspaceId ?? null,
+ event,
+ tooltip: tooltip || null,
+ hasCompleteConditions: !!reward,
+ });
setSuggestions([]);
+ setPayoutFixes([]);
+ setNote(null);
setStatus("idle");
setActiveIndex(0);
return;
}
const cached = reviewCache.get(cacheKey);
- if (cached) {
+ if (cached?.v === REVIEW_CACHE_VERSION) {
+ const cachedNote = noteForFlaggedReward({
+ flagged: cached.flagged,
+ suggestions: cached.suggestions,
+ payoutFixes: cached.payoutFixes,
+ note: cached.note,
+ });
+ console.log("[reward-tooltip-review] cache hit", cached);
setSuggestions(cached.suggestions);
+ setPayoutFixes(cached.payoutFixes);
+ setNote(cachedNote);
setStatus("idle");
setActiveIndex(0);
return;
}
setSuggestions([]);
+ setPayoutFixes([]);
+ setNote(null);
setStatus("idle");
setActiveIndex(0);
const timeout = window.setTimeout(async () => {
@@ -173,7 +233,9 @@ export function useRewardTooltipConsistency({
workspaceId,
event,
tooltip,
- modifiers: serializedModifiers,
+ description: reward.description,
+ basePayout: reward.basePayout,
+ modifiers: reward.modifiers,
});
if (requestId !== requestIdRef.current) {
@@ -181,17 +243,27 @@ export function useRewardTooltipConsistency({
}
flagged = screen.flagged;
- } catch {
+ console.log("[reward-tooltip-review] jev", screen);
+ } catch (error) {
if (requestId !== requestIdRef.current) {
return;
}
+ console.log("[reward-tooltip-review] jev failed", error);
flagged = null;
}
if (flagged === false) {
- reviewCache.set(cacheKey, { flagged: false, suggestions: [] });
+ reviewCache.set(cacheKey, {
+ v: REVIEW_CACHE_VERSION,
+ flagged: false,
+ suggestions: [],
+ payoutFixes: [],
+ note: null,
+ });
setSuggestions([]);
+ setPayoutFixes([]);
+ setNote(null);
setStatus("idle");
setActiveIndex(0);
return;
@@ -206,7 +278,9 @@ export function useRewardTooltipConsistency({
workspaceId,
event,
tooltip,
- modifiers: serializedModifiers,
+ description: reward.description,
+ basePayout: reward.basePayout,
+ modifiers: reward.modifiers,
});
if (requestId !== requestIdRef.current) {
@@ -214,8 +288,28 @@ export function useRewardTooltipConsistency({
}
const next = result.suggestions ?? [];
- reviewCache.set(cacheKey, { flagged: true, suggestions: next });
+ const nextPayoutFixes = result.payoutFixes ?? [];
+ const nextNote = noteForFlaggedReward({
+ flagged,
+ suggestions: next,
+ payoutFixes: nextPayoutFixes,
+ note: result.note,
+ });
+ console.log("[reward-tooltip-review] haiku", {
+ suggestions: next,
+ payoutFixes: nextPayoutFixes,
+ note: nextNote,
+ });
+ reviewCache.set(cacheKey, {
+ v: REVIEW_CACHE_VERSION,
+ flagged: true,
+ suggestions: next,
+ payoutFixes: nextPayoutFixes,
+ note: nextNote,
+ });
setSuggestions(next);
+ setPayoutFixes(nextPayoutFixes);
+ setNote(nextNote);
setStatus("idle");
setActiveIndex(0);
} catch {
@@ -223,7 +317,24 @@ export function useRewardTooltipConsistency({
return;
}
+ const nextNote = noteForFlaggedReward({
+ flagged,
+ suggestions: [],
+ payoutFixes: [],
+ note: null,
+ });
+ if (nextNote) {
+ reviewCache.set(cacheKey, {
+ v: REVIEW_CACHE_VERSION,
+ flagged: true,
+ suggestions: [],
+ payoutFixes: [],
+ note: nextNote,
+ });
+ }
setSuggestions([]);
+ setPayoutFixes([]);
+ setNote(nextNote);
setStatus("idle");
setActiveIndex(0);
}
@@ -232,7 +343,7 @@ export function useRewardTooltipConsistency({
return () => {
window.clearTimeout(timeout);
};
- }, [cacheKey, event, serializedModifiers, tooltip, workspaceId]);
+ }, [REVIEW_CACHE_VERSION, cacheKey, event, tooltip, workspaceId]);
const visibleSuggestions = useMemo(() => {
if (!serializedModifiers?.length) return [];
@@ -413,6 +524,27 @@ export function useRewardTooltipConsistency({
hide();
}, [dismissAll, hide]);
+ const dismissNote = useCallback(() => {
+ setNote(null);
+ setPayoutFixes([]);
+
+ if (!cacheKey) return;
+
+ const cached = reviewCache.get(cacheKey);
+ if (cached) {
+ reviewCache.set(cacheKey, {
+ ...cached,
+ note: null,
+ payoutFixes: [],
+ });
+ }
+ }, [cacheKey]);
+
+ const acceptPayouts = useCallback(() => {
+ onApplyPayout?.(payoutFixes);
+ dismissNote();
+ }, [dismissNote, onApplyPayout, payoutFixes]);
+
return {
status,
suggestions: visibleSuggestions,
@@ -431,6 +563,10 @@ export function useRewardTooltipConsistency({
acceptAll,
dismiss: dismissAndHide,
dismissAll: dismissAllAndHide,
+ note,
+ payoutFixes,
+ acceptPayouts,
+ dismissNote,
};
}
@@ -438,6 +574,26 @@ 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 PAYOUT_MISMATCH_NOTE;
+
+ return null;
+}
+
function dismissalKey(
suggestion: TooltipSuggestion,
current: { operator: string; value: unknown },
@@ -452,13 +608,25 @@ function dismissalKey(
].join(":");
}
-function serializeModifiersForReview({
+function serializeRewardForReview({
event,
+ description,
+ baseReward,
modifiers,
}: {
event: EventType;
+ description?: string | null;
+ baseReward?: {
+ type?: string | null;
+ amount?: number | null;
+ maxDuration?: number | null;
+ } | null;
modifiers?: Array<{
operator?: "AND" | "OR";
+ type?: string | null;
+ amountInCents?: number | null;
+ amountInPercentage?: number | null;
+ maxDuration?: number | null;
conditions?: Array<{
entity?: string;
attribute?: string;
@@ -468,8 +636,13 @@ function serializeModifiersForReview({
metadataField?: string;
} | null>;
} | null> | null;
-}): ReviewRewardTooltipModifier[] | null {
- if (!isAiRewardEvent(event) || !modifiers?.length) return null;
+}): {
+ description: string | null;
+ basePayout: RewardPayout;
+ modifiers: ReviewRewardTooltipModifier[];
+} | null {
+ const basePayout = toBasePayout(baseReward);
+ if (!isAiRewardEvent(event) || !basePayout || !modifiers?.length) return null;
if (
!modifiers.every(
(modifier) =>
@@ -482,34 +655,95 @@ function serializeModifiersForReview({
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,
- });
+ const shownAs = stripRewardTooltipMarkdown(description ?? "");
- let value = condition?.value;
- if (
- attribute &&
- ["number", "currency", "date"].includes(attribute.type) &&
- !Array.isArray(value)
- ) {
- value = Number(value);
+ return {
+ description: shownAs || null,
+ basePayout,
+ modifiers: modifiers.map((modifier) => ({
+ operator: modifier?.operator ?? "AND",
+ payout: resolveModifierPayout(modifier, basePayout),
+ 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,
+ };
+ }),
+ })),
+ };
+}
+
+function toBasePayout(
+ baseReward?: {
+ type?: string | null;
+ amount?: number | null;
+ maxDuration?: number | null;
+ } | null,
+): RewardPayout | null {
+ if (baseReward?.type !== "flat" && baseReward?.type !== "percentage") {
+ return null;
+ }
+
+ return {
+ type: baseReward.type,
+ amount: baseReward.amount ?? null,
+ maxDuration: normalizeDuration(baseReward.maxDuration),
+ };
+}
+
+function resolveModifierPayout(
+ modifier:
+ | {
+ type?: string | null;
+ amountInCents?: number | null;
+ amountInPercentage?: number | null;
+ maxDuration?: number | null;
}
+ | null
+ | undefined,
+ basePayout: RewardPayout,
+): RewardPayout {
+ const type =
+ modifier?.type === "flat" || modifier?.type === "percentage"
+ ? modifier.type
+ : basePayout.type;
+ const amount =
+ type === "percentage"
+ ? modifier?.amountInPercentage ?? basePayout.amount
+ : modifier?.amountInCents ?? basePayout.amount;
+
+ return {
+ type,
+ amount: amount ?? null,
+ maxDuration:
+ modifier?.maxDuration === undefined
+ ? basePayout.maxDuration
+ : normalizeDuration(modifier.maxDuration),
+ };
+}
- 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,
- };
- }),
- }));
+function normalizeDuration(maxDuration: number | null | undefined) {
+ if (maxDuration == null || !Number.isFinite(maxDuration)) return null;
+ return maxDuration;
}