Files
Leon SerfatyandClaude Opus 5 1d02598786 chore: sync in-progress work across marketing, admin, API and tests
Snapshot of uncommitted work that had accumulated in the tree alongside
the Turnstile changes:

- marketing pages, SEO helpers (lib/seo.ts, lib/marketing/) and
  structured data
- admin billing actions and a per-user portfolio view, plus an admin
  error boundary
- rate limiting (lib/rate-limit.ts) applied across the /api/v1 surface
- CSP and proxy adjustments, accounting/webhook lib updates
- Playwright config and an e2e/unit test suite
- next bumped to ^16.3.4 with the lockfile regenerated
- generated AGENTS.md / CLAUDE.md

Authored by other sessions working in this tree; committed here so the
Turnstile work could be pushed without leaving the tree dirty.
Typecheck passes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-05 16:27:16 -04:00

100 lines
3.5 KiB
TypeScript

import { NextResponse } from "next/server"
import { and, desc, eq, gte, lte } from "drizzle-orm"
import { db } from "@/lib/db"
import { rent_payments } from "@/lib/db/schema"
import { rentPaymentSchema } from "@/lib/validations"
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
import { resolveApiRequest } from "@/lib/api-auth"
import { enforceRateLimit } from "@/lib/rate-limit"
import { emitWebhookEvent } from "@/lib/webhooks/emit"
// Public REST API (v1) — rent payments. Bearer API-key auth. Maps to the
// rent_payments table / internal /api/rent logic. Scoped by resolved owner id.
const unauthorized = () =>
NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
const forbidden = () =>
NextResponse.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 })
const VALID_STATUSES = ["pending", "paid", "overdue", "partial", "waived"]
export async function GET(request: Request) {
const ctx = await resolveApiRequest(request)
if (!ctx) return unauthorized()
// Public API budget: 120 requests/minute per key owner.
const limited = enforceRateLimit(`v1:${ctx.userId}`, 120, 60)
if (limited) return limited
const { searchParams } = new URL(request.url)
const status = searchParams.get("status")
const tenantId = searchParams.get("tenant_id")
// Date-range filter on the payment's due_date ("YYYY-MM-DD").
const from = searchParams.get("from")
const to = searchParams.get("to")
if (status && !VALID_STATUSES.includes(status)) {
return NextResponse.json(
{ error: { code: 400, message: "Invalid status" } },
{ status: 400 }
)
}
const data = await db.query.rent_payments.findMany({
where: and(
eq(rent_payments.user_id, ctx.ownerId),
status ? eq(rent_payments.status, status as typeof rent_payments.$inferSelect.status) : undefined,
tenantId ? eq(rent_payments.tenant_id, tenantId) : undefined,
from ? gte(rent_payments.due_date, from) : undefined,
to ? lte(rent_payments.due_date, to) : undefined
),
with: {
tenant: { columns: { first_name: true, last_name: true, email: true } },
property: { columns: { name: true } },
unit: { columns: { unit_number: true } },
},
orderBy: desc(rent_payments.due_date),
})
return NextResponse.json({ data, count: data.length })
}
export async function POST(request: Request) {
const ctx = await resolveApiRequest(request)
if (!ctx) return unauthorized()
// Public API budget: 120 requests/minute per key owner.
const limited = enforceRateLimit(`v1:${ctx.userId}`, 120, 60)
if (limited) return limited
if (!ctx.canWrite) return forbidden()
const body = await request.json().catch(() => null)
const parsed = rentPaymentSchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json(
{ error: { code: 400, message: parsed.error.flatten() } },
{ status: 400 }
)
}
if (
!(await ownsProperty(ctx.ownerId, parsed.data.property_id)) ||
!(await ownsUnit(ctx.ownerId, parsed.data.unit_id)) ||
!(await ownsTenant(ctx.ownerId, parsed.data.tenant_id))
) {
return forbidden()
}
const [data] = await db
.insert(rent_payments)
.values({ ...parsed.data, user_id: ctx.ownerId })
.returning()
await emitWebhookEvent({ ownerId: ctx.ownerId, event: "payment.recorded", data: { payment: data } })
if (data.status === "paid") {
await emitWebhookEvent({ ownerId: ctx.ownerId, event: "payment.paid", data: { payment: data } })
}
return NextResponse.json({ data }, { status: 201 })
}