Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions app/api/webhooks/stripe/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ const buildSubscriptionUpsertData = (
subscription: Stripe.Subscription,
firstItem: Stripe.SubscriptionItem | undefined,
serverId: string,
internalBillingCustomerId: string,
promoCode: string | null,
couponAmountOff: number | null,
periodStart: Date | null,
Expand All @@ -220,7 +221,7 @@ const buildSubscriptionUpsertData = (
const status = toSubscriptionStatus(subscription.status);
return {
create: {
billingCustomerId: subscription.customer as string,
billingCustomerId: internalBillingCustomerId,
canceledAt,
currency: subscription.currency.toUpperCase(),
currentPeriodEnd: periodEnd,
Expand Down Expand Up @@ -260,6 +261,16 @@ const handleSubscriptionChanged = async (
return;
}

// Resolve internal BillingCustomer.id from the Stripe customer ID
const stripeCustomerId = subscription.customer as string;
const billingCustomer = await prisma.billingCustomer.findUnique({
select: { id: true },
where: { stripeCustomerId },
});
if (!billingCustomer) {
return;
}

const { promoCode, couponAmountOff, couponPercentOff } =
resolveSubscriptionDiscount(subscription);
const { periodStart, periodEnd } = resolveSubscriptionPeriod(subscription);
Expand All @@ -275,6 +286,7 @@ const handleSubscriptionChanged = async (
subscription,
firstItem,
serverId,
billingCustomer.id,
promoCode,
couponAmountOff,
periodStart,
Expand Down Expand Up @@ -409,9 +421,21 @@ const upsertCheckoutSubscriptionAndAddons = async (
? firstItem.price.product
: ((firstItem?.price.product as Stripe.Product)?.id ?? "");

// Resolve the internal BillingCustomer.id from the Stripe customer ID —
// billingCustomerId is a FK to BillingCustomer.id (not stripeCustomerId)
const billingCustomer = await prisma.billingCustomer.findUnique({
select: { id: true },
where: { stripeCustomerId: customerId },
});
if (!billingCustomer) {
throw new Error(
`BillingCustomer not found for Stripe customer ${customerId}`
);
}

await prisma.subscription.upsert({
create: {
billingCustomerId: customerId,
billingCustomerId: billingCustomer.id,
currency: (subscription.currency ?? "gbp").toUpperCase(),
id: subscriptionId,
planName: subscription.metadata?.serverType ?? "unknown",
Expand Down
102 changes: 102 additions & 0 deletions lib/mail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -797,3 +797,105 @@ export const sendSuspensionWarningEmail = (
to: toEmail,
});
};

// ---------------------------------------------------------------------------
// Server ready email
// ---------------------------------------------------------------------------

interface ServerReadyParams {
toEmail: string;
userName: string | null | undefined;
serverName: string;
game: string;
region: string;
serverUrl: string;
}

export const sendServerReadyEmail = (
params: ServerReadyParams
): Promise<boolean> => {
const { toEmail, userName, serverName, game, region, serverUrl } = params;
const displayName = userName ?? "there";
const gameLabel =
game.charAt(0).toUpperCase() + game.slice(1).replaceAll("-", " ");

const html = baseTemplate(`
<h1>Your server is ready! 🎮</h1>
<p>Hi <span class="hl">${displayName}</span>, your game server has finished provisioning and is ready to use.</p>
<dl class="info-box">
<dt>Server name</dt><dd>${serverName}</dd>
<dt>Game</dt><dd>${gameLabel}</dd>
<dt>Region</dt><dd>${region}</dd>
</dl>
<a class="btn" href="${serverUrl}">Go to server</a>
<p class="meta">
You'll find the connection details and server controls on your server page.
</p>
`);

const text = [
`Your NodeByte server "${serverName}" is ready!`,
``,
`Game: ${gameLabel}`,
`Region: ${region}`,
``,
`Go to your server: ${serverUrl}`,
].join("\n");

return sendMail({
html,
subject: `Your server "${serverName}" is ready to play`,
text,
to: toEmail,
});
};

// ---------------------------------------------------------------------------
// Server provision failed email
// ---------------------------------------------------------------------------

interface ServerProvisionFailedParams {
toEmail: string;
userName: string | null | undefined;
serverName: string;
reason: string;
supportUrl: string;
}

export const sendServerProvisionFailedEmail = (
params: ServerProvisionFailedParams
): Promise<boolean> => {
const { toEmail, userName, serverName, reason, supportUrl } = params;
const displayName = userName ?? "there";

const html = baseTemplate(`
<h1 style="color:#dc2626">Server provisioning failed</h1>
<p>Hi <span class="hl">${displayName}</span>, we were unable to provision your server <span class="hl">${serverName}</span>.</p>
<dl class="info-box">
<dt>Reason</dt><dd style="color:#f87171">${reason}</dd>
</dl>
<p>Our team has been notified. Please contact support and we'll get this resolved for you.</p>
<a class="btn" href="${supportUrl}">Contact support</a>
<p class="meta">
Your subscription will not be charged for a server that failed to provision.
</p>
`);

const text = [
`Server provisioning failed — NodeByte`,
``,
`Hi ${displayName}, we were unable to provision "${serverName}".`,
``,
`Reason: ${reason}`,
``,
`Please contact support: ${supportUrl}`,
`Your subscription will not be charged for a server that failed to provision.`,
].join("\n");

return sendMail({
html,
subject: `Server "${serverName}" failed to provision`,
text,
to: toEmail,
});
};
48 changes: 48 additions & 0 deletions lib/workflows/steps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ import { enqueueCommand } from "@/lib/agent/commands";
import { prisma } from "@/lib/db";
import { API_URL, env, SNAPSHOT_ENVIRONMENT } from "@/lib/env";
import { emitActivity } from "@/lib/events/emit";
import {
sendServerDeletedEmail,
sendServerProvisionFailedEmail,
sendServerReadyEmail,
} from "@/lib/mail";
import {
getProviderForUser,
getProviderForUserWithImage,
Expand Down Expand Up @@ -285,6 +290,25 @@ export const stepMarkReady = async (serverId: string) => {
phase: "ready",
serverId,
});
const server = await prisma.server.findUnique({
select: {
game: true,
location: true,
name: true,
user: { select: { email: true, name: true } },
},
where: { id: serverId },
});
if (server?.user) {
void sendServerReadyEmail({
game: server.game,
region: server.location,
serverName: server.name,
serverUrl: `${API_URL}/dashboard/${serverId}`,
toEmail: server.user.email,
userName: server.user.name,
});
}
};

export const stepMarkFailed = async (input: {
Expand All @@ -305,6 +329,19 @@ export const stepMarkFailed = async (input: {
phase: "errored",
serverId: input.serverId,
});
const server = await prisma.server.findUnique({
select: { name: true, user: { select: { email: true, name: true } } },
where: { id: input.serverId },
});
if (server?.user) {
void sendServerProvisionFailedEmail({
reason: input.reason,
serverName: server.name,
supportUrl: "https://nodebyte.host/contact",
toEmail: server.user.email,
userName: server.user.name,
});
}
};

const AGENT_LIVENESS_WINDOW_MS = 60_000;
Expand Down Expand Up @@ -353,6 +390,10 @@ export const stepDeleteProviderServer = async (serverId: string) => {

export const stepMarkDeleted = async (serverId: string) => {
"use step";
const server = await prisma.server.findUnique({
select: { name: true, user: { select: { email: true, name: true } } },
where: { id: serverId },
});
const { count } = await prisma.server.updateMany({
data: {
deletedAt: new Date(),
Expand All @@ -369,6 +410,13 @@ export const stepMarkDeleted = async (serverId: string) => {
phase: "deleted",
serverId,
});
if (server?.user) {
void sendServerDeletedEmail({
serverName: server.name,
toEmail: server.user.email,
userName: server.user.name,
});
}
};

export const stepReadPhase = async (
Expand Down