All checks were successful
Docker Deploy / build-and-push (push) Successful in 4m6s
85 lines
2.2 KiB
TypeScript
85 lines
2.2 KiB
TypeScript
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]
|
|
: 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 });
|
|
}
|
|
};
|
|
|
|
export const GET: APIRoute = async ({ redirect }) => {
|
|
return redirect("/dashboard/invoices/new");
|
|
};
|