Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,25 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import Portal from "./Portal.server";
|
||||
|
||||
const originalNodeEnv = process.env.NODE_ENV;
|
||||
const originalPortalServerUrl = process.env.PORTAL_SERVER_URL;
|
||||
|
||||
afterEach(() => {
|
||||
process.env.NODE_ENV = originalNodeEnv;
|
||||
process.env.PORTAL_SERVER_URL = originalPortalServerUrl;
|
||||
});
|
||||
|
||||
describe("Portal.server", () => {
|
||||
it("normalizes production custom domains to https without double-scheming", () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
|
||||
expect(Portal.getPortalUrl({ subdomain: "demo", domain: "http://portal.example.com" })).toBe("https://portal.example.com");
|
||||
});
|
||||
|
||||
it("builds a subdomain URL from PORTAL_SERVER_URL", () => {
|
||||
process.env.NODE_ENV = "development";
|
||||
process.env.PORTAL_SERVER_URL = "http://portals.example.test:3000";
|
||||
|
||||
expect(Portal.getPortalUrl({ subdomain: "demo", domain: null })).toBe("http://demo.portals.example.test:3000");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { loadWebConfig, type WebConfig } from "@toolctrl/config";
|
||||
|
||||
function getPortalUrl(item: { subdomain: string; domain: string | null }, webConfig: WebConfig = loadWebConfig().config) {
|
||||
if (item.domain) {
|
||||
let domain = item.domain.trim();
|
||||
if (!/^https?:\/\//i.test(domain) && webConfig.nodeEnv === "development") {
|
||||
domain = `http://${domain}`;
|
||||
} else if (webConfig.nodeEnv === "production") {
|
||||
domain = domain.replace(/^http:\/\//i, "");
|
||||
if (!/^https:\/\//i.test(domain)) {
|
||||
domain = `https://${domain}`;
|
||||
}
|
||||
}
|
||||
const url = new URL(domain);
|
||||
let urlString = url.toString();
|
||||
// without trailing slash
|
||||
if (urlString.endsWith("/")) {
|
||||
urlString = urlString.slice(0, -1);
|
||||
}
|
||||
return urlString;
|
||||
}
|
||||
if (!webConfig.portalServer.url) {
|
||||
throw new Error("PORTAL_SERVER_URL is not defined");
|
||||
}
|
||||
const portalUrl = new URL(webConfig.portalServer.url);
|
||||
let subdomain = item.subdomain;
|
||||
subdomain = `${portalUrl.protocol}//${subdomain}.${portalUrl.hostname}`;
|
||||
if (portalUrl.port) {
|
||||
subdomain += `:${portalUrl.port}`;
|
||||
}
|
||||
return subdomain;
|
||||
}
|
||||
|
||||
export default {
|
||||
getPortalUrl,
|
||||
};
|
||||
@@ -0,0 +1,200 @@
|
||||
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
|
||||
import {
|
||||
createPortalSubscriptionProduct,
|
||||
createPortalSubscriptionPrice,
|
||||
createPortalSubscriptionFeature,
|
||||
updatePortalSubscriptionProductStripeId,
|
||||
updatePortalSubscriptionPriceStripeId,
|
||||
deletePortalSubscriptionPrice,
|
||||
deletePortalSubscriptionProduct,
|
||||
updatePortalSubscriptionProduct,
|
||||
deletePortalSubscriptionFeatures,
|
||||
} from "../db/portalSubscriptionProducts.db.server";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import PortalSubscriptionServer from "./PortalSubscription.server";
|
||||
import PortalStripeServer from "./PortalStripe.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const portalPricingLogger = createScopedLogger("portals.pricing");
|
||||
|
||||
async function createPlans(portalId: string, plans: SubscriptionProductDto[]) {
|
||||
for (const plan of plans.sort((a, b) => a.order - b.order)) {
|
||||
await createPlan(
|
||||
portalId,
|
||||
plan,
|
||||
plan.prices.map((price) => {
|
||||
return {
|
||||
billingPeriod: price.billingPeriod,
|
||||
currency: price.currency,
|
||||
price: Number(price.price),
|
||||
};
|
||||
}),
|
||||
plan.features
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function createPlan(
|
||||
portalId: string,
|
||||
plan: SubscriptionProductDto,
|
||||
prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[],
|
||||
features: SubscriptionFeatureDto[]
|
||||
) {
|
||||
// Create stripe product
|
||||
const stripeProduct = await PortalStripeServer.createStripeProduct({ title: plan.translatedTitle ?? plan.title });
|
||||
// Save to db
|
||||
const product = await createPortalSubscriptionProduct({
|
||||
portalId,
|
||||
stripeId: stripeProduct?.id ?? "",
|
||||
order: plan.order,
|
||||
title: plan.title,
|
||||
model: plan.model,
|
||||
description: plan.description ?? undefined,
|
||||
badge: plan.badge ?? undefined,
|
||||
groupTitle: plan.groupTitle ?? undefined,
|
||||
groupDescription: plan.groupDescription ?? undefined,
|
||||
active: plan.active,
|
||||
public: plan.public,
|
||||
billingAddressCollection: plan.billingAddressCollection ?? "auto",
|
||||
hasQuantity: plan.hasQuantity ?? false,
|
||||
canBuyAgain: plan.canBuyAgain ?? false,
|
||||
});
|
||||
|
||||
if (!product) {
|
||||
throw new Error("Could not create subscription product");
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
prices.map(async (price) => {
|
||||
// Create stripe price
|
||||
const stripePrice = await PortalStripeServer.createStripePrice(stripeProduct?.id ?? "", price);
|
||||
// Save to db
|
||||
return await createPortalSubscriptionPrice({
|
||||
...price,
|
||||
portalId,
|
||||
subscriptionProductId: product.id,
|
||||
stripeId: stripePrice?.id ?? "",
|
||||
type: SubscriptionPriceType.RECURRING,
|
||||
billingPeriod: price.billingPeriod,
|
||||
price: price.price,
|
||||
currency: price.currency,
|
||||
trialDays: price.trialDays ?? 0,
|
||||
active: true,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
features
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map(async (feature) => {
|
||||
// Save to db
|
||||
return await createPortalSubscriptionFeature(portalId, product.id, feature);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function syncPlan(
|
||||
portalId: string,
|
||||
plan: SubscriptionProductDto,
|
||||
prices: { id?: string; billingPeriod: SubscriptionBillingPeriod; price: number; currency: string }[]
|
||||
) {
|
||||
if (!plan.id) {
|
||||
throw new Error(`Plan ${plan.title} not found on database`);
|
||||
}
|
||||
const stripeProduct = await PortalStripeServer.createStripeProduct({ title: plan.translatedTitle ?? plan.title });
|
||||
if (!stripeProduct) {
|
||||
throw new Error("Could not create product");
|
||||
}
|
||||
await updatePortalSubscriptionProductStripeId(portalId, plan.id, {
|
||||
stripeId: stripeProduct.id,
|
||||
});
|
||||
|
||||
prices.map(async (price) => {
|
||||
// Create stripe price
|
||||
const stripePrice = await PortalStripeServer.createStripePrice(stripeProduct?.id ?? "", price);
|
||||
if (!stripePrice) {
|
||||
throw new Error(`Could not create price ${plan.title} - ${price.price}`);
|
||||
}
|
||||
// Save to db
|
||||
await updatePortalSubscriptionPriceStripeId(portalId, price.id ?? "", {
|
||||
stripeId: stripePrice?.id ?? "",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function updatePlan(portalId: string, plan: SubscriptionProductDto, features: SubscriptionFeatureDto[]) {
|
||||
if (!plan.id) {
|
||||
throw new Error(`Plan ${plan.title} not found on database`);
|
||||
}
|
||||
|
||||
await PortalStripeServer.updateStripeProduct(plan.stripeId, { title: plan.translatedTitle ?? plan.title });
|
||||
|
||||
await updatePortalSubscriptionProduct(portalId, plan.id, {
|
||||
order: plan.order,
|
||||
title: plan.title,
|
||||
model: plan.model,
|
||||
description: plan.description ?? undefined,
|
||||
badge: plan.badge ?? undefined,
|
||||
groupTitle: plan.groupTitle ?? undefined,
|
||||
groupDescription: plan.groupDescription ?? undefined,
|
||||
public: plan.public,
|
||||
billingAddressCollection: plan.billingAddressCollection ?? "auto",
|
||||
hasQuantity: plan.hasQuantity === undefined ? undefined : plan.hasQuantity,
|
||||
canBuyAgain: plan.canBuyAgain === undefined ? undefined : plan.canBuyAgain,
|
||||
});
|
||||
|
||||
await deletePortalSubscriptionFeatures(portalId, plan.id ?? "");
|
||||
await PortalSubscriptionServer.clearSubscriptionsCache(portalId);
|
||||
|
||||
return await Promise.all(
|
||||
features
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map(async (feature) => {
|
||||
return await createPortalSubscriptionFeature(portalId, plan.id ?? "", feature);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function deletePlan(portalId: string, plan: SubscriptionProductDto) {
|
||||
await PortalSubscriptionServer.clearSubscriptionsCache(portalId);
|
||||
portalPricingLogger.info({ count: plan.prices?.length }, `Deleting ${plan.prices?.length} Flat-rate Prices`);
|
||||
|
||||
await Promise.all(
|
||||
plan.prices
|
||||
.filter((f) => f.stripeId)
|
||||
.map(async (price) => {
|
||||
await PortalStripeServer.archiveStripePrice(price.stripeId);
|
||||
|
||||
if (price.id) {
|
||||
await deletePortalSubscriptionPrice(portalId, price.id);
|
||||
}
|
||||
|
||||
return null;
|
||||
})
|
||||
);
|
||||
|
||||
portalPricingLogger.info({ stripeId: plan.stripeId }, "Deleting Product with Stripe ID");
|
||||
if (plan.stripeId) {
|
||||
try {
|
||||
await PortalStripeServer.deleteStripeProduct(plan.stripeId);
|
||||
} catch (e: any) {
|
||||
portalPricingLogger.error({ err: e }, "deleteStripeProduct failed, falling back to archive");
|
||||
await PortalStripeServer.archiveStripeProduct(plan.stripeId);
|
||||
}
|
||||
}
|
||||
|
||||
if (plan.id) {
|
||||
await deletePortalSubscriptionProduct(portalId, plan.id);
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
createPlans,
|
||||
createPlan,
|
||||
syncPlan,
|
||||
updatePlan,
|
||||
deletePlan,
|
||||
};
|
||||
@@ -0,0 +1,562 @@
|
||||
import type Stripe from "stripe";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import { getAllPortalSubscriptionProducts } from "../db/portalSubscriptionProducts.db.server";
|
||||
import { cachified } from "~/utils/cache.server";
|
||||
import PortalSubscriptionServer from "./PortalSubscription.server";
|
||||
import { PortalDto } from "../dtos/PortalDto";
|
||||
import { getAbsoluteCurrentUrl } from "~/utils/url.server";
|
||||
import { getStripeClient } from "~/utils/stripe.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const portalStripeLogger = createScopedLogger("portals.stripe");
|
||||
|
||||
const stripe = new Proxy({} as Stripe, {
|
||||
get(_target, property, receiver) {
|
||||
return Reflect.get(getStripeClient(), property, receiver);
|
||||
},
|
||||
});
|
||||
|
||||
async function createStripeCheckoutSession(data: {
|
||||
portal: PortalDto;
|
||||
subscriptionProduct: SubscriptionProductDto;
|
||||
customer?: string;
|
||||
line_items: { price: string; quantity?: number }[];
|
||||
mode: "payment" | "setup" | "subscription";
|
||||
success_url: string;
|
||||
cancel_url: string;
|
||||
freeTrialDays?: number;
|
||||
coupon?: string;
|
||||
promo_code?: string;
|
||||
referral?: string | null;
|
||||
}) {
|
||||
if (!data.portal.stripeAccountId) {
|
||||
throw new Error("Stripe account not connected");
|
||||
}
|
||||
const discounts: { coupon?: string; promotion_code?: string }[] = [];
|
||||
if (data.coupon) {
|
||||
discounts.push({ coupon: data.coupon });
|
||||
} else if (data.promo_code) {
|
||||
discounts.push({ promotion_code: data.promo_code });
|
||||
}
|
||||
let billing_address_collection: "auto" | "required" | undefined = undefined;
|
||||
if (data.subscriptionProduct.billingAddressCollection === "required") {
|
||||
billing_address_collection = "required";
|
||||
} else if (data.subscriptionProduct.billingAddressCollection === "auto") {
|
||||
billing_address_collection = "auto";
|
||||
}
|
||||
let client_reference_id: string | undefined = undefined;
|
||||
if (data.referral) {
|
||||
client_reference_id = data.referral;
|
||||
}
|
||||
return await stripe.checkout.sessions
|
||||
.create({
|
||||
discounts,
|
||||
customer: data.customer,
|
||||
line_items: data.line_items,
|
||||
mode: data.mode,
|
||||
success_url: data.success_url,
|
||||
cancel_url: data.cancel_url,
|
||||
customer_creation: data.mode === "payment" && !data.customer ? "always" : undefined,
|
||||
payment_method_collection: data.mode === "subscription" ? "if_required" : undefined,
|
||||
subscription_data:
|
||||
data.mode === "subscription"
|
||||
? {
|
||||
trial_period_days: data.freeTrialDays,
|
||||
transfer_data: {
|
||||
destination: data.portal.stripeAccountId,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
billing_address_collection,
|
||||
client_reference_id,
|
||||
payment_intent_data:
|
||||
data.mode == "payment"
|
||||
? {
|
||||
application_fee_amount: 0,
|
||||
transfer_data: {
|
||||
destination: data.portal.stripeAccountId,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
.catch((e) => {
|
||||
portalStripeLogger.error({ err: e }, "Portal stripe checkout session creation failed");
|
||||
throw e;
|
||||
});
|
||||
}
|
||||
|
||||
async function createStripeSetupSession(request: Request, customer: string) {
|
||||
const currentUrl = getAbsoluteCurrentUrl(request);
|
||||
return await stripe.checkout.sessions.create({
|
||||
customer,
|
||||
success_url: `${currentUrl}?session_id={CHECKOUT_SESSION_ID}`,
|
||||
cancel_url: currentUrl,
|
||||
mode: "setup",
|
||||
payment_method_types: ["card"],
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteStripePaymentMethod(id: string) {
|
||||
return await stripe.paymentMethods.detach(id);
|
||||
}
|
||||
|
||||
async function getStripeSession(id: string) {
|
||||
return await stripe.checkout.sessions
|
||||
.retrieve(id, {
|
||||
expand: ["line_items"],
|
||||
})
|
||||
.catch(() => {
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
async function cancelStripeSubscription(subscriptionId: string) {
|
||||
return await stripe.subscriptions.cancel(subscriptionId).catch((e: any) => {
|
||||
portalStripeLogger.warn({ err: e }, "Could not cancel portal stripe subscription");
|
||||
});
|
||||
}
|
||||
|
||||
async function reactivateStripeSubscription(subscriptionId: string) {
|
||||
return await stripe.subscriptions
|
||||
.update(subscriptionId, {
|
||||
cancel_at_period_end: false,
|
||||
})
|
||||
.catch((e: any) => {
|
||||
portalStripeLogger.warn({ err: e }, "Could not reactivate portal stripe subscription");
|
||||
});
|
||||
}
|
||||
|
||||
async function getStripeSubscription(id: string) {
|
||||
try {
|
||||
return await stripe.subscriptions.retrieve(id);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function createStripeSubscription(customer: string, price: string, trial_end?: number) {
|
||||
return await stripe.subscriptions.create({
|
||||
customer,
|
||||
items: [
|
||||
{
|
||||
price,
|
||||
},
|
||||
],
|
||||
trial_end,
|
||||
});
|
||||
}
|
||||
|
||||
async function getStripeInvoices(id: string | null) {
|
||||
if (!id) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
return (
|
||||
await stripe.invoices.list({
|
||||
customer: id,
|
||||
})
|
||||
).data;
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function getStripePaymentIntents(id: string | null, status?: Stripe.PaymentIntent.Status) {
|
||||
if (!id) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
let items = (
|
||||
await stripe.paymentIntents.list({
|
||||
customer: id,
|
||||
})
|
||||
).data;
|
||||
if (status) {
|
||||
items = items.filter((item) => item.status === status);
|
||||
}
|
||||
return items;
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function getStripePaymentIntent(id: string) {
|
||||
try {
|
||||
return await stripe.paymentIntents.retrieve(id);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function getStripeUpcomingInvoice(id: string | null) {
|
||||
if (!id) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return await stripe.invoices.createPreview({
|
||||
customer: id,
|
||||
});
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function getStripePaymentMethods(customer: string | null) {
|
||||
if (!customer) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
return (
|
||||
await stripe.paymentMethods.list({
|
||||
customer,
|
||||
type: "card",
|
||||
})
|
||||
).data;
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function createStripeCustomer(email: string, name: string, stripeAccount: string) {
|
||||
let customer = await stripe.customers
|
||||
.create({
|
||||
stripeAccount,
|
||||
})
|
||||
.catch((e: any) => {
|
||||
portalStripeLogger.error({ err: e }, "Portal createStripeCustomer create failed");
|
||||
return null;
|
||||
});
|
||||
if (customer) {
|
||||
customer = await stripe.customers
|
||||
.update(customer.id, {
|
||||
email,
|
||||
name,
|
||||
})
|
||||
.catch((e: any) => {
|
||||
portalStripeLogger.error({ err: e }, "Portal createStripeCustomer update failed");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
return customer;
|
||||
}
|
||||
|
||||
async function deleteStripeCustomer(id: string) {
|
||||
return await stripe.customers.del(id);
|
||||
}
|
||||
|
||||
async function updateStripeCustomerPaymentMethod(id: string, default_payment_method: string) {
|
||||
return await stripe.customers.update(id, {
|
||||
invoice_settings: { default_payment_method },
|
||||
});
|
||||
}
|
||||
|
||||
async function createStripeProduct(data: { title: string }) {
|
||||
return await stripe.products.create({
|
||||
name: data.title,
|
||||
});
|
||||
}
|
||||
|
||||
async function updateStripeProduct(id: string, data: { title: string }) {
|
||||
return await stripe.products
|
||||
.update(id, {
|
||||
name: data.title,
|
||||
})
|
||||
.catch((error) => {
|
||||
// console.error(error);
|
||||
// ignore
|
||||
});
|
||||
}
|
||||
|
||||
async function createStripePrice(productId: string, data: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }) {
|
||||
if (!productId) {
|
||||
return undefined;
|
||||
}
|
||||
let recurring:
|
||||
| {
|
||||
interval: "day" | "week" | "month" | "year";
|
||||
trial_period_days: number | undefined;
|
||||
interval_count?: number;
|
||||
}
|
||||
| undefined = undefined;
|
||||
switch (data.billingPeriod) {
|
||||
case SubscriptionBillingPeriod.MONTHLY:
|
||||
recurring = { interval: "month", trial_period_days: data.trialDays };
|
||||
break;
|
||||
case SubscriptionBillingPeriod.QUARTERLY:
|
||||
recurring = { interval: "month", interval_count: 3, trial_period_days: data.trialDays };
|
||||
break;
|
||||
case SubscriptionBillingPeriod.SEMI_ANNUAL:
|
||||
recurring = { interval: "month", interval_count: 6, trial_period_days: data.trialDays };
|
||||
break;
|
||||
case SubscriptionBillingPeriod.WEEKLY:
|
||||
recurring = { interval: "week", trial_period_days: data.trialDays };
|
||||
break;
|
||||
case SubscriptionBillingPeriod.YEARLY:
|
||||
recurring = { interval: "year", trial_period_days: data.trialDays };
|
||||
break;
|
||||
case SubscriptionBillingPeriod.DAILY:
|
||||
recurring = { interval: "day", trial_period_days: data.trialDays };
|
||||
break;
|
||||
}
|
||||
return await stripe.prices.create({
|
||||
unit_amount: Math.round(data.price * 100),
|
||||
currency: data.currency,
|
||||
recurring,
|
||||
product: productId,
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteStripeProduct(productId: string) {
|
||||
return await stripe.products.del(productId);
|
||||
}
|
||||
|
||||
async function archiveStripeProduct(productId: string) {
|
||||
return await stripe.products
|
||||
.update(productId, {
|
||||
active: false,
|
||||
})
|
||||
.catch(() => {
|
||||
// ignore
|
||||
});
|
||||
}
|
||||
|
||||
async function archiveStripePrice(productId: string) {
|
||||
return await stripe.prices
|
||||
.update(productId, {
|
||||
active: false,
|
||||
})
|
||||
.catch(() => {
|
||||
// ignore
|
||||
});
|
||||
}
|
||||
|
||||
async function getStripeCoupon(id: string) {
|
||||
return await stripe.coupons.retrieve(id, {
|
||||
expand: ["applies_to"],
|
||||
});
|
||||
}
|
||||
|
||||
async function getStripePromotionCode(id: string) {
|
||||
return await stripe.promotionCodes.retrieve(id);
|
||||
}
|
||||
|
||||
async function getStripeCustomer(id: string | null) {
|
||||
if (!id) {
|
||||
return null;
|
||||
}
|
||||
return await stripe.customers.retrieve(id, {
|
||||
expand: ["invoice_settings"],
|
||||
});
|
||||
}
|
||||
|
||||
async function getOpenInvoices(id: string) {
|
||||
return await cachified({
|
||||
key: `stripe:openInvoices:${id}`,
|
||||
ttl: 1000 * 60 * 60 * 24, // 24 hours
|
||||
getFreshValue: () =>
|
||||
stripe.invoices.list({
|
||||
customer: id,
|
||||
status: "open",
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
async function createCustomerPortalSession(request: Request, id: string) {
|
||||
return await stripe.billingPortal.sessions.create({
|
||||
customer: id,
|
||||
return_url: getAbsoluteCurrentUrl(request),
|
||||
});
|
||||
}
|
||||
|
||||
async function getAllStripePayments() {
|
||||
return cachified({
|
||||
key: `stripe:payments`,
|
||||
ttl: 1000 * 60 * 60 * 24, // 24 hours
|
||||
getFreshValue: async () => {
|
||||
let items: Stripe.PaymentIntent[] = [];
|
||||
let hasMore = true;
|
||||
let startingAfter: string | undefined = undefined;
|
||||
let max = 10;
|
||||
while (hasMore) {
|
||||
const result: Stripe.ApiList<Stripe.PaymentIntent> = await stripe.paymentIntents.list({
|
||||
limit: 100,
|
||||
starting_after: startingAfter,
|
||||
expand: ["data.charges"],
|
||||
});
|
||||
items = items.concat(result.data);
|
||||
hasMore = result.has_more;
|
||||
startingAfter = result.data[result.data.length - 1].id;
|
||||
max--;
|
||||
if (max <= 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return items;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Portal-scoped inverted map `paymentIntentId → Invoice`. See
|
||||
* `getAllStripeInvoicesByPaymentIntent` in `stripe.server.ts` for the
|
||||
* rationale (Stripe 19 removed `PaymentIntent.invoice`).
|
||||
*/
|
||||
async function getAllStripeInvoicesByPaymentIntent(): Promise<Map<string, Stripe.Invoice>> {
|
||||
return cachified({
|
||||
key: `stripe:portal:invoicesByPaymentIntent`,
|
||||
ttl: 1000 * 60 * 60 * 24, // 24 hours
|
||||
getFreshValue: async () => {
|
||||
const map = new Map<string, Stripe.Invoice>();
|
||||
let hasMore = true;
|
||||
let startingAfter: string | undefined = undefined;
|
||||
let max = 10;
|
||||
while (hasMore) {
|
||||
const result: Stripe.ApiList<Stripe.Invoice> = await stripe.invoices.list({
|
||||
limit: 100,
|
||||
starting_after: startingAfter,
|
||||
});
|
||||
for (const invoice of result.data) {
|
||||
// Stripe 19 removed Invoice.payment_intent. The id now lives on
|
||||
// each Invoice.payments[].payment.payment_intent (one invoice
|
||||
// can have multiple payment attempts; we index by all).
|
||||
for (const invoicePayment of invoice.payments?.data ?? []) {
|
||||
const ref = invoicePayment.payment.payment_intent;
|
||||
const piId = typeof ref === "string" ? ref : ref?.id;
|
||||
if (piId) {
|
||||
map.set(piId, invoice);
|
||||
}
|
||||
}
|
||||
}
|
||||
hasMore = result.has_more;
|
||||
startingAfter = result.data[result.data.length - 1]?.id;
|
||||
max--;
|
||||
if (max <= 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return map;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export type StripeRevenueByProductPriceCurrency = {
|
||||
product: string;
|
||||
billingPeriod: SubscriptionBillingPeriod;
|
||||
currency: string;
|
||||
revenueInCurrency: number;
|
||||
count: number;
|
||||
countPercentage: number;
|
||||
revenueUsd: number;
|
||||
revenuePercentageUsd: number;
|
||||
};
|
||||
async function getStripeRevenueByProductPriceCurrency(portalId: string): Promise<StripeRevenueByProductPriceCurrency[]> {
|
||||
const items: StripeRevenueByProductPriceCurrency[] = [];
|
||||
const allProducts = await getAllPortalSubscriptionProducts(portalId);
|
||||
|
||||
const [payments, invoicesByPaymentIntent] = await Promise.all([
|
||||
getAllStripePayments(),
|
||||
getAllStripeInvoicesByPaymentIntent(),
|
||||
]);
|
||||
payments.forEach((payment) => {
|
||||
if (payment.status !== "succeeded") {
|
||||
return;
|
||||
}
|
||||
// Stripe 19 removed PaymentIntent.invoice. Traverse via the
|
||||
// inverted map built from Invoice.payment_intent instead.
|
||||
const invoice = invoicesByPaymentIntent.get(payment.id);
|
||||
const lines = invoice?.lines?.data[0];
|
||||
// Stripe 19 dropped InvoiceLineItem.plan; the (price, product)
|
||||
// identifiers now live on InvoiceLineItem.pricing.price_details.
|
||||
const pricing = lines?.pricing;
|
||||
const amount = payment.amount / 100;
|
||||
const currency = payment.currency;
|
||||
const priceId = pricing?.price_details?.price;
|
||||
|
||||
const productId = pricing?.price_details?.product;
|
||||
|
||||
const product = allProducts.find((x) => x.stripeId === productId);
|
||||
let productName = "?";
|
||||
let billingPeriod: SubscriptionBillingPeriod = SubscriptionBillingPeriod.DAILY;
|
||||
if (product) {
|
||||
productName = product.title;
|
||||
}
|
||||
|
||||
const price = product?.prices.find((x) => x.stripeId === priceId);
|
||||
if (price) {
|
||||
billingPeriod = price.billingPeriod;
|
||||
}
|
||||
|
||||
const existing = items.find((x) => x.product === productName && x.currency === currency && x.billingPeriod === billingPeriod);
|
||||
|
||||
let revenueUsd = amount;
|
||||
if (currency !== "usd") {
|
||||
revenueUsd = PortalSubscriptionServer.convertToCurrency({
|
||||
from: currency,
|
||||
to: "usd",
|
||||
price: amount,
|
||||
});
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
existing.revenueInCurrency += amount;
|
||||
existing.revenueUsd += revenueUsd;
|
||||
existing.count++;
|
||||
} else {
|
||||
items.push({
|
||||
product: productName,
|
||||
billingPeriod,
|
||||
currency,
|
||||
revenueInCurrency: amount,
|
||||
revenueUsd,
|
||||
count: 1,
|
||||
countPercentage: 0,
|
||||
revenuePercentageUsd: 0,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// process percentages
|
||||
const totalRevenue = items.reduce((x, y) => x + y.revenueUsd, 0);
|
||||
const totalCount = items.reduce((x, y) => x + y.count, 0);
|
||||
items.forEach((item) => {
|
||||
item.countPercentage = item.count / totalCount;
|
||||
item.revenuePercentageUsd = item.revenueUsd / totalRevenue;
|
||||
});
|
||||
|
||||
// sort by revenue desc
|
||||
return items.sort((x, y) => (x.revenueUsd > y.revenueUsd ? -1 : 1));
|
||||
}
|
||||
|
||||
export default {
|
||||
createStripeCheckoutSession,
|
||||
createStripeSetupSession,
|
||||
deleteStripePaymentMethod,
|
||||
getStripeSession,
|
||||
cancelStripeSubscription,
|
||||
reactivateStripeSubscription,
|
||||
getStripeSubscription,
|
||||
createStripeSubscription,
|
||||
getStripeInvoices,
|
||||
getStripePaymentIntents,
|
||||
getStripePaymentIntent,
|
||||
getStripeUpcomingInvoice,
|
||||
getStripePaymentMethods,
|
||||
createStripeCustomer,
|
||||
deleteStripeCustomer,
|
||||
updateStripeCustomerPaymentMethod,
|
||||
createStripeProduct,
|
||||
updateStripeProduct,
|
||||
createStripePrice,
|
||||
deleteStripeProduct,
|
||||
archiveStripeProduct,
|
||||
archiveStripePrice,
|
||||
getStripeCoupon,
|
||||
getStripePromotionCode,
|
||||
getStripeCustomer,
|
||||
getOpenInvoices,
|
||||
createCustomerPortalSession,
|
||||
getAllStripePayments,
|
||||
getStripeRevenueByProductPriceCurrency,
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import currencies from "~/application/pricing/currencies";
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
async function clearSubscriptionsCache(portalId: string) {
|
||||
const portalUserSubscriptions = await db.portalUserSubscription.findMany({ where: { portalId } });
|
||||
portalUserSubscriptions.forEach((item) => {
|
||||
clearCacheKey(`portalUserSubscription:${item.portalId}:${item.portalUserId}`);
|
||||
});
|
||||
}
|
||||
|
||||
function convertToCurrency({ from, price, to }: { from: string; price: number; to: string }): number {
|
||||
const fromCurrency = currencies.find((f) => f.value === from);
|
||||
const toCurrency = currencies.find((f) => f.value === to);
|
||||
if (!fromCurrency || !toCurrency) {
|
||||
return 0;
|
||||
}
|
||||
const fromParity = fromCurrency.parities?.find((f) => f.from === to);
|
||||
const toParity = toCurrency.parities?.find((f) => f.from === from);
|
||||
if (fromParity && fromParity.parity !== 0) {
|
||||
return price / fromParity.parity;
|
||||
} else if (toParity && toParity.parity !== 0) {
|
||||
return price / toParity.parity;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export default {
|
||||
clearSubscriptionsCache,
|
||||
convertToCurrency,
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
import type Stripe from "stripe";
|
||||
import { getStripeClient } from "~/utils/stripe.server";
|
||||
|
||||
const stripe = new Proxy({} as Stripe, {
|
||||
get(_target, property, receiver) {
|
||||
return Reflect.get(getStripeClient(), property, receiver);
|
||||
},
|
||||
});
|
||||
|
||||
async function getStripeAccount(id: string) {
|
||||
return await stripe.accounts.retrieve(id);
|
||||
}
|
||||
|
||||
async function createStripeAccount({ email, country, metadata }: { email: string; country: string; metadata?: { [key: string]: string | number } }) {
|
||||
return await stripe.accounts.create({
|
||||
type: "standard",
|
||||
email,
|
||||
country,
|
||||
// capabilities: {
|
||||
// card_payments: {
|
||||
// requested: true,
|
||||
// },
|
||||
// transfers: {
|
||||
// requested: true,
|
||||
// },
|
||||
// },
|
||||
metadata,
|
||||
});
|
||||
}
|
||||
|
||||
async function createStripeAccountLink({ account, refresh_url, return_url }: { account: string; refresh_url: string; return_url: string }) {
|
||||
return await stripe.accountLinks.create({
|
||||
account,
|
||||
refresh_url,
|
||||
return_url,
|
||||
type: "account_onboarding",
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteStripeAccount(id: string) {
|
||||
return await stripe.accounts.del(id);
|
||||
}
|
||||
|
||||
async function getStripeAccountProducts(id: string) {
|
||||
return (
|
||||
await stripe.products.list({
|
||||
stripeAccount: id,
|
||||
})
|
||||
).data;
|
||||
}
|
||||
|
||||
export default {
|
||||
getStripeAccount,
|
||||
createStripeAccount,
|
||||
createStripeAccountLink,
|
||||
deleteStripeAccount,
|
||||
getStripeAccountProducts,
|
||||
};
|
||||
Reference in new issue
Block a user