import { fail } from "@sveltejs/kit"; import type { Actions, PageServerLoad } from "./$types"; import type { StackqReceipt } from "$lib/types/receipts"; import { validateImageUpload } from "$lib/validate-image-upload"; const COLLECTION = "Stackq_Receipts"; const TYPE_OPTIONS = ["Purchase", "Gas"] as const; export const load: PageServerLoad = async ({ locals }) => { const list = await locals.pb .collection(COLLECTION) .getFullList({ sort: "-created", expand: "User", }) .catch((err) => { console.error(COLLECTION, err); return [] as StackqReceipt[]; }); return { receipts: list }; }; export const actions: Actions = { create: async ({ request, locals }) => { const user = locals.user; if (!user?.id) return fail(401, { error: "You must be logged in to create a receipt." }); const form = await request.formData(); const Type = (form.get("Type") as string)?.trim() || "Purchase"; const imageFile = form.get("Image") as File | null; const hasImage = imageFile && imageFile.size > 0; if (hasImage) { const imgError = validateImageUpload(imageFile); if (imgError) return fail(400, { error: imgError, Type }); } const body: Record = { Status: "New", Type: TYPE_OPTIONS.includes(Type as (typeof TYPE_OPTIONS)[number]) ? Type : "Purchase", User: user.id, }; if (hasImage) body.Image = imageFile; try { await locals.pb.collection(COLLECTION).create(body); } catch (err: unknown) { const message = err && typeof err === "object" && "message" in err ? String((err as { message: string }).message) : "Failed to create receipt."; return fail(500, { error: message, Type }); } return { success: true }; }, };