Initial import: property management SaaS + security hardening + admin dashboard

Property Management Network — Next.js 16 (App Router), Better Auth,
Drizzle ORM over PostgreSQL, Stripe, OpenAI, Resend.

Includes:
- Security hardening: access-control/IDOR fixes, TLS-by-default DB layer,
  constant-time cron auth, strict security headers, atomic AI quota gating,
  HTML/email output encoding, demo-backdoor disabled in production.
- Superadmin dashboard at /admin (overview/MRR, server-paginated users with
  ban/impersonate/plan/delete, billing, platform activity + admin audit log,
  AI usage, system health) via the Better Auth admin plugin.
- Seed/migration utility scripts under scripts/.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Leon Serfaty
2026-06-23 20:36:07 -04:00
co-authored by Claude Opus 4.8
commit 857b9a7811
291 changed files with 38996 additions and 0 deletions
@@ -0,0 +1,116 @@
"use client"
import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import Link from "next/link"
import { FileText, Download, Trash2, Loader2 } from "lucide-react"
import { FileUpload } from "@/components/shared/file-upload"
import { formatDate } from "@/lib/utils"
function formatBytes(bytes: number) {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
export default function DocumentsPage() {
const params = useParams()
const propertyId = params.propertyId as string
const router = useRouter()
const [docs, setDocs] = useState<any[]>([])
const [loading, setLoading] = useState(true)
const [deleting, setDeleting] = useState<string | null>(null)
const [propertyName, setPropertyName] = useState("")
useEffect(() => {
fetch(`/api/documents?property_id=${propertyId}`)
.then((r) => r.json())
.then((data) => {
setDocs(data.documents ?? [])
setPropertyName(data.propertyName ?? "")
setLoading(false)
})
}, [propertyId])
async function deleteDoc(id: string) {
setDeleting(id)
await fetch(`/api/documents/${id}`, { method: "DELETE" })
setDocs((prev) => prev.filter((d) => d.id !== id))
setDeleting(null)
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<div className="flex items-center gap-2 text-sm text-white/40 mb-1">
<Link href="/properties" className="hover:text-white transition">Properties</Link>
<span>/</span>
<Link href={`/properties/${propertyId}`} className="hover:text-white transition">{propertyName || propertyId}</Link>
<span>/</span>
<span className="text-white/70">Documents</span>
</div>
<h2 className="text-lg font-semibold text-white">Documents</h2>
<p className="text-sm text-white/40">{docs.length} file{docs.length !== 1 ? "s" : ""}</p>
</div>
</div>
<FileUpload
propertyId={propertyId}
onUploaded={(doc) => setDocs((prev) => [doc, ...prev])}
/>
{loading ? (
<div className="flex items-center justify-center py-16">
<Loader2 className="h-6 w-6 animate-spin text-white/30" />
</div>
) : docs.length === 0 ? (
<div className="flex flex-col items-center justify-center rounded-xl border border-white/[0.06] bg-[#16161f] py-16 text-center">
<FileText className="h-10 w-10 text-white/10 mb-3" />
<p className="text-sm text-white/40">No documents yet</p>
<p className="text-xs text-white/25 mt-1">Upload leases, insurance, or any property files</p>
</div>
) : (
<div className="rounded-xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
<div className="divide-y divide-white/[0.04]">
{docs.map((doc) => (
<div key={doc.id} className="flex items-center gap-4 px-5 py-4">
<div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg bg-indigo-500/10">
<FileText className="h-4 w-4 text-indigo-400" />
</div>
<div className="flex-1 min-w-0">
<p className="truncate text-sm font-medium text-white">{doc.name}</p>
<p className="text-xs text-white/40">
{formatBytes(doc.file_size ?? 0)} · {formatDate(doc.created_at)}
</p>
</div>
<div className="flex items-center gap-2">
<a
href={doc.file_url}
target="_blank"
rel="noopener noreferrer"
className="flex h-8 w-8 items-center justify-center rounded-lg border border-white/10 text-white/50 hover:text-white transition"
>
<Download className="h-3.5 w-3.5" />
</a>
<button
onClick={() => deleteDoc(doc.id)}
disabled={deleting === doc.id}
className="flex h-8 w-8 items-center justify-center rounded-lg border border-white/10 text-white/50 hover:text-red-400 hover:border-red-500/30 transition disabled:opacity-40"
>
{deleting === doc.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</button>
</div>
</div>
))}
</div>
</div>
)}
</div>
)
}
@@ -0,0 +1,28 @@
import { notFound, redirect } from "next/navigation"
import { and, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { properties } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { PropertyForm } from "@/components/forms/property-form"
export default async function EditPropertyPage({ params }: { params: Promise<{ propertyId: string }> }) {
const user = await getSessionUser()
if (!user) redirect("/login")
const { propertyId } = await params
const property = await db.query.properties.findFirst({
where: and(eq(properties.id, propertyId), eq(properties.user_id, user.id)),
})
if (!property) notFound()
return (
<div className="mx-auto max-w-2xl space-y-6">
<div>
<h2 className="text-lg font-semibold text-white">Edit Property</h2>
<p className="text-sm text-white/40">{property.name}</p>
</div>
<PropertyForm property={property} />
</div>
)
}
@@ -0,0 +1,201 @@
import { notFound, redirect } from "next/navigation"
import { and, eq, gte } from "drizzle-orm"
import { db } from "@/lib/db"
import { properties as propertiesTable, rent_payments, expenses as expensesTable } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import Link from "next/link"
import { MapPin, Plus, BedDouble, Bath, Edit } from "lucide-react"
import { formatCurrency, getOccupancyRate } from "@/lib/utils"
import { DeletePropertyButton } from "@/components/forms/delete-property-button"
import { AiMaintenanceSummary } from "@/components/forms/ai-maintenance-summary"
import { PropertyRevenueChart } from "@/components/dashboard/property-revenue-chart"
import { PropertyPhotoUpload } from "@/components/forms/property-photo-upload"
export default async function PropertyDetailPage({ params }: { params: Promise<{ propertyId: string }> }) {
const user = await getSessionUser()
if (!user) redirect("/login")
const { propertyId } = await params
const sixMonthsAgo = new Date()
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 5)
sixMonthsAgo.setDate(1)
const rangeStart = sixMonthsAgo.toISOString().slice(0, 10)
const [property, payments, expenses] = await Promise.all([
db.query.properties.findFirst({
where: and(eq(propertiesTable.id, propertyId), eq(propertiesTable.user_id, user.id)),
with: {
units: {
with: {
current_tenant: { columns: { first_name: true, last_name: true } },
},
},
},
}),
db
.select({ amount: rent_payments.amount, status: rent_payments.status, due_date: rent_payments.due_date })
.from(rent_payments)
.where(
and(
eq(rent_payments.user_id, user.id),
eq(rent_payments.property_id, propertyId),
gte(rent_payments.due_date, rangeStart)
)
),
db
.select({ amount: expensesTable.amount, expense_date: expensesTable.expense_date })
.from(expensesTable)
.where(
and(
eq(expensesTable.user_id, user.id),
eq(expensesTable.property_id, propertyId),
gte(expensesTable.expense_date, rangeStart)
)
),
])
if (!property) notFound()
// Build 6-month chart data
const chartData = Array.from({ length: 6 }, (_, i) => {
const d = new Date(); d.setMonth(d.getMonth() - (5 - i)); d.setDate(1)
const key = d.toISOString().slice(0, 7)
const label = d.toLocaleDateString("en-US", { month: "short" })
const revenue = (payments ?? []).filter(p => p.status === "paid" && p.due_date?.startsWith(key)).reduce((s, p) => s + Number(p.amount), 0)
const expense = (expenses ?? []).filter(e => e.expense_date?.startsWith(key)).reduce((s, e) => s + Number(e.amount), 0)
return { label, revenue, expense }
})
const units = property.units ?? []
const occupied = units.filter((u: any) => u.status === "occupied").length
const occupancy = getOccupancyRate(occupied, units.length)
const statusColors: Record<string, string> = {
occupied: "text-emerald-400 bg-emerald-500/10 border-emerald-500/20",
vacant: "text-white/50 bg-white/5 border-white/10",
maintenance: "text-amber-400 bg-amber-500/10 border-amber-500/20",
unavailable: "text-red-400 bg-red-500/10 border-red-500/20",
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-start justify-between">
<div>
<div className="flex items-center gap-2 text-sm text-white/40 mb-1">
<Link href="/properties" className="hover:text-white transition">Properties</Link>
<span>/</span>
<span className="text-white/70">{property.name}</span>
</div>
<h2 className="text-xl font-bold text-white">{property.name}</h2>
<div className="mt-1 flex items-center gap-1 text-sm text-white/40">
<MapPin className="h-3.5 w-3.5" />
{property.address_line1}, {property.city}{property.state ? `, ${property.state}` : ""}
</div>
</div>
<div className="flex items-center gap-2">
<AiMaintenanceSummary propertyId={propertyId} />
<Link
href={`/properties/${propertyId}/edit`}
className="flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-2 text-sm text-white/70 hover:border-white/20 hover:text-white transition"
>
<Edit className="h-3.5 w-3.5" /> Edit
</Link>
<DeletePropertyButton propertyId={propertyId} />
</div>
</div>
{/* Property Photo */}
<PropertyPhotoUpload propertyId={propertyId} currentImageUrl={property.image_url} />
{/* Stats row */}
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
{[
{ label: "Total Units", value: units.length },
{ label: "Occupied", value: occupied },
{ label: "Vacant", value: units.length - occupied },
{ label: "Occupancy", value: `${occupancy}%` },
].map((s) => (
<div key={s.label} className="rounded-xl border border-white/[0.06] bg-[#16161f] p-4">
<p className="text-xs text-white/40">{s.label}</p>
<p className="mt-1 text-xl font-bold text-white">{s.value}</p>
</div>
))}
</div>
{/* Units */}
<div className="rounded-xl border border-white/[0.06] bg-[#16161f]">
<div className="flex items-center justify-between border-b border-white/[0.06] px-5 py-4">
<h3 className="text-sm font-semibold text-white">Units</h3>
<Link
href={`/properties/${propertyId}/units/new`}
className="flex items-center gap-1.5 rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 transition"
>
<Plus className="h-3.5 w-3.5" /> Add Unit
</Link>
</div>
{units.length === 0 ? (
<div className="py-10 text-center text-sm text-white/30">
No units yet. Add your first unit.
</div>
) : (
<div className="divide-y divide-white/[0.04]">
{units.map((unit: any) => (
<div key={unit.id} className="flex items-center justify-between px-5 py-4">
<div className="flex items-center gap-4">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/5 text-sm font-bold text-white">
{unit.unit_number}
</div>
<div>
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-white">Unit {unit.unit_number}</span>
<span className={`rounded-full border px-2 py-0.5 text-xs font-medium ${statusColors[unit.status] ?? statusColors.vacant}`}>
{unit.status}
</span>
</div>
<div className="mt-0.5 flex items-center gap-3 text-xs text-white/40">
<span className="flex items-center gap-1"><BedDouble className="h-3 w-3" />{unit.bedrooms} bed</span>
<span className="flex items-center gap-1"><Bath className="h-3 w-3" />{unit.bathrooms} bath</span>
{unit.sq_ft && <span>{unit.sq_ft} sqft</span>}
</div>
{unit.current_tenant && (
<p className="mt-0.5 text-xs text-indigo-400">
{unit.current_tenant.first_name} {unit.current_tenant.last_name}
</p>
)}
</div>
</div>
<div className="text-right">
<p className="text-sm font-semibold text-white">{formatCurrency(unit.rent_amount)}<span className="text-xs text-white/40">/mo</span></p>
</div>
</div>
))}
</div>
)}
</div>
{/* Revenue chart */}
<PropertyRevenueChart data={chartData} />
{/* Quick links */}
<div className="flex gap-3 flex-wrap">
{[
{ label: "View Tenants", href: `/tenants?property=${propertyId}` },
{ label: "Maintenance", href: `/maintenance?property=${propertyId}` },
{ label: "Expenses", href: `/expenses?property=${propertyId}` },
{ label: "Documents", href: `/properties/${propertyId}/documents` },
].map((link) => (
<Link
key={link.href}
href={link.href}
className="rounded-lg border border-white/10 px-4 py-2 text-sm text-white/60 hover:border-white/20 hover:text-white transition"
>
{link.label}
</Link>
))}
</div>
</div>
)
}
@@ -0,0 +1,36 @@
import { redirect } from "next/navigation"
import { and, eq } from "drizzle-orm"
import { db } from "@/lib/db"
import { properties } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import { BackButton } from "@/components/ui/back-button"
import { UnitForm } from "@/components/forms/unit-form"
export const metadata = { title: "Add Unit" }
export default async function NewUnitPage({ params }: { params: Promise<{ propertyId: string }> }) {
const user = await getSessionUser()
if (!user) redirect("/login")
const { propertyId } = await params
const property = await db.query.properties.findFirst({
where: and(eq(properties.id, propertyId), eq(properties.user_id, user.id)),
columns: { id: true, name: true },
})
if (!property) redirect("/properties")
return (
<div className="mx-auto max-w-2xl space-y-6">
<BackButton href={`/properties/${propertyId}`} />
<div>
<h2 className="text-lg font-semibold text-white">Add Unit</h2>
<p className="text-sm text-white/40">{property.name}</p>
</div>
<div className="rounded-xl border border-white/[0.06] bg-[#16161f] p-6">
<UnitForm propertyId={propertyId} />
</div>
</div>
)
}
+5
View File
@@ -0,0 +1,5 @@
import { CardGridSkeleton } from "@/components/shared/skeleton"
export default function PropertiesLoading() {
return <CardGridSkeleton cards={6} />
}
+22
View File
@@ -0,0 +1,22 @@
import { redirect } from "next/navigation"
import { getSessionUser } from "@/lib/session"
import { PropertyForm } from "@/components/forms/property-form"
import { BackButton } from "@/components/ui/back-button"
export const metadata = { title: "Add Property" }
export default async function NewPropertyPage() {
const user = await getSessionUser()
if (!user) redirect("/login")
return (
<div className="mx-auto max-w-2xl space-y-6">
<BackButton href="/properties" />
<div>
<h2 className="text-lg font-semibold text-white">Add Property</h2>
<p className="text-sm text-white/40">Fill in the details for your rental property</p>
</div>
<PropertyForm />
</div>
)
}
+138
View File
@@ -0,0 +1,138 @@
import { redirect } from "next/navigation"
import { eq, desc } from "drizzle-orm"
import { db } from "@/lib/db"
import { properties as propertiesTable } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
import Link from "next/link"
import { Building2, MapPin, BedDouble, ArrowRight, TrendingUp } from "lucide-react"
import { EmptyState } from "@/components/shared/empty-state"
import { formatCurrency, getOccupancyRate } from "@/lib/utils"
export const metadata = { title: "Properties" }
export default async function PropertiesPage() {
const user = await getSessionUser()
if (!user) redirect("/login")
const properties = await db.query.properties.findMany({
where: eq(propertiesTable.user_id, user.id),
with: {
units: { columns: { id: true, status: true, rent_amount: true } },
},
orderBy: desc(propertiesTable.created_at),
})
const totalMonthly = (properties ?? []).reduce((sum: number, p: any) => {
return sum + (p.units ?? []).filter((u: any) => u.status === "occupied").reduce((s: number, u: any) => s + Number(u.rent_amount), 0)
}, 0)
return (
<div className="space-y-6">
{/* Page header */}
<div className="flex items-end justify-between">
<div>
<h2 className="text-lg font-semibold text-white">Properties</h2>
<p className="text-sm text-white/40 mt-0.5">
{properties?.length ?? 0} {(properties?.length ?? 0) === 1 ? "property" : "properties"}
{totalMonthly > 0 && <span className="ml-2 text-emerald-400">· {formatCurrency(totalMonthly)}/mo</span>}
</p>
</div>
</div>
{!properties?.length ? (
<EmptyState
icon={Building2}
title="No properties yet"
description="Add your first rental property to start managing tenants, rent, and maintenance."
action={{ label: "Add property", href: "/properties/new" }}
/>
) : (
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
{(properties as any[]).map((property) => {
const units = property.units ?? []
const occupied = units.filter((u: any) => u.status === "occupied").length
const totalUnits = units.length
const occupancy = getOccupancyRate(occupied, totalUnits)
const monthlyRent = units
.filter((u: any) => u.status === "occupied")
.reduce((sum: number, u: any) => sum + Number(u.rent_amount), 0)
const potential = units.reduce((sum: number, u: any) => sum + Number(u.rent_amount), 0)
const occupancyColor =
occupancy === 100 ? "text-emerald-400" :
occupancy >= 50 ? "text-amber-400" :
"text-red-400"
const barColor =
occupancy === 100 ? "bg-emerald-500" :
occupancy >= 50 ? "bg-amber-500" :
"bg-red-500"
return (
<Link
key={property.id}
href={`/properties/${property.id}`}
className="group relative rounded-2xl border border-white/[0.06] bg-[#16161f] p-5 transition-all duration-200 hover:border-indigo-500/30 hover:bg-[#1a1a2e] hover:shadow-xl hover:shadow-indigo-500/5"
>
{/* Top row */}
<div className="flex items-start justify-between mb-4">
<div className="flex h-11 w-11 items-center justify-center rounded-xl bg-indigo-500/10 ring-1 ring-inset ring-indigo-500/20">
<Building2 className="h-5 w-5 text-indigo-400" />
</div>
<span className={`rounded-full px-2.5 py-0.5 text-xs font-semibold ${
occupancy === 100 ? "bg-emerald-500/10 text-emerald-400 ring-1 ring-emerald-500/20" :
occupancy >= 50 ? "bg-amber-500/10 text-amber-400 ring-1 ring-amber-500/20" :
"bg-red-500/10 text-red-400 ring-1 ring-red-500/20"
}`}>
{occupancy}% full
</span>
</div>
{/* Name + address */}
<div>
<h3 className="font-semibold text-white group-hover:text-indigo-200 transition-colors">{property.name}</h3>
<div className="mt-1 flex items-center gap-1 text-xs text-white/40">
<MapPin className="h-3 w-3 shrink-0" />
<span className="truncate">{property.address_line1 ? `${property.address_line1}, ` : ""}{property.city}{property.state ? `, ${property.state}` : ""}</span>
</div>
</div>
{/* Occupancy bar */}
<div className="mt-4">
<div className="h-1 w-full rounded-full bg-white/[0.06]">
<div
className={`h-1 rounded-full transition-all ${barColor}`}
style={{ width: `${Math.max(occupancy, 2)}%` }}
/>
</div>
<div className="mt-1 flex items-center justify-between text-[10px] text-white/30">
<span>{occupied} of {totalUnits} units occupied</span>
<span>{totalUnits - occupied} vacant</span>
</div>
</div>
{/* Stats */}
<div className="mt-4 grid grid-cols-2 gap-3 border-t border-white/[0.06] pt-4">
<div>
<p className="text-xs text-white/30">Collected / mo</p>
<p className="mt-0.5 text-sm font-semibold text-white">{formatCurrency(monthlyRent)}</p>
</div>
<div>
<p className="text-xs text-white/30">Potential / mo</p>
<p className="mt-0.5 text-sm font-semibold text-white/60">{formatCurrency(potential)}</p>
</div>
</div>
{/* Hover arrow */}
<div className="mt-3 flex items-center gap-1 text-xs text-indigo-400/0 group-hover:text-indigo-400/80 transition-all">
<span>View details</span>
<ArrowRight className="h-3 w-3" />
</div>
</Link>
)
})}
</div>
)}
</div>
)
}