Files
cat-sitting-planner/app/actions/booking.ts

72 lines
2.2 KiB
TypeScript

"use server"
import prisma from "@/lib/prisma"
import { revalidatePath } from "next/cache"
import { headers } from "next/headers"
import { sendNotification } from "@/lib/notifications"
export async function createBooking(planId: string, date: Date, name: string, type: "SITTER" | "OWNER_HOME" = "SITTER") {
// Simple check to ensure no double booking on server side
const existing = await prisma.booking.findFirst({
where: {
planId,
date: date,
}
})
if (existing) {
throw new Error("Day is already booked")
}
const plan = await prisma.plan.findUnique({
where: { id: planId }
})
await prisma.booking.create({
data: {
planId,
date,
sitterName: name,
type
}
})
if (plan?.webhookUrl && plan.notifyAll) {
const host = (await headers()).get("host")
const protocol = host?.includes("localhost") ? "http" : "https"
const planUrl = `${protocol}://${host}/dashboard/${planId}`
const dateStr = date.toLocaleDateString()
const message = type === "OWNER_HOME"
? `🏠 OWNER HOME: Marked for ${dateStr}.\nPlan: ${planUrl}`
: `✅ NEW BOOKING: ${name} is sitting on ${dateStr}.\nPlan: ${planUrl}`
await sendNotification(plan.webhookUrl, message)
}
revalidatePath(`/dashboard/${planId}`)
}
export async function deleteBooking(bookingId: number, planId: string) {
const booking = await prisma.booking.findUnique({
where: { id: bookingId },
include: { plan: true }
})
if (!booking) return
await prisma.booking.delete({
where: { id: bookingId }
})
if (booking.plan.webhookUrl) {
const host = (await headers()).get("host")
const protocol = host?.includes("localhost") ? "http" : "https"
const planUrl = `${protocol}://${host}/dashboard/${planId}`
const dateStr = booking.date.toLocaleDateString()
await sendNotification(booking.plan.webhookUrl, `🚨 CANCELLATION: ${booking.sitterName} removed their booking for ${dateStr}.\nPlan: ${planUrl}`)
}
revalidatePath(`/dashboard/${planId}`)
}