integratedhub/routes/api/lease/pending-approvals.ts
2026-02-14 02:20:19 +00:00

124 lines
3.6 KiB
TypeScript

// routes/api/lease/pending-approvals.ts
import { define } from "../../../utils.ts";
import { page as _page } from "fresh";
import { SessionCookie } from "../../auth/callback.ts";
import { getPendingApprovals } from "../../../services/leaseService.ts";
import { properties, users } from "../../../db/schema.ts";
import { and as _and, eq as _eq, inArray } from "drizzle-orm";
import { db } from "../../../db/db.ts";
export const handler = define.handlers({
async GET(ctx) {
try {
const stateData: SessionCookie = ctx.state.data;
const { user_id } = stateData;
if (!user_id) {
return new Response(
JSON.stringify({
success: false,
error: "Unauthorized: No session found",
}),
{
status: 401,
headers: { "Content-Type": "application/json" },
},
);
}
const pendingLeases = await getPendingApprovals(user_id);
if (!pendingLeases || pendingLeases.length === 0) {
return new Response(
JSON.stringify({
success: true,
approvals: [],
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
}
const propertyIds = pendingLeases
.map((lease) => lease.property_id)
.filter((id): id is string => Boolean(id));
const tenantIds = pendingLeases
.map((lease) => lease.tenant_id)
.filter((id): id is string => Boolean(id));
// Fetch ALL properties using inArray instead of just the first one
const propertiesData = propertyIds.length > 0
? await db
.select({
id: properties.id,
title: properties.title,
address_1: properties.address_1,
address_2: properties.address_2,
city: properties.city,
state: properties.state,
zip: properties.zip,
image_url: properties.image_url,
monthly_rent: properties.monthly_rent,
bedrooms: properties.bedrooms,
bathrooms: properties.bathrooms,
})
.from(properties)
.where(inArray(properties.id, propertyIds))
: [];
// Fetch ALL tenants using inArray instead of just the first one
const tenantsData = tenantIds.length > 0
? await db
.select({
id: users.id,
name: users.name,
email: users.email,
phone: users.phone,
})
.from(users)
.where(inArray(users.id, tenantIds))
: [];
const propertyMap = new Map(
propertiesData.map((p) => [p.id, p]),
);
const tenantMap = new Map(
tenantsData.map((t) => [t.id, t]),
);
const enrichedApprovals = pendingLeases.map((lease) => ({
...lease,
property: lease.property_id ? propertyMap.get(lease.property_id) : null,
tenant: lease.tenant_id ? tenantMap.get(lease.tenant_id) : null,
}));
return new Response(
JSON.stringify({
success: true,
approvals: enrichedApprovals,
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
} catch (error) {
console.error("Error fetching pending approvals:", error);
return new Response(
JSON.stringify({
success: false,
error: "Internal server error",
details: String(error),
}),
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
},
});