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
164 changes: 164 additions & 0 deletions app/(authenticated)/checkout/actions.ts
Comment thread
martin0024 marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
"use server";

import { headers } from "next/headers";
import { and, eq } from "drizzle-orm";
import type Stripe from "stripe";

import { db } from "@/lib/db";
import { coachingSessions, serviceBookings, services } from "@/lib/db/schema";
import { getOrCreateStripeCustomer, stripe } from "@/lib/stripe";
import { createClient } from "@/utils/supabase/server";

export type CheckoutResult = { url: string } | { error: string };

async function getDefaultPriceId(stripeProductId: string): Promise<string> {
const product = await stripe.products.retrieve(stripeProductId);
const defaultPriceId = product.default_price;
if (!defaultPriceId) {
throw new Error(`Stripe product ${stripeProductId} has no default price`);
}
return defaultPriceId as string;
}

async function getRequestOrigin(): Promise<string> {
const origin = (await headers()).get("origin");
if (!origin) {
throw new Error("Missing request origin");
}
return origin;
}

type CreateSessionResult =
| { session: Stripe.Checkout.Session }
| { error: string };

async function createStripeCheckoutSession(params: {
userId: string;
email: string;
stripeProductId: string;
metadata: Record<string, string>;
}): Promise<CreateSessionResult> {
const priceId = await getDefaultPriceId(params.stripeProductId);

const customerId = await getOrCreateStripeCustomer(
params.userId,
params.email,
);
const origin = await getRequestOrigin();

const session = await stripe.checkout.sessions.create({
customer: customerId,
mode: "payment",
payment_method_types: ["card"],
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${origin}/checkout/success`,
cancel_url: `${origin}/checkout/cancel`,
metadata: params.metadata,
});

if (!session.url)
return { error: "Stripe did not return a checkout URL" };
return { session };
}

export async function checkoutServiceBooking({
serviceId,
}: {
serviceId: string;
}): Promise<CheckoutResult> {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return { error: "Not authenticated" };

const service = await db.query.services.findFirst({
where: eq(services.id, serviceId),
});
Comment on lines +75 to +77
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (!service) return { error: "Service not found" };
if (service.status !== "active")
return { error: "Service is not available" };
if (service.type !== "programs")
return { error: "Service is not a program" };

const [row] = await db
.insert(serviceBookings)
.values({
userId: user.id,
serviceId: service.id,
status: "awaiting_payment",
})
.returning({ id: serviceBookings.id });

const result = await createStripeCheckoutSession({
userId: user.id,
email: user.email!,
stripeProductId: service.stripeProductId,
metadata: {
type: "program",
bookingId: row.id,
},
});
if ("error" in result) {
await db.delete(serviceBookings).where(eq(serviceBookings.id, row.id));
return { error: result.error };
}

await db
.update(serviceBookings)
.set({ stripeOrderId: result.session.id })
.where(eq(serviceBookings.id, row.id));

return { url: result.session.url! };
}

export async function checkoutCoachingSession({
coachingSessionId,
}: {
coachingSessionId: string;
}): Promise<CheckoutResult> {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return { error: "Not authenticated" };

const row = await db.query.coachingSessions.findFirst({
where: and(
eq(coachingSessions.id, coachingSessionId),
eq(coachingSessions.userId, user.id),
),
});
if (!row) return { error: "Coaching session not found" };
if (row.status !== "awaiting_payment")
return { error: "Coaching session is not awaiting payment" };

const service = await db.query.services.findFirst({
where: eq(services.id, row.serviceId),
});
Comment on lines +136 to +138
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as previous comment

if (!service) return { error: "Service not found" };

const result = await createStripeCheckoutSession({
userId: user.id,
email: user.email!,
stripeProductId: service.stripeProductId,
metadata: {
type: "private_lesson",
coachingSessionId: row.id,
},
});
if ("error" in result) {
await db
.delete(coachingSessions)
.where(eq(coachingSessions.id, row.id));
return { error: result.error };
}

await db
.update(coachingSessions)
.set({ stripeOrderId: result.session.id })
.where(eq(coachingSessions.id, row.id));

return { url: result.session.url! };
}

36 changes: 34 additions & 2 deletions app/api/webhooks/stripe/route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { NextRequest, NextResponse } from "next/server";
import { deleteCouponIfExhausted, stripe, syncStripeData } from "@/lib/stripe";
import { db } from "@/lib/db";
import { profiles, purchases } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
import {
coachingSessions,
profiles,
purchases,
serviceBookings,
} from "@/lib/db/schema";
import { and, eq } from "drizzle-orm";
import Stripe from "stripe";

const allowedEvents: Stripe.Event.Type[] = [
Expand Down Expand Up @@ -43,6 +48,33 @@ export async function POST(request: NextRequest) {

if (event.type === "checkout.session.completed") {
const session = event.data.object as Stripe.Checkout.Session;
const metadata = session.metadata ?? {};

if (metadata.type === "private_lesson" && metadata.coachingSessionId) {
await db
.update(coachingSessions)
.set({ status: "pending", stripeOrderId: session.id })
.where(
and(
eq(coachingSessions.id, metadata.coachingSessionId),
eq(coachingSessions.status, "awaiting_payment"),
),
);
return NextResponse.json({ received: true });
}

if (metadata.type === "program" && metadata.bookingId) {
await db
.update(serviceBookings)
.set({ status: "confirmed", stripeOrderId: session.id })
.where(
and(
eq(serviceBookings.id, metadata.bookingId),
eq(serviceBookings.status, "awaiting_payment"),
),
);
return NextResponse.json({ received: true });
}

for (const d of session.discounts ?? []) {
const couponId =
Expand Down
54 changes: 54 additions & 0 deletions app/coaching/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"use server";

import { eq } from "drizzle-orm";

import { db } from "@/lib/db";
import { coachingSessions, services } from "@/lib/db/schema";
import { createClient } from "@/utils/supabase/server";

export type Availability = { start: string; end: string };

export type SubmitAvailabilitiesResult =
| { coachingSessionId: string }
| { error: string };

export async function submitAvailabilities({
serviceId,
availabilities,
}: {
serviceId: string;
availabilities: Availability[];
}): Promise<SubmitAvailabilitiesResult> {
if (!availabilities?.length)
return { error: "At least one availability window is required" };

const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return { error: "Not authenticated" };

const service = await db.query.services.findFirst({
where: eq(services.id, serviceId),
});
if (!service) return { error: "Service not found" };
if (service.status !== "active")
return { error: "Service is not available" };
if (service.type !== "private_lessons")
return { error: "Service is not a private lesson" };
if (!service.coachId) return { error: "Service has no coach assigned" };

const [row] = await db
.insert(coachingSessions)
.values({
userId: user.id,
serviceId: service.id,
coachId: service.coachId,
durationMinutes: service.durationMinutes,
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This field shouldn't exist anymore. We will remove it in another issue.

selectedTimeSlots: availabilities,
status: "awaiting_payment",
})
.returning({ id: coachingSessions.id });

return { coachingSessionId: row.id };
}
7 changes: 7 additions & 0 deletions lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@ export const serviceTypeEnum = pgEnum("service_type", [
"programs",
]);
export const bookingStatusEnum = pgEnum("booking_status", [
"awaiting_payment",
"pending",
"confirmed",
"cancelled",
]);
export const webinarTierEnum = pgEnum("webinar_tier", ["free", "premium"]);
export const sessionStatusEnum = pgEnum("session_status", [
"awaiting_payment",
"pending",
"confirmed",
"cancelled",
Expand Down Expand Up @@ -69,6 +71,9 @@ export const services = pgTable("services", {
durationMinutes: integer("duration_minutes").notNull(),
stripeProductId: text("stripe_product_id").notNull(),
status: serviceStatusEnum("status").notNull().default("active"),
coachId: uuid("coach_id").references(() => profiles.id, {
onDelete: "set null",
}),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
});
Expand All @@ -84,6 +89,7 @@ export const serviceBookings = pgTable("service_bookings", {
status: bookingStatusEnum("status").notNull().default("pending"),
notes: text("notes"),
isActive: boolean("is_active").notNull().default(true),
stripeOrderId: text("stripe_order_id").unique(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
});
Expand Down Expand Up @@ -117,6 +123,7 @@ export const coachingSessions = pgTable("coaching_sessions", {
meetingUrl: text("meeting_url"),
notes: text("notes"),
selectedTimeSlots: jsonb("selected_time_slots").notNull(),
stripeOrderId: text("stripe_order_id").unique(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
});
Expand Down
Loading