Files
cfw-autumn/server/tests/advanced/coupons/coupon1.test.ts
2025-11-08 19:31:38 +00:00

242 lines
5.6 KiB
TypeScript

import { beforeAll, describe, expect, test } from "bun:test";
import {
type AppEnv,
CouponDurationType,
type CreateReward,
LegacyVersion,
type Organization,
RewardType,
} from "@autumn/shared";
import chalk from "chalk";
import { addHours, addMonths } from "date-fns";
import type Stripe from "stripe";
import { TestFeature } from "tests/setup/v2Features.js";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { getExpectedInvoiceTotal } from "tests/utils/expectUtils/expectInvoiceUtils.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { timeout } from "tests/utils/genUtils.js";
import { createReward } from "tests/utils/productUtils.js";
import {
advanceTestClock,
completeCheckoutForm,
getDiscount,
} from "tests/utils/stripeUtils.js";
import ctx from "tests/utils/testInitUtils/createTestContext.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { getOriginalCouponId } from "@/internal/rewards/rewardUtils.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomerV3 } from "@/utils/scriptUtils/testUtils/initCustomerV3.js";
import { initProductsV0 } from "@/utils/scriptUtils/testUtils/initProductsV0.js";
const testCase = "coupon1";
const pro = constructProduct({
type: "pro",
items: [constructArrearItem({ featureId: TestFeature.Words })],
});
// Create reward inline - matching rolloverAll config from global.ts
const rewardId = `${testCase}rolloverAll`;
const promoCode = `${testCase}rolloverAllCode`;
const reward: CreateReward = {
id: rewardId,
name: "Rollover All",
type: RewardType.InvoiceCredits,
promo_codes: [{ code: promoCode }],
discount_config: {
discount_value: 1000,
duration_type: CouponDurationType.Forever,
duration_value: 0,
should_rollover: true,
apply_to_all: true,
price_ids: [],
},
};
const simulateOneCycle = async ({
customerId,
db,
org,
env,
stripeCli,
autumn,
testClockId,
couponAmount,
curUnix,
}: {
customerId: string;
db: DrizzleCli;
org: Organization;
env: AppEnv;
stripeCli: Stripe;
autumn: AutumnInt;
testClockId: string;
couponAmount: number;
curUnix: number;
}) => {
const usage = Math.random() * 100000 + 10000;
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Words,
value: usage,
});
// Expected invoice total
const expectedTotal = await getExpectedInvoiceTotal({
usage: [{ featureId: TestFeature.Words, value: usage }],
customerId,
productId: pro.id,
db,
org,
env,
stripeCli,
});
couponAmount -= expectedTotal;
curUnix = await advanceTestClock({
stripeCli,
testClockId,
advanceTo: addHours(
addMonths(curUnix, 1),
hoursToFinalizeInvoice,
).getTime(),
waitForSeconds: 30,
});
const customer = await autumn.customers.get(customerId);
expect(customer.invoices![0].total).toBe(0);
const cusDiscount = await getDiscount({
stripeCli: stripeCli,
stripeId: customer.stripe_id!,
});
expect(cusDiscount).toBeDefined();
expect(getOriginalCouponId(cusDiscount.coupon?.id)).toBe(rewardId);
expect(cusDiscount.coupon?.amount_off).toBe(Math.round(couponAmount * 100));
return {
couponAmount,
curUnix,
};
};
describe(
chalk.yellow(
`${testCase} - Testing invoice credits reward, apply to all product`,
),
() => {
const customerId = "coupon1";
let stripeCli: Stripe;
let testClockId: string;
let db: DrizzleCli;
let org: Organization;
let env: AppEnv;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let couponAmount = reward.discount_config!.discount_value;
let curUnix = Date.now();
beforeAll(async () => {
db = ctx.db;
org = ctx.org;
env = ctx.env;
stripeCli = ctx.stripeCli;
await initProductsV0({
ctx,
products: [pro],
prefix: testCase,
customerId,
});
const res = await initCustomerV3({
ctx,
customerId,
});
await createReward({
orgId: org.id,
env,
db,
autumn,
reward,
productId: pro.id,
});
testClockId = res.testClockId;
});
// CYCLE 0
test("should attach pro", async () => {
const res = await autumn.attach({
customer_id: customerId,
product_id: pro.id,
});
await completeCheckoutForm(res.checkout_url, undefined, promoCode);
await timeout(10000);
couponAmount -= getBasePrice({ product: pro });
const customer = await autumn.customers.get(customerId);
expectProductAttached({ customer, product: pro });
expect(customer.invoices![0].total).toBe(0);
console.log("Customer", customer);
const cusDiscount = await getDiscount({
stripeCli,
stripeId: customer.stripe_id!,
});
// console.log("CusDiscount", cusDiscount);
expect(cusDiscount).toBeDefined();
expect(getOriginalCouponId(cusDiscount.coupon?.id)).toBe(rewardId);
expect(cusDiscount.coupon?.amount_off).toBe(couponAmount * 100);
});
test("should run one cycle and have correct invoice + coupon amount", async () => {
const res = await simulateOneCycle({
customerId,
db,
org,
env,
stripeCli,
autumn,
testClockId,
couponAmount,
curUnix: Date.now(),
});
couponAmount = res.couponAmount;
curUnix = res.curUnix;
});
// CYCLE 1
test("should run another cycle and have correct invoice + coupon amount", async () => {
await simulateOneCycle({
customerId,
db,
org,
env,
stripeCli,
autumn,
testClockId,
couponAmount,
curUnix,
});
});
},
);