Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+1
-1
@@ -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) {
|
||||
|
||||
+9
-40
@@ -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);
|
||||
}
|
||||
|
||||
-562
@@ -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,
|
||||
};
|
||||
-58
@@ -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,
|
||||
};
|
||||
Reference in new issue
Block a user