// routes/api/update/obligation.ts import { updateObligation } from "../../../services/financhalServices.ts"; import { define } from "../../../utils.ts"; import { SessionCookie } from "../../auth/callback.ts"; import { invalidateBalanceCache } from "../../../services/dailyBalanceCache.ts"; export const handler = define.handlers({ async POST(ctx) { const contentType = ctx.req.headers.get("content-type") || ""; const isJsonRequest = contentType.includes("application/json"); // Get user_id from session for cache invalidation const stateData: SessionCookie = ctx.state.data; let obligationId: string; const updates: Partial<{ encrypted_data: string; description: string; amount: number; frequency: string; due_date: number; updated_on: number; }> = {}; let sender: string | null = null; if (isJsonRequest) { // Handle JSON request const body = await ctx.req.json(); obligationId = body.obligation_id; // Extract update fields if (body.encrypted_data !== undefined) { updates.encrypted_data = body.encrypted_data; } if (body.description !== undefined) { updates.description = body.description; } if (body.amount !== undefined) updates.amount = body.amount; if (body.frequency !== undefined) updates.frequency = body.frequency; if (body.due_date !== undefined) updates.due_date = body.due_date; // Set updated timestamp updates.updated_on = Date.now(); } else { // Handle form data request const formData = await ctx.req.formData(); obligationId = formData.get("obligation_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("description")) { updates.description = formData.get("description")?.toString(); } 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("due_date")) { updates.due_date = parseInt( formData.get("due_date")?.toString() || "0", ); } // Set updated timestamp updates.updated_on = Date.now(); } if (!obligationId) { return new Response(JSON.stringify({ error: "Missing obligation_id" }), { status: 400, headers: { "Content-Type": "application/json" }, }); } try { await updateObligation(obligationId, updates); // Invalidate balance cache for this user if (stateData.user_id) { try { await invalidateBalanceCache(stateData.user_id); } catch (cacheError) { console.error("Failed to invalidate cache:", cacheError); // Non-fatal error - continue with success response } } 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 obligation:", error); return new Response( JSON.stringify({ error: "Failed to update obligation" }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } }, });