integratedhub/routes/api/update/financial-balance.ts
2026-01-20 09:02:26 -06:00

84 lines
2.4 KiB
TypeScript

import { upsertFinancialBalance } from "../../../services/userService.ts";
import { define } from "../../../utils.ts";
import { MakeNewDate } from "../../../helpers.ts";
import { SessionCookie } from "../../auth/callback.ts";
export const handler = define.handlers({
async POST(ctx) {
const contentType = ctx.req.headers.get("content-type") || "";
const isJsonRequest = contentType.includes("application/json");
console.log("Content-Type:", contentType);
console.log("Is JSON request:", isJsonRequest);
if (!isJsonRequest) {
return new Response(
JSON.stringify({ error: "Content-Type must be application/json" }),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
try {
const body = await ctx.req.json();
const { balance, date, year: _year, month: _month } = body;
// Validate required fields
if (balance === undefined || date === undefined) {
return new Response(
JSON.stringify({ error: "Balance and date are required" }),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
// Get user data from session
const stateData: SessionCookie = ctx.state.data;
if (!stateData?.user_id) {
return new Response(
JSON.stringify({ error: "User not authenticated" }),
{
status: 401,
headers: { "Content-Type": "application/json" },
},
);
}
// Convert date string to timestamp
const balanceDate = MakeNewDate(date).getTime();
// Update financial balance
const updatedBalance = await upsertFinancialBalance(
stateData.user_id,
balance,
balanceDate,
);
return new Response(
JSON.stringify({
success: true,
data: updatedBalance,
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
} catch (error) {
console.error("Error updating financial balance:", error);
return new Response(
JSON.stringify({
error: "Internal server error",
message: error instanceof Error ? error.message : "Unknown error",
}),
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
},
});