integratedhub/routes/api/create/maintenance_request.ts
2026-02-14 02:20:19 +00:00

110 lines
3.5 KiB
TypeScript

// routes/api/create/maintenance_request.ts
import { define } from "../../../utils.ts";
import { createMaintenanceRequest } from "../../../services/maintenanceRequestService.ts";
import { SessionCookie } from "../../auth/callback.ts";
import { verifyTenantForProperty } from "../../../services/leaseService.ts";
export const handler = define.handlers({
async POST(ctx) {
try {
const stateData: SessionCookie = ctx.state.data;
const { user_id } = stateData;
const contentType = ctx.req.headers.get("content-type") || "";
let data: Record<string, string> = {};
let sender: string | null = null;
let isJsonRequest = false;
// Handle both JSON and form data
if (contentType.includes("application/json")) {
isJsonRequest = true;
const jsonData = await ctx.req.json();
data = jsonData;
} else {
const formData = await ctx.req.formData();
sender = formData.get("sender")?.toString() || null;
data = {
property_id: formData.get("property_id")?.toString() || "",
request_type: formData.get("request_type")?.toString() || "",
description: formData.get("description")?.toString() || "",
priority: formData.get("priority")?.toString() || "medium",
};
}
const property_id = data.property_id;
const request_type = data.request_type;
const description = data.description;
const priority = data.priority || "medium";
if (!property_id || !request_type || !description) {
return new Response(
JSON.stringify({
error:
"Property ID, request type, and encrypted description are required",
}),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
// Verify that the tenant has an active lease for this property
const hasLease = await verifyTenantForProperty(user_id, property_id);
if (!hasLease) {
return new Response(
JSON.stringify({
error:
"You do not have an active lease for this property. You can only create maintenance requests for properties you lease.",
}),
{
status: 403,
headers: { "Content-Type": "application/json" },
},
);
}
const result = await createMaintenanceRequest(
property_id,
user_id, // tenant_id
request_type,
description,
priority,
);
// Return appropriate response based on request type
if (isJsonRequest) {
return new Response(
JSON.stringify({
success: true,
maintenance_request: result[0],
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
} else {
// Redirect back to the sender URL
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,
headers: { "Content-Type": "application/json" },
});
}
},
});