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

134 lines
3.7 KiB
TypeScript

// routes/api/update/maintenance_request.ts
import { define } from "../../../utils.ts";
import {
updateRequestPriority,
updateRequestStatus,
} from "../../../services/maintenanceRequestService.ts";
import { SessionCookie } from "../../auth/callback.ts";
export const handler = define.handlers({
async POST(ctx) {
try {
const stateData: SessionCookie = ctx.state.data;
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 = {
id: formData.get("id")?.toString() || "",
status: formData.get("status")?.toString() || "",
priority: formData.get("priority")?.toString() || "",
};
}
const id = data.id;
const status = data.status;
const priority = data.priority;
if (!id) {
return new Response(
JSON.stringify({
error: "Maintenance request ID is required",
}),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
let result;
// Update status if provided
if (status) {
if (
!["open", "in_progress", "completed", "cancelled"].includes(status)
) {
return new Response(
JSON.stringify({
error:
"Status must be 'open', 'in_progress', 'completed', or 'cancelled'",
}),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
result = await updateRequestStatus(id, status as any);
}
// Update priority if provided
if (priority) {
if (!["low", "medium", "high", "urgent"].includes(priority)) {
return new Response(
JSON.stringify({
error: "Priority must be 'low', 'medium', 'high', or 'urgent'",
}),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
result = await updateRequestPriority(id, priority as any);
}
if (!result) {
return new Response(
JSON.stringify({
error: "No valid update fields provided",
}),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
// 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" },
});
}
},
});