All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m3s
59 lines
1.5 KiB
TypeScript
59 lines
1.5 KiB
TypeScript
import type { APIRoute } from "astro";
|
|
import { db } from "../../../db";
|
|
import { invoices, invoiceItems, members } from "../../../db/schema";
|
|
import { eq, and } from "drizzle-orm";
|
|
|
|
export const POST: APIRoute = async ({ request, redirect, locals }) => {
|
|
const user = locals.user;
|
|
if (!user) {
|
|
return redirect("/login");
|
|
}
|
|
|
|
const formData = await request.formData();
|
|
const invoiceId = formData.get("id") as string;
|
|
|
|
if (!invoiceId) {
|
|
return new Response("Invoice ID required", { status: 400 });
|
|
}
|
|
|
|
// Fetch invoice to verify existence and check ownership
|
|
const invoice = await db
|
|
.select()
|
|
.from(invoices)
|
|
.where(eq(invoices.id, invoiceId))
|
|
.get();
|
|
|
|
if (!invoice) {
|
|
return new Response("Invoice not found", { status: 404 });
|
|
}
|
|
|
|
// Verify membership
|
|
const membership = await db
|
|
.select()
|
|
.from(members)
|
|
.where(
|
|
and(
|
|
eq(members.userId, user.id),
|
|
eq(members.organizationId, invoice.organizationId)
|
|
)
|
|
)
|
|
.get();
|
|
|
|
if (!membership) {
|
|
return new Response("Unauthorized", { status: 401 });
|
|
}
|
|
|
|
try {
|
|
// Delete invoice items first (manual cascade)
|
|
await db.delete(invoiceItems).where(eq(invoiceItems.invoiceId, invoiceId));
|
|
|
|
// Delete the invoice
|
|
await db.delete(invoices).where(eq(invoices.id, invoiceId));
|
|
|
|
return redirect("/dashboard/invoices");
|
|
} catch (error) {
|
|
console.error("Error deleting invoice:", error);
|
|
return new Response("Internal Server Error", { status: 500 });
|
|
}
|
|
};
|