File size: 9,458 Bytes
689359a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import { getStripeClient } from "@/lib/stripe";
import { fetchBackend } from "@/server/backend-api";
import type { getPrismaClient } from "@/server/prisma";

type PrismaClient = ReturnType<typeof getPrismaClient>;

/**
 * Creator (affiliate) program.
 *
 * A signed-in user applies with a slug (`maya`). An admin approves it, which
 * creates the Stripe promotion code `MAYA` on the shared creator coupon (20%
 * off for 3 months) and gives the creator Pro for free. Their audience gets
 * the discount through `?ref=maya` or by typing the code at checkout.
 */

export const AFFILIATE_PLATFORMS = ["tiktok", "youtube", "instagram", "x", "other"] as const;
export const AUDIENCE_SIZES = ["under-1k", "1k-10k", "10k-100k", "100k-plus"] as const;
export const REAPPLY_AFTER_DAYS = 30;
/** Entitlement owner for Pro granted by the program (see the Stripe/Apple webhooks' provider filters). */
export const AFFILIATE_PROVIDER = "affiliate";
/** Error `code` checkout returns when a creator code can't be applied; the client then drops it. */
export const INVALID_CREATOR_CODE = "invalid_creator_code";

const RESERVED_SLUGS = new Set([
  "admin", "affiliate", "affiliates", "api", "billing", "creator", "creators", "free", "help",
  "official", "pro", "scale", "settings", "staff", "support", "supoclip", "team", "test",
]);
const SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{1,18})[a-z0-9]$/;

export function creatorCouponId() {
  return process.env.STRIPE_CREATOR_COUPON_ID || "creator-20-3mo";
}

export type SlugCheck = { ok: true; slug: string } | { ok: false; error: string };

export function validateSlug(raw: unknown): SlugCheck {
  const slug = typeof raw === "string" ? raw.trim().toLowerCase() : "";
  if (slug.length < 3 || slug.length > 20) {
    return { ok: false, error: "Use 3 to 20 characters." };
  }
  if (!SLUG_PATTERN.test(slug) || slug.includes("--")) {
    return { ok: false, error: "Use letters, numbers and single hyphens, starting and ending with a letter or number." };
  }
  if (RESERVED_SLUGS.has(slug) || slug.startsWith("supoclip")) {
    return { ok: false, error: "That code is reserved." };
  }
  return { ok: true, slug };
}

/** A slug is free unless another user's pending, approved or revoked application holds it. */
export async function isSlugAvailable(prisma: PrismaClient, slug: string, userId: string) {
  const holder = await prisma.affiliate.findUnique({ where: { slug }, select: { user_id: true } });
  return !holder || holder.user_id === userId;
}

export type AffiliateApplication = {
  slug: string;
  platform: (typeof AFFILIATE_PLATFORMS)[number];
  profile_url: string;
  audience_size: (typeof AUDIENCE_SIZES)[number];
  video_url: string | null;
  promotion_plan: string | null;
};

function parseUrl(raw: unknown, label: string, required: boolean): { value: string | null } | { error: string } {
  const value = typeof raw === "string" ? raw.trim() : "";
  if (!value) return required ? { error: `${label} is required.` } : { value: null };
  try {
    const url = new URL(value);
    if ((url.protocol !== "https:" && url.protocol !== "http:") || value.length > 500) throw new Error();
  } catch {
    return { error: `${label} must be a full link starting with https://` };
  }
  return { value };
}

export function parseApplication(body: unknown): { ok: true; application: AffiliateApplication } | { ok: false; error: string } {
  const input = (body && typeof body === "object" ? body : {}) as Record<string, unknown>;

  const slug = validateSlug(input.slug);
  if (!slug.ok) return slug;

  const platform = AFFILIATE_PLATFORMS.find((value) => value === input.platform);
  if (!platform) return { ok: false, error: "Pick the platform you post on." };

  const audience = AUDIENCE_SIZES.find((value) => value === input.audience_size);
  if (!audience) return { ok: false, error: "Pick your audience size." };

  const profile = parseUrl(input.profile_url, "Profile link", true);
  if ("error" in profile) return { ok: false, error: profile.error };
  const video = parseUrl(input.video_url, "Video link", false);
  if ("error" in video) return { ok: false, error: video.error };

  const plan = typeof input.promotion_plan === "string" ? input.promotion_plan.trim() : "";
  if (plan.length > 1000) return { ok: false, error: "Keep your plan under 1000 characters." };

  if (input.accept_terms !== true) {
    return { ok: false, error: "Please accept the program terms." };
  }

  return {
    ok: true,
    application: {
      slug: slug.slug,
      platform,
      profile_url: profile.value as string,
      audience_size: audience,
      video_url: video.value,
      promotion_plan: plan || null,
    },
  };
}

type ExistingApplication = { status: string; reviewed_at: Date | null } | null;

/** When the user may (re)apply, or null if they can't right now. */
export function applyAvailableAt(existing: ExistingApplication, now = new Date()): Date | null {
  if (!existing) return now;
  if (existing.status !== "declined") return null;
  const reviewedAt = existing.reviewed_at ?? now;
  return new Date(Math.max(now.getTime(), reviewedAt.getTime() + REAPPLY_AFTER_DAYS * 24 * 60 * 60 * 1000));
}

export type CreatorOffer = {
  /** Null for a house code, which no creator owns. */
  affiliateUserId: string | null;
  code: string;
  promotionCodeId: string;
};

/** The approved affiliate (or house code) behind a ref/code, or null. */
export async function findCreatorOffer(prisma: PrismaClient, rawCode: string): Promise<CreatorOffer | null> {
  const slug = validateSlug(rawCode);
  if (!slug.ok) return null;
  const affiliate = await prisma.affiliate.findUnique({
    where: { slug: slug.slug },
    select: { user_id: true, status: true, stripe_promotion_code_id: true },
  });
  if (!affiliate) return findHouseOffer(slug.slug);
  if (affiliate.status !== "approved" || !affiliate.stripe_promotion_code_id) return null;
  return {
    affiliateUserId: affiliate.user_id,
    code: slug.slug.toUpperCase(),
    promotionCodeId: affiliate.stripe_promotion_code_id,
  };
}

/**
 * A house code: an active Stripe promotion code on the creator coupon that no
 * creator owns, e.g. `PRODUCTHUNT` for a launch. It's created by hand in Stripe,
 * which also enforces its expiry and redemption limits.
 */
async function findHouseOffer(slug: string): Promise<CreatorOffer | null> {
  const code = slug.toUpperCase();
  const { data } = await getStripeClient().promotionCodes.list({ code, active: true, limit: 1 });
  const promotionCode = data[0];
  const coupon = promotionCode?.promotion.coupon;
  const couponId = typeof coupon === "string" ? coupon : coupon?.id;
  if (!promotionCode || couponId !== creatorCouponId()) return null;
  if (promotionCode.expires_at && promotionCode.expires_at * 1000 <= Date.now()) return null;
  return { affiliateUserId: null, code, promotionCodeId: promotionCode.id };
}

/** Gives Pro to a creator who isn't already paying; never touches a paid Stripe or App Store plan. */
export async function grantAffiliatePro(prisma: PrismaClient, userId: string) {
  await prisma.user.updateMany({
    where: {
      id: userId,
      OR: [
        { subscription_provider: AFFILIATE_PROVIDER },
        { subscription_status: { notIn: ["active", "trialing"] } },
      ],
    },
    data: { plan: "pro", subscription_status: "active", subscription_provider: AFFILIATE_PROVIDER },
  });
}

/**
 * When a paid Stripe or App Store plan ends, an approved creator falls back to
 * their free Pro instead of Free. Returns whether it was restored.
 */
export async function restoreAffiliateProIfApproved(prisma: PrismaClient, userId: string) {
  const affiliate = await prisma.affiliate.findUnique({ where: { user_id: userId }, select: { status: true } });
  if (affiliate?.status !== "approved") return false;
  await grantAffiliatePro(prisma, userId);
  return true;
}

/** Best effort: an inactive code is never applied by our checkout anyway, this just frees it in Stripe. */
export async function deactivatePromotionCode(promotionCodeId: string) {
  try {
    await getStripeClient().promotionCodes.update(promotionCodeId, { active: false });
  } catch (error) {
    console.error(`Failed to deactivate Stripe promotion code ${promotionCodeId}`, error);
  }
}

export async function revokeAffiliatePro(prisma: PrismaClient, userId: string) {
  await prisma.user.updateMany({
    where: { id: userId, subscription_provider: AFFILIATE_PROVIDER },
    data: { plan: "free", subscription_status: "inactive", subscription_provider: null },
  });
}

type AffiliateEmail =
  | { event: "applied"; slug: string; platform: string; profile_url: string; audience_size: string; video_url: string | null; promotion_plan: string | null }
  | { event: "approved"; slug: string }
  | { event: "declined"; slug: string; decline_reason: string | null };

/** Fire-and-forget: a failed email must never fail the application or review. */
export function sendAffiliateEmail(userId: string, email: AffiliateEmail) {
  void fetchBackend("/account/affiliate-email", {
    method: "POST",
    userId,
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(email),
    cache: "no-store",
  })
    .then(async (response) => {
      if (!response.ok) {
        console.error(`Affiliate ${email.event} email failed with ${response.status}: ${await response.text()}`);
      }
    })
    .catch((error) => console.error(`Affiliate ${email.event} email failed`, error));
}