Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,4 +1,4 @@
import type { PortalSubscriptionFeature, PortalSubscriptionPrice, PortalSubscriptionProduct } from "@toolctrl/db/prisma-browser";
import type { PortalSubscriptionFeature, PortalSubscriptionPrice, PortalSubscriptionProduct } from "@hivegrid/db/prisma-browser";
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
@@ -140,11 +140,11 @@ export async function getPortalSubscriptionProduct(portalId: string, id: string)
});
}
export async function getPortalSubscriptionProductByStripeId(portalId: string, stripeId: string) {
export async function getPortalSubscriptionProductByBillingProviderId(portalId: string, billingProviderId: string) {
return await db.portalSubscriptionProduct.findFirst({
where: {
portalId,
stripeId,
billingProviderId,
},
});
}
@@ -187,10 +187,10 @@ export async function getPortalSubscriptionPrice(portalId: string, id: string):
});
}
export async function getPortalSubscriptionPriceByStripeId(portalId: string, stripeId: string): Promise<PortalSubscriptionPriceWithProduct | null> {
export async function getPortalSubscriptionPriceByBillingProviderId(portalId: string, billingProviderId: string): Promise<PortalSubscriptionPriceWithProduct | null> {
return await db.portalSubscriptionPrice
.findFirst({
where: { portalId, stripeId },
where: { portalId, billingProviderId },
include: {
subscriptionProduct: true,
},
@@ -202,7 +202,7 @@ export async function getPortalSubscriptionPriceByStripeId(portalId: string, str
export async function createPortalSubscriptionProduct(data: {
portalId: string;
stripeId: string;
billingProviderId: string;
order: number;
title: string;
model: PricingModel;
@@ -219,7 +219,7 @@ export async function createPortalSubscriptionProduct(data: {
return await db.portalSubscriptionProduct.create({
data: {
portalId: data.portalId,
stripeId: data.stripeId,
billingProviderId: data.billingProviderId,
order: data.order,
title: data.title,
model: data.model,
@@ -240,7 +240,7 @@ export async function updatePortalSubscriptionProduct(
portalId: string,
id: string,
data: {
stripeId?: string;
billingProviderId?: string;
order?: number;
title?: string;
model?: PricingModel;
@@ -260,7 +260,7 @@ export async function updatePortalSubscriptionProduct(
portalId,
},
data: {
stripeId: data.stripeId,
billingProviderId: data.billingProviderId,
order: data.order,
title: data.title,
model: data.model,
@@ -285,7 +285,7 @@ export async function updatePortalSubscriptionProduct(
return item;
}
export async function updatePortalSubscriptionProductStripeId(portalId: string, id: string, data: { stripeId: string }) {
export async function updatePortalSubscriptionProductBillingProviderId(portalId: string, id: string, data: { billingProviderId: string }) {
return await db.portalSubscriptionProduct.update({
where: {
portalId,
@@ -295,7 +295,7 @@ export async function updatePortalSubscriptionProductStripeId(portalId: string,
});
}
export async function updatePortalSubscriptionPriceStripeId(portalId: string, id: string, data: { stripeId: string }) {
export async function updatePortalSubscriptionPriceBillingProviderId(portalId: string, id: string, data: { billingProviderId: string }) {
return await db.portalSubscriptionPrice.update({
where: {
portalId,
@@ -308,7 +308,7 @@ export async function updatePortalSubscriptionPriceStripeId(portalId: string, id
export async function createPortalSubscriptionPrice(data: {
portalId: string;
subscriptionProductId: string;
stripeId: string;
billingProviderId: string;
type: SubscriptionPriceType;
billingPeriod: SubscriptionBillingPeriod;
price: number;
@@ -320,7 +320,7 @@ export async function createPortalSubscriptionPrice(data: {
data: {
portalId: data.portalId,
subscriptionProductId: data.subscriptionProductId,
stripeId: data.stripeId,
billingProviderId: data.billingProviderId,
type: data.type,
billingPeriod: data.billingPeriod,
price: data.price,
@@ -6,7 +6,7 @@ import {
PortalUserSubscription,
PortalUserSubscriptionProduct,
PortalUserSubscriptionProductPrice,
} from "@toolctrl/db/prisma-browser";
} from "@hivegrid/db/prisma-browser";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { db } from "~/utils/db.server";
@@ -154,14 +154,14 @@ export async function getPortalUserSubscriptionProductById(portalId: string, id:
});
}
export async function getPortalUserSubscriptionProductByStripeSubscriptionId(
export async function getPortalUserSubscriptionProductByBillingProviderSubscriptionId(
portalId: string,
stripeSubscriptionId: string
billingProviderSubscriptionId: string
): Promise<PortalUserSubscriptionProductWithTenant | null> {
return await db.portalUserSubscriptionProduct.findFirst({
where: {
portalId,
stripeSubscriptionId,
billingProviderSubscriptionId,
},
include: {
portalUserSubscription: {
@@ -176,7 +176,7 @@ export async function addPortalUserSubscriptionProduct(data: {
portalId: string;
portalUserSubscriptionId: string;
subscriptionProductId: string;
stripeSubscriptionId?: string;
billingProviderSubscriptionId?: string;
quantity?: number;
fromCheckoutSessionId?: string | null;
prices: {
@@ -189,7 +189,7 @@ export async function addPortalUserSubscriptionProduct(data: {
portalId: data.portalId,
portalUserSubscriptionId: data.portalUserSubscriptionId,
subscriptionProductId: data.subscriptionProductId,
stripeSubscriptionId: data.stripeSubscriptionId,
billingProviderSubscriptionId: data.billingProviderSubscriptionId,
quantity: data.quantity,
fromCheckoutSessionId: data.fromCheckoutSessionId,
endsAt: null,
@@ -1,4 +1,4 @@
import { PortalUserSubscription } from "@toolctrl/db/prisma-browser";
import { PortalUserSubscription } from "@hivegrid/db/prisma-browser";
import { clearCacheKey } from "~/utils/cache.server";
import { PortalUserSubscriptionProductWithDetails } from "./portalUserSubscriptionProducts.db.server";
import { db } from "~/utils/db.server";
@@ -72,13 +72,13 @@ export async function getPortalUserSubscriptions(portalId: string): Promise<Port
});
}
export async function createPortalUserSubscription(portalId: string, portalUserId: string, stripeCustomerId: string) {
export async function createPortalUserSubscription(portalId: string, portalUserId: string, billingProviderCustomerId: string) {
return await db.portalUserSubscription
.create({
data: {
portalId,
portalUserId,
stripeCustomerId,
billingProviderCustomerId,
},
include: {
products: {
@@ -100,7 +100,7 @@ export async function createPortalUserSubscription(portalId: string, portalUserI
});
}
export async function updatePortalUserSubscriptionCustomerId(portalId: string, portalUserId: string, data: { stripeCustomerId: string }) {
export async function updatePortalUserSubscriptionCustomerId(portalId: string, portalUserId: string, data: { billingProviderCustomerId: string }) {
return await db.portalUserSubscription
.update({
where: {
@@ -1,10 +1,10 @@
import { Prisma, Portal } from "@toolctrl/db/prisma-browser";
import { Prisma, Portal } from "@hivegrid/db/prisma-browser";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { loadWebConfig } from "@toolctrl/config";
import { loadWebConfig } from "@hivegrid/config";
import { db, dbRead } from "~/utils/db.server";
import { TenantSimple } from "~/utils/db/tenants.db.server";
import TenantModelHelper from "~/utils/helpers/models/TenantModelHelper";
@@ -171,7 +171,7 @@ export async function createPortal(data: {
domain: string | null;
title: string;
isPublished: boolean;
stripeAccountId: string | null;
paymentProviderAccountId: string | null;
metadata: JsonPropertiesValuesDto;
themeColor: string | null;
themeScheme: string | null;
@@ -203,7 +203,7 @@ export async function createPortal(data: {
domain: data.domain,
title: data.title,
isPublished: data.isPublished,
stripeAccountId: data.stripeAccountId,
paymentProviderAccountId: data.paymentProviderAccountId,
metadata: data.metadata,
themeColor: data.themeColor,
themeScheme: data.themeScheme,
@@ -241,7 +241,7 @@ export async function updatePortal(
domain?: string | null;
title?: string;
isPublished?: boolean;
stripeAccountId?: string | null;
paymentProviderAccountId?: string | null;
metadata?: JsonPropertiesValuesDto;
themeColor?: string | null;
themeScheme?: string | null;
@@ -272,7 +272,7 @@ export async function updatePortal(
domain: data.domain,
title: data.title,
isPublished: data.isPublished,
stripeAccountId: data.stripeAccountId,
paymentProviderAccountId: data.paymentProviderAccountId,
metadata: data.metadata,
themeColor: data.themeColor,
themeScheme: data.themeScheme,
@@ -8,7 +8,7 @@ export type PortalDto = {
domain: string | null;
title: string;
isPublished: boolean;
stripeAccountId: string | null;
paymentProviderAccountId: string | null;
metadata: JsonPropertiesValuesDto;
theme: {
color: string;
@@ -11,13 +11,9 @@ const requiredFixtureFiles = [
"docs/feature-decisions/portals-sites-decision-report.md",
"docs/feature-inventory.md",
"docs/feature-manifests/plugin-candidates.json",
"apps/web/app/routes/admin/portals.tsx",
"apps/web/app/modules/portals/services/PortalStripe.server.ts",
"apps/web/app/modules/portals/services/StripeConnect.server.ts",
"apps/web/app/modules/portals/db/portals.db.server.ts",
"apps/web/app/modules/sites/db/sites.db.server.ts",
"apps/web/app/modules/sites/site-types.ts",
"apps/web/app/routes/admin/analytics/page-views.tsx",
"prisma/schema/analytics.prisma",
"apps/web/app/modules/domains/services/Domains.server.ts",
"apps/web/app/application/sidebar/AppSidebar.test.tsx",
@@ -25,7 +21,6 @@ const requiredFixtureFiles = [
"prisma/schema/sites.prisma",
".env.example",
".env.production.example",
".env.fly.example",
];
const requiredFixtureDirectories = [
"apps/web/app/modules/portals",
@@ -1,4 +1,4 @@
import { loadWebConfig, type WebConfig } from "@toolctrl/config";
import { loadWebConfig, type WebConfig } from "@hivegrid/config";
function getPortalUrl(item: { subdomain: string; domain: string | null }, webConfig: WebConfig = loadWebConfig().config) {
if (item.domain) {
@@ -5,8 +5,8 @@ import {
createPortalSubscriptionProduct,
createPortalSubscriptionPrice,
createPortalSubscriptionFeature,
updatePortalSubscriptionProductStripeId,
updatePortalSubscriptionPriceStripeId,
updatePortalSubscriptionProductBillingProviderId,
updatePortalSubscriptionPriceBillingProviderId,
deletePortalSubscriptionPrice,
deletePortalSubscriptionProduct,
updatePortalSubscriptionProduct,
@@ -14,7 +14,6 @@ import {
} 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");
@@ -42,12 +41,9 @@ async function createPlan(
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 ?? "",
billingProviderId: plan.billingProviderId || plan.id || plan.title,
order: plan.order,
title: plan.title,
model: plan.model,
@@ -68,14 +64,11 @@ async function createPlan(
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 ?? "",
billingProviderId: `${product.id}:${price.billingPeriod}:${price.currency}:${price.price}`,
type: SubscriptionPriceType.RECURRING,
billingPeriod: price.billingPeriod,
price: price.price,
@@ -104,23 +97,13 @@ async function syncPlan(
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,
await updatePortalSubscriptionProductBillingProviderId(portalId, plan.id, {
billingProviderId: plan.billingProviderId || plan.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 ?? "",
await updatePortalSubscriptionPriceBillingProviderId(portalId, price.id ?? "", {
billingProviderId: price.id ?? `${plan.id}:${price.billingPeriod}:${price.currency}`,
});
});
}
@@ -130,8 +113,6 @@ async function updatePlan(portalId: string, plan: SubscriptionProductDto, featur
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,
@@ -164,10 +145,8 @@ async function deletePlan(portalId: string, plan: SubscriptionProductDto) {
await Promise.all(
plan.prices
.filter((f) => f.stripeId)
.filter((f) => f.billingProviderId)
.map(async (price) => {
await PortalStripeServer.archiveStripePrice(price.stripeId);
if (price.id) {
await deletePortalSubscriptionPrice(portalId, price.id);
}
@@ -176,16 +155,6 @@ async function deletePlan(portalId: string, plan: SubscriptionProductDto) {
})
);
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);
}
@@ -1,562 +0,0 @@
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,
};
@@ -1,58 +0,0 @@
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,
};
@@ -1,56 +0,0 @@
const stripeConnectCountries = [
{ value: "AU", name: "Australia" },
{ value: "LV", name: "Latvia" },
{ value: "AT", name: "Austria" },
{ value: "LT", name: "Lithuania" },
{ value: "BE", name: "Belgium" },
{ value: "LU", name: "Luxembourg" },
{ value: "MY", name: "Malaysia" },
{ value: "BG", name: "Bulgaria" },
{ value: "BR", name: "Brazil" },
{ value: "MT", name: "Malta" },
{ value: "CA", name: "Canada" },
{ value: "MX", name: "Mexico" },
{ value: "CY", name: "Cyprus" },
{ value: "NL", name: "Netherlands" },
{ value: "CZ", name: "Czech Republic" },
{ value: "NZ", name: "New Zealand" },
{ value: "DK", name: "Denmark" },
{ value: "NO", name: "Norway" },
{ value: "EE", name: "Estonia" },
{ value: "PL", name: "Poland" },
{ value: "FI", name: "Finland" },
{ value: "PT", name: "Portugal" },
{ value: "FR", name: "France" },
{ value: "RO", name: "Romania" },
{ value: "DE", name: "Germany" },
{ value: "SG", name: "Singapore" },
{ value: "GR", name: "Greece" },
{ value: "SK", name: "Slovakia" },
{ value: "HK", name: "Hong Kong" },
{ value: "SI", name: "Slovenia" },
{ value: "HU", name: "Hungary" },
{ value: "ES", name: "Spain" },
{ value: "SE", name: "Sweden" },
{ value: "IN", name: "India" },
{ value: "IE", name: "Ireland" },
{ value: "CH", name: "Switzerland" },
{ value: "IT", name: "Italy" },
{ value: "GB", name: "United Kingdom" },
{ value: "JP", name: "Japan" },
{ value: "US", name: "United States" },
{ value: "AE", name: "United Arab Emirates" },
];
function getLocalizedStripeConnectCountries(locale: string | undefined) {
const displayNames = typeof Intl.DisplayNames === "function" ? new Intl.DisplayNames([locale || "en"], { type: "region" }) : null;
return stripeConnectCountries.map((country) => ({
...country,
name: displayNames?.of(country.value) ?? country.name,
}));
}
export default {
stripeConnectCountries,
getLocalizedStripeConnectCountries,
};