// routes/api/update/obligation.ts import { updateIncome } from "../../../services/financhalServices.ts"; import { define } from "../../../utils.ts"; export const handler = define.handlers({ async POST(ctx) { const contentType = ctx.req.headers.get("content-type") || ""; const isJsonRequest = contentType.includes("application/json"); let incomeId: string; const updates: Partial<{ encrypted_data: string; source: string | null; amount: number | null; frequency: string; received_date: number; updated_on: number; }> = {}; let sender: string | null = null; if (isJsonRequest) { // Handle JSON request const body = await ctx.req.json(); incomeId = body.income_id; // Extract update fields if (body.encrypted_data !== undefined) { updates.encrypted_data = body.encrypted_data; } if (body.source !== undefined) updates.source = body.source; if (body.amount !== undefined) updates.amount = body.amount; if (body.frequency !== undefined) updates.frequency = body.frequency; if (body.received_date !== undefined) { updates.received_date = body.received_date; } // Set updated timestamp updates.updated_on = Date.now(); } else { // Handle form data request const formData = await ctx.req.formData(); incomeId = formData.get("income_id")?.toString() || ""; sender = formData.get("sender")?.toString() || null; // Extract update fields from form data if (formData.has("encrypted_data")) { updates.encrypted_data = formData.get("encrypted_data")?.toString(); } if (formData.has("source")) { updates.source = formData.get("source")?.toString() ?? null; } if (formData.has("amount")) { updates.amount = parseFloat(formData.get("amount")?.toString() ?? "0"); } if (formData.has("frequency")) { updates.frequency = formData.get("frequency")?.toString(); } if (formData.has("received_date")) { updates.received_date = parseInt( formData.get("received_date")?.toString() || "0", ); } // Set updated timestamp updates.updated_on = Date.now(); } if (!incomeId) { return new Response(JSON.stringify({ error: "Missing income_id" }), { status: 400, headers: { "Content-Type": "application/json" }, }); } try { await updateIncome(incomeId, updates); if (isJsonRequest) { // Return JSON response for JSON requests return new Response(JSON.stringify({ success: true }), { status: 200, headers: { "Content-Type": "application/json" }, }); } else { // Redirect back to the sender URL (must be absolute) const senderPath = sender?.toString() || "/"; let redirectUrl = senderPath; try { if (senderPath.startsWith("/")) { const url = new URL(ctx.req.url); redirectUrl = url.origin + senderPath; } } catch (_) { // fallback: just use senderPath } return Response.redirect(redirectUrl, 303); } } catch (error) { console.error("Error updating income:", error); return new Response( JSON.stringify({ error: "Failed to update income" }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } }, });