2026-01-20 09:02:26 -06:00

53 lines
1.7 KiB
TypeScript

// routes/api/create/lease.ts
import { define } from "../../../utils.ts";
import { createLease, getProperty } from "../../../services/propertyService.ts";
import { SessionCookie } from "../../auth/callback.ts";
export const handler = define.handlers({
async POST(ctx) {
try {
const stateData: SessionCookie = ctx.state.data;
const form = await ctx.req.formData();
const sender = form.get("sender");
const tenant_id = stateData.user_id;
const propertyId = form.get("property_id")?.toString() || "";
const title = form.get("title")?.toString() || "";
const rent = Number(form.get("rent"));
const start_date = form.get("start_date")
? Date.parse(form.get("start_date")?.toString() + "T00:00:00")
: null;
const end_date = form.get("end_date")
? Date.parse(form.get("end_date")?.toString() + "T00:00:00")
: null;
const property = await getProperty(propertyId);
if (property.length == 1 && start_date && end_date) {
const owner_id = property[0].owner_id as string;
await createLease(
propertyId,
tenant_id,
owner_id,
title,
rent,
start_date,
end_date,
);
}
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 (e) {
return new Response(JSON.stringify({ error: e }), { status: 500 });
}
},
});