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:
@@ -0,0 +1,59 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { rent_payments } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { rentPaymentSchema } from "@/lib/validations"
|
||||
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
|
||||
import { logActivity } from "@/lib/activity"
|
||||
|
||||
export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
|
||||
const { id } = await params
|
||||
const body = await request.json()
|
||||
const parsed = rentPaymentSchema.partial().safeParse(body)
|
||||
if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
||||
|
||||
if (
|
||||
!(await ownsProperty(user.id, parsed.data.property_id)) ||
|
||||
!(await ownsUnit(user.id, parsed.data.unit_id)) ||
|
||||
!(await ownsTenant(user.id, parsed.data.tenant_id))
|
||||
) {
|
||||
return NextResponse.json({ error: "Invalid reference" }, { status: 403 })
|
||||
}
|
||||
|
||||
// Auto-set paid_date when status → paid
|
||||
const updateData = { ...parsed.data }
|
||||
if (parsed.data.status === "paid" && !parsed.data.paid_date) {
|
||||
updateData.paid_date = new Date().toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
const [data] = await db
|
||||
.update(rent_payments)
|
||||
.set(updateData)
|
||||
.where(and(eq(rent_payments.id, id), eq(rent_payments.user_id, user.id)))
|
||||
.returning()
|
||||
|
||||
if (parsed.data.status === "paid") {
|
||||
await logActivity({
|
||||
userId: user.id,
|
||||
type: "rent_paid",
|
||||
title: "Rent payment marked as paid",
|
||||
entityType: "rent_payment",
|
||||
entityId: id,
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json(data)
|
||||
}
|
||||
|
||||
export async function DELETE(_: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
|
||||
const { id } = await params
|
||||
await db.delete(rent_payments).where(and(eq(rent_payments.id, id), eq(rent_payments.user_id, user.id)))
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { leases, rent_payments } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
|
||||
const { year, month } = await request.json() as { year: number; month: number }
|
||||
if (!year || month === undefined) return NextResponse.json({ error: "year and month required" }, { status: 400 })
|
||||
|
||||
// Get all active leases with rent amount
|
||||
const activeLeases = await db
|
||||
.select({
|
||||
id: leases.id,
|
||||
tenant_id: leases.tenant_id,
|
||||
property_id: leases.property_id,
|
||||
unit_id: leases.unit_id,
|
||||
rent_amount: leases.rent_amount,
|
||||
})
|
||||
.from(leases)
|
||||
.where(and(eq(leases.user_id, user.id), eq(leases.status, "active")))
|
||||
|
||||
if (!activeLeases.length) return NextResponse.json({ created: 0, skipped: 0 })
|
||||
|
||||
// Build due date: first of selected month
|
||||
const pad = (n: number) => String(n).padStart(2, "0")
|
||||
const due_date = `${year}-${pad(month + 1)}-01`
|
||||
|
||||
// Check which already exist for this month
|
||||
const existing = await db
|
||||
.select({ tenant_id: rent_payments.tenant_id })
|
||||
.from(rent_payments)
|
||||
.where(and(eq(rent_payments.user_id, user.id), eq(rent_payments.due_date, due_date)))
|
||||
|
||||
const existingTenantIds = new Set(existing.map((p) => p.tenant_id))
|
||||
|
||||
const toInsert = activeLeases
|
||||
.filter((l) => !existingTenantIds.has(l.tenant_id))
|
||||
.map((l) => ({
|
||||
user_id: user.id,
|
||||
tenant_id: l.tenant_id,
|
||||
property_id: l.property_id,
|
||||
unit_id: l.unit_id ?? null,
|
||||
amount: l.rent_amount,
|
||||
due_date,
|
||||
status: "pending" as const,
|
||||
}))
|
||||
|
||||
if (toInsert.length === 0) {
|
||||
return NextResponse.json({ created: 0, skipped: activeLeases.length, message: "All payments already exist for this month." })
|
||||
}
|
||||
|
||||
await db.insert(rent_payments).values(toInsert)
|
||||
|
||||
return NextResponse.json({
|
||||
created: toInsert.length,
|
||||
skipped: existingTenantIds.size,
|
||||
message: `Created ${toInsert.length} payment${toInsert.length !== 1 ? "s" : ""} for ${due_date.slice(0, 7)}.`,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { rent_payments } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { createRentPaymentLink } from "@/lib/stripe/payment-links"
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
|
||||
const { payment_id } = await request.json() as { payment_id: string }
|
||||
|
||||
const payment = await db.query.rent_payments.findFirst({
|
||||
where: and(eq(rent_payments.id, payment_id), eq(rent_payments.user_id, user.id)),
|
||||
with: {
|
||||
tenant: { columns: { first_name: true, last_name: true } },
|
||||
property: { columns: { name: true } },
|
||||
unit: { columns: { unit_number: true } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!payment) return NextResponse.json({ error: "Payment not found" }, { status: 404 })
|
||||
|
||||
const link = await createRentPaymentLink({
|
||||
tenantName: `${payment.tenant.first_name} ${payment.tenant.last_name}`,
|
||||
propertyName: payment.property.name,
|
||||
unitNumber: payment.unit?.unit_number ?? "—",
|
||||
amount: payment.amount,
|
||||
tenantId: payment.tenant_id,
|
||||
paymentId: payment.id,
|
||||
})
|
||||
|
||||
// Save link ID to payment record
|
||||
await db
|
||||
.update(rent_payments)
|
||||
.set({ stripe_payment_link_id: link.id })
|
||||
.where(and(eq(rent_payments.id, payment_id), eq(rent_payments.user_id, user.id)))
|
||||
|
||||
return NextResponse.json({ url: link.url })
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { and, desc, eq, sql } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { rent_payments } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { rentPaymentSchema } from "@/lib/validations"
|
||||
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const status = searchParams.get("status")
|
||||
const tenantId = searchParams.get("tenant_id")
|
||||
const page = Math.max(1, parseInt(searchParams.get("page") ?? "1", 10))
|
||||
const limit = Math.min(100, Math.max(1, parseInt(searchParams.get("limit") ?? "50", 10)))
|
||||
const offset = (page - 1) * limit
|
||||
|
||||
const where = and(
|
||||
eq(rent_payments.user_id, user.id),
|
||||
status ? eq(rent_payments.status, status as typeof rent_payments.$inferSelect.status) : undefined,
|
||||
tenantId ? eq(rent_payments.tenant_id, tenantId) : undefined
|
||||
)
|
||||
|
||||
const [data, [{ count }]] = await Promise.all([
|
||||
db.query.rent_payments.findMany({
|
||||
where,
|
||||
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),
|
||||
limit,
|
||||
offset,
|
||||
}),
|
||||
db.select({ count: sql<number>`count(*)::int` }).from(rent_payments).where(where),
|
||||
])
|
||||
|
||||
return NextResponse.json({ data, total: count ?? 0, page, limit })
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
|
||||
const body = await request.json()
|
||||
const parsed = rentPaymentSchema.safeParse(body)
|
||||
if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
||||
|
||||
if (
|
||||
!(await ownsProperty(user.id, parsed.data.property_id)) ||
|
||||
!(await ownsUnit(user.id, parsed.data.unit_id)) ||
|
||||
!(await ownsTenant(user.id, parsed.data.tenant_id))
|
||||
) {
|
||||
return NextResponse.json({ error: "Invalid reference" }, { status: 403 })
|
||||
}
|
||||
|
||||
const [data] = await db
|
||||
.insert(rent_payments)
|
||||
.values({ ...parsed.data, user_id: user.id })
|
||||
.returning()
|
||||
|
||||
return NextResponse.json(data, { status: 201 })
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
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 } from "@/lib/email/send"
|
||||
import { paymentLinkSchema } from "@/lib/validations"
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
||||
|
||||
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, user.id)),
|
||||
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 profile for payment instructions
|
||||
const profile = await db.query.profiles.findFirst({
|
||||
where: eq(profiles.id, user.id),
|
||||
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 html = `
|
||||
<div style="font-family:sans-serif;max-width:560px;margin:0 auto;background:#09090b;color:#fff;border-radius:12px;overflow:hidden;">
|
||||
<div style="background:linear-gradient(135deg,#4f46e5,#7c3aed);padding:32px;text-align:center;">
|
||||
<h1 style="margin:0;font-size:24px;font-weight:700;">Rent Payment Due</h1>
|
||||
<p style="margin:8px 0 0;opacity:.8;font-size:14px;">Property Management Network</p>
|
||||
</div>
|
||||
<div style="padding:32px;">
|
||||
<p style="font-size:16px;margin:0 0 8px;">Hi ${tenantName},</p>
|
||||
<p style="color:rgba(255,255,255,.6);font-size:14px;margin:0 0 24px;">
|
||||
Your rent payment of <strong style="color:#fff;">${amount}</strong> is due on <strong style="color:#fff;">${dueDate}</strong>
|
||||
for ${payment.property?.name}${payment.unit ? ` Unit ${payment.unit.unit_number}` : ""}.
|
||||
</p>
|
||||
<p style="color:rgba(255,255,255,.6);font-size:14px;margin:0 0 16px;">
|
||||
Please arrange payment at your earliest convenience. Contact your landlord if you have any questions.
|
||||
</p>
|
||||
<p style="color:rgba(255,255,255,.4);font-size:12px;margin:24px 0 0;border-top:1px solid rgba(255,255,255,.08);padding-top:16px;">
|
||||
Sent by ${profile?.full_name ?? "Your Landlord"} via Property Management Network
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
|
||||
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 = ${user.id}`
|
||||
)
|
||||
} 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}` })
|
||||
}
|
||||
Reference in New Issue
Block a user