Files
sign/packages/ee/server-only/stripe/get-prices-by-interval.ts

59 lines
1.9 KiB
TypeScript
Raw Normal View History

import type Stripe from 'stripe';
2023-10-13 23:33:40 +11:00
import { stripe } from '@documenso/lib/server-only/stripe';
// Utility type to handle usage of the `expand` option.
type PriceWithProduct = Stripe.Price & { product: Stripe.Product };
export type PriceIntervals = Record<Stripe.Price.Recurring.Interval, PriceWithProduct[]>;
export type GetPricesByIntervalOptions = {
/**
* Filter products by their meta 'type' attribute.
*/
type?: 'individual';
};
export const getPricesByInterval = async ({ type }: GetPricesByIntervalOptions = {}) => {
2023-10-14 13:02:36 +11:00
let { data: prices } = await stripe.prices.search({
2023-10-13 23:33:40 +11:00
query: `active:'true' type:'recurring'`,
expand: ['data.product'],
limit: 100,
});
2023-10-14 13:02:36 +11:00
prices = prices.filter((price) => {
// We use `expand` to get the product, but it's not typed as part of the Price type.
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const product = price.product as Stripe.Product;
const filter = !type || product.metadata?.type === type;
2023-10-14 13:02:36 +11:00
// Filter out prices for products that are not active.
return product.active && filter;
2023-10-14 13:02:36 +11:00
});
2023-10-13 23:33:40 +11:00
const intervals: PriceIntervals = {
day: [],
week: [],
month: [],
year: [],
};
// Add each price to the correct interval.
for (const price of prices) {
if (price.recurring?.interval) {
// We use `expand` to get the product, but it's not typed as part of the Price type.
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
intervals[price.recurring.interval].push(price as PriceWithProduct);
}
}
// Order all prices by unit_amount.
intervals.day.sort((a, b) => Number(a.unit_amount) - Number(b.unit_amount));
intervals.week.sort((a, b) => Number(a.unit_amount) - Number(b.unit_amount));
intervals.month.sort((a, b) => Number(a.unit_amount) - Number(b.unit_amount));
intervals.year.sort((a, b) => Number(a.unit_amount) - Number(b.unit_amount));
return intervals;
};