68 lines
2.0 KiB
TypeScript
68 lines
2.0 KiB
TypeScript
import { NextResponse } from "next/server"
|
|||
|
|
import { and, eq, lte } from "drizzle-orm"
|
||
|
|
import { db } from "@/lib/db"
|
||
|
|
import { leases } from "@/lib/db/schema"
|
||
|
|
import { sendEmail, leaseExpiryHtml } from "@/lib/email/send"
|
||
|
|
import { formatDate, daysUntil } from "@/lib/utils"
|
||
|
|
import { isAuthorizedCron } from "@/lib/cron-auth"
|
||
|
|
|
||
|
|
export async function GET(request: Request) {
|
||
|
|
if (!isAuthorizedCron(request)) {
|
||
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||
|
|
}
|
||
|
|
|
||
|
|
const checkpoints = [
|
||
|
|
{ days: 60, field: "reminder_60_sent" as const },
|
||
|
|
{ days: 30, field: "reminder_30_sent" as const },
|
||
|
|
{ days: 7, field: "reminder_7_sent" as const },
|
||
|
|
]
|
||
|
|
|
||
|
|
let sent = 0
|
||
|
|
|
||
|
|
for (const { days, field } of checkpoints) {
|
||
|
|
const target = new Date()
|
||
|
|
target.setDate(target.getDate() + days)
|
||
|
|
const targetStr = target.toISOString().slice(0, 10)
|
||
|
|
|
||
|
|
const expiringLeases = await db.query.leases.findMany({
|
||
|
|
where: and(
|
||
|
|
eq(leases.status, "active"),
|
||
|
|
eq(leases[field], false),
|
||
|
|
lte(leases.lease_end, targetStr)
|
||
|
|
),
|
||
|
|
with: {
|
||
|
|
tenant: { columns: { first_name: true, last_name: true, email: true } },
|
||
|
|
property: { columns: { name: true } },
|
||
|
|
unit: { columns: { unit_number: true } },
|
||
|
|
},
|
||
|
|
})
|
||
|
|
|
||
|
|
for (const lease of expiringLeases) {
|
||
|
|
if (!lease.tenant?.email) continue
|
||
|
|
|
||
|
|
const daysLeft = daysUntil(lease.lease_end)
|
||
|
|
|
||
|
|
await sendEmail({
|
||
|
|
to: lease.tenant.email,
|
||
|
|
subject: `Your lease expires in ${daysLeft} days — ${lease.property?.name}`,
|
||
|
|
html: leaseExpiryHtml({
|
||
|
|
tenantName: `${lease.tenant.first_name} ${lease.tenant.last_name}`,
|
||
|
|
propertyName: lease.property?.name ?? "",
|
||
|
|
unitNumber: lease.unit?.unit_number ?? "—",
|
||
|
|
leaseEnd: formatDate(lease.lease_end),
|
||
|
|
daysLeft,
|
||
|
|
}),
|
||
|
|
})
|
||
|
|
|
||
|
|
await db
|
||
|
|
.update(leases)
|
||
|
|
.set({ [field]: true })
|
||
|
|
.where(eq(leases.id, lease.id))
|
||
|
|
|
||
|
|
sent++
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return NextResponse.json({ reminders_sent: sent })
|
||
|
|
}
|