56 lines
1.9 KiB
TypeScript
56 lines
1.9 KiB
TypeScript
// routes/api/create/lease.ts
|
|
import { define } from "../../../utils.ts";
|
|
import { createLease } from "../../../services/leaseService.ts";
|
|
import { 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 = form.get("tenant_id")?.toString();
|
|
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 security_deposit = Number(form.get("security_deposit")) || 0;
|
|
const property = await getProperty(propertyId);
|
|
|
|
if (property.length == 1 && start_date && end_date) {
|
|
const owner_id = property[0].owner_id as string;
|
|
await createLease(
|
|
title,
|
|
propertyId,
|
|
owner_id,
|
|
start_date,
|
|
end_date,
|
|
rent,
|
|
security_deposit,
|
|
tenant_id,
|
|
);
|
|
}
|
|
|
|
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 });
|
|
}
|
|
},
|
|
});
|