Files
property-management-network/app/api/v1/maintenance/route.ts
T
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

99 lines
3.5 KiB
TypeScript

import { NextResponse } from "next/server"
import { and, desc, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { maintenance_requests } from "@/lib/db/schema"
import { maintenanceSchema } 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) — maintenance requests. Bearer API-key auth.
// Scoped by the 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 = ["open", "in_progress", "resolved", "closed"]
const VALID_PRIORITIES = ["low", "medium", "high", "emergency"]
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 priority = searchParams.get("priority")
const propertyId = searchParams.get("property_id")
if (status && !VALID_STATUSES.includes(status)) {
return NextResponse.json({ error: { code: 400, message: "Invalid status" } }, { status: 400 })
}
if (priority && !VALID_PRIORITIES.includes(priority)) {
return NextResponse.json({ error: { code: 400, message: "Invalid priority" } }, { status: 400 })
}
const data = await db.query.maintenance_requests.findMany({
where: and(
eq(maintenance_requests.user_id, ctx.ownerId),
status ? eq(maintenance_requests.status, status as typeof maintenance_requests.$inferSelect.status) : undefined,
priority ? eq(maintenance_requests.priority, priority as typeof maintenance_requests.$inferSelect.priority) : undefined,
propertyId ? eq(maintenance_requests.property_id, propertyId) : undefined
),
with: {
property: { columns: { name: true } },
unit: { columns: { unit_number: true } },
tenant: { columns: { first_name: true, last_name: true } },
},
orderBy: desc(maintenance_requests.created_at),
})
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 = maintenanceSchema.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(maintenance_requests)
.values({ ...parsed.data, user_id: ctx.ownerId, status: "open" })
.returning()
await emitWebhookEvent({
ownerId: ctx.ownerId,
event: "maintenance.created",
data: { maintenance: data },
})
return NextResponse.json({ data }, { status: 201 })
}