Files
property-management-network/app/api/rent/send-payment-link/route.ts
T
Leon SerfatyandClaude Opus 4.8 c9968531e4 Consolidate audit-fixes branch: webhooks, integrations, and deploy hardening
Batch commit of the pending working tree on security/audit-fixes-2026-07.
Major areas:
- Outbound webhooks / Zapier: schema + signed delivery with retries, public
  v1 API (REST-hook subscribe/unsubscribe), settings UI, cron drain.
- Deploy hardening: email via SMTP2GO (Resend fully removed), verified DB TLS
  (DATABASE_SSL=require + DATABASE_CA), storage fails loud in production when
  Spaces is unconfigured instead of silently using ephemeral disk.
- Integrations & features (concurrent work): accounting (QuickBooks/Xero),
  e-signature (DocuSign/Dropbox Sign), PayPal, geocoding/maps, onboarding,
  expanded legal pages.
- DB migrations 0006–0009.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 13:42:34 -04:00

83 lines
3.1 KiB
TypeScript

import { NextResponse } from "next/server"
import { and, eq, sql } from "drizzle-orm"
import { db } from "@/lib/db"
import { rent_payments, profiles } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { sendEmail, paymentLinkHtml } from "@/lib/email/send"
import { paymentLinkSchema } from "@/lib/validations"
import { getAccountContext } from "@/lib/account"
export async function POST(request: Request) {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const ctx = await getAccountContext(user.id)
const ownerId = ctx.ownerId
if (!ctx.canWrite) return NextResponse.json({ error: "Forbidden" }, { status: 403 })
const body = await request.json()
const parsed = paymentLinkSchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.issues[0]?.message ?? "Invalid payment ID" }, { status: 400 })
}
const { payment_id } = parsed.data
// Fetch payment with tenant details
const payment = await db.query.rent_payments.findFirst({
where: and(eq(rent_payments.id, payment_id), eq(rent_payments.user_id, ownerId)),
with: {
tenant: { columns: { first_name: true, last_name: true, email: true } },
property: { columns: { name: true } },
unit: { columns: { unit_number: true } },
},
})
if (!payment) return NextResponse.json({ error: "Payment not found" }, { status: 404 })
if (!payment.tenant?.email) return NextResponse.json({ error: "Tenant has no email address" }, { status: 400 })
// Fetch landlord (portfolio owner) profile for payment instructions
const profile = await db.query.profiles.findFirst({
where: eq(profiles.id, ownerId),
columns: { full_name: true },
})
const tenantName = `${payment.tenant.first_name} ${payment.tenant.last_name}`
const amount = Number(payment.amount).toLocaleString("en-US", { style: "currency", currency: "USD" })
const dueDate = new Date(payment.due_date).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })
const propertyLabel = `${payment.property?.name ?? "your property"}${
payment.unit ? ` — Unit ${payment.unit.unit_number}` : ""
}`
const html = paymentLinkHtml({
tenantName,
amount,
dueDate,
propertyLabel,
senderName: profile?.full_name ?? "Your Landlord",
})
try {
await sendEmail({
to: payment.tenant.email,
subject: `Rent Payment Due — ${amount} on ${dueDate}`,
html,
})
} catch {
return NextResponse.json({ error: "Failed to send email" }, { status: 500 })
}
// Update rent_payment to mark reminder sent
try {
await db.execute(
sql`update rent_payments set reminder_sent_at = now() where id = ${payment_id} and user_id = ${ownerId}`
)
} catch {
// Email sent successfully, but tracking update failed — still return ok
return NextResponse.json({ ok: true, message: `Payment reminder sent to ${payment.tenant.email} (tracking update failed)` })
}
return NextResponse.json({ ok: true, message: `Payment reminder sent to ${payment.tenant.email}` })
}