working on api versioninf system

This commit is contained in:
John Yeo
2025-10-04 14:07:18 +01:00
parent dc0546cc67
commit 700e96bdcc
206 changed files with 3649 additions and 3870 deletions

View File

@@ -47,6 +47,7 @@
"@react-email/components": "^0.0.42",
"@sentry/node": "^9.30.0",
"@supabase/supabase-js": "^2.46.2",
"@types/semver": "^7.7.1",
"@upstash/redis": "^1.35.1",
"ai": "^4.3.10",
"autumn-js": "^0.1.8",
@@ -88,6 +89,7 @@
"react": "^18.2.0",
"recaseai": "^0.0.37",
"resend": "^4.1.1",
"semver": "^7.7.2",
"stripe": "^18.4.0",
"svix": "^1.45.1",
"tsc-alias": "^1.8.16",
@@ -1187,6 +1189,8 @@
"@types/recharts": ["@types/recharts@2.0.1", "", { "dependencies": { "recharts": "*" } }, "sha512-/cFs7oiafzByUwBSWA1IzE6FW+ppPwQAWsDTadSgVOwzveY9MESpyLHyyHY0SfPPKLW4+4qVNYHPXd0rFiC8vg=="],
"@types/semver": ["@types/semver@7.7.1", "", {}, "sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA=="],
"@types/send": ["@types/send@0.17.5", "", { "dependencies": { "@types/mime": "^1", "@types/node": "*" } }, "sha512-z6F2D3cOStZvuk2SaP6YrwkNO65iTZcwA2ZkSABegdkAh/lf+Aa/YQndZVfmEXT5vgAp6zv06VQ3ejSVjAny4w=="],
"@types/serve-static": ["@types/serve-static@1.15.8", "", { "dependencies": { "@types/http-errors": "*", "@types/node": "*", "@types/send": "*" } }, "sha512-roei0UY3LhpOJvjbIP6ZZFngyLKl5dskOtDhxY5THRSpO+ZI+nzJ+m5yUMzGrp89YRa7lvknKkMYjqQFGwA7Sg=="],

View File

@@ -10,7 +10,6 @@
"dev": "cross-env NODE_ENV=development bunx nodemon --exec bun src/index.ts --ignore scripts --ignore tests",
"workers:dev": "cross-env NODE_ENV=development bunx nodemon --exec bun src/workers.ts --watch src/workers.ts --watch src/queue --ignore scripts --ignore tests",
"workers": "bun src/workers.ts",
"cron": "bun src/cron.ts",
"check": "bun src/check.ts",
"build": "bun build ./src/index.ts ./src/workers.ts ./src/cron.ts --outdir dist --target bun",
@@ -50,6 +49,7 @@
"@react-email/components": "^0.0.42",
"@sentry/node": "^9.30.0",
"@supabase/supabase-js": "^2.46.2",
"@types/semver": "^7.7.1",
"@upstash/redis": "^1.35.1",
"ai": "^4.3.10",
"autumn-js": "^0.1.8",
@@ -91,6 +91,7 @@
"react": "^18.2.0",
"recaseai": "^0.0.37",
"resend": "^4.1.1",
"semver": "^7.7.2",
"stripe": "^18.4.0",
"svix": "^1.45.1",
"tsc-alias": "^1.8.16",

View File

@@ -4,13 +4,13 @@ import dotenv from "dotenv";
dotenv.config();
import {
type APIVersion,
type AttachBody,
type CreateEntity,
type CreateRewardProgram,
CusExpand,
EntityExpand,
ErrCode,
type LegacyVersion,
type OrgConfig,
type RewardRedemption,
} from "@autumn/shared";
@@ -56,7 +56,7 @@ export class AutumnInt {
apiKey?: string;
secretKey?: string;
baseUrl?: string;
version?: string | APIVersion;
version?: string | LegacyVersion;
orgConfig?: Partial<OrgConfig>;
liveUrl?: boolean;
} = {}) {

View File

@@ -1,5 +1,4 @@
import {
APIVersion,
BillingType,
type EntitlementWithFeature,
ErrCode,
@@ -7,6 +6,7 @@ import {
type FixedPriceConfig,
type FullProduct,
InternalError,
LegacyVersion,
type Organization,
type Price,
type ProductOptions,
@@ -69,7 +69,7 @@ export const priceToStripeItem = ({
existingUsage: number;
withEntity: boolean;
isCheckout: boolean;
apiVersion?: APIVersion;
apiVersion?: LegacyVersion;
productOptions?: ProductOptions | undefined;
}) => {
// TODO: Implement this
@@ -140,7 +140,7 @@ export const priceToStripeItem = ({
};
}
if (apiVersion === APIVersion.v1_4 && !isCheckout) {
if (apiVersion === LegacyVersion.v1_4 && !isCheckout) {
return {
lineItem: {
// lineItem: getEmptyPriceItem({ price, org }),

View File

@@ -1,5 +1,4 @@
import {
type APIVersion,
type AttachConfig,
type AttachReplaceable,
BillingInterval,
@@ -10,6 +9,7 @@ import {
type FullProduct,
InternalError,
isUsagePrice,
type LegacyVersion,
type Organization,
type Price,
type ProductOptions,
@@ -79,7 +79,7 @@ export const getStripeSubItems = async ({
internalEntityId?: string;
cusProducts?: FullCusProduct[];
entities: Entity[];
apiVersion?: APIVersion;
apiVersion?: LegacyVersion;
replaceables: AttachReplaceable[];
};
isCheckout?: boolean;

View File

@@ -1,16 +1,19 @@
import { DrizzleCli } from "@/db/initDrizzle.js";
import { APIVersion, BillingType, UsagePriceConfig } from "@autumn/shared";
import Stripe from "stripe";
import { SubService } from "@/internal/subscriptions/SubService.js";
import { constructSub } from "@/internal/subscriptions/subUtils.js";
import { AttachParams } from "@/internal/customers/cusProducts/AttachParams.js";
import {
BillingType,
LegacyVersion,
type UsagePriceConfig,
} from "@autumn/shared";
import type Stripe from "stripe";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import type { AttachParams } from "@/internal/customers/cusProducts/AttachParams.js";
import {
findPriceFromPlaceholderId,
findPriceFromStripeId,
} from "@/internal/products/prices/priceUtils/findPriceUtils.js";
import { getArrearItems } from "../../stripeSubUtils/getStripeSubItems/getArrearItems.js";
import { subToPeriodStartEnd } from "../../stripeSubUtils/convertSubUtils.js";
import { SubService } from "@/internal/subscriptions/SubService.js";
import { constructSub } from "@/internal/subscriptions/subUtils.js";
import { getEmptyPriceItem } from "../../priceToStripeItem/priceToStripeItem.js";
import { subToPeriodStartEnd } from "../../stripeSubUtils/convertSubUtils.js";
export const handleCheckoutSub = async ({
stripeCli,
@@ -44,12 +47,12 @@ export const handleCheckoutSub = async ({
});
const curSubItems = subscription.items.data;
let itemsUpdate = [];
const itemsUpdate = [];
for (const item of curSubItems) {
let stripePriceId = item.price.id;
const stripePriceId = item.price.id;
let arrearProratedPrice = findPriceFromPlaceholderId({
const arrearProratedPrice = findPriceFromPlaceholderId({
prices: attachParams.prices,
placeholderId: stripePriceId,
});
@@ -67,7 +70,7 @@ export const handleCheckoutSub = async ({
continue;
}
let arrearPrice = findPriceFromStripeId({
const arrearPrice = findPriceFromStripeId({
prices: attachParams.prices,
stripePriceId,
billingType: BillingType.UsageInArrear,
@@ -76,7 +79,7 @@ export const handleCheckoutSub = async ({
if (
arrearPrice &&
(attachParams.internalEntityId ||
attachParams.apiVersion == APIVersion.v1_4)
attachParams.apiVersion == LegacyVersion.v1_4)
) {
itemsUpdate.push({
id: item.id,

View File

@@ -1,4 +1,4 @@
import { APIVersion, isUsagePrice, type Organization } from "@autumn/shared";
import { isUsagePrice, LegacyVersion, type Organization } from "@autumn/shared";
import type Stripe from "stripe";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import type { AttachParams } from "@/internal/customers/cusProducts/AttachParams.js";
@@ -38,7 +38,7 @@ export const handleRemainingSets = async ({
if (
attachParams.internalEntityId ||
attachParams.apiVersion === APIVersion.v1_4
attachParams.apiVersion === LegacyVersion.v1_4
) {
const replaceIndex = remainingItems.findIndex(
(item) => item.price === config.stripe_price_id,

View File

@@ -1,27 +1,25 @@
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { CusEntService } from "@/internal/customers/cusProducts/cusEnts/CusEntitlementService.js";
import { getResetBalancesUpdate } from "@/internal/customers/cusProducts/cusEnts/groupByUtils.js";
import {
FullCustomerEntitlement,
Price,
FullCusProduct,
UsagePriceConfig,
type Customer,
EntInterval,
Customer,
APIVersion,
RolloverConfig,
Organization,
type FullCusProduct,
type FullCustomerEntitlement,
LegacyVersion,
type Organization,
type Price,
type UsagePriceConfig,
} from "@autumn/shared";
import { differenceInMinutes, subDays } from "date-fns";
import type Stripe from "stripe";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { CusEntService } from "@/internal/customers/cusProducts/cusEnts/CusEntitlementService.js";
import { RolloverService } from "@/internal/customers/cusProducts/cusEnts/cusRollovers/RolloverService.js";
import { getRolloverUpdates } from "@/internal/customers/cusProducts/cusEnts/cusRollovers/rolloverUtils.js";
import { getResetBalancesUpdate } from "@/internal/customers/cusProducts/cusEnts/groupByUtils.js";
import { getCusPriceUsage } from "@/internal/customers/cusProducts/cusPrices/cusPriceUtils.js";
import { submitUsageToStripe } from "../../stripeMeterUtils.js";
import { getInvoiceItemForUsage } from "../../stripePriceUtils.js";
import { getCusPriceUsage } from "@/internal/customers/cusProducts/cusPrices/cusPriceUtils.js";
import { findStripeItemForPrice } from "../../stripeSubUtils/stripeSubItemUtils.js";
import { getRolloverUpdates } from "@/internal/customers/cusProducts/cusEnts/cusRollovers/rolloverUtils.js";
import { RolloverService } from "@/internal/customers/cusProducts/cusEnts/cusRollovers/RolloverService.js";
import { notNullish } from "@/utils/genUtils.js";
import { subToPeriodStartEnd } from "../../stripeSubUtils/convertSubUtils.js";
import { findStripeItemForPrice } from "../../stripeSubUtils/stripeSubItemUtils.js";
export const handleUsagePrices = async ({
db,
@@ -46,7 +44,7 @@ export const handleUsagePrices = async ({
logger: any;
activeProduct: FullCusProduct;
}) => {
let invoiceCreatedRecently =
const invoiceCreatedRecently =
Math.abs(
differenceInMinutes(
new Date(activeProduct.created_at),
@@ -54,7 +52,7 @@ export const handleUsagePrices = async ({
),
) < 10;
let invoiceFromUpgrade =
const invoiceFromUpgrade =
invoice.billing_reason == "subscription_update" ||
invoice.billing_reason == "manual";
@@ -71,7 +69,7 @@ export const handleUsagePrices = async ({
logger.info(`✨ Handling usage prices for ${customer.name || customer.id}`);
logger.info(`✨ org: ${org.slug}, product: ${activeProduct.product.id}`);
let config = price.config as UsagePriceConfig;
const config = price.config as UsagePriceConfig;
// If relatedCusEnt's balance > 0 and next_reset_at is null, skip...
if (relatedCusEnt.balance! > 0 && !relatedCusEnt.next_reset_at) {
@@ -86,10 +84,10 @@ export const handleUsagePrices = async ({
const isNewUsageMethod =
activeProduct.internal_entity_id ||
activeProduct.api_version === APIVersion.v1_4;
activeProduct.api_version === LegacyVersion.v1_4;
if (isNewUsageMethod) {
let invoiceItem = getInvoiceItemForUsage({
const invoiceItem = getInvoiceItemForUsage({
stripeInvoiceId: invoice.id!,
price,
customer,
@@ -136,9 +134,9 @@ export const handleUsagePrices = async ({
return;
}
let ent = relatedCusEnt.entitlement;
const ent = relatedCusEnt.entitlement;
let resetBalancesUpdate = getResetBalancesUpdate({
const resetBalancesUpdate = getResetBalancesUpdate({
cusEnt: relatedCusEnt,
allowance: ent.interval == EntInterval.Lifetime ? 0 : ent.allowance!,
});
@@ -154,7 +152,7 @@ export const handleUsagePrices = async ({
},
});
let rolloverUpdate = getRolloverUpdates({
const rolloverUpdate = getRolloverUpdates({
cusEnt: relatedCusEnt,
nextResetAt: end * 1000,
});

View File

@@ -1,10 +1,10 @@
import {
APIVersion,
AttachScenario,
BillingType,
CusProductStatus,
cusProductToPrices,
type FullCusProduct,
LegacyVersion,
} from "@autumn/shared";
import type Stripe from "stripe";
import type { DrizzleCli } from "@/db/initDrizzle.js";
@@ -53,7 +53,7 @@ export const handleCusProductDeleted = async ({
stripeId: fullCus.processor?.id,
});
const isV4Usage = cusProduct.api_version === APIVersion.v1_4;
const isV4Usage = cusProduct.api_version === LegacyVersion.v1_4;
// refer to handleUpgradeFlow.ts, when cancel immediately through API / dashboard, this happens...?
const isAutumnCancel =

View File

@@ -1,9 +1,9 @@
import { ErrCode } from "@autumn/shared";
import type { Context, Next } from "hono";
import semver, { type SemVer } from "semver";
import type { HonoEnv } from "@/honoUtils/HonoEnv.js";
import RecaseError from "@/utils/errorUtils.js";
import { floatToVersion } from "@/utils/versionUtils.js";
import { floatToVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
/**
* Middleware to verify and set API version from x-api-version header
*/
@@ -24,7 +24,9 @@ export const apiVersionMiddleware = async (c: Context<HonoEnv>, next: Next) => {
}
// Store in context
ctx.apiVersion = apiVersion.toString();
// ctx.apiVersion = apiVersion.toString();
ctx.apiVersion = semver.parse(version) as SemVer;
// ctx.apiVersion.
}
await next();

View File

@@ -1,5 +1,6 @@
import type { AppEnv, AuthType, Feature, Organization } from "@autumn/shared";
import type { ClickHouseClient } from "@clickhouse/client";
import type { SemVer } from "semver";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import type { Logger } from "@/external/logtail/logtailUtils.js";
@@ -19,7 +20,7 @@ export type RequestContext = {
id: string;
isPublic: boolean;
authType: AuthType;
apiVersion: string;
apiVersion: SemVer;
timestamp: number;
};

View File

@@ -1,3 +1,13 @@
// Suppress BullMQ eviction policy warnings BEFORE any imports
const originalWarn = console.warn;
console.warn = (...args: any[]) => {
const msg = args.join(" ");
if (msg.includes("Eviction policy")) {
return;
}
originalWarn.apply(console, args);
};
import { config } from "dotenv";
config();

View File

@@ -1,6 +1,5 @@
import {
type APICusProduct,
APIVersion,
type AppEnv,
type Entity,
type EntityExpand,
@@ -9,6 +8,7 @@ import {
type Feature,
type FullCusProduct,
type FullCustomer,
LegacyVersion,
notNullish,
type Organization,
type Subscription,
@@ -37,7 +37,7 @@ export const getSingleEntityResponse = async ({
features: Feature[];
withAutumnId?: boolean;
}) => {
const apiVersion = APIVersion.v1_2;
const apiVersion = LegacyVersion.v1_2;
if (!entity) {
throw new RecaseError({
@@ -74,7 +74,7 @@ export const getSingleEntityResponse = async ({
entity,
subs: entitySubs,
org,
apiVersion: APIVersion.v1_2,
apiVersion: LegacyVersion.v1_2,
features,
});

View File

@@ -1,10 +1,14 @@
import { routeHandler } from "@/utils/routerUtils.js";
import { APIVersion, EntityExpand, EntityResponseSchema } from "@autumn/shared";
import {
EntityExpand,
EntityResponseSchema,
LegacyVersion,
} from "@autumn/shared";
import { invoicesToResponse } from "@/internal/invoices/invoiceUtils.js";
import { OrgService } from "@/internal/orgs/OrgService.js";
import { routeHandler } from "@/utils/routerUtils.js";
import { orgToVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
import { parseEntityExpand } from "../entityUtils.js";
import { getEntityResponse } from "../getEntityUtils.js";
import { invoicesToResponse } from "@/internal/invoices/invoiceUtils.js";
import { orgToVersion } from "@/utils/versionUtils.js";
export const handleGetEntity = async (req: any, res: any) =>
routeHandler({
@@ -16,17 +20,19 @@ export const handleGetEntity = async (req: any, res: any) =>
const customerId = req.params.customer_id as string;
const expand = parseEntityExpand(req.query.expand);
let { orgId, env, db, logger, features } = req;
const { orgId, env, db, logger, features } = req;
let org = await OrgService.getFromReq(req);
let apiVersion = orgToVersion({
const org = await OrgService.getFromReq(req);
const apiVersion = orgToVersion({
org,
reqApiVersion:
req.apiVersion >= APIVersion.v1_1 ? req.apiVersion : APIVersion.v1_2,
req.apiVersion >= LegacyVersion.v1_1
? req.apiVersion
: LegacyVersion.v1_2,
});
// const start = performance.now();
let { entities, customer, fullEntities, invoices } =
const { entities, customer, fullEntities, invoices } =
await getEntityResponse({
db,
entityIds: [entityId],
@@ -40,8 +46,8 @@ export const handleGetEntity = async (req: any, res: any) =>
logger,
});
let entity = entities[0];
let withInvoices = expand.includes(EntityExpand.Invoices);
const entity = entities[0];
const withInvoices = expand.includes(EntityExpand.Invoices);
res.status(200).json(
EntityResponseSchema.parse({

View File

@@ -1,9 +1,14 @@
import { APIVersion, ErrCode, type Feature, FeatureType } from "@autumn/shared";
import {
ErrCode,
type Feature,
FeatureType,
LegacyVersion,
} from "@autumn/shared";
import { Router } from "express";
import { StatusCodes } from "http-status-codes";
import RecaseError, { handleRequestError } from "@/utils/errorUtils.js";
import { notNullish } from "@/utils/genUtils.js";
import { orgToVersion } from "@/utils/versionUtils.js";
import { orgToVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
import { handleEventSent } from "../events/eventRouter.js";
import { getCheckData } from "./checkUtils/getCheckData.js";
import { getV1CheckResponse } from "./checkUtils/getV1CheckResponse.js";
@@ -185,7 +190,7 @@ checkRouter.post("", async (req: any, res: any) => {
}
}
if (apiVersion >= APIVersion.v1_1) {
if (apiVersion >= LegacyVersion.v1_1) {
res.status(200).json({
...v2Response,
preview,

View File

@@ -1,8 +1,4 @@
import { itemToPriceOrTiers } from "@/internal/products/product-items/productItemUtils.js";
import { isFeaturePriceItem } from "@/internal/products/product-items/productItemUtils/getItemType.js";
import {
APIVersion,
BillingInterval,
type Feature,
type FreeTrial,
@@ -10,23 +6,20 @@ import {
type FullCustomer,
type FullCustomerEntitlement,
isTrialing,
LegacyVersion,
type ProductItem,
SuccessCode,
UsageModel,
} from "@autumn/shared";
import { getCheckPreview } from "./getCheckPreview.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { getProration } from "@/internal/invoices/previewItemUtils/getItemsForNewProduct.js";
import {
formatUnixToDate,
formatUnixToDateTime,
notNullish,
} from "@/utils/genUtils.js";
import { featureToCusPrice } from "@/internal/customers/cusProducts/cusPrices/convertCusPriceUtils.js";
import { priceToInvoiceAmount } from "@/internal/products/prices/priceUtils/priceToInvoiceAmount.js";
import { Decimal } from "decimal.js";
import { isOneOffPrice } from "@/internal/products/prices/priceUtils/usagePriceUtils/classifyUsagePrice.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { featureToCusPrice } from "@/internal/customers/cusProducts/cusPrices/convertCusPriceUtils.js";
import { getProration } from "@/internal/invoices/previewItemUtils/getItemsForNewProduct.js";
import { priceToInvoiceAmount } from "@/internal/products/prices/priceUtils/priceToInvoiceAmount.js";
import { isFeaturePriceItem } from "@/internal/products/product-items/productItemUtils/getItemType.js";
import { itemToPriceOrTiers } from "@/internal/products/product-items/productItemUtils.js";
import { notNullish } from "@/utils/genUtils.js";
import { getCheckPreview } from "./getCheckPreview.js";
export const getBooleanEntitledResult = async ({
db,
@@ -50,20 +43,20 @@ export const getBooleanEntitledResult = async ({
allFeatures: Feature[];
}) => {
const allowed = cusEnts.some((cusEnt) => {
let featureMatch = cusEnt.internal_feature_id === feature.internal_id;
const featureMatch = cusEnt.internal_feature_id === feature.internal_id;
let entityFeatureId = cusEnt.entitlement.entity_feature_id;
let compareEntity =
const entityFeatureId = cusEnt.entitlement.entity_feature_id;
const compareEntity =
notNullish(entityFeatureId) && notNullish(fullCus.entity);
let entityMatch = compareEntity
const entityMatch = compareEntity
? entityFeatureId === fullCus.entity!.feature_id
: true;
return featureMatch && entityMatch;
});
if (apiVersion >= APIVersion.v1_1) {
if (apiVersion >= LegacyVersion.v1_1) {
return res.status(200).json({
customer_id: fullCus.id,
feature_id: feature.id,
@@ -136,7 +129,7 @@ export const getOptions = ({
proration: finalProration,
});
let actualPrice = itemToPriceOrTiers({
const actualPrice = itemToPriceOrTiers({
item: i,
});

View File

@@ -1,5 +1,4 @@
import {
APIVersion,
type AppEnv,
CreateEventSchema,
CusProductStatus,
@@ -9,6 +8,7 @@ import {
type Feature,
FeatureType,
type FullCustomer,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import { Router } from "express";
@@ -23,7 +23,7 @@ import { addTaskToQueue } from "@/queue/queueUtils.js";
import RecaseError, { handleRequestError } from "@/utils/errorUtils.js";
import { generateId, notNullish } from "@/utils/genUtils.js";
import type { ExtendedRequest } from "@/utils/models/Request.js";
import { orgToVersion } from "@/utils/versionUtils.js";
import { orgToVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
import { EventService } from "./EventService.js";
import { getEventTimestamp } from "./eventUtils.js";
import { handleUsageEvent } from "./usageRouter.js";
@@ -259,7 +259,7 @@ eventsRouter.post("", async (req: any, res: any) => {
response.event_name = event.event_name;
}
if (apiVersion >= APIVersion.v1_1) {
if (apiVersion >= LegacyVersion.v1_1) {
res.status(200).json(response);
} else {
res.status(200).json({ success: true });

View File

@@ -1,5 +1,4 @@
import {
type APIVersion,
CollectionMethod,
type CusProduct,
CusProductStatus,
@@ -11,6 +10,7 @@ import {
type FullCusProduct,
type FullProduct,
type InsertReplaceable,
type LegacyVersion,
type Price,
ProcessorType,
type ProductOptions,
@@ -98,7 +98,7 @@ export const initCusProduct = ({
isCustom?: boolean;
entityId?: string;
internalEntityId?: string;
apiVersion?: APIVersion;
apiVersion?: LegacyVersion;
quantity?: number;
}) => {
const isFuture = startsAt && startsAt > Date.now();

View File

@@ -1,6 +1,6 @@
import {
APIVersion,
type AttachConfig,
LegacyVersion,
RecaseError,
SuccessCode,
} from "@autumn/shared";
@@ -188,8 +188,8 @@ export const handleCreateCheckout = async ({
return checkout;
}
const apiVersion = attachParams.apiVersion || APIVersion.v1;
if (apiVersion >= APIVersion.v1_1) {
const apiVersion = attachParams.apiVersion || LegacyVersion.v1;
if (apiVersion >= LegacyVersion.v1_1) {
res.status(200).json(
AttachResultSchema.parse({
checkout_url: checkout.url,

View File

@@ -1,7 +1,7 @@
import {
APIVersion,
AttachBranch,
type AttachConfig,
LegacyVersion,
SuccessCode,
} from "@autumn/shared";
import { subToPeriodStartEnd } from "@/external/stripe/stripeSubUtils/convertSubUtils.js";
@@ -89,10 +89,10 @@ export const handleAddProduct = async ({
logger.info("Successfully created full cus product");
if (res) {
const apiVersion = attachParams.org.api_version || APIVersion.v1;
const apiVersion = attachParams.org.api_version || LegacyVersion.v1;
const productNames = products.map((p) => p.name).join(", ");
const customerName = customer.name || customer.email || customer.id;
if (apiVersion >= APIVersion.v1_1) {
if (apiVersion >= LegacyVersion.v1_1) {
res.status(200).json(
AttachResultSchema.parse({
success: true,

View File

@@ -1,9 +1,9 @@
import {
APIVersion,
type AttachConfig,
AttachScenario,
ErrCode,
isTrialing,
LegacyVersion,
SuccessCode,
} from "@autumn/shared";
import type Stripe from "stripe";
@@ -249,10 +249,10 @@ export const handlePaidProduct = async ({
await Promise.all(batchInsert);
if (res) {
const apiVersion = attachParams.apiVersion || APIVersion.v1;
const apiVersion = attachParams.apiVersion || LegacyVersion.v1;
const productNames = products.map((p) => p.name).join(", ");
const customerName = customer.name || customer.email || customer.id;
if (apiVersion >= APIVersion.v1_1) {
if (apiVersion >= LegacyVersion.v1_1) {
res.status(200).json(
AttachResultSchema.parse({
message: `Successfully created subscriptions and attached ${productNames} to ${customerName}`,

View File

@@ -1,8 +1,8 @@
import {
APIVersion,
type AttachConfig,
AttachScenario,
ErrCode,
LegacyVersion,
SuccessCode,
} from "@autumn/shared";
import { StatusCodes } from "http-status-codes";
@@ -208,10 +208,10 @@ export const handleScheduleFunction2 = async ({
}
}
const apiVersion = attachParams.apiVersion || APIVersion.v1;
const apiVersion = attachParams.apiVersion || LegacyVersion.v1;
if (res) {
if (apiVersion >= APIVersion.v1_1) {
if (apiVersion >= LegacyVersion.v1_1) {
res.status(200).json(
AttachResultSchema.parse({
code: SuccessCode.DowngradeScheduled,

View File

@@ -1,10 +1,10 @@
import {
APIVersion,
AttachBranch,
type AttachConfig,
AttachScenario,
CusProductStatus,
cusProductToProduct,
LegacyVersion,
ProrationBehavior,
} from "@autumn/shared";
import type Stripe from "stripe";
@@ -229,8 +229,8 @@ export const handleUpgradeFlow = async ({
}
if (res) {
const apiVersion = attachParams.org.api_version || APIVersion.v1;
if (apiVersion >= APIVersion.v1_1) {
const apiVersion = attachParams.org.api_version || LegacyVersion.v1;
if (apiVersion >= LegacyVersion.v1_1) {
res.status(200).json(
AttachResultSchema.parse({
customer_id: attachParams.customer.id,

View File

@@ -1,16 +1,14 @@
import { createStripeCli } from "@/external/stripe/utils.js";
import { AttachParams } from "@/internal/customers/cusProducts/AttachParams.js";
import { ExtendedRequest } from "@/utils/models/Request.js";
import {
APIVersion,
Feature,
FullCusProduct,
FullCustomer,
FullProduct,
type FullCustomer,
type FullProduct,
LegacyVersion,
} from "@autumn/shared";
import { getStripeCusData } from "./attachParamsUtils/getStripeCusData.js";
import { createStripeCli } from "@/external/stripe/utils.js";
import type { AttachParams } from "@/internal/customers/cusProducts/AttachParams.js";
import { getFreeTrialAfterFingerprint } from "@/internal/products/free-trials/freeTrialUtils.js";
import { orgToVersion } from "@/utils/versionUtils.js";
import type { ExtendedRequest } from "@/utils/models/Request.js";
import { orgToVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
import { getStripeCusData } from "./attachParamsUtils/getStripeCusData.js";
export const checkToAttachParams = async ({
req,
@@ -29,10 +27,10 @@ export const checkToAttachParams = async ({
orgToVersion({
org,
reqApiVersion: req.apiVersion,
}) || APIVersion.v1;
}) || LegacyVersion.v1;
const stripeCli = createStripeCli({ org, env });
let stripeCusData = await getStripeCusData({
const stripeCusData = await getStripeCusData({
stripeCli,
db,
org,
@@ -42,7 +40,7 @@ export const checkToAttachParams = async ({
allowNoStripe: true,
});
let freeTrial = await getFreeTrialAfterFingerprint({
const freeTrial = await getFreeTrialAfterFingerprint({
db,
freeTrial: product.free_trial,
fingerprint: customer.fingerprint,

View File

@@ -1,7 +1,7 @@
import { APIVersion, type AttachBody } from "@autumn/shared";
import { type AttachBody, LegacyVersion } from "@autumn/shared";
import { nullish } from "@/utils/genUtils.js";
import type { ExtendedRequest } from "@/utils/models/Request.js";
import { orgToVersion } from "@/utils/versionUtils.js";
import { orgToVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
import type { AttachParams } from "../../../cusProducts/AttachParams.js";
import { processAttachBody } from "./processAttachBody.js";
@@ -34,7 +34,7 @@ export const getAttachParams = async ({
orgToVersion({
org,
reqApiVersion: req.apiVersion,
}) || APIVersion.v1;
}) || LegacyVersion.v1;
const entityId = attachBody.entity_id;
const internalEntityId = entityId ? customer.entity?.internal_id : undefined;

View File

@@ -1,5 +1,4 @@
import type {
APIVersion,
AttachReplaceable,
AttachScenario,
Customer,
@@ -11,6 +10,7 @@ import type {
FullCusProduct,
FullCustomer,
FullProduct,
LegacyVersion,
Organization,
Price,
ProductOptions,
@@ -109,7 +109,7 @@ export type InsertCusProductParams = {
entityId?: string;
internalEntityId?: string;
fromMigration?: boolean;
apiVersion?: APIVersion;
apiVersion?: LegacyVersion;
finalizeInvoice?: boolean;
};

View File

@@ -1,7 +1,6 @@
import {
ACTIVE_STATUSES,
APICusProductSchema,
APIVersion,
type AppEnv,
AttachScenario,
CusProductStatus,
@@ -11,6 +10,7 @@ import {
type FullCusProduct,
type FullCustomer,
type FullProduct,
LegacyVersion,
type Organization,
PriceType,
type Subscription,
@@ -507,7 +507,7 @@ export const processFullCusProduct = ({
};
}
if (apiVersion >= APIVersion.v1_1) {
if (apiVersion >= LegacyVersion.v1_1) {
if ((!subIds || subIds.length === 0) && trialing) {
stripeSubData = {
current_period_start: cusProduct.starts_at,

View File

@@ -1,28 +1,24 @@
import RecaseError, { handleRequestError } from "@/utils/errorUtils.js";
import { APIVersion } from "@autumn/shared";
import { ErrCode } from "@autumn/shared";
import { ErrCode, LegacyVersion } from "@autumn/shared";
import { Router } from "express";
import { StatusCodes } from "http-status-codes";
import { CusService } from "./CusService.js";
import { OrgService } from "@/internal/orgs/OrgService.js";
import { createStripeCli } from "@/external/stripe/utils.js";
import { handleDeleteCustomer } from "./handlers/handleDeleteCustomer.js";
import { handleUpdateBalances } from "./handlers/handleUpdateBalances.js";
import { handleUpdateEntitlement } from "./handlers/handleUpdateEntitlement.js";
import { handleAddCouponToCus } from "./handlers/handleAddCouponToCus.js";
import { handlePostCustomerRequest } from "./handlers/handlePostCustomer.js";
import { entityRouter } from "../api/entities/entityRouter.js";
import { handleUpdateCustomer } from "./handlers/handleUpdateCustomer.js";
import { handleCreateBillingPortal } from "./handlers/handleCreateBillingPortal.js";
import { handleGetCustomer } from "./handlers/handleGetCustomer.js";
import { CusSearchService } from "@/internal/customers/CusSearchService.js";
import { createStripeCusIfNotExists } from "@/external/stripe/stripeCusUtils.js";
import { handleTransferProduct } from "./handlers/handleTransferProduct.js";
import { createStripeCli } from "@/external/stripe/utils.js";
import { CusSearchService } from "@/internal/customers/CusSearchService.js";
import { OrgService } from "@/internal/orgs/OrgService.js";
import RecaseError, { handleRequestError } from "@/utils/errorUtils.js";
import { handleBatchCustomers } from "../api/batch/handlers/handleBatchCustomers.js";
import { entityRouter } from "../api/entities/entityRouter.js";
import { toSuccessUrl } from "../orgs/orgUtils/convertOrgUtils.js";
import { CusService } from "./CusService.js";
import { handleAddCouponToCus } from "./handlers/handleAddCouponToCus.js";
import { handleCreateBillingPortal } from "./handlers/handleCreateBillingPortal.js";
import { handleDeleteCustomer } from "./handlers/handleDeleteCustomer.js";
import { handleGetCustomer } from "./handlers/handleGetCustomer.js";
import { handlePostCustomerRequest } from "./handlers/handlePostCustomer.js";
import { handleTransferProduct } from "./handlers/handleTransferProduct.js";
import { handleUpdateBalances } from "./handlers/handleUpdateBalances.js";
import { handleUpdateCustomer } from "./handlers/handleUpdateCustomer.js";
import { handleUpdateEntitlement } from "./handlers/handleUpdateEntitlement.js";
export const cusRouter: Router = Router();
@@ -72,7 +68,7 @@ cusRouter.post("/:customer_id/balances", handleUpdateBalances);
cusRouter.get("/:customer_id/billing_portal", async (req: any, res: any) => {
try {
let returnUrl = req.query.return_url;
const returnUrl = req.query.return_url;
const customerId = req.params.customer_id;
@@ -126,7 +122,7 @@ cusRouter.get("/:customer_id/billing_portal", async (req: any, res: any) => {
return_url: returnUrl || toSuccessUrl({ org, env: req.env }),
});
if (org.api_version >= APIVersion.v1_1) {
if (org.api_version >= LegacyVersion.v1_1) {
return res.status(200).json({
customer_id: customer.id,
url: portal.url,
@@ -144,7 +140,7 @@ cusRouter.get("/:customer_id/billing_portal", async (req: any, res: any) => {
return_url: returnUrl || toSuccessUrl({ org, env: req.env }),
});
if (org.api_version >= APIVersion.v1_1) {
if (org.api_version >= LegacyVersion.v1_1) {
res.status(200).json({
customer_id: customer.id,
url: portal.url,

View File

@@ -1,25 +1,24 @@
import {
APIVersion,
EntInterval,
EntitlementWithFeature,
Entity,
type EntInterval,
type EntitlementWithFeature,
type Entity,
FeatureType,
FullCusProduct,
FullCustomerEntitlement,
FullCustomerPrice,
Organization,
type FullCusProduct,
type FullCustomerEntitlement,
type FullCustomerPrice,
getCusEntBalance,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import { getEntOptions } from "@/internal/products/prices/priceUtils.js";
import { notNullish, notNullOrUndefined } from "@/utils/genUtils.js";
import { BREAK_API_VERSION } from "@/utils/constants.js";
import { notNullish, notNullOrUndefined } from "@/utils/genUtils.js";
import {
getRelatedCusPrice,
getResetBalance,
getUnlimitedAndUsageAllowed,
} from "../../cusProducts/cusEnts/cusEntUtils.js";
import { getCusEntBalance } from "@autumn/shared";
export interface CusFeatureBalance {
feature_id: string;
@@ -48,7 +47,7 @@ export const getV1EntitlementsRes = ({
unlimited: boolean;
ent: EntitlementWithFeature;
}) => {
let res: any = {
const res: any = {
feature_id: ent.feature.id,
unlimited: isBoolean ? undefined : unlimited,
interval: isBoolean || unlimited ? null : ent.interval || undefined,
@@ -76,12 +75,12 @@ export const getRolloverFields = ({
cusEnt: FullCustomerEntitlement;
entityId?: string;
}) => {
let hasRollover = notNullish(cusEnt.entitlement.rollover);
const hasRollover = notNullish(cusEnt.entitlement.rollover);
if (!hasRollover) {
return null;
}
let rollovers = cusEnt.rollovers || [];
const rollovers = cusEnt.rollovers || [];
if (cusEnt.entitlement.entity_feature_id) {
if (entityId) {
@@ -204,10 +203,10 @@ export const getCusBalances = async ({
const cusProduct = cusEnt.customer_product;
const feature = cusEnt.entitlement.feature;
const ent: EntitlementWithFeature = cusEnt.entitlement;
let key = `${ent.interval || "no-interval"}-${ent.interval_count || 1}-${feature.id}`;
const key = `${ent.interval || "no-interval"}-${ent.interval_count || 1}-${feature.id}`;
// 1. Handle boolean
let isBoolean = feature.type == FeatureType.Boolean;
const isBoolean = feature.type == FeatureType.Boolean;
const { unlimited, usageAllowed } = getUnlimitedAndUsageAllowed({
cusEnts: cusEntsWithCusProduct,
@@ -215,7 +214,7 @@ export const getCusBalances = async ({
});
// 1. Initialize balance object
if (!data[key] && apiVersion == APIVersion.v1) {
if (!data[key] && apiVersion == LegacyVersion.v1) {
data[key] = getV1EntitlementsRes({
org,
cusEnt,
@@ -266,7 +265,7 @@ export const getCusBalances = async ({
continue;
}
let { balance, adjustment, count, unused } = getCusEntBalance({
const { balance, adjustment, count, unused } = getCusEntBalance({
cusEnt,
entityId: entity?.id,
});
@@ -274,7 +273,7 @@ export const getCusBalances = async ({
data[key].balance += balance || 0;
data[key].adjustment += adjustment || 0;
let total =
const total =
(getResetBalance({
entitlement: ent,
options: getEntOptions(cusProduct.options, ent),
@@ -285,7 +284,7 @@ export const getCusBalances = async ({
data[key].total += total;
data[key].unused += unused || 0;
let rollover = getRolloverFields({
const rollover = getRolloverFields({
cusEnt,
entityId: entity?.id,
});
@@ -313,7 +312,7 @@ export const getCusBalances = async ({
data[key].allowance += (resetBalance || 0) * count;
let usageLimit = ent.usage_limit;
const usageLimit = ent.usage_limit;
if (notNullish(usageLimit)) {
data[key].usage_limit += usageLimit;
@@ -343,10 +342,10 @@ export const getCusBalances = async ({
}
// Sort balances
if (org.api_version == APIVersion.v1) {
if (org.api_version == LegacyVersion.v1) {
balances.sort((a: any, b: any) => {
let featureA = features.find((f) => f.id == a.feature_id);
let featureB = features.find((f) => f.id == b.feature_id);
const featureA = features.find((f) => f.id == a.feature_id);
const featureB = features.find((f) => f.id == b.feature_id);
if (
featureA?.type == FeatureType.Boolean &&
@@ -370,7 +369,7 @@ export const getCusBalances = async ({
});
}
// if (org.api_version == APIVersion.v1) {
// if (org.api_version == LegacyVersion.v1) {
// }

View File

@@ -1,11 +1,12 @@
import { balancesToFeatureResponse } from "./balancesToFeatureResponse.js";
import {
FullCusProduct,
Organization,
Entity,
APIVersion,
cusProductsToCusEnts,
cusProductsToCusPrices,
type Entity,
type FullCusProduct,
type LegacyVersion,
type Organization,
} from "@autumn/shared";
import { cusProductsToCusEnts, cusProductsToCusPrices } from "@autumn/shared";
import { balancesToFeatureResponse } from "./balancesToFeatureResponse.js";
import { getCusBalances } from "./getCusBalances.js";
export const getCusFeaturesResponse = async ({
@@ -17,9 +18,9 @@ export const getCusFeaturesResponse = async ({
cusProducts: FullCusProduct[];
org: Organization;
entity?: Entity;
apiVersion: APIVersion;
apiVersion: LegacyVersion;
}) => {
let cusEnts = cusProductsToCusEnts({ cusProducts }) as any;
const cusEnts = cusProductsToCusEnts({ cusProducts }) as any;
const balances = await getCusBalances({
cusEntsWithCusProduct: cusEnts,

View File

@@ -1,11 +1,11 @@
import {
APICusProductSchema,
APIVersion,
CusProductStatus,
type Entity,
type Feature,
type FixedPriceConfig,
type FullCusProduct,
LegacyVersion,
type Organization,
PriceType,
type Subscription,
@@ -137,7 +137,7 @@ export const getCusProductResponse = async ({
};
}
if (apiVersion >= APIVersion.v1_1) {
if (apiVersion >= LegacyVersion.v1_1) {
if ((!subIds || subIds.length === 0) && trialing) {
stripeSubData = {
current_period_start: cusProduct.starts_at,

View File

@@ -1,10 +1,10 @@
import {
ACTIVE_STATUSES,
type APICusProduct,
APIVersion,
type CusProductStatus,
type Entity,
type Feature,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import { getCusProductResponse } from "./getCusProductResponse.js";
@@ -81,7 +81,7 @@ export const processFullCusProducts = async ({
}
}
if (apiVersion >= APIVersion.v1_1) {
if (apiVersion >= LegacyVersion.v1_1) {
main = mergeCusProductResponses({
cusProductResponses: main as APICusProduct[],
});

View File

@@ -1,6 +1,5 @@
import {
APICustomerSchema,
APIVersion,
type AppEnv,
CusEntResponseSchema,
CusExpand,
@@ -13,13 +12,14 @@ import {
FeatureType,
type FullCusProduct,
type FullCustomer,
LegacyVersion,
type Organization,
type RewardResponse,
} from "@autumn/shared";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { invoicesToResponse } from "@/internal/invoices/invoiceUtils.js";
import { BREAK_API_VERSION } from "@/utils/constants.js";
import { orgToVersion } from "@/utils/versionUtils.js";
import { orgToVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
import { featuresToObject } from "./cusFeatureResponseUtils/balancesToFeatureResponse.js";
import { getCusBalances } from "./cusFeatureResponseUtils/getCusBalances.js";
import { processFullCusProducts } from "./cusProductResponseUtils/processFullCusProducts.js";
@@ -85,7 +85,7 @@ export const getCustomerDetails = async ({
features,
});
if (apiVersion >= APIVersion.v1_1) {
if (apiVersion >= LegacyVersion.v1_1) {
let entList: any = balances.map((b) => {
const isBoolean =
features.find((f: Feature) => f.id === b.feature_id)?.type ===
@@ -103,7 +103,7 @@ export const getCustomerDetails = async ({
const products: any = [...main, ...addOns];
if (apiVersion >= APIVersion.v1_2) {
if (apiVersion >= LegacyVersion.v1_2) {
entList = featuresToObject({
features,
entList,

View File

@@ -1,7 +1,7 @@
import { APIVersion, CusExpand, ErrCode } from "@autumn/shared";
import { CusExpand, ErrCode, LegacyVersion } from "@autumn/shared";
import { StatusCodes } from "http-status-codes";
import { routeHandler } from "@/utils/routerUtils.js";
import { orgToVersion } from "@/utils/versionUtils.js";
import { orgToVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
import { getCusWithCache } from "../cusCache/getCusWithCache.js";
import { parseCusExpand } from "../cusUtils/cusUtils.js";
import { getCustomerDetails } from "../cusUtils/getCustomerDetails.js";
@@ -23,7 +23,7 @@ export const handleGetCustomer = async (req: any, res: any) =>
reqApiVersion: req.apiVersion,
});
const getInvoices = apiVersion < APIVersion.v1_1;
const getInvoices = apiVersion < LegacyVersion.v1_1;
if (getInvoices) expandArray.push(CusExpand.Invoices);
logger.info(`getting customer ${customerId} for org ${org.slug}`);

View File

@@ -11,7 +11,7 @@ import { and, desc, eq } from "drizzle-orm";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { CacheManager } from "@/external/caching/CacheManager.js";
import { CacheType } from "@/external/caching/cacheActions.js";
import { getApiVersion } from "@/utils/versionUtils.js";
import { getApiVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
export class ApiKeyService {
static async verifyAndFetch({

View File

@@ -1,12 +1,17 @@
import { EntityService } from "../../../api/entities/EntityService.js";
import { APIVersion, CreateEntity, CustomerData, Entity } from "@autumn/shared";
import { getEntityResponse } from "../../../api/entities/getEntityUtils.js";
import { orgToVersion } from "@/utils/versionUtils.js";
import {
type CreateEntity,
type CustomerData,
type Entity,
LegacyVersion,
} from "@autumn/shared";
import type { ExtendedRequest } from "@/utils/models/Request.js";
import { routeHandler } from "@/utils/routerUtils.js";
import { ExtendedRequest } from "@/utils/models/Request.js";
import { orgToVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
import { EntityService } from "../../../api/entities/EntityService.js";
import { getEntityResponse } from "../../../api/entities/getEntityUtils.js";
import { constructEntity } from "../../entityUtils/entityUtils.js";
import { validateAndGetInputEntities } from "./getInputEntities.js";
import { createEntityForCusProduct } from "./createEntityForCusProduct.js";
import { validateAndGetInputEntities } from "./getInputEntities.js";
export const createEntities = async ({
req,
@@ -24,7 +29,7 @@ export const createEntities = async ({
customerId: string;
createEntityData: CreateEntity[] | CreateEntity;
withAutumnId?: boolean;
apiVersion?: APIVersion;
apiVersion?: LegacyVersion;
fromAutoCreate?: boolean;
}) => {
const { db, org, env, features } = req;
@@ -59,9 +64,9 @@ export const createEntities = async ({
}),
);
let newEntities: Entity[] = [];
const newEntities: Entity[] = [];
if (existingEntities.some((e: any) => e.id === null)) {
let updatedEntity = await EntityService.update({
const updatedEntity = await EntityService.update({
db,
internalId: existingEntities.find((e: any) => e.id === null)!.internal_id,
update: {
@@ -74,7 +79,7 @@ export const createEntities = async ({
newEntities.push(updatedEntity);
}
let insertedEntities = await EntityService.insert({
const insertedEntities = await EntityService.insert({
db,
data,
});
@@ -85,7 +90,7 @@ export const createEntities = async ({
return newEntities;
}
let { entities } = await getEntityResponse({
const { entities } = await getEntityResponse({
db,
entityIds: newEntities.map((e: any) => e.id || e.internal_id),
org,
@@ -109,12 +114,12 @@ export const handlePostEntityRequest = async (req: any, res: any) =>
handler: async (req: any, res: any) => {
const { logtail: logger, org } = req;
let apiVersion = orgToVersion({
const apiVersion = orgToVersion({
org,
reqApiVersion: req.apiVersion,
});
let customerData =
const customerData =
Array.isArray(req.body) && req.body.length > 0
? req.body[0].customer_data
: req.body.customer_data;
@@ -131,7 +136,7 @@ export const handlePostEntityRequest = async (req: any, res: any) =>
logger.info(` Created / replaced entities!`);
if (apiVersion < APIVersion.v1_2) {
if (apiVersion < LegacyVersion.v1_2) {
res.status(200).json({
success: true,
});

View File

@@ -1,13 +1,13 @@
import { getStripeCusData } from "@/internal/customers/attach/attachUtils/attachParams/attachParamsUtils/getStripeCusData.js";
import { AttachParams } from "@/internal/customers/cusProducts/AttachParams.js";
import { ExtendedRequest } from "@/utils/models/Request.js";
import {
APIVersion,
FullCusProduct,
FullCustomer,
FullProduct,
type FullCusProduct,
type FullCustomer,
type FullProduct,
LegacyVersion,
} from "@autumn/shared";
import Stripe from "stripe";
import type Stripe from "stripe";
import { getStripeCusData } from "@/internal/customers/attach/attachUtils/attachParams/attachParamsUtils/getStripeCusData.js";
import type { AttachParams } from "@/internal/customers/cusProducts/AttachParams.js";
import type { ExtendedRequest } from "@/utils/models/Request.js";
export const migrationToAttachParams = async ({
req,
@@ -24,7 +24,7 @@ export const migrationToAttachParams = async ({
}): Promise<AttachParams> => {
const { org } = req;
const apiVersion = org.config.api_version || APIVersion.v1;
const apiVersion = org.config.api_version || LegacyVersion.v1;
const internalEntityId = cusProduct.internal_entity_id || undefined;
const { stripeCus, paymentMethod, now } = await getStripeCusData({

View File

@@ -1,28 +1,28 @@
import RecaseError from "@/utils/errorUtils.js";
import { and, eq, sql, inArray } from "drizzle-orm";
import {
AppEnv,
apiKeys,
ErrCode,
Feature,
type Feature,
features,
invitation,
member,
Organization,
type Organization,
OrgConfigSchema,
organizations,
user,
} from "@autumn/shared";
import { getApiVersion } from "@/utils/versionUtils.js";
import { and, eq, sql } from "drizzle-orm";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import RecaseError from "@/utils/errorUtils.js";
import { getApiVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
import { clearOrgCache } from "./orgUtils/clearOrgCache.js";
import { organizations, apiKeys } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
export class OrgService {
static async getFromReq(req: any) {
if (req.org) {
let org = structuredClone(req.org);
let config = org.config || {};
let apiVersion = getApiVersion({
const org = structuredClone(req.org);
const config = org.config || {};
const apiVersion = getApiVersion({
createdAt: org.created_at,
});
return {
@@ -32,7 +32,7 @@ export class OrgService {
};
}
return await this.get({ db: req.db, orgId: req.orgId });
return await OrgService.get({ db: req.db, orgId: req.orgId });
}
static async getMembers({ db, orgId }: { db: DrizzleCli; orgId: string }) {
@@ -200,7 +200,7 @@ export class OrgService {
});
}
let org = structuredClone(result);
const org = structuredClone(result);
delete (org as any).features;
return {
org: {
@@ -223,7 +223,7 @@ export class OrgService {
pkey: string;
env: AppEnv;
}) {
let org = await db.query.organizations.findFirst({
const org = await db.query.organizations.findFirst({
where:
env === AppEnv.Sandbox
? eq(organizations.test_pkey, pkey)
@@ -270,7 +270,7 @@ export class OrgService {
updates: any;
}) {
try {
let result = await db
const result = await db
.update(organizations)
.set(updates)
.where(eq(organizations.id, orgId))

View File

@@ -1,8 +1,8 @@
import {
APIVersion,
BillingInterval,
BillingType,
type FullCusProduct,
LegacyVersion,
OnDecrease,
OnIncrease,
type Price,
@@ -75,7 +75,7 @@ export const isV4Usage = ({
return (
billingType === BillingType.UsageInArrear &&
(cusProduct.api_version === APIVersion.v1_4 ||
(cusProduct.api_version === LegacyVersion.v1_4 ||
notNullish(cusProduct.internal_entity_id))
);
};

View File

@@ -2,7 +2,7 @@ import { AuthType, ErrCode } from "@autumn/shared";
import { verifyKey } from "@/internal/dev/api-keys/apiKeyUtils.js";
import { dashboardOrigins } from "@/utils/constants.js";
import RecaseError from "@/utils/errorUtils.js";
import { floatToVersion } from "@/utils/versionUtils.js";
import { floatToVersion } from "@/utils/versionUtils/legacyVersionUtils.js";
import { withOrgAuth } from "./authMiddleware.js";
import { verifyBearerPublishableKey } from "./publicAuthMiddleware.js";
import { trmnlAuthMiddleware, trmnlExclusions } from "./trmnlAuthMiddleware.js";

View File

@@ -1,20 +1,19 @@
import { DrizzleCli } from "@/db/initDrizzle.js";
import {
type AppEnv,
type Feature,
type FullCusEntWithFullCusProduct,
type FullCusProduct,
type FullCustomer,
LegacyVersion,
type Organization,
WebhookEventType,
} from "@autumn/shared";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { sendSvixEvent } from "@/external/svix/svixHelpers.js";
import { EntityService } from "@/internal/api/entities/EntityService.js";
import { getSingleEntityResponse } from "@/internal/api/entities/getEntityUtils.js";
import { getV2CheckResponse } from "@/internal/api/entitled/checkUtils/getV2CheckResponse.js";
import { getCustomerDetails } from "@/internal/customers/cusUtils/getCustomerDetails.js";
import { toAPIFeature } from "@/internal/features/utils/mapFeatureUtils.js";
import {
FullCusEntWithFullCusProduct,
Feature,
FullCustomer,
Organization,
AppEnv,
FullCusProduct,
APIVersion,
WebhookEventType,
} from "@autumn/shared";
export const mergeNewCusEntsIntoCusProducts = ({
cusProducts,
@@ -25,7 +24,7 @@ export const mergeNewCusEntsIntoCusProducts = ({
}) => {
for (const cusProduct of cusProducts) {
for (let i = 0; i < cusProduct.customer_entitlements.length; i++) {
let correspondingCusEnt = newCusEnts.find(
const correspondingCusEnt = newCusEnts.find(
(cusEnt) => cusEnt.id == cusProduct.customer_entitlements[i].id,
);
@@ -135,7 +134,7 @@ export const handleAllowanceUsed = async ({
feature,
org,
cusProducts: fullCus.customer_products,
apiVersion: APIVersion.v1_2,
apiVersion: LegacyVersion.v1_2,
});
const v2CheckResponse = await getV2CheckResponse({
@@ -145,7 +144,7 @@ export const handleAllowanceUsed = async ({
feature,
org,
cusProducts: fullCus.customer_products,
apiVersion: APIVersion.v1_2,
apiVersion: LegacyVersion.v1_2,
});
// console.log(`Handling allowance used for feature: ${feature.id}`);
@@ -207,7 +206,7 @@ export const handleThresholdReached = async ({
feature,
org,
cusProducts: fullCus.customer_products,
apiVersion: APIVersion.v1_2,
apiVersion: LegacyVersion.v1_2,
});
const v2CheckResponse = await getV2CheckResponse({
@@ -217,7 +216,7 @@ export const handleThresholdReached = async ({
feature,
org,
cusProducts: newCusProducts,
apiVersion: APIVersion.v1_2,
apiVersion: LegacyVersion.v1_2,
});
if (

View File

@@ -1,7 +1,7 @@
import { Organization, APIVersion } from "@autumn/shared";
import { LegacyVersion, type Organization } from "@autumn/shared";
export const floatToVersion = (version: number) => {
if (Object.values(APIVersion).includes(version)) {
if (Object.values(LegacyVersion).includes(version)) {
return version;
}
@@ -12,21 +12,21 @@ export const getApiVersion = ({
createdAt,
}: {
createdAt: number;
}): APIVersion => {
}): LegacyVersion => {
// v1.1 -- 17 April
let v1_2 = new Date("2025-05-05");
let v1_1 = new Date("2025-04-17");
const v1_2 = new Date("2025-05-05");
const v1_1 = new Date("2025-04-17");
if (createdAt >= v1_2.getTime()) {
return APIVersion.v1_2;
return LegacyVersion.v1_2;
}
if (createdAt >= v1_1.getTime()) {
return APIVersion.v1_1;
return LegacyVersion.v1_1;
}
return APIVersion.v1;
return LegacyVersion.v1;
};
export const orgToVersion = ({
@@ -36,5 +36,5 @@ export const orgToVersion = ({
org: Organization;
reqApiVersion?: number;
}) => {
return reqApiVersion || org.api_version || APIVersion.v1;
return reqApiVersion || org.api_version || LegacyVersion.v1;
};

View File

@@ -1,5 +1,15 @@
import { initWorkers } from "./queue/workersInit.js";
// Suppress BullMQ eviction policy warnings BEFORE any imports
const originalWarn = console.warn;
console.warn = (...args: any[]) => {
const msg = args.join(" ");
if (msg.includes("Eviction policy")) {
return;
}
originalWarn.apply(console, args);
};
import { QueueManager } from "./queue/QueueManager.js";
import { initWorkers } from "./queue/workersInit.js";
const init = async () => {
await QueueManager.getInstance(); // initialize the queue manager

View File

@@ -1,31 +1,31 @@
import chalk from "chalk";
import { setupBefore } from "tests/before.js";
import { Stripe } from "stripe";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { addPrefixToProducts } from "tests/utils/testProductUtils/testProductUtils.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import { cusProductToSub } from "@/internal/customers/cusProducts/cusProductUtils/convertCusProduct.js";
import chalk from "chalk";
import type { Stripe } from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { getMainCusProduct } from "tests/utils/cusProductUtils/cusProductUtils.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "tests/utils/testProductUtils/testProductUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { cusProductToSub } from "@/internal/customers/cusProducts/cusProductUtils/convertCusProduct.js";
import { timeout } from "@/utils/genUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
// UNCOMMENT FROM HERE
let pro = constructProduct({
const pro = constructProduct({
id: "pro",
items: [constructFeatureItem({ featureId: TestFeature.Words })],
type: "pro",
});
describe(`${chalk.yellowBright("advancedOthers1: Testing convert collection method from send_invoice")}`, () => {
let customerId = "advancedOthers1";
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = "advancedOthers1";
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let stripeCli: Stripe;
let testClockId: string;
@@ -69,7 +69,7 @@ describe(`${chalk.yellowBright("advancedOthers1: Testing convert collection meth
testClockId = testClockId1!;
});
it("should attach pro product and pay for it", async function () {
it("should attach pro product and pay for it", async () => {
const res = await autumn.attach({
customer_id: customerId,
product_id: pro.id,
@@ -90,7 +90,7 @@ describe(`${chalk.yellowBright("advancedOthers1: Testing convert collection meth
await stripeCli.invoices.pay(invoiceStripeId);
});
it("should have collection method charge automatically", async function () {
it("should have collection method charge automatically", async () => {
await timeout(5000);
const cusProduct = await getMainCusProduct({

View File

@@ -1,20 +1,20 @@
import chalk from "chalk";
import Stripe from "stripe";
import { type Customer, LegacyVersion, type LimitedItem } from "@autumn/shared";
import { expect } from "chai";
import { addPrefixToProducts } from "tests/utils/testProductUtils/testProductUtils.js";
import { APIVersion, Customer, LimitedItem } from "@autumn/shared";
import { setupBefore } from "tests/before.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { createProducts } from "tests/utils/productUtils.js";
import chalk from "chalk";
import { Decimal } from "decimal.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "tests/utils/testProductUtils/testProductUtils.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const creditCost = 0.2;
let freeProduct = constructProduct({
const freeProduct = constructProduct({
id: "free",
items: [constructFeatureItem({ featureId: TestFeature.Action1 })],
type: "free",
@@ -24,7 +24,7 @@ let freeProduct = constructProduct({
const creditFeatureItem = constructFeatureItem({
featureId: TestFeature.Credits,
}) as LimitedItem;
let pro = constructProduct({
const pro = constructProduct({
id: "pro",
items: [creditFeatureItem],
type: "pro",
@@ -36,7 +36,7 @@ describe(`${chalk.yellowBright("check1: Checking credit systems")}`, () => {
let testClockId: string;
let customer: Customer;
let stripeCli: Stripe;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
before(async function () {
await setupBefore(this);
@@ -68,18 +68,18 @@ describe(`${chalk.yellowBright("check1: Checking credit systems")}`, () => {
testClockId = testClockId_;
});
it("should attach free product and check action1 allowed", async function () {
it("should attach free product and check action1 allowed", async () => {
await autumn.attach({
customer_id: customerId,
product_id: freeProduct.id,
});
let actionCheck = await autumn.check({
const actionCheck = await autumn.check({
customer_id: customerId,
feature_id: TestFeature.Action1,
});
let creditsCheck = await autumn.check({
const creditsCheck = await autumn.check({
customer_id: customerId,
feature_id: TestFeature.Credits,
});
@@ -88,18 +88,18 @@ describe(`${chalk.yellowBright("check1: Checking credit systems")}`, () => {
expect(creditsCheck.allowed).to.be.false;
});
it("should attach pro product and check allowed", async function () {
it("should attach pro product and check allowed", async () => {
await autumn.attach({
customer_id: customerId,
product_id: pro.id,
});
let creditsCheck = await autumn.check({
const creditsCheck = await autumn.check({
customer_id: customerId,
feature_id: TestFeature.Credits,
});
let actionCheck = await autumn.check({
const actionCheck = await autumn.check({
customer_id: customerId,
feature_id: TestFeature.Action1,
});
@@ -108,11 +108,11 @@ describe(`${chalk.yellowBright("check1: Checking credit systems")}`, () => {
expect(creditsCheck.allowed).to.be.true;
});
it("should use up credits and have correct check response", async function () {
let usage = 50;
let creditUsage = new Decimal(creditCost).mul(usage).toNumber();
it("should use up credits and have correct check response", async () => {
const usage = 50;
const creditUsage = new Decimal(creditCost).mul(usage).toNumber();
let creditBalance = new Decimal(creditFeatureItem.included_usage)
const creditBalance = new Decimal(creditFeatureItem.included_usage)
.sub(creditUsage)
.toNumber();
@@ -124,7 +124,7 @@ describe(`${chalk.yellowBright("check1: Checking credit systems")}`, () => {
await timeout(3000);
let creditsCheck = await autumn.check({
const creditsCheck = await autumn.check({
customer_id: customerId,
feature_id: TestFeature.Credits,
});

View File

@@ -1,7 +1,7 @@
import {
APIVersion,
type AppEnv,
type Customer,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import { expect } from "chai";
@@ -128,7 +128,7 @@ describe(
let org: Organization;
let env: AppEnv;
const autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let couponAmount = rewards.rolloverAll.discount_config.discount_value;
let curUnix = new Date().getTime();

View File

@@ -1,8 +1,8 @@
import {
APIVersion,
type AppEnv,
CouponDurationType,
type CreateReward,
LegacyVersion,
type Organization,
RewardType,
} from "@autumn/shared";
@@ -62,7 +62,7 @@ describe(
let stripeCli: Stripe;
let testClockId: string;
const autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let org: Organization;
let env: AppEnv;
let db: DrizzleCli;

View File

@@ -1,33 +1,30 @@
import chalk from "chalk";
import Stripe from "stripe";
import { expect } from "chai";
import {
APIVersion,
AppEnv,
type AppEnv,
CouponDurationType,
CreateReward,
Organization,
type CreateReward,
LegacyVersion,
type Organization,
RewardType,
} from "@autumn/shared";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { expect } from "chai";
import chalk from "chalk";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import {
constructArrearItem,
constructFeatureItem,
} from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { expectAttachCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { createProducts, createReward } from "tests/utils/productUtils.js";
import {
addPrefixToProducts,
getBasePrice,
} from "tests/utils/testProductUtils/testProductUtils.js";
import { createProducts, createReward } from "tests/utils/productUtils.js";
import { expectAttachCorrect } from "tests/utils/expectUtils/expectAttach.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import {
constructArrearItem,
constructFeatureItem,
} from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const pro = constructProduct({
type: "pro",
@@ -64,16 +61,16 @@ const reward: CreateReward = {
const testCase = "coupon3";
describe(chalk.yellow(`${testCase} - Testing attach coupon`), () => {
let customerId = testCase;
const customerId = testCase;
let stripeCli: Stripe;
let testClockId: string;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let org: Organization;
let env: AppEnv;
let db: DrizzleCli;
let couponAmount = reward.discount_config!.discount_value;
const couponAmount = reward.discount_config!.discount_value;
before(async function () {
await setupBefore(this);
@@ -132,7 +129,7 @@ describe(chalk.yellow(`${testCase} - Testing attach coupon`), () => {
});
const invoice = customer.invoices![0];
let basePrice = getBasePrice({ product: pro });
const basePrice = getBasePrice({ product: pro });
expect(invoice.total).to.equal(basePrice - couponAmount);
});
@@ -150,7 +147,7 @@ describe(chalk.yellow(`${testCase} - Testing attach coupon`), () => {
});
const invoice = customer.invoices![0];
let basePrice = getBasePrice({ product: oneOff });
const basePrice = getBasePrice({ product: oneOff });
expect(invoice.total).to.equal(basePrice - couponAmount);
expect(invoice.product_ids).to.include(oneOff.id);
});
@@ -169,9 +166,9 @@ describe(chalk.yellow(`${testCase} - Testing attach coupon`), () => {
});
expect(customer.invoices!.length).to.equal(3);
let basePrice = getBasePrice({ product: oneOff });
const basePrice = getBasePrice({ product: oneOff });
for (let i = 0; i < 2; i++) {
let invoice = customer.invoices![i];
const invoice = customer.invoices![i];
expect(invoice.total).to.equal(basePrice - couponAmount);
expect(invoice.product_ids).to.include(oneOff.id);
}

View File

@@ -1,27 +1,25 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import { addHours, addMonths } from "date-fns";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import { addHours, addMonths } from "date-fns";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { createProducts } from "tests/utils/productUtils.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const testCase = "customInterval1";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Words,
@@ -33,7 +31,7 @@ export let pro = constructProduct({
type: "pro",
});
export let premium = constructProduct({
export const premium = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Words,
@@ -50,8 +48,8 @@ export let premium = constructProduct({
});
describe(`${chalk.yellowBright(`${testCase}: Testing custom interval and interval count`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
@@ -90,7 +88,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing custom interval and interva
testClockId = testClockId1!;
});
it("should attach pro product", async function () {
it("should attach pro product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -102,8 +100,8 @@ describe(`${chalk.yellowBright(`${testCase}: Testing custom interval and interva
});
});
let usage = 100012;
it("should upgrade to premium product and have correct invoice next cycle", async function () {
const usage = 100012;
it("should upgrade to premium product and have correct invoice next cycle", async () => {
const curUnix = await advanceTestClock({
stripeCli,
testClockId,
@@ -141,7 +139,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing custom interval and interva
expect(invoices[0].total).to.equal(getBasePrice({ product: premium }));
const wordsFeature = customer2.features[TestFeature.Words];
// @ts-ignore
// @ts-expect-error
expect(wordsFeature.interval_count).to.equal(2);
});
});

View File

@@ -1,28 +1,25 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructRawProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import { addHours, addMonths } from "date-fns";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import { addHours, addMonths } from "date-fns";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import { getExpectedInvoiceTotal } from "tests/utils/expectUtils/expectInvoiceUtils.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { getExpectedInvoiceTotal } from "tests/utils/expectUtils/expectInvoiceUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { constructRawProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const testCase = "customInterval2";
export let pro = constructRawProduct({
export const pro = constructRawProduct({
id: "pro",
items: [
constructArrearItem({
@@ -34,8 +31,8 @@ export let pro = constructRawProduct({
});
describe(`${chalk.yellowBright(`${testCase}: Testing custom interval on arrear prorated price`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
@@ -74,7 +71,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing custom interval on arrear p
testClockId = testClockId1!;
});
it("should attach pro product", async function () {
it("should attach pro product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -86,8 +83,8 @@ describe(`${chalk.yellowBright(`${testCase}: Testing custom interval on arrear p
});
});
let usage = 100012;
it("should upgrade to premium product and have correct invoice next cycle", async function () {
const usage = 100012;
it("should upgrade to premium product and have correct invoice next cycle", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Words,

View File

@@ -1,45 +1,31 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
BillingInterval,
LimitedItem,
Organization,
Product,
} from "@autumn/shared";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { addDays, addMonths } from "date-fns";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { calculateProrationAmount } from "@/internal/invoices/prorationUtils.js";
import {
constructArrearItem,
constructFeatureItem,
constructPrepaidItem,
} from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import {
constructProduct,
constructRawProduct,
} from "@/utils/scriptUtils/createTestProducts.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import { addDays, addHours, addMonths } from "date-fns";
import { expect } from "chai";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import { getExpectedInvoiceTotal } from "tests/utils/expectUtils/expectInvoiceUtils.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { calculateProrationAmount } from "@/internal/invoices/prorationUtils.js";
import { getProration } from "@/internal/invoices/previewItemUtils/getItemsForNewProduct.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const testCase = "customInterval3";
export let pro = constructProduct({
export const pro = constructProduct({
type: "pro",
items: [
constructFeatureItem({
@@ -65,8 +51,8 @@ export const addOn = constructRawProduct({
});
describe(`${chalk.yellowBright(`${testCase}: Testing custom interval on add on merged product`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
@@ -105,7 +91,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing custom interval on add on m
testClockId = testClockId1!;
});
it("should attach pro product", async function () {
it("should attach pro product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -117,7 +103,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing custom interval on add on m
});
});
it("should upgrade to attached add on and have correct invoice next cycle", async function () {
it("should upgrade to attached add on and have correct invoice next cycle", async () => {
const curUnix = await advanceTestClock({
stripeCli,
testClockId,
@@ -151,7 +137,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing custom interval on add on m
product: addOn,
});
let expectedPrice = wordsBillingUnits * prepaidWordsItem.price!;
const expectedPrice = wordsBillingUnits * prepaidWordsItem.price!;
const proratedPrice = calculateProrationAmount({
amount: expectedPrice,
periodStart: new Date().getTime(),

View File

@@ -1,30 +1,27 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { addMonths } from "date-fns";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import { addMonths } from "date-fns";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import {
expectDowngradeCorrect,
expectNextCycleCorrect,
} from "tests/utils/expectUtils/expectScheduleUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const testCase = "customInterval4";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Words,
@@ -35,7 +32,7 @@ export let pro = constructProduct({
type: "pro",
});
export let premium = constructProduct({
export const premium = constructProduct({
id: "premium",
items: [
constructFeatureItem({
@@ -48,8 +45,8 @@ export let premium = constructProduct({
});
describe(`${chalk.yellowBright(`${testCase}: Testing downgrades for custom intervals`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
@@ -88,7 +85,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrades for custom inter
testClockId = testClockId1!;
});
it("should attach premium product", async function () {
it("should attach premium product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -100,13 +97,13 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrades for custom inter
});
});
it("should have correct next cycle at on checkout", async function () {
it("should have correct next cycle at on checkout", async () => {
const checkout = await autumn.checkout({
customer_id: customerId,
product_id: pro.id,
});
let expectedNextCycle = addMonths(new Date(), 2);
const expectedNextCycle = addMonths(new Date(), 2);
expect(checkout.next_cycle?.starts_at).to.be.approximately(
expectedNextCycle.getTime(),
1000 * 60 * 60 * 24,
@@ -116,7 +113,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrades for custom inter
});
let preview: any;
it("should downgrade to pro", async function () {
it("should downgrade to pro", async () => {
const { preview: preview_ } = await expectDowngradeCorrect({
autumn,
customerId,
@@ -131,7 +128,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrades for custom inter
preview = preview_;
});
it("should have pro attached on next cycle", async function () {
it("should have pro attached on next cycle", async () => {
await expectNextCycleCorrect({
preview: preview!,
autumn,

View File

@@ -1,21 +1,19 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, FullCustomer, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import type { Customer } from "autumn-js";
import { expect } from "chai";
import { Customer } from "autumn-js";
import { timeout } from "@/utils/genUtils.js";
import chalk from "chalk";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const testCase = "customInterval5";
@@ -31,7 +29,7 @@ const biMonthlyWords = constructFeatureItem({
includedUsage,
});
export let pro = constructProduct({
export const pro = constructProduct({
items: [monthlyWords, biMonthlyWords],
intervalCount: 2,
type: "pro",
@@ -45,15 +43,15 @@ const getBreakdown = ({
intervalCount: number;
}) => {
const wordsFeature = customer.features[TestFeature.Words];
// @ts-ignore
// @ts-expect-error
return wordsFeature.breakdown?.find(
(b: any) => b.interval_count == intervalCount,
);
};
describe(`${chalk.yellowBright(`${testCase}: Testing multi interval features with custom intervals`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
@@ -92,7 +90,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing multi interval features wit
testClockId = testClockId1!;
});
it("should attach pro product", async function () {
it("should attach pro product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -105,7 +103,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing multi interval features wit
const customer = await autumn.customers.get(customerId);
const wordsFeature = customer.features[TestFeature.Words];
// @ts-ignore
// @ts-expect-error
expect(wordsFeature.interval_count).to.equal(null);
expect(wordsFeature.breakdown?.length).to.equal(2);
@@ -122,7 +120,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing multi interval features wit
});
const trackVal = 300;
it("should have correct breakdown after usage", async function () {
it("should have correct breakdown after usage", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Words,

View File

@@ -1,23 +1,23 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
// Manual customer creation - not using initCustomer to control test clock properly
import {
APIVersion,
AppEnv,
type AppEnv,
CusProductStatus,
Organization,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomerV2 } from "@/utils/scriptUtils/initCustomer.js";
import {
defaultTrialFree,
defaultTrialPro,
setupDefaultTrialBefore,
} from "./defaultTrialBefore.test.js";
import { initCustomerV2 } from "@/utils/scriptUtils/initCustomer.js";
// Case 1: ✅
// Pro product with default trial exists alongside a free default product
@@ -31,13 +31,13 @@ import { initCustomerV2 } from "@/utils/scriptUtils/initCustomer.js";
const testCase = "defaultTrial1";
describe(`${chalk.yellowBright(`advanced/${testCase}: ensure default trials are attached when creating a customer`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockID: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = Math.floor(new Date().getTime() / 1000);
const curUnix = Math.floor(new Date().getTime() / 1000);
before(async function () {
await setupBefore(this);
@@ -59,8 +59,8 @@ describe(`${chalk.yellowBright(`advanced/${testCase}: ensure default trials are
testClockID = res.testClockId;
});
it("should create a customer with the paid default trial", async function () {
let customer = await autumn.customers.get(customerId);
it("should create a customer with the paid default trial", async () => {
const customer = await autumn.customers.get(customerId);
expectProductAttached({
customer,
@@ -70,7 +70,7 @@ describe(`${chalk.yellowBright(`advanced/${testCase}: ensure default trials are
});
describe("ensure trials automatically cancel if no payment method is provided", () => {
it("should expire after 7 days", async function () {
it("should expire after 7 days", async () => {
await advanceTestClock({
stripeCli,
testClockId: testClockID,
@@ -78,7 +78,7 @@ describe(`${chalk.yellowBright(`advanced/${testCase}: ensure default trials are
waitForSeconds: 10,
});
let customer = await autumn.customers.get(customerId);
const customer = await autumn.customers.get(customerId);
expectProductAttached({
customer,

View File

@@ -1,25 +1,24 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
// Manual customer creation - not using initCustomer to control test clock properly
import {
APIVersion,
AppEnv,
type AppEnv,
CusProductStatus,
Organization,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { addDays, addHours } from "date-fns";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomerV2 } from "@/utils/scriptUtils/initCustomer.js";
import {
defaultTrialPro,
setupDefaultTrialBefore,
} from "./defaultTrialBefore.test.js";
import { initCustomerV2 } from "@/utils/scriptUtils/initCustomer.js";
import { addDays, addHours } from "date-fns";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
// 2.2:
// -> Creating a new customer with a payment method should attach the pro product with default trial
@@ -28,13 +27,13 @@ import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
const testCase = "defaultTrial2";
describe(`${chalk.yellowBright(`advanced/${testCase}: ensure trial transitions into full product if payment method is valid`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockID: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = Math.floor(new Date().getTime() / 1000);
const curUnix = Math.floor(new Date().getTime() / 1000);
before(async function () {
await setupBefore(this);
@@ -57,8 +56,8 @@ describe(`${chalk.yellowBright(`advanced/${testCase}: ensure trial transitions i
testClockID = res.testClockId;
});
it("should create a customer with the paid default trial", async function () {
let customer = await autumn.customers.get(customerId);
it("should create a customer with the paid default trial", async () => {
const customer = await autumn.customers.get(customerId);
expectProductAttached({
customer,
@@ -66,7 +65,7 @@ describe(`${chalk.yellowBright(`advanced/${testCase}: ensure trial transitions i
});
});
it("should be active after 7 days", async function () {
it("should be active after 7 days", async () => {
await advanceTestClock({
stripeCli,
testClockId: testClockID,
@@ -77,7 +76,7 @@ describe(`${chalk.yellowBright(`advanced/${testCase}: ensure trial transitions i
waitForSeconds: 10,
});
let customer = await autumn.customers.get(customerId);
const customer = await autumn.customers.get(customerId);
expectProductAttached({
customer,

View File

@@ -1,26 +1,24 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
// Manual customer creation - not using initCustomer to control test clock properly
import {
APIVersion,
AppEnv,
type AppEnv,
CusProductStatus,
Organization,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { addDays, addHours } from "date-fns";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomerV2 } from "@/utils/scriptUtils/initCustomer.js";
import {
defaultTrialFree,
defaultTrialPro,
setupDefaultTrialBefore,
} from "./defaultTrialBefore.test.js";
import { initCustomerV2 } from "@/utils/scriptUtils/initCustomer.js";
import { addDays, addHours } from "date-fns";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
// 2.3:
// -> Creating a new customer with a fake payment method should attach the pro product with default trial
@@ -29,13 +27,13 @@ import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
const testCase = "defaultTrial3";
describe(`${chalk.yellowBright(`advanced/${testCase}: ensure trials cancel with bad payment method`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockID: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = Math.floor(new Date().getTime() / 1000);
const curUnix = Math.floor(new Date().getTime() / 1000);
before(async function () {
await setupBefore(this);
@@ -58,8 +56,8 @@ describe(`${chalk.yellowBright(`advanced/${testCase}: ensure trials cancel with
testClockID = res.testClockId;
});
it("should create a customer with the paid default trial", async function () {
let customer = await autumn.customers.get(customerId);
it("should create a customer with the paid default trial", async () => {
const customer = await autumn.customers.get(customerId);
expectProductAttached({
customer,
@@ -67,7 +65,7 @@ describe(`${chalk.yellowBright(`advanced/${testCase}: ensure trials cancel with
});
});
it("should cancel after 7 days", async function () {
it("should cancel after 7 days", async () => {
await advanceTestClock({
stripeCli,
testClockId: testClockID,
@@ -78,7 +76,7 @@ describe(`${chalk.yellowBright(`advanced/${testCase}: ensure trials cancel with
waitForSeconds: 30,
});
let customer = await autumn.customers.get(customerId);
const customer = await autumn.customers.get(customerId);
expectProductAttached({
customer,

View File

@@ -1,14 +1,14 @@
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import {
APIVersion,
FreeTrialDuration,
LegacyVersion,
ProductItemInterval,
} from "@autumn/shared";
import { TestFeature } from "tests/setup/v2Features.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
export let defaultTrialPro = constructProduct({
export const defaultTrialPro = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Words,
@@ -29,7 +29,7 @@ export let defaultTrialPro = constructProduct({
},
});
export let defaultTrialFree = constructProduct({
export const defaultTrialFree = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Words,
@@ -44,9 +44,9 @@ export let defaultTrialFree = constructProduct({
});
export const setupDefaultTrialBefore = async ({}: {}) => {
const autumn = new AutumnInt({ version: APIVersion.v1_2 });
const autumn = new AutumnInt({ version: LegacyVersion.v1_2 });
for (const product of [defaultTrialPro, defaultTrialFree]) {
let res = await autumn.products.get(product.id);
const res = await autumn.products.get(product.id);
if (res.code === "product_not_found") {
try {

View File

@@ -1,26 +1,28 @@
import { expect } from "chai";
import chalk from "chalk";
import { features } from "tests/global.js";
import { setupBefore } from "tests/before.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
BillingInterval,
LegacyVersion,
ProductItemFeatureType,
UsageModel,
} from "@autumn/shared";
import { createProducts } from "tests/utils/productUtils.js";
import { expect } from "chai";
import chalk from "chalk";
import { setupBefore } from "tests/before.js";
import { features } from "tests/global.js";
import {
getPrepaidCusEnt,
getUsageCusEnt,
} from "tests/utils/cusProductUtils/cusEntSearchUtils.js";
import { getMainCusProduct } from "tests/utils/cusProductUtils/cusProductUtils.js";
import { getUsageCusEnt } from "tests/utils/cusProductUtils/cusEntSearchUtils.js";
import { getPrepaidCusEnt } from "tests/utils/cusProductUtils/cusEntSearchUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeaturePriceItem } from "@/internal/products/product-items/productItemUtils.js";
import { timeout } from "@/utils/genUtils.js";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
// Scenario 1: prepaid + pay per use monthly -> prepaid + pay per use monthly
let pro = {
const pro = {
id: "multiFeature1Pro",
name: "Multi Feature 1 Pro",
items: {
@@ -43,7 +45,7 @@ let pro = {
},
};
let premium = {
const premium = {
id: "multiFeature1Premium",
name: "Multi Feature 1 Premium",
items: {
@@ -82,19 +84,19 @@ export const getPrepaidAndUsageCusEnts = async ({
env: AppEnv;
featureId: string;
}) => {
let mainCusProduct = await getMainCusProduct({
const mainCusProduct = await getMainCusProduct({
customerId,
db,
orgId,
env,
});
let prepaidCusEnt = getPrepaidCusEnt({
const prepaidCusEnt = getPrepaidCusEnt({
cusProduct: mainCusProduct!,
featureId,
});
let usageCusEnt = getUsageCusEnt({
const usageCusEnt = getUsageCusEnt({
cusProduct: mainCusProduct!,
featureId,
});
@@ -107,17 +109,17 @@ describe(`${chalk.yellowBright(
"multiFeature1: Testing prepaid + pay per use -> prepaid + pay per use",
)}`, () => {
let autumn: AutumnInt = new AutumnInt();
let autumn2: AutumnInt = new AutumnInt({ version: APIVersion.v1_2 });
let customerId = testCase;
const autumn2: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_2 });
const customerId = testCase;
let prepaidQuantity = 10;
let prepaidAllowance = pro.items.prepaid.included_usage + prepaidQuantity;
const prepaidQuantity = 10;
const prepaidAllowance = pro.items.prepaid.included_usage + prepaidQuantity;
let totalUsage = 0;
let premiumPrepaidAllowance =
const premiumPrepaidAllowance =
premium.items.prepaid.included_usage + prepaidQuantity;
let optionsList = [
const optionsList = [
{
feature_id: features.metered1.id,
quantity: prepaidQuantity,
@@ -154,7 +156,7 @@ describe(`${chalk.yellowBright(
options: optionsList,
});
let { prepaidCusEnt, usageCusEnt } = await getPrepaidAndUsageCusEnts({
const { prepaidCusEnt, usageCusEnt } = await getPrepaidAndUsageCusEnts({
customerId,
db: this.db,
orgId: this.org.id,
@@ -170,7 +172,7 @@ describe(`${chalk.yellowBright(
});
it("should use prepaid allowance first", async function () {
let value = 60;
const value = 60;
await autumn.track({
customer_id: customerId,
@@ -182,7 +184,7 @@ describe(`${chalk.yellowBright(
await timeout(3000);
let { prepaidCusEnt, usageCusEnt } = await getPrepaidAndUsageCusEnts({
const { prepaidCusEnt, usageCusEnt } = await getPrepaidAndUsageCusEnts({
customerId,
db: this.db,
orgId: this.org.id,
@@ -195,7 +197,7 @@ describe(`${chalk.yellowBright(
});
it("should have correct usage / invoice after upgrade", async function () {
let value = 60;
const value = 60;
await autumn.track({
customer_id: customerId,
value,
@@ -206,7 +208,7 @@ describe(`${chalk.yellowBright(
await timeout(10000);
let { usageCusEnt } = await getPrepaidAndUsageCusEnts({
const { usageCusEnt } = await getPrepaidAndUsageCusEnts({
customerId,
db: this.db,
orgId: this.org.id,
@@ -220,7 +222,7 @@ describe(`${chalk.yellowBright(
options: optionsList,
});
let { prepaidCusEnt, usageCusEnt: newUsageCusEnt } =
const { prepaidCusEnt, usageCusEnt: newUsageCusEnt } =
await getPrepaidAndUsageCusEnts({
customerId,
db: this.db,
@@ -230,19 +232,19 @@ describe(`${chalk.yellowBright(
});
// Check invoice too
let { invoices } = await autumn2.customers.get(customerId);
const { invoices } = await autumn2.customers.get(customerId);
let invoice1Amount =
const invoice1Amount =
(premium.items.prepaid.price ?? 0) * prepaidQuantity -
(pro.items.prepaid.price ?? 0) * prepaidQuantity;
let invoice0Amount = value * (pro.items.payPerUse.price ?? 0);
const invoice0Amount = value * (pro.items.payPerUse.price ?? 0);
let totalAmount = invoice1Amount + invoice0Amount;
const totalAmount = invoice1Amount + invoice0Amount;
expect(invoices![0].total).to.equal(totalAmount);
let leftover = premiumPrepaidAllowance - totalUsage + value;
const leftover = premiumPrepaidAllowance - totalUsage + value;
expect(prepaidCusEnt?.balance).to.equal(Math.max(0, leftover));
expect(newUsageCusEnt?.balance).to.equal(0);
});

View File

@@ -1,34 +1,32 @@
import { expect } from "chai";
import chalk from "chalk";
import { features } from "tests/global.js";
import { setupBefore } from "tests/before.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
BillingInterval,
EntInterval,
LegacyVersion,
ProductItemFeatureType,
UsageModel,
} from "@autumn/shared";
import { createProduct } from "tests/utils/productUtils.js";
import { getMainCusProduct } from "tests/utils/cusProductUtils/cusProductUtils.js";
import { expect } from "chai";
import chalk from "chalk";
import { setupBefore } from "tests/before.js";
import { features } from "tests/global.js";
import {
getLifetimeFreeCusEnt,
getUsageCusEnt,
} from "tests/utils/cusProductUtils/cusEntSearchUtils.js";
import { getMainCusProduct } from "tests/utils/cusProductUtils/cusProductUtils.js";
import { createProduct } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import {
constructFeatureItem,
constructFeaturePriceItem,
} from "@/internal/products/product-items/productItemUtils.js";
import { timeout } from "@/utils/genUtils.js";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
// Scenario 1: prepaid + pay per use monthly -> prepaid + pay per use monthly
let pro = {
const pro = {
id: "multiFeature2Pro",
name: "Multi Feature 2 Pro",
items: {
@@ -48,7 +46,7 @@ let pro = {
},
};
let premium = {
const premium = {
id: "multiFeature2Premium",
name: "Multi Feature 2 Premium",
items: {
@@ -77,19 +75,19 @@ export const getLifetimeAndUsageCusEnts = async ({
env: AppEnv;
featureId: string;
}) => {
let mainCusProduct = await getMainCusProduct({
const mainCusProduct = await getMainCusProduct({
customerId: customerId,
db,
orgId,
env,
});
let lifetimeCusEnt = getLifetimeFreeCusEnt({
const lifetimeCusEnt = getLifetimeFreeCusEnt({
cusProduct: mainCusProduct!,
featureId,
});
let usageCusEnt = getUsageCusEnt({
const usageCusEnt = getUsageCusEnt({
cusProduct: mainCusProduct!,
featureId,
});
@@ -102,8 +100,8 @@ describe(`${chalk.yellowBright(
"multiFeature2: Testing lifetime + pay per use -> pay per use",
)}`, () => {
let autumn: AutumnInt = new AutumnInt();
let autumn2: AutumnInt = new AutumnInt({ version: APIVersion.v1_2 });
let customerId = testCase;
const autumn2: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_2 });
const customerId = testCase;
let totalUsage = 0;
@@ -144,7 +142,7 @@ describe(`${chalk.yellowBright(
product_id: pro.id,
});
let { lifetimeCusEnt, usageCusEnt } = await getLifetimeAndUsageCusEnts({
const { lifetimeCusEnt, usageCusEnt } = await getLifetimeAndUsageCusEnts({
customerId,
db: this.db,
orgId: this.org.id,
@@ -158,7 +156,7 @@ describe(`${chalk.yellowBright(
});
it("should use lifetime allowance first", async function () {
let value = pro.items.lifetime.included_usage as number;
const value = pro.items.lifetime.included_usage as number;
await autumn.events.send({
customerId,
@@ -170,7 +168,7 @@ describe(`${chalk.yellowBright(
await timeout(3000);
let { lifetimeCusEnt, usageCusEnt } = await getLifetimeAndUsageCusEnts({
const { lifetimeCusEnt, usageCusEnt } = await getLifetimeAndUsageCusEnts({
customerId,
db: this.db,
orgId: this.org.id,
@@ -185,7 +183,7 @@ describe(`${chalk.yellowBright(
});
it("should have correct usage after upgrade", async function () {
let value = 20;
const value = 20;
await autumn.track({
customer_id: customerId,
@@ -201,7 +199,7 @@ describe(`${chalk.yellowBright(
});
// return;
let { lifetimeCusEnt, usageCusEnt: newUsageCusEnt } =
const { lifetimeCusEnt, usageCusEnt: newUsageCusEnt } =
await getLifetimeAndUsageCusEnts({
customerId,
db: this.db,
@@ -214,10 +212,10 @@ describe(`${chalk.yellowBright(
expect(newUsageCusEnt?.balance).to.equal(-50);
// Check invoice too
let res = await autumn2.customers.get(customerId);
let invoices = res.invoices;
const res = await autumn2.customers.get(customerId);
const invoices = res.invoices;
let invoice0Amount = value * (pro.items.payPerUse.price ?? 0);
const invoice0Amount = value * (pro.items.payPerUse.price ?? 0);
expect(invoices![0].total).to.equal(
invoice0Amount,
"Invoice 0 should be 0",

View File

@@ -1,31 +1,32 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
Customer,
LimitedItem,
Organization,
type AppEnv,
type Customer,
LegacyVersion,
type LimitedItem,
type Organization,
ProductItemInterval,
RolloverDuration,
} from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { expect } from "chai";
import chalk from "chalk";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { resetAndGetCusEnt } from "./rolloverTestUtils.js";
let rolloverConfig = { max: 500, length: 1, duration: RolloverDuration.Month };
const rolloverConfig = {
max: 500,
length: 1,
duration: RolloverDuration.Month,
};
const messagesItem = constructFeatureItem({
featureId: TestFeature.Messages,
includedUsage: 400,
@@ -33,7 +34,7 @@ const messagesItem = constructFeatureItem({
rolloverConfig,
}) as LimitedItem;
export let free = constructProduct({
export const free = constructProduct({
items: [messagesItem],
type: "free",
isDefault: false,
@@ -43,14 +44,14 @@ const testCase = "rollover1";
// , per entity and regular
describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let customer: Customer;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -88,17 +89,17 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item`
customer = res.customer;
});
it("should attach free product", async function () {
it("should attach free product", async () => {
await autumn.attach({
customer_id: customerId,
product_id: free.id,
});
});
let messageUsage = 250;
const messageUsage = 250;
let curBalance = messagesItem.included_usage;
it("should create track messages, reset, and have correct rollover", async function () {
it("should create track messages, reset, and have correct rollover", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
@@ -114,25 +115,25 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item`
featureId: TestFeature.Messages,
});
let cus = await autumn.customers.get(customerId);
let msgesFeature = cus.features[TestFeature.Messages];
const cus = await autumn.customers.get(customerId);
const msgesFeature = cus.features[TestFeature.Messages];
let expectedRollover = Math.min(
const expectedRollover = Math.min(
messagesItem.included_usage - messageUsage,
rolloverConfig.max,
);
let expectedBalance = messagesItem.included_usage + expectedRollover;
const expectedBalance = messagesItem.included_usage + expectedRollover;
expect(msgesFeature).to.exist;
expect(msgesFeature?.balance).to.equal(expectedBalance);
// @ts-ignore
// @ts-expect-error
expect(msgesFeature?.rollovers[0].balance).to.equal(expectedRollover);
curBalance = expectedBalance;
});
// let usage2 = 50;
it("should reset again and have correct rollover", async function () {
it("should reset again and have correct rollover", async () => {
await resetAndGetCusEnt({
db,
customer,
@@ -140,22 +141,22 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item`
featureId: TestFeature.Messages,
});
let expectedRollover = Math.min(curBalance, rolloverConfig.max);
let expectedBalance = messagesItem.included_usage + expectedRollover;
const expectedRollover = Math.min(curBalance, rolloverConfig.max);
const expectedBalance = messagesItem.included_usage + expectedRollover;
let cus = await autumn.customers.get(customerId);
let msgesFeature = cus.features[TestFeature.Messages];
const cus = await autumn.customers.get(customerId);
const msgesFeature = cus.features[TestFeature.Messages];
expect(msgesFeature).to.exist;
expect(msgesFeature?.balance).to.equal(expectedBalance);
// @ts-ignore (oldest rollover should be 100 (150 - 50))
// @ts-expect-error (oldest rollover should be 100 (150 - 50))
expect(msgesFeature?.rollovers[0].balance).to.equal(100);
// @ts-ignore (newest rollover should be 400 (msges.included_usage))
// @ts-expect-error (newest rollover should be 400 (msges.included_usage))
expect(msgesFeature?.rollovers[1].balance).to.equal(400);
});
it("should track messages and deduct from rollovers first", async function () {
it("should track messages and deduct from rollovers first", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
@@ -164,19 +165,19 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item`
await timeout(3000);
let cus = await autumn.customers.get(customerId);
let msgesFeature = cus.features[TestFeature.Messages];
const cus = await autumn.customers.get(customerId);
const msgesFeature = cus.features[TestFeature.Messages];
// @ts-ignore
let rollover1 = msgesFeature?.rollovers[0];
// @ts-ignore
let rollover2 = msgesFeature?.rollovers[1];
// @ts-expect-error
const rollover1 = msgesFeature?.rollovers[0];
// @ts-expect-error
const rollover2 = msgesFeature?.rollovers[1];
expect(rollover1.balance).to.equal(0);
expect(rollover2.balance).to.equal(350);
});
it("should track and deduct from rollover + original balance", async function () {
it("should track and deduct from rollover + original balance", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
@@ -185,11 +186,11 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item`
await timeout(3000);
let cus = await autumn.customers.get(customerId);
let msgesFeature = cus.features[TestFeature.Messages];
const cus = await autumn.customers.get(customerId);
const msgesFeature = cus.features[TestFeature.Messages];
// @ts-ignore
let rollovers = msgesFeature.rollovers;
// @ts-expect-error
const rollovers = msgesFeature.rollovers;
expect(rollovers![0].balance).to.equal(0);
expect(rollovers![1].balance).to.equal(0);
expect(msgesFeature.balance).to.equal(messagesItem.included_usage - 50);

View File

@@ -1,34 +1,32 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
Customer,
LimitedItem,
Organization,
type AppEnv,
type Customer,
LegacyVersion,
type LimitedItem,
type Organization,
ProductItemInterval,
RolloverDuration,
} from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { expect } from "chai";
import { getMainCusProduct } from "@/internal/customers/cusProducts/cusProductUtils.js";
import { cusProductToCusEnt } from "@/internal/customers/cusProducts/cusProductUtils/convertCusProduct.js";
import chalk from "chalk";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import { resetCustomerEntitlement } from "@/cron/cronUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { resetAndGetCusEnt } from "./rolloverTestUtils.js";
let rolloverConfig = { max: 500, length: 1, duration: RolloverDuration.Month };
const rolloverConfig = {
max: 500,
length: 1,
duration: RolloverDuration.Month,
};
const msgesItem = constructFeatureItem({
featureId: TestFeature.Messages,
@@ -38,7 +36,7 @@ const msgesItem = constructFeatureItem({
entityFeatureId: TestFeature.Users,
}) as LimitedItem;
export let free = constructProduct({
export const free = constructProduct({
items: [msgesItem],
type: "free",
isDefault: false,
@@ -48,14 +46,14 @@ const testCase = "rollover2";
// , per entity and regular
describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item (per entity)`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let customer: Customer;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -106,7 +104,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item
},
];
it("should attach pro product", async function () {
it("should attach pro product", async () => {
await autumn.attach({
customer_id: customerId,
product_id: free.id,
@@ -115,12 +113,12 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item
await autumn.entities.create(customerId, entities);
});
let entity1Id = entities[0].id;
let entity2Id = entities[1].id;
let newEntity1Balance = 300;
let newEntity2Balance = 200;
let includedUsage = msgesItem.included_usage;
let usages = [
const entity1Id = entities[0].id;
const entity2Id = entities[1].id;
const newEntity1Balance = 300;
const newEntity2Balance = 200;
const includedUsage = msgesItem.included_usage;
const usages = [
{
entityId: entity1Id,
usage: includedUsage - newEntity1Balance,
@@ -133,7 +131,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item
},
];
it("should create track messages, reset, and have correct rollover", async function () {
it("should create track messages, reset, and have correct rollover", async () => {
for (const usage of usages) {
await autumn.track({
customer_id: customerId,
@@ -154,9 +152,9 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item
});
for (const usage of usages) {
let entity = await autumn.entities.get(customerId, usage.entityId);
let msgesFeature = entity.features[TestFeature.Messages];
let expectedRollover = Math.min(usage.rollover, rolloverConfig.max);
const entity = await autumn.entities.get(customerId, usage.entityId);
const msgesFeature = entity.features[TestFeature.Messages];
const expectedRollover = Math.min(usage.rollover, rolloverConfig.max);
expect(msgesFeature.rollovers.length).to.equal(1);
expect(msgesFeature.balance).to.equal(includedUsage + expectedRollover);
@@ -164,7 +162,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item
}
});
it("should reset again and have correct rollovers", async function () {
it("should reset again and have correct rollovers", async () => {
await resetAndGetCusEnt({
db,
customer,
@@ -172,22 +170,22 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item
featureId: TestFeature.Messages,
});
let entity1 = await autumn.entities.get(customerId, entity1Id);
let entity1Msges = entity1.features[TestFeature.Messages];
const entity1 = await autumn.entities.get(customerId, entity1Id);
const entity1Msges = entity1.features[TestFeature.Messages];
// 400, 300 -> 400, 100 (max is 500)
let rollovers = entity1Msges.rollovers;
const rollovers = entity1Msges.rollovers;
expect(rollovers[0].balance).to.equal(100);
expect(rollovers[1].balance).to.equal(400);
let entity2 = await autumn.entities.get(customerId, entity2Id);
let entity2Msges = entity2.features[TestFeature.Messages];
const entity2 = await autumn.entities.get(customerId, entity2Id);
const entity2Msges = entity2.features[TestFeature.Messages];
// 400, 200 -> 400, 0 (max is 500)
let rollovers2 = entity2Msges.rollovers;
const rollovers2 = entity2Msges.rollovers;
expect(rollovers2[0].balance).to.equal(100);
expect(rollovers2[1].balance).to.equal(400);
});
it("should track and deduct from oldest rollovers first", async function () {
it("should track and deduct from oldest rollovers first", async () => {
for (const entity of entities) {
await autumn.track({
customer_id: customerId,
@@ -197,16 +195,16 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item
});
await timeout(2000);
let entRes = await autumn.entities.get(customerId, entity.id);
let msgesFeature = entRes.features[TestFeature.Messages];
let rollovers = msgesFeature.rollovers;
const entRes = await autumn.entities.get(customerId, entity.id);
const msgesFeature = entRes.features[TestFeature.Messages];
const rollovers = msgesFeature.rollovers;
expect(rollovers[0].balance).to.equal(0);
expect(rollovers[1].balance).to.equal(350);
expect(msgesFeature.balance).to.equal(includedUsage + 350);
}
});
it("should track past rollovers and deduct from original balance", async function () {
it("should track past rollovers and deduct from original balance", async () => {
for (const entity of entities) {
await autumn.track({
customer_id: customerId,
@@ -216,9 +214,9 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for feature item
});
await timeout(2000);
let entRes = await autumn.entities.get(customerId, entity.id);
let msgesFeature = entRes.features[TestFeature.Messages];
let rollovers = msgesFeature.rollovers;
const entRes = await autumn.entities.get(customerId, entity.id);
const msgesFeature = entRes.features[TestFeature.Messages];
const rollovers = msgesFeature.rollovers;
expect(rollovers[0].balance).to.equal(0);
expect(rollovers[1].balance).to.equal(0);
expect(msgesFeature.balance).to.equal(includedUsage - 50);

View File

@@ -1,38 +1,39 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
Customer,
LimitedItem,
Organization,
type AppEnv,
type Customer,
LegacyVersion,
type LimitedItem,
type Organization,
RolloverDuration,
} from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructArrearProratedItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { expect } from "chai";
import { timeout } from "@/utils/genUtils.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import chalk from "chalk";
import { addMonths } from "date-fns";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import { constructArrearProratedItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
let rolloverConfig = { max: 500, length: 1, duration: RolloverDuration.Month };
const rolloverConfig = {
max: 500,
length: 1,
duration: RolloverDuration.Month,
};
const messagesItem = constructArrearProratedItem({
featureId: TestFeature.Messages,
includedUsage: 400,
rolloverConfig,
}) as LimitedItem;
export let pro = constructProduct({
export const pro = constructProduct({
items: [messagesItem],
type: "pro",
isDefault: false,
@@ -41,14 +42,14 @@ export let pro = constructProduct({
const testCase = "rollover3";
describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for usage price feature`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let customer: Customer;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -86,17 +87,17 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for usage price f
customer = res.customer;
});
it("should attach pro product", async function () {
it("should attach pro product", async () => {
await autumn.attach({
customer_id: customerId,
product_id: pro.id,
});
});
let rollover = 250;
const rollover = 250;
let curBalance = messagesItem.included_usage;
it("should create track messages, reset, and have correct rollover", async function () {
it("should create track messages, reset, and have correct rollover", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
@@ -112,14 +113,14 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for usage price f
waitForSeconds: 20,
});
let cus = await autumn.customers.get(customerId);
let msgesFeature = cus.features[TestFeature.Messages];
const cus = await autumn.customers.get(customerId);
const msgesFeature = cus.features[TestFeature.Messages];
let expectedBalance = messagesItem.included_usage + rollover;
const expectedBalance = messagesItem.included_usage + rollover;
expect(msgesFeature).to.exist;
expect(msgesFeature?.balance).to.equal(expectedBalance);
// @ts-ignore
// @ts-expect-error
expect(msgesFeature?.rollovers[0].balance).to.equal(rollover);
curBalance = expectedBalance;
});

View File

@@ -1,32 +1,32 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
Customer,
LimitedItem,
Organization,
type AppEnv,
type Customer,
LegacyVersion,
type LimitedItem,
type Organization,
RolloverDuration,
} from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { expect } from "chai";
import { timeout } from "@/utils/genUtils.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import chalk from "chalk";
import { addMonths } from "date-fns";
import { resetAndGetCusEnt } from "./rolloverTestUtils.js";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
let rolloverConfig = { max: 400, length: 1, duration: RolloverDuration.Month };
const rolloverConfig = {
max: 400,
length: 1,
duration: RolloverDuration.Month,
};
const messagesItem = constructPrepaidItem({
featureId: TestFeature.Messages,
includedUsage: 100,
@@ -35,7 +35,7 @@ const messagesItem = constructPrepaidItem({
rolloverConfig,
}) as LimitedItem;
export let pro = constructProduct({
export const pro = constructProduct({
items: [messagesItem],
type: "pro",
isDefault: false,
@@ -44,8 +44,8 @@ export let pro = constructProduct({
const testCase = "rollover4";
describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for usage price feature`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let customer: Customer;
@@ -89,8 +89,8 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for usage price f
customer = res.customer;
});
let paidQuantity = 300;
let balance = paidQuantity + messagesItem.included_usage;
const paidQuantity = 300;
const balance = paidQuantity + messagesItem.included_usage;
const options = [
{
feature_id: TestFeature.Messages,
@@ -98,7 +98,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for usage price f
},
];
it("should attach pro product", async function () {
it("should attach pro product", async () => {
await autumn.attach({
customer_id: customerId,
product_id: pro.id,
@@ -106,8 +106,8 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for usage price f
});
});
let rollover = 50;
it("should create track messages, reset, and have correct rollover", async function () {
const rollover = 50;
it("should create track messages, reset, and have correct rollover", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
@@ -123,11 +123,11 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for usage price f
waitForSeconds: 20,
});
let cus = await autumn.customers.get(customerId);
let msgesFeature = cus.features[TestFeature.Messages];
const cus = await autumn.customers.get(customerId);
const msgesFeature = cus.features[TestFeature.Messages];
// @ts-ignore
let rollovers = msgesFeature?.rollovers;
// @ts-expect-error
const rollovers = msgesFeature?.rollovers;
expect(msgesFeature).to.exist;
expect(msgesFeature?.balance).to.equal(balance + rollover);
@@ -135,7 +135,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for usage price f
});
// let usage2 = 50;
it("should reset again and have correct rollover", async function () {
it("should reset again and have correct rollover", async () => {
await advanceTestClock({
stripeCli,
testClockId,
@@ -143,11 +143,11 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for usage price f
waitForSeconds: 20,
});
let newRollover = Math.min(balance + rollover, rolloverConfig.max);
let cus = await autumn.customers.get(customerId);
let msgesFeature = cus.features[TestFeature.Messages];
// @ts-ignore
let rollovers = msgesFeature?.rollovers;
const newRollover = Math.min(balance + rollover, rolloverConfig.max);
const cus = await autumn.customers.get(customerId);
const msgesFeature = cus.features[TestFeature.Messages];
// @ts-expect-error
const rollovers = msgesFeature?.rollovers;
expect(msgesFeature).to.exist;
expect(msgesFeature?.balance).to.equal(balance + newRollover);

View File

@@ -1,30 +1,27 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
Customer,
LimitedItem,
Organization,
type AppEnv,
type Customer,
LegacyVersion,
type LimitedItem,
type Organization,
RolloverDuration,
} from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { expect } from "chai";
import chalk from "chalk";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { resetAndGetCusEnt } from "./rolloverTestUtils.js";
let freeRollover = { max: 1000, length: 1, duration: RolloverDuration.Month };
let proRollover = { max: 600, length: 1, duration: RolloverDuration.Month };
const freeRollover = { max: 1000, length: 1, duration: RolloverDuration.Month };
const proRollover = { max: 600, length: 1, duration: RolloverDuration.Month };
const freeMsges = constructFeatureItem({
featureId: TestFeature.Messages,
@@ -52,13 +49,13 @@ const pro = constructProduct({
const testCase = "rollover5";
describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for upgrade`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let customer: Customer;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -96,14 +93,14 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for upgrade`)}`,
customer = res.customer;
});
it("should attach free product", async function () {
it("should attach free product", async () => {
await autumn.attach({
customer_id: customerId,
product_id: free.id,
});
});
it("should create rollovers", async function () {
it("should create rollovers", async () => {
await resetAndGetCusEnt({
customer,
db,
@@ -123,17 +120,17 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for upgrade`)}`,
product_id: pro.id,
});
let cus = await autumn.customers.get(customerId);
let msgesFeature = cus.features[TestFeature.Messages];
let freeRolloverBalance = freeMsges.included_usage * 2;
let proRolloverBalance = Math.min(proRollover.max, freeRolloverBalance);
const cus = await autumn.customers.get(customerId);
const msgesFeature = cus.features[TestFeature.Messages];
const freeRolloverBalance = freeMsges.included_usage * 2;
const proRolloverBalance = Math.min(proRollover.max, freeRolloverBalance);
expect(msgesFeature).to.exist;
expect(msgesFeature?.balance).to.equal(
proMsges.included_usage + proRolloverBalance,
);
// @ts-ignore
let rollovers = msgesFeature?.rollovers;
// @ts-expect-error
const rollovers = msgesFeature?.rollovers;
expect(rollovers[0].balance).to.equal(100);
expect(rollovers[1].balance).to.equal(500);
});

View File

@@ -1,33 +1,30 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
Customer,
LimitedItem,
Organization,
type AppEnv,
type Customer,
LegacyVersion,
type LimitedItem,
type Organization,
RolloverDuration,
} from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { expect } from "chai";
import { resetAndGetCusEnt } from "./rolloverTestUtils.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import chalk from "chalk";
import { addHours, addMonths } from "date-fns";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import { resetAndGetCusEnt } from "./rolloverTestUtils.js";
let freeRollover = { max: 600, length: 1, duration: RolloverDuration.Month };
let proRollover = { max: 1000, length: 1, duration: RolloverDuration.Month };
const freeRollover = { max: 600, length: 1, duration: RolloverDuration.Month };
const proRollover = { max: 1000, length: 1, duration: RolloverDuration.Month };
const freeMsges = constructFeatureItem({
featureId: TestFeature.Messages,
@@ -55,13 +52,13 @@ const pro = constructProduct({
const testCase = "rollover6";
describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for upgrade`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let customer: Customer;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -99,14 +96,14 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for upgrade`)}`,
customer = res.customer;
});
it("should attach free product", async function () {
it("should attach free product", async () => {
await autumn.attach({
customer_id: customerId,
product_id: pro.id,
});
});
it("should create rollovers", async function () {
it("should create rollovers", async () => {
await resetAndGetCusEnt({
customer,
db,
@@ -136,18 +133,18 @@ describe(`${chalk.yellowBright(`${testCase}: Testing rollovers for upgrade`)}`,
waitForSeconds: 20,
});
let cus = await autumn.customers.get(customerId);
let msgesFeature = cus.features[TestFeature.Messages];
let proRolloverBalance = proMsges.included_usage * 2;
let freeRolloverBalance = Math.min(freeRollover.max, proRolloverBalance);
const cus = await autumn.customers.get(customerId);
const msgesFeature = cus.features[TestFeature.Messages];
const proRolloverBalance = proMsges.included_usage * 2;
const freeRolloverBalance = Math.min(freeRollover.max, proRolloverBalance);
expect(msgesFeature).to.exist;
expect(msgesFeature?.balance).to.equal(
freeMsges.included_usage + freeRolloverBalance,
);
// @ts-ignore
let rollovers = msgesFeature?.rollovers;
// @ts-expect-error
const rollovers = msgesFeature?.rollovers;
expect(rollovers[0].balance).to.equal(100);
expect(rollovers[1].balance).to.equal(500);
});

View File

@@ -1,19 +1,23 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, ErrCode, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructArrearProratedItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { expectAutumnError } from "tests/utils/expectUtils/expectErrUtils.js";
import {
type AppEnv,
ErrCode,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectAutumnError } from "tests/utils/expectUtils/expectErrUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructArrearProratedItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const userItem = constructArrearProratedItem({
featureId: TestFeature.Users,
@@ -22,7 +26,7 @@ const userItem = constructArrearProratedItem({
usageLimit: 2,
});
export let pro = constructProduct({
export const pro = constructProduct({
items: [userItem],
type: "pro",
});
@@ -30,13 +34,13 @@ export let pro = constructProduct({
const testCase = "usageLimit1";
describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for entities`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -96,7 +100,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for entities`)
},
];
it("should attach pro product", async function () {
it("should attach pro product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -107,7 +111,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for entities`)
env,
});
});
it("should create more entities than the limit and hit error", async function () {
it("should create more entities than the limit and hit error", async () => {
await expectAutumnError({
errCode: ErrCode.FeatureLimitReached,
func: async () => {
@@ -116,7 +120,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for entities`)
});
});
it("should create entities one by one, then hit usage limit", async function () {
it("should create entities one by one, then hit usage limit", async () => {
await autumn.entities.create(customerId, entities[0]);
await autumn.entities.create(customerId, entities[1]);
@@ -128,7 +132,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for entities`)
});
});
it("should have correct check and get customer value", async function () {
it("should have correct check and get customer value", async () => {
const check = await autumn.check({
customer_id: customerId,
feature_id: TestFeature.Users,
@@ -136,10 +140,10 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for entities`)
const customer = await autumn.customers.get(customerId);
expect(check.balance).to.equal(-2);
// @ts-ignore
// @ts-expect-error
expect(check.usage_limit).to.equal(userItem.usage_limit);
// @ts-ignore
// @ts-expect-error
expect(customer.features[TestFeature.Users].usage_limit).to.equal(
userItem.usage_limit,
);

View File

@@ -1,22 +1,26 @@
import {
type AppEnv,
LegacyVersion,
type LimitedItem,
type Organization,
} from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, LimitedItem, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import {
constructArrearItem,
constructFeatureItem,
} from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { expect } from "chai";
import { timeout } from "@/utils/genUtils.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const messageItem = constructArrearItem({
featureId: TestFeature.Messages,
@@ -26,7 +30,7 @@ const messageItem = constructArrearItem({
usageLimit: 500,
}) as LimitedItem;
export let pro = constructProduct({
export const pro = constructProduct({
items: [messageItem],
type: "pro",
});
@@ -45,13 +49,13 @@ const messageAddOn = constructProduct({
const testCase = "usageLimit2";
describe(`${chalk.yellowBright(`${testCase}: Testing usage limits, usage prices`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -88,7 +92,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits, usage prices`
testClockId = testClockId1!;
});
it("should attach pro product", async function () {
it("should attach pro product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -100,10 +104,10 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits, usage prices`
});
});
let initialUsage =
const initialUsage =
messageItem.included_usage + messageItem.usage_limit! + 1000;
it("should track more messages than limit and not surpass", async function () {
it("should track more messages than limit and not surpass", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
@@ -112,36 +116,37 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits, usage prices`
await timeout(2000);
let check = await autumn.check({
const check = await autumn.check({
customer_id: customerId,
feature_id: TestFeature.Messages,
});
let customer = await autumn.customers.get(customerId);
const customer = await autumn.customers.get(customerId);
let expectedBalance = messageItem.included_usage - messageItem.usage_limit!;
const expectedBalance =
messageItem.included_usage - messageItem.usage_limit!;
expect(check.balance).to.equal(expectedBalance);
expect(check.allowed).to.equal(false);
// @ts-ignore
// @ts-expect-error
expect(check.usage_limit!).to.equal(messageItem.usage_limit!);
// @ts-ignore
// @ts-expect-error
expect(customer.features[TestFeature.Messages].usage_limit).to.equal(
messageItem.usage_limit!,
);
});
it("should purchase add ons and have correct check results", async function () {
it("should purchase add ons and have correct check results", async () => {
await autumn.attach({
customer_id: customerId,
product_id: messageAddOn.id,
});
let check = await autumn.check({
const check = await autumn.check({
customer_id: customerId,
feature_id: TestFeature.Messages,
});
let customer = await autumn.customers.get(customerId);
let expectedBalance =
const customer = await autumn.customers.get(customerId);
const expectedBalance =
messageItem.included_usage -
messageItem.usage_limit! +
addOnMessages.included_usage;
@@ -149,17 +154,17 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits, usage prices`
expect(check.balance).to.equal(expectedBalance);
expect(check.allowed).to.equal(true);
// @ts-ignore
// @ts-expect-error
expect(check.usage_limit!).to.equal(
messageItem.usage_limit! + addOnMessages.included_usage,
);
// @ts-ignore
// @ts-expect-error
expect(customer.features[TestFeature.Messages].usage_limit).to.equal(
messageItem.usage_limit! + addOnMessages.included_usage,
);
});
it("should use up all add ons and have correct check results", async function () {
it("should use up all add ons and have correct check results", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
@@ -168,20 +173,21 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits, usage prices`
await timeout(2000);
let check = await autumn.check({
const check = await autumn.check({
customer_id: customerId,
feature_id: TestFeature.Messages,
});
let customer = await autumn.customers.get(customerId);
const customer = await autumn.customers.get(customerId);
let expectedBalance = messageItem.included_usage - messageItem.usage_limit!;
const expectedBalance =
messageItem.included_usage - messageItem.usage_limit!;
expect(check.balance).to.equal(expectedBalance);
expect(check.allowed).to.equal(false);
// @ts-ignore
// @ts-expect-error
expect(check.usage_limit!).to.equal(
messageItem.usage_limit! + addOnMessages.included_usage,
);
// @ts-ignore
// @ts-expect-error
expect(customer.features[TestFeature.Messages].usage_limit).to.equal(
messageItem.usage_limit! + addOnMessages.included_usage,
);

View File

@@ -1,29 +1,23 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
ErrCode,
LimitedItem,
Organization,
LegacyVersion,
type LimitedItem,
type Organization,
} from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import {
constructFeatureItem,
constructPrepaidItem,
} from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import chalk from "chalk";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { expect } from "chai";
import { timeout } from "@/utils/genUtils.js";
import { expectAutumnError } from "tests/utils/expectUtils/expectErrUtils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectAutumnError } from "tests/utils/expectUtils/expectErrUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const messageItem = constructPrepaidItem({
featureId: TestFeature.Messages,
@@ -33,7 +27,7 @@ const messageItem = constructPrepaidItem({
usageLimit: 500,
}) as LimitedItem;
export let pro = constructProduct({
export const pro = constructProduct({
items: [messageItem],
type: "pro",
});
@@ -52,13 +46,13 @@ export let pro = constructProduct({
const testCase = "usageLimit3";
describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for prepaid`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -95,7 +89,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for prepaid`)}
testClockId = testClockId1!;
});
it("should attach pro product with quantity exceeding usage limit and get an error", async function () {
it("should attach pro product with quantity exceeding usage limit and get an error", async () => {
expectAutumnError({
errCode: ErrCode.InvalidOptions,
func: async () => {
@@ -117,7 +111,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for prepaid`)}
},
});
});
it("should attach pro product and update quantity with quantity exceeding usage limit and get an error", async function () {
it("should attach pro product and update quantity with quantity exceeding usage limit and get an error", async () => {
await autumn.attach({
customer_id: customerId,
product_id: pro.id,

View File

@@ -1,30 +1,24 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
ErrCode,
LimitedItem,
Organization,
LegacyVersion,
type LimitedItem,
type Organization,
} from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import {
constructArrearProratedItem,
constructFeatureItem,
constructPrepaidItem,
} from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { expect } from "chai";
import { timeout } from "@/utils/genUtils.js";
import { expectAutumnError } from "tests/utils/expectUtils/expectErrUtils.js";
import chalk from "chalk";
import type Stripe from "stripe";
import { addPrefixToProducts } from "tests/attach/utils.js";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectAutumnError } from "tests/utils/expectUtils/expectErrUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructArrearProratedItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const messageItem = constructArrearProratedItem({
featureId: TestFeature.Users,
@@ -33,7 +27,7 @@ const messageItem = constructArrearProratedItem({
usageLimit: 3,
}) as LimitedItem;
export let pro = constructProduct({
export const pro = constructProduct({
items: [messageItem],
type: "pro",
});
@@ -41,13 +35,13 @@ export let pro = constructProduct({
const testCase = "usageLimit4";
describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for cont use item`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -84,7 +78,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for cont use i
testClockId = testClockId1!;
});
it("should attach pro product with quantity exceeding usage limit and get an error", async function () {
it("should attach pro product with quantity exceeding usage limit and get an error", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -95,7 +89,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing usage limits for cont use i
env,
});
});
it("should attach pro product and update quantity with quantity exceeding usage limit and get an error", async function () {
it("should attach pro product and update quantity with quantity exceeding usage limit and get an error", async () => {
await expectAutumnError({
errCode: ErrCode.InvalidInputs,
func: async () => {

View File

@@ -1,38 +1,36 @@
import chalk from "chalk";
import Stripe from "stripe";
import { APIVersion, Customer } from "@autumn/shared";
import { createStripeCli } from "@/external/stripe/utils.js";
import { getOriginalCouponId } from "@/internal/rewards/rewardUtils.js";
import { getPriceForOverage } from "@/internal/products/prices/priceUtils.js";
import { type Customer, LegacyVersion } from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import { addHours, addMonths } from "date-fns";
import { features, products, rewards } from "tests/global.js";
import { getFixedPriceAmount, timeout } from "tests/utils/genUtils.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { AutumnCli } from "tests/cli/AutumnCli.js";
import { features, products, rewards } from "tests/global.js";
import { compareMainProduct } from "tests/utils/compare.js";
import { getFixedPriceAmount, timeout } from "tests/utils/genUtils.js";
import {
advanceClockForInvoice,
advanceTestClock,
completeCheckoutForm,
getDiscount,
} from "tests/utils/stripeUtils.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { setupBefore } from "tests/before.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { getPriceForOverage } from "@/internal/products/prices/priceUtils.js";
import { getOriginalCouponId } from "@/internal/rewards/rewardUtils.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
const testCase = "coupon1";
describe(
chalk.yellow(`${testCase} -- Testing one-off rollover, apply to all`),
() => {
let customerId = "coupon1";
const customerId = "coupon1";
let stripeCli: Stripe;
let customer: Customer;
let testClockId: string;
let db, org, env;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
let autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let couponAmount = rewards.rolloverAll.discount_config.discount_value;
@@ -159,7 +157,7 @@ describe(
// CYCLE 2
it("CYCLE 2: should have $0 invoice and correct new coupon amount after 2nd cycle", async () => {
await timeout(20000);
let advanceTo = addHours(addMonths(new Date(), 2), 2);
const advanceTo = addHours(addMonths(new Date(), 2), 2);
await advanceTestClock({
stripeCli,
testClockId,

View File

@@ -1,26 +1,23 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts, replaceItems } from "../utils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import {
constructProduct,
constructRawProduct,
} from "@/utils/scriptUtils/createTestProducts.js";
import {
constructArrearProratedItem,
constructFeatureItem,
} from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expect } from "chai";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts, replaceItems } from "../utils.js";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Messages,
@@ -30,7 +27,7 @@ export let pro = constructProduct({
type: "pro",
});
export let addOn = constructRawProduct({
export const addOn = constructRawProduct({
id: "add_on_1",
items: [
constructFeatureItem({
@@ -44,13 +41,13 @@ export let addOn = constructRawProduct({
const testCase = "addOn1";
describe(`${chalk.yellowBright(`${testCase}: Testing free add on, and updating free add on`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_2 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_2 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -87,7 +84,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing free add on, and updating f
testClockId = testClockId1!;
});
it("should should attach pro product, then add on product", async function () {
it("should should attach pro product, then add on product", async () => {
await attachAndExpectCorrect({
autumn,
db,
@@ -99,7 +96,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing free add on, and updating f
});
});
it("should should attach add on product", async function () {
it("should should attach add on product", async () => {
const preview = await autumn.attachPreview({
customer_id: customerId,
product_id: addOn.id,
@@ -132,7 +129,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing free add on, and updating f
}),
});
it("should update add on product", async function () {
it("should update add on product", async () => {
const preview = await autumn.attachPreview({
customer_id: customerId,
product_id: addOn.id,

View File

@@ -1,24 +1,23 @@
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectFeaturesCorrect } from "tests/utils/expectUtils/expectFeaturesCorrect.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import {
constructProduct,
constructRawProduct,
} from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectAutumnError } from "tests/utils/expectUtils/expectErrUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { expectFeaturesCorrect } from "tests/utils/expectUtils/expectFeaturesCorrect.js";
import { addPrefixToProducts } from "../utils.js";
export let pro = constructProduct({
export const pro = constructProduct({
type: "pro",
items: [],
});
@@ -36,8 +35,8 @@ export const addOn = constructRawProduct({
const testCase = "addOn2";
describe(`${chalk.yellowBright(`${testCase}: Testing attach free add on twice (should be treated as one off?)`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
@@ -73,7 +72,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach free add on twice (s
});
});
it("should attach pro product and free add on", async function () {
it("should attach pro product and free add on", async () => {
await attachAndExpectCorrect({
autumn,
customerId,

View File

@@ -1,20 +1,19 @@
import { LegacyVersion } from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import { setupBefore } from "tests/before.js";
import { AutumnCli } from "tests/cli/AutumnCli.js";
import { features, products } from "tests/global.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { compareMainProduct } from "tests/utils/compare.js";
import { expectFeaturesCorrect } from "tests/utils/expectUtils/expectFeaturesCorrect.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "tests/utils/testProductUtils/testProductUtils.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { expect } from "chai";
import { setupBefore } from "tests/before.js";
import { AutumnCli } from "tests/cli/AutumnCli.js";
import { features, products } from "tests/global.js";
import { compareMainProduct } from "tests/utils/compare.js";
import { createProducts } from "tests/utils/productUtils.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { expectFeaturesCorrect } from "tests/utils/expectUtils/expectFeaturesCorrect.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { APIVersion } from "@autumn/shared";
import { addPrefixToProducts } from "tests/utils/testProductUtils/testProductUtils.js";
const freeProd = constructProduct({
type: "free",
@@ -33,8 +32,8 @@ const freeProd = constructProduct({
// UNCOMMENT FROM HERE
const testCase = "basic1";
describe(`${chalk.yellowBright("basic1: Testing attach free product")}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_2 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_2 });
let db, org, env;
before(async function () {
@@ -67,7 +66,7 @@ describe(`${chalk.yellowBright("basic1: Testing attach free product")}`, () => {
});
});
it("should create customer and have default free active", async function () {
it("should create customer and have default free active", async () => {
const data = await AutumnCli.getCustomer(customerId);
compareMainProduct({
@@ -76,7 +75,7 @@ describe(`${chalk.yellowBright("basic1: Testing attach free product")}`, () => {
});
});
it("should have correct entitlements", async function () {
it("should have correct entitlements", async () => {
const expectedEntitlement = products.free.entitlements.metered1;
const entitled = (await AutumnCli.entitled(
@@ -94,12 +93,12 @@ describe(`${chalk.yellowBright("basic1: Testing attach free product")}`, () => {
expect(metered1Balance.unlimited).to.not.exist;
});
it("should have correct boolean1 entitlement", async function () {
it("should have correct boolean1 entitlement", async () => {
const entitled = await AutumnCli.entitled(customerId, features.boolean1.id);
expect(entitled!.allowed).to.be.false;
});
it("should attach free (with $0 price) and force checkout and succeed", async function () {
it("should attach free (with $0 price) and force checkout and succeed", async () => {
await autumn.attach({
customer_id: customerId,
product_id: freeProd.id,

View File

@@ -1,24 +1,21 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import {
constructArrearProratedItem,
constructFeatureItem,
} from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { completeCheckoutForm } from "tests/utils/stripeUtils.js";
import { timeout } from "@/utils/genUtils.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { expectFeaturesCorrect } from "tests/utils/expectUtils/expectFeaturesCorrect.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import { completeCheckoutForm } from "tests/utils/stripeUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Messages,
@@ -41,12 +38,12 @@ export const oneOff = constructProduct({
const testCase = "checkout3";
describe(`${chalk.yellowBright(`${testCase}: Testing multi attach checkout, pro + one off`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -83,7 +80,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing multi attach checkout, pro
testClockId = testClockId1!;
});
it("should attach pro and one off product", async function () {
it("should attach pro and one off product", async () => {
const res = await autumn.attach({
customer_id: customerId,
product_ids: [pro.id, oneOff.id],

View File

@@ -1,24 +1,22 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import { completeInvoiceCheckout } from "tests/utils/stripeUtils/completeInvoiceCheckout.js";
import chalk from "chalk";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { expectFeaturesCorrect } from "tests/utils/expectUtils/expectFeaturesCorrect.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import { completeInvoiceCheckout } from "tests/utils/stripeUtils/completeInvoiceCheckout.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Messages,
@@ -30,12 +28,12 @@ export let pro = constructProduct({
const testCase = "checkout5";
describe(`${chalk.yellowBright(`${testCase}: Testing invoice checkout, no product till paid`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_2 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_2 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -72,7 +70,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing invoice checkout, no produc
testClockId = testClockId1!;
});
it("should attach pro product", async function () {
it("should attach pro product", async () => {
const res = await autumn.attach({
customer_id: customerId,
product_id: pro.id,

View File

@@ -1,24 +1,23 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { completeInvoiceCheckout } from "tests/utils/stripeUtils/completeInvoiceCheckout.js";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { expectFeaturesCorrect } from "tests/utils/expectUtils/expectFeaturesCorrect.js";
import chalk from "chalk";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { expectAutumnError } from "tests/utils/expectUtils/expectErrUtils.js";
import { expectFeaturesCorrect } from "tests/utils/expectUtils/expectFeaturesCorrect.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import { completeInvoiceCheckout } from "tests/utils/stripeUtils/completeInvoiceCheckout.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Messages,
@@ -28,7 +27,7 @@ export let pro = constructProduct({
type: "pro",
});
export let premium = constructProduct({
export const premium = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Messages,
@@ -40,12 +39,12 @@ export let premium = constructProduct({
const testCase = "checkout6";
describe(`${chalk.yellowBright(`${testCase}: Testing invoice checkout via checkout endpoint`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_2 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_2 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -82,7 +81,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing invoice checkout via checko
testClockId = testClockId1!;
});
it("should attach pro product via invoice checkout", async function () {
it("should attach pro product via invoice checkout", async () => {
const res = await autumn.checkout({
customer_id: customerId,
product_id: pro.id,
@@ -108,7 +107,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing invoice checkout via checko
});
});
it("should have no URL returned if try to attach premium (with invoice true)", async function () {
it("should have no URL returned if try to attach premium (with invoice true)", async () => {
await expectAutumnError({
func: async () => {
await autumn.attach({
@@ -128,7 +127,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing invoice checkout via checko
expect(res.url).to.not.exist;
});
it("should attach premium product via invoice enable immediately", async function () {
it("should attach premium product via invoice enable immediately", async () => {
const res = await autumn.attach({
customer_id: customerId,
product_id: premium.id,

View File

@@ -1,28 +1,27 @@
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { expectFeaturesCorrect } from "tests/utils/expectUtils/expectFeaturesCorrect.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import {
constructProduct,
constructRawProduct,
} from "@/utils/scriptUtils/createTestProducts.js";
import { completeInvoiceCheckout } from "tests/utils/stripeUtils/completeInvoiceCheckout.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import {
constructFeatureItem,
constructPrepaidItem,
} from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { completeInvoiceCheckout } from "tests/utils/stripeUtils/completeInvoiceCheckout.js";
import { expect } from "chai";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { expectFeaturesCorrect } from "tests/utils/expectUtils/expectFeaturesCorrect.js";
import {
constructProduct,
constructRawProduct,
} from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Messages,
@@ -32,7 +31,7 @@ export let pro = constructProduct({
type: "pro",
});
export let addOn = constructRawProduct({
export const addOn = constructRawProduct({
id: "addOn",
items: [
constructPrepaidItem({
@@ -46,12 +45,12 @@ export let addOn = constructRawProduct({
const testCase = "checkout7";
describe(`${chalk.yellowBright(`${testCase}: Testing invoice checkout with one off product`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_2 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_2 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -88,7 +87,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing invoice checkout with one o
testClockId = testClockId1!;
});
it("should attach pro product, then add on product via invoice checkout", async function () {
it("should attach pro product, then add on product via invoice checkout", async () => {
await autumn.attach({
customer_id: customerId,
product_id: pro.id,

View File

@@ -1,4 +1,4 @@
import { APIVersion, type AppEnv, type Organization } from "@autumn/shared";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import chalk from "chalk";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
@@ -30,7 +30,7 @@ const premium = constructProduct({
describe(`${chalk.yellowBright(`${testCase}: Testing downgrade from premium -> pro`)}`, () => {
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;

View File

@@ -1,27 +1,25 @@
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/internal/products/product-items/productItemUtils.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import {
expectDowngradeCorrect,
expectNextCycleCorrect,
} from "tests/utils/expectUtils/expectScheduleUtils.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/internal/products/product-items/productItemUtils.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
const testCase = "downgrade2";
let free = constructProduct({
const free = constructProduct({
items: [
constructFeatureItem({
feature_id: TestFeature.Words,
@@ -32,19 +30,19 @@ let free = constructProduct({
isDefault: false,
});
let premium = constructProduct({
const premium = constructProduct({
items: [constructArrearItem({ featureId: TestFeature.Words })],
type: "premium",
});
describe(`${chalk.yellowBright(`${testCase}: Testing downgrade from premium -> free`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -81,7 +79,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade from premium -> f
testClockId = testClockId1!;
});
it("should attach premium product", async function () {
it("should attach premium product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -95,7 +93,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade from premium -> f
// let nextCycle = Date.now();
let preview = null;
it("should downgrade to free", async function () {
it("should downgrade to free", async () => {
const { preview: preview_ } = await expectDowngradeCorrect({
autumn,
customerId,
@@ -110,7 +108,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade from premium -> f
preview = preview_;
});
it("should have pro attached on next cycle", async function () {
it("should have pro attached on next cycle", async () => {
await expectNextCycleCorrect({
preview: preview!,
autumn,

View File

@@ -1,24 +1,28 @@
import {
type AppEnv,
type Customer,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Customer, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/internal/products/product-items/productItemUtils.js";
import { expectDowngradeCorrect } from "tests/utils/expectUtils/expectScheduleUtils.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { expectDowngradeCorrect } from "tests/utils/expectUtils/expectScheduleUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/internal/products/product-items/productItemUtils.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
const testCase = "downgrade3";
let free = constructProduct({
const free = constructProduct({
items: [
constructFeatureItem({
feature_id: TestFeature.Words,
@@ -29,25 +33,25 @@ let free = constructProduct({
isDefault: false,
});
let pro = constructProduct({
const pro = constructProduct({
items: [constructArrearItem({ featureId: TestFeature.Words })],
type: "pro",
});
let premium = constructProduct({
const premium = constructProduct({
items: [constructArrearItem({ featureId: TestFeature.Words })],
type: "premium",
});
describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: premium -> pro -> free -> pro -> premium`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let customer: Customer;
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -86,7 +90,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: premium -> pro -
customer = customer_!;
});
it("should attach premium product", async function () {
it("should attach premium product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -100,7 +104,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: premium -> pro -
// let nextCycle = Date.now();
let preview = null;
it("should downgrade to pro", async function () {
it("should downgrade to pro", async () => {
const { preview: preview_ } = await expectDowngradeCorrect({
autumn,
customerId,
@@ -115,7 +119,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: premium -> pro -
preview = preview_;
});
it("should downgrade to free", async function () {
it("should downgrade to free", async () => {
const { preview: preview_ } = await expectDowngradeCorrect({
autumn,
customerId,
@@ -130,7 +134,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: premium -> pro -
preview = preview_;
});
it("should change downgrade to pro", async function () {
it("should change downgrade to pro", async () => {
const { preview: preview_ } = await expectDowngradeCorrect({
autumn,
customerId,
@@ -143,7 +147,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: premium -> pro -
});
});
it("should renew premium", async function () {
it("should renew premium", async () => {
await autumn.attach({
customer_id: customerId,
product_id: premium.id,

View File

@@ -1,57 +1,56 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
BillingInterval,
Customer,
Organization,
type Customer,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import chalk from "chalk";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { addPrefixToProducts } from "../utils.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import {
expectDowngradeCorrect,
expectNextCycleCorrect,
} from "tests/utils/expectUtils/expectScheduleUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import { advanceMonths } from "tests/utils/stripeUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
const testCase = "downgrade4";
let proQuarter = constructProduct({
const proQuarter = constructProduct({
items: [constructArrearItem({ featureId: TestFeature.Words })],
type: "pro",
interval: BillingInterval.Quarter,
});
let pro = constructProduct({
const pro = constructProduct({
items: [constructArrearItem({ featureId: TestFeature.Words })],
type: "pro",
});
let premium = constructProduct({
const premium = constructProduct({
items: [constructArrearItem({ featureId: TestFeature.Words })],
type: "premium",
});
describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: pro-quarter -> premium -> pro`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let customer: Customer;
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -90,7 +89,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: pro-quarter -> p
customer = customer_!;
});
it("should attach pro quarterly product", async function () {
it("should attach pro quarterly product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -102,7 +101,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: pro-quarter -> p
});
});
it("should downgrade to premium", async function () {
it("should downgrade to premium", async () => {
await expectDowngradeCorrect({
autumn,
customerId,
@@ -117,7 +116,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: pro-quarter -> p
let preview = null;
it("should downgrade to pro", async function () {
it("should downgrade to pro", async () => {
const { preview: preview_ } = await expectDowngradeCorrect({
autumn,
customerId,
@@ -132,7 +131,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing downgrade: pro-quarter -> p
preview = preview_;
});
it("should have correct invoice after cycle", async function () {
it("should have correct invoice after cycle", async () => {
await advanceMonths({ stripeCli, testClockId, numberOfMonths: 3 });
await timeout(10000);

View File

@@ -1,4 +1,4 @@
import { APIVersion, type AppEnv, type Organization } from "@autumn/shared";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import chalk from "chalk";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
@@ -27,7 +27,7 @@ const pro = constructProduct({
describe(`${chalk.yellowBright(`attach/${testCase}: Testing attach to entity via checkout`)}`, () => {
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;

View File

@@ -1,37 +1,37 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
CreateFreeTrialSchema,
CusProductStatus,
FreeTrialDuration,
Organization,
LegacyVersion,
type Organization,
organizations,
} from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { addDays } from "date-fns";
import { expect } from "chai";
import chalk from "chalk";
import { addDays } from "date-fns";
import { eq } from "drizzle-orm";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { CacheManager } from "@/external/caching/CacheManager.js";
import { clearOrgCache } from "@/internal/orgs/orgUtils/clearOrgCache.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
const testCase = "free1";
let trial1 = CreateFreeTrialSchema.parse({
const trial1 = CreateFreeTrialSchema.parse({
length: 7,
duration: FreeTrialDuration.Day,
});
export let free = constructProduct({
export const free = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Messages,
@@ -43,7 +43,7 @@ export let free = constructProduct({
type: "free",
id: "enterprise_trial",
});
export let addOn = constructProduct({
export const addOn = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Credits,
@@ -57,14 +57,14 @@ export let addOn = constructProduct({
});
describe(`${chalk.yellowBright(`${testCase}: Testing free product with trial and attaching add on`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
let numUsers = 0;
const curUnix = new Date().getTime();
const numUsers = 0;
before(async function () {
await setupBefore(this);
@@ -117,19 +117,19 @@ describe(`${chalk.yellowBright(`${testCase}: Testing free product with trial and
});
const approximateDiff = 1000 * 60 * 30; // 30 minutes
it("should attach free product with trial", async function () {
let attachPreview = await autumn.attachPreview({
it("should attach free product with trial", async () => {
const attachPreview = await autumn.attachPreview({
customer_id: customerId,
product_id: free.id,
});
let attach = await autumn.attach({
const attach = await autumn.attach({
customer_id: customerId,
product_id: free.id,
});
let customer = await autumn.customers.get(customerId);
let freeProduct = customer.products.find((p) => p.id === free.id);
const customer = await autumn.customers.get(customerId);
const freeProduct = customer.products.find((p) => p.id === free.id);
expect(freeProduct).to.exist;
expect(freeProduct?.status).to.equal(CusProductStatus.Trialing);
@@ -144,23 +144,23 @@ describe(`${chalk.yellowBright(`${testCase}: Testing free product with trial and
duration: FreeTrialDuration.Day,
});
it("should update free product's trial end date", async function () {
let attachPreview = await autumn.attachPreview({
it("should update free product's trial end date", async () => {
const attachPreview = await autumn.attachPreview({
customer_id: customerId,
product_id: free.id,
free_trial: trial2,
is_custom: true,
});
let attach = await autumn.attach({
const attach = await autumn.attach({
customer_id: customerId,
product_id: free.id,
free_trial: trial2,
is_custom: true,
});
let customer = await autumn.customers.get(customerId);
let freeProduct = customer.products.find((p) => p.id === free.id);
const customer = await autumn.customers.get(customerId);
const freeProduct = customer.products.find((p) => p.id === free.id);
expect(freeProduct?.status).to.equal(CusProductStatus.Trialing);
expect(freeProduct?.current_period_end).to.approximately(
@@ -169,20 +169,20 @@ describe(`${chalk.yellowBright(`${testCase}: Testing free product with trial and
);
});
it("should attach add on product", async function () {
let attachPreview = await autumn.attachPreview({
it("should attach add on product", async () => {
const attachPreview = await autumn.attachPreview({
customer_id: customerId,
product_id: addOn.id,
});
let attach = await autumn.attach({
const attach = await autumn.attach({
customer_id: customerId,
product_id: addOn.id,
});
let customer = await autumn.customers.get(customerId);
let addOnProduct = customer.products.find((p) => p.id === addOn.id);
let freeProduct = customer.products.find((p) => p.id === free.id);
const customer = await autumn.customers.get(customerId);
const addOnProduct = customer.products.find((p) => p.id === addOn.id);
const freeProduct = customer.products.find((p) => p.id === free.id);
expect(addOnProduct).to.exist;
expect(addOnProduct?.status).to.equal(CusProductStatus.Active);

View File

@@ -1,24 +1,23 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
BillingInterval,
Organization,
LegacyVersion,
type Organization,
} from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructPriceItem } from "@/internal/products/product-items/productItemUtils.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
export const free = constructProduct({
items: [
@@ -46,14 +45,14 @@ export const free = constructProduct({
const testCase = "free2";
describe(`${chalk.yellowBright(`${testCase}: Testing free product with trial and attaching add on`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
let numUsers = 0;
const curUnix = new Date().getTime();
const numUsers = 0;
before(async function () {
await setupBefore(this);
@@ -90,7 +89,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing free product with trial and
});
const approximateDiff = 1000 * 60 * 30; // 30 minutes
it("should attach free product", async function () {
it("should attach free product", async () => {
await autumn.attach({
customer_id: customerId,
product_id: free.id,
@@ -110,7 +109,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing free product with trial and
interval: BillingInterval.Month,
}),
];
it("should update free product with price", async function () {
it("should update free product with price", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -119,7 +118,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing free product with trial and
org,
env,
attachParams: {
// @ts-ignore
// @ts-expect-error
is_custom: true,
items: customItems,
},

View File

@@ -1,32 +1,31 @@
import { expect } from "chai";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
BillingInterval,
Organization,
ProductV2,
LegacyVersion,
type Organization,
type ProductV2,
} from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { replaceItems } from "../utils.js";
import { constructPriceItem } from "@/internal/products/product-items/productItemUtils.js";
import runUpdateEntsTest from "../updateEnts/expectUpdateEnts.js";
import { timeout } from "@/utils/genUtils.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import { addHours, addMonths, addWeeks } from "date-fns";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { getExpectedInvoiceTotal } from "tests/utils/expectUtils/expectInvoiceUtils.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
export let pro = constructProduct({
import { getExpectedInvoiceTotal } from "tests/utils/expectUtils/expectInvoiceUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import { advanceTestClock } from "tests/utils/stripeUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructPriceItem } from "@/internal/products/product-items/productItemUtils.js";
import { timeout } from "@/utils/genUtils.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import runUpdateEntsTest from "../updateEnts/expectUpdateEnts.js";
import { addPrefixToProducts, replaceItems } from "../utils.js";
export const pro = constructProduct({
items: [constructArrearItem({ featureId: TestFeature.Words })],
type: "pro",
});
@@ -34,13 +33,13 @@ export let pro = constructProduct({
const testCase = "newVersion1";
describe(`${chalk.yellowBright(`${testCase}: Testing attach with new version`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -77,7 +76,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach with new version`)}`
testClockId = testClockId1!;
});
it("should attach pro product", async function () {
it("should attach pro product", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -89,9 +88,9 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach with new version`)}`
});
});
let usage = 50000;
const usage = 50000;
let newPro: ProductV2;
it("should update product to new version", async function () {
it("should update product to new version", async () => {
newPro = structuredClone(pro);
let newItems = replaceItems({
items: pro.items,
@@ -119,7 +118,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach with new version`)}`
});
});
it("should attach pro v2", async function () {
it("should attach pro v2", async () => {
await advanceTestClock({
stripeCli,
testClockId,
@@ -152,7 +151,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach with new version`)}`
});
});
it("should have correct invoice total on next cycle", async function () {
it("should have correct invoice total on next cycle", async () => {
const invoiceTotal = await getExpectedInvoiceTotal({
org,
env,

View File

@@ -1,7 +1,7 @@
import {
APIVersion,
type AppEnv,
BillingInterval,
LegacyVersion,
type Organization,
type ProductV2,
} from "@autumn/shared";
@@ -30,7 +30,7 @@ const testCase = "newVersion2";
describe(`${chalk.yellowBright(`${testCase}: Testing attach new version for trial product`)}`, () => {
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;

View File

@@ -1,47 +1,47 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import {
expectDowngradeCorrect,
expectNextCycleCorrect,
} from "tests/utils/expectUtils/expectScheduleUtils.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
const testCase = "others1";
export let free = constructProduct({
export const free = constructProduct({
items: [],
type: "free",
isDefault: false,
});
export let pro = constructProduct({
export const pro = constructProduct({
items: [],
type: "pro",
trial: true,
});
export let premium = constructProduct({
export const premium = constructProduct({
items: [],
type: "premium",
trial: true,
});
describe(`${chalk.yellowBright(`${testCase}: Testing trials: pro with trial -> premium with trial -> free`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -78,7 +78,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing trials: pro with trial -> p
testClockId = testClockId1!;
});
it("should attach pro product (with trial)", async function () {
it("should attach pro product (with trial)", async () => {
await attachAndExpectCorrect({
autumn,
stripeCli,
@@ -90,7 +90,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing trials: pro with trial -> p
});
});
it("should attach premium product (with trial)", async function () {
it("should attach premium product (with trial)", async () => {
await attachAndExpectCorrect({
autumn,
stripeCli,
@@ -102,7 +102,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing trials: pro with trial -> p
});
});
it("should attach free product at the end of the trial", async function () {
it("should attach free product at the end of the trial", async () => {
const { preview } = await expectDowngradeCorrect({
autumn,
stripeCli,

View File

@@ -1,23 +1,23 @@
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { attachFailedPaymentMethod } from "@/external/stripe/stripeCusUtils.js";
import { CusService } from "@/internal/customers/CusService.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
const testCase = "others2";
export let oneOff = constructProduct({
export const oneOff = constructProduct({
type: "one_off",
items: [
constructPrepaidItem({
@@ -30,13 +30,13 @@ export let oneOff = constructProduct({
});
describe(`${chalk.yellowBright(`${testCase}: Testing one-off`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -80,7 +80,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing one-off`)}`, () => {
},
];
it("should attach one-off product", async function () {
it("should attach one-off product", async () => {
await attachAndExpectCorrect({
autumn,
stripeCli,
@@ -99,7 +99,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing one-off`)}`, () => {
quantity: 750,
},
];
it("should be able to attach again", async function () {
it("should be able to attach again", async () => {
await attachAndExpectCorrect({
autumn,
stripeCli,
@@ -120,8 +120,8 @@ describe(`${chalk.yellowBright(`${testCase}: Testing one-off`)}`, () => {
});
// Payment failure
it("should handle payment failure", async function () {
let customer = await CusService.get({
it("should handle payment failure", async () => {
const customer = await CusService.get({
db,
idOrInternalId: customerId,
orgId: org.id,

View File

@@ -1,32 +1,32 @@
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { expect } from "chai";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { attachFailedPaymentMethod } from "@/external/stripe/stripeCusUtils.js";
import { CusService } from "@/internal/customers/CusService.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
const testCase = "others3";
export let pro = constructProduct({
export const pro = constructProduct({
type: "pro",
items: [],
});
describe(`${chalk.yellowBright(`${testCase}: Testing attach payment failure`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -63,8 +63,8 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach payment failure`)}`,
});
// Payment failure
it("should handle payment failure", async function () {
let customer = await CusService.get({
it("should handle payment failure", async () => {
const customer = await CusService.get({
db,
idOrInternalId: customerId,
orgId: org.id,

View File

@@ -1,19 +1,19 @@
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { expectAttachCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { CusService } from "@/internal/customers/CusService.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { addPrefixToProducts } from "../utils.js";
export let pro = constructProduct({
export const pro = constructProduct({
items: [constructArrearItem({ featureId: TestFeature.Words })],
type: "pro",
});
@@ -21,8 +21,8 @@ export let pro = constructProduct({
const testCase = "others6";
describe(`${chalk.yellowBright(`${testCase}: Testing attach with customer ID and entity ID null`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
@@ -37,7 +37,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach with customer ID and
stripeCli = this.stripeCli;
let customer = await CusService.getByEmail({
const customer = await CusService.getByEmail({
db,
orgId: org.id,
env,
@@ -64,10 +64,10 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach with customer ID and
let internalCustomerId = "";
let internalEntityId = "";
let entityId = "1";
it("should attach create customer with no ID", async function () {
let customer = await autumn.customers.create({
// @ts-ignore
const entityId = "1";
it("should attach create customer with no ID", async () => {
const customer = await autumn.customers.create({
// @ts-expect-error
id: null,
email: `${customerId}@test.com`,
name: customerId,
@@ -77,8 +77,8 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach with customer ID and
internalCustomerId = customer.autumn_id;
let data = await autumn.entities.create(internalCustomerId, {
// @ts-ignore
const data = await autumn.entities.create(internalCustomerId, {
// @ts-expect-error
id: null,
feature_id: TestFeature.Users,
});
@@ -88,7 +88,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach with customer ID and
expect(internalEntityId, "Entity ID should exist").to.exist;
});
it("should be able to attach pro product, invoice only", async function () {
it("should be able to attach pro product, invoice only", async () => {
await autumn.attach({
customer_id: internalCustomerId,
entity_id: internalEntityId,
@@ -108,15 +108,15 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach with customer ID and
expect(customer.invoices[0].status).to.equal("draft");
});
it("should create customer with ID, and attach pro product", async function () {
let customer = await autumn.customers.create({
it("should create customer with ID, and attach pro product", async () => {
const customer = await autumn.customers.create({
id: customerId,
email: `${customerId}@test.com`,
});
expect(customer.autumn_id).to.equal(internalCustomerId);
let entity = await autumn.entities.create(customer.autumn_id, {
const entity = await autumn.entities.create(customer.autumn_id, {
id: entityId,
feature_id: TestFeature.Users,
});

View File

@@ -1,20 +1,20 @@
import chalk from "chalk";
import Stripe from "stripe";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import chalk from "chalk";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { expectAttachCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { createProducts } from "tests/utils/productUtils.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructArrearItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
export let pro = constructProduct({
export const pro = constructProduct({
items: [constructArrearItem({ featureId: TestFeature.Words })],
type: "pro",
trial: true,
@@ -23,8 +23,8 @@ export let pro = constructProduct({
const testCase = "others7";
describe(`${chalk.yellowBright(`${testCase}: Testing attach with free_trial=False`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
@@ -60,7 +60,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach with free_trial=Fals
});
});
it("should attach pro product with free_trial=False", async function () {
it("should attach pro product with free_trial=False", async () => {
await autumn.attach({
customer_id: customerId,
product_id: pro.id,

View File

@@ -1,24 +1,22 @@
import chalk from "chalk";
import Stripe from "stripe";
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import { expect } from "chai";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import chalk from "chalk";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import {
constructArrearItem,
constructFeatureItem,
constructPrepaidItem,
} from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { expectAttachCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { getBasePrice } from "tests/utils/testProductUtils/testProductUtils.js";
import { addPrefixToProducts } from "../utils.js";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Words,
@@ -37,8 +35,8 @@ export let pro = constructProduct({
const testCase = "others8";
describe(`${chalk.yellowBright(`${testCase}: Testing annual pro with one off prepaid`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
@@ -74,7 +72,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing annual pro with one off pre
});
});
it("should attach annual pro product with one off prepaid", async function () {
it("should attach annual pro product with one off prepaid", async () => {
const options = [
{
feature_id: TestFeature.Users,

View File

@@ -1,19 +1,19 @@
import { type AppEnv, LegacyVersion, type Organization } from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { APIVersion, AppEnv, Organization } from "@autumn/shared";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectAutumnError } from "tests/utils/expectUtils/expectErrUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructFeatureItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
export let free = constructProduct({
export const free = constructProduct({
items: [
constructFeatureItem({
featureId: TestFeature.Words,
@@ -31,8 +31,8 @@ export let free = constructProduct({
const testCase = "others9";
describe(`${chalk.yellowBright(`${testCase}: Testing attach free product again`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
@@ -68,7 +68,7 @@ describe(`${chalk.yellowBright(`${testCase}: Testing attach free product again`)
});
});
it("should attach free product, then try again and hit error", async function () {
it("should attach free product, then try again and hit error", async () => {
await attachAndExpectCorrect({
autumn,
customerId,

View File

@@ -1,7 +1,7 @@
import {
APIVersion,
type AppEnv,
type Customer,
LegacyVersion,
OnDecrease,
OnIncrease,
type Organization,
@@ -45,7 +45,7 @@ export const pro = constructProduct({
describe(`${chalk.yellowBright(`attach/${testCase}: update quantity, no proration downgrade, single use`)}`, () => {
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;

View File

@@ -1,29 +1,29 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
LegacyVersion,
OnDecrease,
OnIncrease,
Organization,
type Organization,
} from "@autumn/shared";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { addWeeks } from "date-fns";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import { addWeeks } from "date-fns";
import { addPrefixToProducts } from "../utils.js";
const testCase = "prepaid2";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructPrepaidItem({
featureId: TestFeature.Messages,
@@ -40,13 +40,13 @@ export let pro = constructProduct({
});
describe(`${chalk.yellowBright(`attach/${testCase}: upgrade quantity, prorate immediately, single use`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -89,7 +89,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: upgrade quantity, prorate im
},
];
it("should attach pro product to customer", async function () {
it("should attach pro product to customer", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -101,14 +101,14 @@ describe(`${chalk.yellowBright(`attach/${testCase}: upgrade quantity, prorate im
options,
});
let customer = await autumn.customers.get(customerId);
const customer = await autumn.customers.get(customerId);
expectProductAttached({
customer,
product: pro,
});
});
it("should increase advance test clock, increase quantity to 400 and have correct sub item quantity + invoice..", async function () {
it("should increase advance test clock, increase quantity to 400 and have correct sub item quantity + invoice..", async () => {
const usage = Math.floor(Math.random() * 220);
await autumn.track({
customer_id: customerId,

View File

@@ -1,31 +1,31 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
LegacyVersion,
OnDecrease,
OnIncrease,
Organization,
type Organization,
} from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { addHours, addMonths } from "date-fns";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import { addHours, addMonths, addWeeks } from "date-fns";
import { expect } from "chai";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { addPrefixToProducts } from "../utils.js";
const testCase = "prepaid3";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructPrepaidItem({
featureId: TestFeature.Messages,
@@ -42,13 +42,13 @@ export let pro = constructProduct({
});
describe(`${chalk.yellowBright(`attach/${testCase}: upgrade quantity, prorate next cycle, single use`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -91,7 +91,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: upgrade quantity, prorate ne
},
];
it("should attach pro product to customer", async function () {
it("should attach pro product to customer", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -103,14 +103,14 @@ describe(`${chalk.yellowBright(`attach/${testCase}: upgrade quantity, prorate ne
options,
});
let customer = await autumn.customers.get(customerId);
const customer = await autumn.customers.get(customerId);
expectProductAttached({
customer,
product: pro,
});
});
it("should increase advance test clock, increase quantity to 400", async function () {
it("should increase advance test clock, increase quantity to 400", async () => {
const usage = Math.floor(Math.random() * 220);
await autumn.track({
customer_id: customerId,
@@ -144,7 +144,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: upgrade quantity, prorate ne
expect(customer.invoices.length).to.equal(1);
});
it("should advance test clock to end of cycle and have correct invoice", async function () {
it("should advance test clock to end of cycle and have correct invoice", async () => {
await advanceTestClock({
stripeCli,
testClockId,

View File

@@ -1,32 +1,32 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
type AppEnv,
LegacyVersion,
OnDecrease,
OnIncrease,
Organization,
type Organization,
} from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { addHours, addMonths } from "date-fns";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import { expect } from "chai";
import { addHours, addMonths } from "date-fns";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import { addPrefixToProducts } from "../utils.js";
const testCase = "prepaid4";
export let pro = constructProduct({
export const pro = constructProduct({
items: [
constructPrepaidItem({
featureId: TestFeature.Messages,
@@ -43,13 +43,13 @@ export let pro = constructProduct({
});
describe(`${chalk.yellowBright(`attach/${testCase}: Testing prepaid reset`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
before(async function () {
await setupBefore(this);
@@ -92,7 +92,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: Testing prepaid reset`)}`, (
},
];
it("should attach pro product to customer", async function () {
it("should attach pro product to customer", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -104,7 +104,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: Testing prepaid reset`)}`, (
options,
});
let customer = await autumn.customers.get(customerId);
const customer = await autumn.customers.get(customerId);
expectProductAttached({
customer,
product: pro,
@@ -113,7 +113,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: Testing prepaid reset`)}`, (
// return;
const usage = 100;
it("should track usage for prepaid and have correct balance", async function () {
it("should track usage for prepaid and have correct balance", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
@@ -129,7 +129,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: Testing prepaid reset`)}`, (
);
});
it("should advance clock to next cycle and have correct balance", async function () {
it("should advance clock to next cycle and have correct balance", async () => {
await advanceTestClock({
stripeCli,
testClockId,

View File

@@ -1,38 +1,31 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
Customer,
type AppEnv,
type Customer,
LegacyVersion,
OnDecrease,
OnIncrease,
Organization,
type Organization,
} from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import {
constructFeatureItem,
constructPrepaidItem,
} from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import { addHours, addMonths, addWeeks } from "date-fns";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { expect } from "chai";
import { getMainCusProduct } from "@/internal/customers/cusProducts/cusProductUtils.js";
import { CusService } from "@/internal/customers/CusService.js";
import { CusProductService } from "@/internal/customers/cusProducts/CusProductService.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { addPrefixToProducts } from "../utils.js";
const testCase = "prepaid5";
export let prepaidAddOn = constructProduct({
export const prepaidAddOn = constructProduct({
type: "pro",
excludeBase: true,
id: "topup",
@@ -50,7 +43,7 @@ export let prepaidAddOn = constructProduct({
isAddOn: true,
});
export let pro = constructProduct({
export const pro = constructProduct({
type: "pro",
items: [
constructFeatureItem({
@@ -59,7 +52,7 @@ export let pro = constructProduct({
}),
],
});
export let premium = constructProduct({
export const premium = constructProduct({
type: "premium",
items: [
constructFeatureItem({
@@ -70,13 +63,13 @@ export let premium = constructProduct({
});
describe(`${chalk.yellowBright(`attach/${testCase}: prepaid add on, with entities`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
let customer: Customer;
before(async function () {
@@ -130,7 +123,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: prepaid add on, with entitie
},
];
it("should attach pro product to entity1", async function () {
it("should attach pro product to entity1", async () => {
await autumn.entities.create(customerId, entities);
await attachAndExpectCorrect({
@@ -165,7 +158,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: prepaid add on, with entitie
});
const oldEntity2Quantity = 300;
it("should advance test clock and attach top up to entity2", async function () {
it("should advance test clock and attach top up to entity2", async () => {
// await advanceTestClock({
// stripeCli,
// testClockId,
@@ -205,7 +198,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: prepaid add on, with entitie
});
});
it("should increase prepaid add on quantity for entity1", async function () {
it("should increase prepaid add on quantity for entity1", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -228,7 +221,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: prepaid add on, with entitie
});
const newEntity2Quantity = 200;
it("should decrease prepaid add on quantity for entity2", async function () {
it("should decrease prepaid add on quantity for entity2", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -251,7 +244,9 @@ describe(`${chalk.yellowBright(`attach/${testCase}: prepaid add on, with entitie
const entity2 = await autumn.entities.get(customerId, entity2Id);
expect(entity2.invoices.length).to.equal(2);
let creditProd = entity2.products.find((p: any) => p.id == prepaidAddOn.id);
const creditProd = entity2.products.find(
(p: any) => p.id == prepaidAddOn.id,
);
expect(creditProd).to.exist;
const messagesItem = creditProd!.items.find(
(i: any) => i.feature_id == TestFeature.Messages,

View File

@@ -1,30 +1,29 @@
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import {
APIVersion,
AppEnv,
Customer,
type AppEnv,
type Customer,
LegacyVersion,
OnDecrease,
OnIncrease,
Organization,
type Organization,
} from "@autumn/shared";
import { expect } from "chai";
import chalk from "chalk";
import Stripe from "stripe";
import { DrizzleCli } from "@/db/initDrizzle.js";
import { addHours, addMonths } from "date-fns";
import type Stripe from "stripe";
import { setupBefore } from "tests/before.js";
import { createProducts } from "tests/utils/productUtils.js";
import { addPrefixToProducts } from "../utils.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { TestFeature } from "tests/setup/v2Features.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { attachAndExpectCorrect } from "tests/utils/expectUtils/expectAttach.js";
import { expectProductAttached } from "tests/utils/expectUtils/expectProductAttached.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import { addHours, addMonths } from "date-fns";
import { hoursToFinalizeInvoice } from "tests/utils/constants.js";
import { expect } from "chai";
import { getMainCusProduct } from "@/internal/customers/cusProducts/cusProductUtils.js";
import { createProducts } from "tests/utils/productUtils.js";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { AutumnInt } from "@/external/autumn/autumnCli.js";
import { timeout } from "@/utils/genUtils.js";
import { constructPrepaidItem } from "@/utils/scriptUtils/constructItem.js";
import { constructProduct } from "@/utils/scriptUtils/createTestProducts.js";
import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
import { advanceTestClock } from "@/utils/scriptUtils/testClockUtils.js";
import { addPrefixToProducts } from "../utils.js";
const userItem = constructPrepaidItem({
featureId: TestFeature.Users,
@@ -36,7 +35,7 @@ const userItem = constructPrepaidItem({
},
});
export let pro = constructProduct({
export const pro = constructProduct({
items: [userItem],
excludeBase: true,
type: "pro",
@@ -44,13 +43,13 @@ export let pro = constructProduct({
const testCase = "prepaid6";
describe(`${chalk.yellowBright(`attach/${testCase}: update quantity, no proration downgrade, cont use`)}`, () => {
let customerId = testCase;
let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
const customerId = testCase;
const autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
let testClockId: string;
let db: DrizzleCli, org: Organization, env: AppEnv;
let stripeCli: Stripe;
let curUnix = new Date().getTime();
const curUnix = new Date().getTime();
let customer: Customer;
before(async function () {
@@ -96,7 +95,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: update quantity, no proratio
];
const originalQuantity = 4;
it("should attach pro product to customer", async function () {
it("should attach pro product to customer", async () => {
await attachAndExpectCorrect({
autumn,
customerId,
@@ -108,7 +107,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: update quantity, no proratio
options,
});
let customer = await autumn.customers.get(customerId);
const customer = await autumn.customers.get(customerId);
expectProductAttached({
customer,
product: pro,
@@ -117,7 +116,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: update quantity, no proratio
const usage = 3;
const newQuantity = 3;
it("should use 3 users, then downgrade to 3 seats", async function () {
it("should use 3 users, then downgrade to 3 seats", async () => {
await autumn.track({
customer_id: customerId,
feature_id: TestFeature.Users,
@@ -148,7 +147,7 @@ describe(`${chalk.yellowBright(`attach/${testCase}: update quantity, no proratio
],
});
});
it("should have correct balance (0) next cycle", async function () {
it("should have correct balance (0) next cycle", async () => {
await advanceTestClock({
stripeCli,
testClockId,
@@ -162,8 +161,8 @@ describe(`${chalk.yellowBright(`attach/${testCase}: update quantity, no proratio
const autumnCus = await autumn.customers.get(customerId);
expect(autumnCus.features[TestFeature.Users].balance).to.equal(0);
let product = autumnCus.products.find((p: any) => p.id == pro.id) as any;
let userItem = product.items.find(
const product = autumnCus.products.find((p: any) => p.id == pro.id) as any;
const userItem = product.items.find(
(i: any) => i.feature_id == TestFeature.Users,
);

View File

@@ -1,7 +1,7 @@
// import { AutumnInt } from "@/external/autumn/autumnCli.js";
// import { initCustomer } from "@/utils/scriptUtils/initCustomer.js";
// import {
// APIVersion,
// LegacyVersion,
// AppEnv,
// Customer,
// OnDecrease,
@@ -56,7 +56,7 @@
// describe(`${chalk.yellowBright(`attach/${testCase}: prepaid add on, with entities`)}`, () => {
// let customerId = testCase;
// let autumn: AutumnInt = new AutumnInt({ version: APIVersion.v1_4 });
// let autumn: AutumnInt = new AutumnInt({ version: LegacyVersion.v1_4 });
// let testClockId: string;
// let db: DrizzleCli, org: Organization, env: AppEnv;
// let stripeCli: Stripe;

Some files were not shown because too many files have changed in this diff Show More