This commit is contained in:
74
src/pages/api/invoices/create.ts
Normal file
74
src/pages/api/invoices/create.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import type { APIRoute } from "astro";
|
||||
import { db } from "../../../db";
|
||||
import { invoices, members } from "../../../db/schema";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
|
||||
export const POST: APIRoute = async ({ request, redirect, locals, cookies }) => {
|
||||
const user = locals.user;
|
||||
if (!user) {
|
||||
return redirect("/login");
|
||||
}
|
||||
|
||||
const formData = await request.formData();
|
||||
const type = formData.get("type") as string;
|
||||
const clientId = formData.get("clientId") as string;
|
||||
const number = formData.get("number") as string;
|
||||
const issueDateStr = formData.get("issueDate") as string;
|
||||
const dueDateStr = formData.get("dueDate") as string;
|
||||
const currency = formData.get("currency") as string;
|
||||
|
||||
if (!type || !clientId || !number || !issueDateStr || !dueDateStr) {
|
||||
return new Response("Missing required fields", { status: 400 });
|
||||
}
|
||||
|
||||
// Get current team context
|
||||
const currentTeamId = cookies.get("currentTeamId")?.value;
|
||||
|
||||
// Verify membership
|
||||
const userMemberships = await db
|
||||
.select()
|
||||
.from(members)
|
||||
.where(eq(members.userId, user.id))
|
||||
.all();
|
||||
|
||||
if (userMemberships.length === 0) {
|
||||
return redirect("/dashboard");
|
||||
}
|
||||
|
||||
const membership = currentTeamId
|
||||
? userMemberships.find((m) => m.organizationId === currentTeamId)
|
||||
: userMemberships[0];
|
||||
|
||||
if (!membership) {
|
||||
return new Response("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
const organizationId = membership.organizationId;
|
||||
|
||||
try {
|
||||
const issueDate = new Date(issueDateStr);
|
||||
const dueDate = new Date(dueDateStr);
|
||||
|
||||
const [newInvoice] = await db
|
||||
.insert(invoices)
|
||||
.values({
|
||||
organizationId,
|
||||
clientId,
|
||||
number,
|
||||
type: type as "invoice" | "quote",
|
||||
status: "draft",
|
||||
issueDate,
|
||||
dueDate,
|
||||
currency: currency || "USD",
|
||||
subtotal: 0,
|
||||
taxAmount: 0,
|
||||
total: 0,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return redirect(`/dashboard/invoices/${newInvoice.id}`);
|
||||
} catch (error) {
|
||||
console.error("Error creating invoice:", error);
|
||||
return new Response("Internal Server Error", { status: 500 });
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user