Skip to content

Open source CapCut alternative.

TypeScript

feat(site): credit offers carry a kind, a claim window and the credit's expiry

David Le1ce05e7b2216
diff --git a/site/prisma/Credits.prisma b/site/prisma/Credits.prisma
index da1b32dd..374782ac 100644
--- a/site/prisma/Credits.prisma
+++ b/site/prisma/Credits.prisma
@@ -41,24 +41,36 @@ model UserCreditGrant {
@@map("user_credit_grant")
}
-// Credit given by hand waits here until the person claims it from the email
-// they were sent. The claim makes the grant, with the lifetime counted from
-// the claim; until then nothing reaches the balance.
+// A credit offer: credit promised to an account, landing as a grant when the
+// account claims it. Kinds differ in what makes the offer and what claims it:
+// a manual one is claimed from the email it was sent in, a promotion's by the
+// act it rewards, within its window. The row carries what was promised, so a
+// later change to a setting leaves a shown offer as shown, and every kind
+// shares the one shape: a new promotion is a setting and code.
model CreditOffer {
id String @id @default(cuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ // What made the offer: "manual" from su, or the promotion's key.
+ kind String @default("manual")
amountMicros BigInt
+ // The credit's life once claimed: a fixed moment, or days from the claim;
+ // neither keeps it forever.
+ expiresAt DateTime?
expiresAfterDays Int?
+ // The last moment the offer can be claimed; null keeps it open.
+ closesAt DateTime?
description String?
- offeredByUserId String
+ // Whatever else the kind promised, in the kind's own shape.
+ terms Json?
+ offeredByUserId String?
emailSentAt DateTime?
claimedAt DateTime?
grantId String? @unique
grant UserCreditGrant? @relation(fields: [grantId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
- @@index([userId])
+ @@index([userId, kind])
@@map("credit_offer")
}
diff --git a/site/prisma/migrations/20260907070826/migration.sql b/site/prisma/migrations/20260907070826/migration.sql
new file mode 100644
index 00000000..cb92b14c
--- /dev/null
+++ b/site/prisma/migrations/20260907070826/migration.sql
@@ -0,0 +1,27 @@
+/*
+ Warnings:
+
+ - You are about to drop the `subscribe_bonus_offer` table. If the table is not empty, all the data it contains will be lost.
+
+*/
+-- DropForeignKey
+ALTER TABLE "subscribe_bonus_offer" DROP CONSTRAINT "subscribe_bonus_offer_grantId_fkey";
+
+-- DropForeignKey
+ALTER TABLE "subscribe_bonus_offer" DROP CONSTRAINT "subscribe_bonus_offer_userId_fkey";
+
+-- DropIndex
+DROP INDEX "credit_offer_userId_idx";
+
+-- AlterTable
+ALTER TABLE "credit_offer" ADD COLUMN "closesAt" TIMESTAMP(3),
+ADD COLUMN "expiresAt" TIMESTAMP(3),
+ADD COLUMN "kind" TEXT NOT NULL DEFAULT 'manual',
+ADD COLUMN "terms" JSONB,
+ALTER COLUMN "offeredByUserId" DROP NOT NULL;
+
+-- DropTable
+DROP TABLE "subscribe_bonus_offer";
+
+-- CreateIndex
+CREATE INDEX "credit_offer_userId_kind_idx" ON "credit_offer"("userId", "kind");
diff --git a/site/src/lib/credits/offers.ts b/site/src/lib/credits/offers.ts
index a2c8dad7..3d68de66 100644
--- a/site/src/lib/credits/offers.ts
+++ b/site/src/lib/credits/offers.ts
@@ -1,5 +1,6 @@
import { createHmac, timingSafeEqual } from "node:crypto";
+import type { CreditOffer } from "@/generated/prisma/client";
import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
import { grantCredits } from "@/lib/credits/inference";
import { creditGrantExpiry } from "@/lib/credits/top-up";
@@ -11,6 +12,9 @@ import { prisma } from "@/lib/prisma";
// unsubscribe link. The claim itself also needs the offered account's session.
const TOKEN_DOMAIN = "donkey-credit-offer-v1";
+// The kind su makes by hand; a promotion's offers carry the promotion's key.
+export const MANUAL_OFFER_KIND = "manual";
+
function signature(offerId: string): Buffer {
const secret = process.env.BETTER_AUTH_SECRET;
if (!secret) throw new Error("BETTER_AUTH_SECRET is not set.");
@@ -55,6 +59,7 @@ export async function createCreditOffer(input: {
claimedAt: null,
emailSentAt: null,
expiresAfterDays: input.expiresAfterDays,
+ kind: MANUAL_OFFER_KIND,
userId: input.user.id,
},
})) ??
@@ -63,6 +68,7 @@ export async function createCreditOffer(input: {
amountMicros: input.amountMicros,
description: input.description,
expiresAfterDays: input.expiresAfterDays,
+ kind: MANUAL_OFFER_KIND,
offeredByUserId: input.offeredByUserId,
userId: input.user.id,
},
@@ -81,28 +87,47 @@ export async function createCreditOffer(input: {
export class CreditOfferNotYoursError extends Error {}
-// Makes the grant for a claimed offer. The grant dedupes on the offer id, so
-// a second click returns the first claim.
-export async function claimCreditOffer(offerId: string, userId: string) {
- const offer = await prisma.creditOffer.findUnique({ where: { id: offerId } });
- if (!offer) return null;
- if (offer.userId !== userId) throw new CreditOfferNotYoursError();
+/** Whether an offer can still be claimed now. */
+export function creditOfferOpen(offer: { claimedAt: Date | null; closesAt: Date | null }, now: Date): boolean {
+ return offer.claimedAt === null && (offer.closesAt === null || now.getTime() <= offer.closesAt.getTime());
+}
+
+/** Lands an offer as a grant and records the claim. The grant dedupes on
+ * its source id, so landing twice returns the first grant; a kind whose
+ * offers must land once per account keys the id on the account. */
+export async function landCreditOffer(
+ offer: CreditOffer,
+ grant: { source: string; sourceId: string; description: string },
+) {
if (offer.claimedAt && offer.grantId) {
- const grant = await prisma.userCreditGrant.findUnique({ where: { id: offer.grantId } });
- if (grant) return { grant, offer };
+ const existing = await prisma.userCreditGrant.findUnique({ where: { id: offer.grantId } });
+ if (existing) return { grant: existing, offer };
}
- const grant = await grantCredits({
+ const landed = await grantCredits({
amountMicros: offer.amountMicros,
- description: offer.description ?? "Manual credit grant",
- expiresAt: creditGrantExpiry(offer.expiresAfterDays),
- metadata: { expiresAfterDays: offer.expiresAfterDays, offerId: offer.id, offeredByUserId: offer.offeredByUserId },
- source: "manual_dollar",
- sourceId: `offer:${offer.id}`,
- userId,
+ description: offer.description ?? grant.description,
+ expiresAt: offer.expiresAt ?? creditGrantExpiry(offer.expiresAfterDays),
+ metadata: { kind: offer.kind, offerId: offer.id, offeredByUserId: offer.offeredByUserId },
+ source: grant.source,
+ sourceId: grant.sourceId,
+ userId: offer.userId,
});
const claimed = await prisma.creditOffer.update({
- data: { claimedAt: new Date(), grantId: grant.id },
+ data: { claimedAt: new Date(), grantId: landed.id },
where: { id: offer.id },
});
- return { grant, offer: claimed };
+ return { grant: landed, offer: claimed };
+}
+
+// Claims a manual offer from its email link. An email token never names a
+// promotion's offer; those land from the act they reward.
+export async function claimCreditOffer(offerId: string, userId: string) {
+ const offer = await prisma.creditOffer.findUnique({ where: { id: offerId } });
+ if (!offer || offer.kind !== MANUAL_OFFER_KIND) return null;
+ if (offer.userId !== userId) throw new CreditOfferNotYoursError();
+ return landCreditOffer(offer, {
+ description: "Manual credit grant",
+ source: "manual_dollar",
+ sourceId: `offer:${offer.id}`,
+ });
}