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>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
969d5d4c8a
commit
c9968531e4
@@ -3,6 +3,7 @@ import { desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { activity_log } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { ActivityFeed } from "./activity-feed"
|
||||
|
||||
export const metadata = { title: "Activity" }
|
||||
@@ -11,10 +12,12 @@ export default async function ActivityPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const activities = await db
|
||||
.select()
|
||||
.from(activity_log)
|
||||
.where(eq(activity_log.user_id, user.id))
|
||||
.where(eq(activity_log.user_id, ownerId))
|
||||
.orderBy(desc(activity_log.created_at))
|
||||
.limit(100)
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
maintenance_requests,
|
||||
} from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { AiDashboardClient } from "./ai-dashboard-client"
|
||||
|
||||
export const metadata = { title: "AI Dashboard" }
|
||||
@@ -18,6 +19,8 @@ export default async function AiDashboardPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const now = new Date()
|
||||
const threeMonthsAgo = new Date(now)
|
||||
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3)
|
||||
@@ -26,19 +29,19 @@ export default async function AiDashboardPage() {
|
||||
db
|
||||
.select()
|
||||
.from(ai_recommendations)
|
||||
.where(eq(ai_recommendations.user_id, user.id))
|
||||
.where(eq(ai_recommendations.user_id, ownerId))
|
||||
.orderBy(desc(ai_recommendations.created_at))
|
||||
.limit(3),
|
||||
db
|
||||
.select()
|
||||
.from(ai_predictions)
|
||||
.where(eq(ai_predictions.user_id, user.id))
|
||||
.where(eq(ai_predictions.user_id, ownerId))
|
||||
.orderBy(desc(ai_predictions.created_at))
|
||||
.limit(3),
|
||||
db
|
||||
.select()
|
||||
.from(activity_log)
|
||||
.where(and(eq(activity_log.user_id, user.id), eq(activity_log.type, "ai_action")))
|
||||
.where(and(eq(activity_log.user_id, ownerId), eq(activity_log.type, "ai_action")))
|
||||
.orderBy(desc(activity_log.created_at))
|
||||
.limit(5),
|
||||
db
|
||||
@@ -46,20 +49,20 @@ export default async function AiDashboardPage() {
|
||||
.from(rent_payments)
|
||||
.where(
|
||||
and(
|
||||
eq(rent_payments.user_id, user.id),
|
||||
eq(rent_payments.user_id, ownerId),
|
||||
gte(rent_payments.due_date, threeMonthsAgo.toISOString().slice(0, 10))
|
||||
)
|
||||
),
|
||||
db
|
||||
.select({ status: unitsTable.status })
|
||||
.from(unitsTable)
|
||||
.where(eq(unitsTable.user_id, user.id)),
|
||||
.where(eq(unitsTable.user_id, ownerId)),
|
||||
db
|
||||
.select({ status: maintenance_requests.status, priority: maintenance_requests.priority })
|
||||
.from(maintenance_requests)
|
||||
.where(
|
||||
and(
|
||||
eq(maintenance_requests.user_id, user.id),
|
||||
eq(maintenance_requests.user_id, ownerId),
|
||||
inArray(maintenance_requests.status, ["open", "in_progress"])
|
||||
)
|
||||
),
|
||||
@@ -68,7 +71,7 @@ export default async function AiDashboardPage() {
|
||||
const allRecsData = await db
|
||||
.select({ status: ai_recommendations.status, action_data: ai_recommendations.action_data })
|
||||
.from(ai_recommendations)
|
||||
.where(eq(ai_recommendations.user_id, user.id))
|
||||
.where(eq(ai_recommendations.user_id, ownerId))
|
||||
const approvedRecs = allRecsData.filter((r) => r.status === "approved")
|
||||
|
||||
let totalImpact = 0
|
||||
|
||||
@@ -1,222 +1,227 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { ChevronLeft, ChevronRight, CreditCard, FileText } from "lucide-react"
|
||||
import { cn, formatCurrency } from "@/lib/utils"
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import FullCalendar from "@fullcalendar/react"
|
||||
import dayGridPlugin from "@fullcalendar/daygrid"
|
||||
import timeGridPlugin from "@fullcalendar/timegrid"
|
||||
import listPlugin from "@fullcalendar/list"
|
||||
import interactionPlugin from "@fullcalendar/interaction"
|
||||
import type { EventClickArg, EventDropArg } from "@fullcalendar/core"
|
||||
import { toast } from "sonner"
|
||||
import { CreditCard, FileText, ClipboardList, X, CalendarDays, Copy, Check, ArrowRight } from "lucide-react"
|
||||
import "./calendar.css"
|
||||
|
||||
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
|
||||
const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"]
|
||||
type EventType = "rent" | "lease" | "inspection"
|
||||
|
||||
interface CalendarClientProps {
|
||||
payments: any[]
|
||||
leases: any[]
|
||||
export interface CalEvent {
|
||||
id: string
|
||||
title: string
|
||||
start: string
|
||||
allDay: boolean
|
||||
backgroundColor: string
|
||||
borderColor: string
|
||||
editable: boolean
|
||||
extendedProps: {
|
||||
type: EventType
|
||||
entityId: string
|
||||
status?: string
|
||||
subtitle: string
|
||||
href: string
|
||||
}
|
||||
}
|
||||
|
||||
export function CalendarClient({ payments, leases }: CalendarClientProps) {
|
||||
const today = new Date()
|
||||
const [year, setYear] = useState(today.getFullYear())
|
||||
const [month, setMonth] = useState(today.getMonth())
|
||||
const [selected, setSelected] = useState<string | null>(null)
|
||||
const TYPE_META: Record<EventType, { label: string; color: string; Icon: typeof CreditCard }> = {
|
||||
rent: { label: "Rent", color: "#6366f1", Icon: CreditCard },
|
||||
lease: { label: "Leases", color: "#f59e0b", Icon: FileText },
|
||||
inspection: { label: "Inspections", color: "#14b8a6", Icon: ClipboardList },
|
||||
}
|
||||
|
||||
function prevMonth() {
|
||||
if (month === 0) { setMonth(11); setYear(y => y - 1) }
|
||||
else setMonth(m => m - 1)
|
||||
}
|
||||
function nextMonth() {
|
||||
if (month === 11) { setMonth(0); setYear(y => y + 1) }
|
||||
else setMonth(m => m + 1)
|
||||
export function CalendarClient({
|
||||
events,
|
||||
canWrite,
|
||||
subscribeUrl,
|
||||
}: {
|
||||
events: CalEvent[]
|
||||
canWrite: boolean
|
||||
subscribeUrl: string
|
||||
}) {
|
||||
const [mounted, setMounted] = useState(false)
|
||||
const [active, setActive] = useState<Record<EventType, boolean>>({ rent: true, lease: true, inspection: true })
|
||||
const [selected, setSelected] = useState<(CalEvent["extendedProps"] & { title: string; start: string }) | null>(null)
|
||||
const [showSubscribe, setShowSubscribe] = useState(false)
|
||||
|
||||
useEffect(() => setMounted(true), [])
|
||||
|
||||
const shown = events.filter((e) => active[e.extendedProps.type])
|
||||
|
||||
function toggle(t: EventType) {
|
||||
setActive((a) => ({ ...a, [t]: !a[t] }))
|
||||
}
|
||||
|
||||
// Build calendar grid
|
||||
const firstDay = new Date(year, month, 1).getDay()
|
||||
const daysInMonth = new Date(year, month + 1, 0).getDate()
|
||||
const cells: (number | null)[] = [
|
||||
...Array(firstDay).fill(null),
|
||||
...Array.from({ length: daysInMonth }, (_, i) => i + 1),
|
||||
]
|
||||
// Pad to complete last row
|
||||
while (cells.length % 7 !== 0) cells.push(null)
|
||||
|
||||
function dateKey(day: number) {
|
||||
return `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`
|
||||
function onEventClick(info: EventClickArg) {
|
||||
info.jsEvent.preventDefault()
|
||||
const p = info.event.extendedProps as CalEvent["extendedProps"]
|
||||
setSelected({ ...p, title: info.event.title, start: info.event.startStr })
|
||||
}
|
||||
|
||||
// Group events by date
|
||||
const eventsByDate: Record<string, { type: "payment" | "lease"; item: any }[]> = {}
|
||||
|
||||
for (const p of payments) {
|
||||
const key = p.due_date?.slice(0, 10)
|
||||
if (!key) continue
|
||||
if (!eventsByDate[key]) eventsByDate[key] = []
|
||||
eventsByDate[key].push({ type: "payment", item: p })
|
||||
async function onEventDrop(info: EventDropArg) {
|
||||
const { type, entityId } = info.event.extendedProps as CalEvent["extendedProps"]
|
||||
if (!canWrite || type === "lease") {
|
||||
info.revert()
|
||||
toast.error(type === "lease" ? "Lease end dates can't be moved here" : "You don't have permission to reschedule")
|
||||
return
|
||||
}
|
||||
const newDate = info.event.startStr.slice(0, 10)
|
||||
const endpoint = type === "rent" ? `/api/rent/${entityId}` : `/api/inspections/${entityId}`
|
||||
const body = type === "rent" ? { due_date: newDate } : { date: newDate }
|
||||
try {
|
||||
const res = await fetch(endpoint, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
|
||||
if (res.ok) toast.success(`Rescheduled to ${newDate}`)
|
||||
else {
|
||||
info.revert()
|
||||
toast.error("Couldn't reschedule")
|
||||
}
|
||||
} catch {
|
||||
info.revert()
|
||||
toast.error("Network error")
|
||||
}
|
||||
}
|
||||
|
||||
for (const l of leases) {
|
||||
const key = l.lease_end?.slice(0, 10)
|
||||
if (!key) continue
|
||||
if (!eventsByDate[key]) eventsByDate[key] = []
|
||||
eventsByDate[key].push({ type: "lease", item: l })
|
||||
}
|
||||
|
||||
const selectedEvents = selected ? (eventsByDate[selected] ?? []) : []
|
||||
|
||||
const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
|
||||
{/* Calendar grid */}
|
||||
<div className="lg:col-span-2 rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
|
||||
{/* Month nav */}
|
||||
<div className="flex items-center justify-between border-b border-white/[0.06] px-5 py-4">
|
||||
<button onClick={prevMonth} className="rounded-lg p-1.5 text-white/40 hover:text-white transition hover:bg-white/[0.05]">
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</button>
|
||||
<h3 className="text-sm font-semibold text-white">{MONTHS[month]} {year}</h3>
|
||||
<button onClick={nextMonth} className="rounded-lg p-1.5 text-white/40 hover:text-white transition hover:bg-white/[0.05]">
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Day headers */}
|
||||
<div className="grid grid-cols-7 border-b border-white/[0.04]">
|
||||
{DAYS.map((d) => (
|
||||
<div key={d} className="py-2 text-center text-[10px] font-semibold uppercase tracking-wider text-white/25">
|
||||
{d}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Days */}
|
||||
<div className="grid grid-cols-7">
|
||||
{cells.map((day, i) => {
|
||||
const key = day ? dateKey(day) : null
|
||||
const events = key ? (eventsByDate[key] ?? []) : []
|
||||
const isToday = key === todayKey
|
||||
const isSelected = key === selected
|
||||
const paymentEvents = events.filter((e) => e.type === "payment")
|
||||
const leaseEvents = events.filter((e) => e.type === "lease")
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Toolbar: filters + subscribe */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{(Object.keys(TYPE_META) as EventType[]).map((t) => {
|
||||
const m = TYPE_META[t]
|
||||
const on = active[t]
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
onClick={() => day && key && setSelected(isSelected ? null : key)}
|
||||
className={cn(
|
||||
"relative min-h-[72px] border-b border-r border-white/[0.03] p-1.5 transition-colors",
|
||||
day ? "cursor-pointer hover:bg-white/[0.03]" : "opacity-0 pointer-events-none",
|
||||
isSelected && "bg-indigo-600/10 border-indigo-500/20",
|
||||
)}
|
||||
<button
|
||||
key={t}
|
||||
onClick={() => toggle(t)}
|
||||
className="flex items-center gap-2 rounded-lg border px-3 py-1.5 text-xs font-medium transition"
|
||||
style={{
|
||||
borderColor: on ? m.color + "66" : "rgba(255,255,255,0.08)",
|
||||
background: on ? m.color + "1a" : "transparent",
|
||||
color: on ? "#fff" : "rgba(255,255,255,0.4)",
|
||||
}}
|
||||
>
|
||||
{day && (
|
||||
<>
|
||||
<span className={cn(
|
||||
"flex h-6 w-6 items-center justify-center rounded-full text-xs font-medium",
|
||||
isToday ? "bg-indigo-600 text-white font-bold" : "text-white/50"
|
||||
)}>
|
||||
{day}
|
||||
</span>
|
||||
<div className="mt-1 space-y-0.5">
|
||||
{paymentEvents.slice(0, 2).map((e, j) => (
|
||||
<div key={j} className={cn(
|
||||
"truncate rounded px-1 py-0.5 text-[9px] font-medium",
|
||||
e.item.status === "paid"
|
||||
? "bg-emerald-500/15 text-emerald-400"
|
||||
: e.item.status === "overdue"
|
||||
? "bg-red-500/15 text-red-400"
|
||||
: "bg-indigo-500/15 text-indigo-400"
|
||||
)}>
|
||||
{e.item.tenant?.first_name} {formatCurrency(e.item.amount)}
|
||||
</div>
|
||||
))}
|
||||
{leaseEvents.slice(0, 1).map((e, j) => (
|
||||
<div key={j} className="truncate rounded bg-amber-500/15 px-1 py-0.5 text-[9px] font-medium text-amber-400">
|
||||
Lease ends: {e.item.tenant?.first_name}
|
||||
</div>
|
||||
))}
|
||||
{events.length > 3 && (
|
||||
<div className="text-[9px] text-white/30 px-1">+{events.length - 3} more</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<span className="h-2 w-2 rounded-full" style={{ background: m.color, opacity: on ? 1 : 0.4 }} />
|
||||
{m.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowSubscribe(true)}
|
||||
className="flex items-center gap-2 rounded-lg border border-indigo-500/30 bg-indigo-500/10 px-3 py-1.5 text-xs font-semibold text-indigo-300 transition hover:bg-indigo-500/15"
|
||||
>
|
||||
<CalendarDays className="h-3.5 w-3.5" /> Subscribe / Sync
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Side panel */}
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
|
||||
<div className="border-b border-white/[0.06] px-5 py-4">
|
||||
<h3 className="text-sm font-semibold text-white">
|
||||
{selected ? new Date(selected + "T12:00:00").toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" }) : "Select a date"}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{!selected ? (
|
||||
<div className="flex flex-col items-center justify-center py-16 text-center px-4">
|
||||
<p className="text-sm text-white/30">Click any day to see events</p>
|
||||
</div>
|
||||
) : selectedEvents.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-16 text-center px-4">
|
||||
<p className="text-sm text-white/30">No events this day</p>
|
||||
</div>
|
||||
{/* Calendar */}
|
||||
<div className="fc-dark rounded-2xl border border-white/[0.06] bg-[#16161f] p-3 sm:p-4">
|
||||
{mounted ? (
|
||||
<FullCalendar
|
||||
plugins={[dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin]}
|
||||
initialView="dayGridMonth"
|
||||
headerToolbar={{ left: "prev,next today", center: "title", right: "dayGridMonth,timeGridWeek,timeGridDay,listMonth" }}
|
||||
buttonText={{ today: "Today", month: "Month", week: "Week", day: "Day", list: "Agenda" }}
|
||||
events={shown}
|
||||
editable={canWrite}
|
||||
eventStartEditable={canWrite}
|
||||
eventDurationEditable={false}
|
||||
dayMaxEvents={4}
|
||||
height="auto"
|
||||
firstDay={0}
|
||||
eventClick={onEventClick}
|
||||
eventDrop={onEventDrop}
|
||||
noEventsText="Nothing scheduled"
|
||||
/>
|
||||
) : (
|
||||
<div className="divide-y divide-white/[0.04] p-3 space-y-1">
|
||||
{selectedEvents.map((e, i) => (
|
||||
<div key={i} className={cn(
|
||||
"flex items-start gap-3 rounded-xl p-3",
|
||||
e.type === "payment" ? "bg-indigo-500/5" : "bg-amber-500/5"
|
||||
)}>
|
||||
<div className={cn(
|
||||
"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border",
|
||||
e.type === "payment"
|
||||
? "border-indigo-500/20 bg-indigo-500/10 text-indigo-400"
|
||||
: "border-amber-500/20 bg-amber-500/10 text-amber-400"
|
||||
)}>
|
||||
{e.type === "payment" ? <CreditCard className="h-3.5 w-3.5" /> : <FileText className="h-3.5 w-3.5" />}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
{e.type === "payment" ? (
|
||||
<>
|
||||
<p className="text-xs font-semibold text-white">{e.item.tenant?.first_name} {e.item.tenant?.last_name}</p>
|
||||
<p className="text-xs text-white/40">{formatCurrency(e.item.amount)} due</p>
|
||||
<span className={cn(
|
||||
"mt-1 inline-block rounded-full px-2 py-0.5 text-[10px] font-medium capitalize",
|
||||
e.item.status === "paid" ? "bg-emerald-500/15 text-emerald-400" :
|
||||
e.item.status === "overdue" ? "bg-red-500/15 text-red-400" :
|
||||
"bg-white/10 text-white/40"
|
||||
)}>
|
||||
{e.item.status}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-xs font-semibold text-white">Lease Expiry</p>
|
||||
<p className="text-xs text-white/40">{e.item.tenant?.first_name} {e.item.tenant?.last_name}</p>
|
||||
<p className="text-xs text-white/30">{e.item.property?.name}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex h-[520px] items-center justify-center text-sm text-white/30">Loading calendar…</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Legend */}
|
||||
<div className="border-t border-white/[0.06] px-5 py-3 space-y-1.5">
|
||||
<p className="text-[10px] font-semibold uppercase tracking-wider text-white/20 mb-2">Legend</p>
|
||||
{[
|
||||
{ color: "bg-indigo-500/20 text-indigo-400", label: "Rent pending" },
|
||||
{ color: "bg-emerald-500/20 text-emerald-400", label: "Rent paid" },
|
||||
{ color: "bg-red-500/20 text-red-400", label: "Rent overdue" },
|
||||
{ color: "bg-amber-500/20 text-amber-400", label: "Lease expiry" },
|
||||
].map((l) => (
|
||||
<div key={l.label} className="flex items-center gap-2">
|
||||
<div className={cn("h-2 w-2 rounded-full", l.color)} />
|
||||
<span className="text-xs text-white/40">{l.label}</span>
|
||||
{selected && <EventDetail ev={selected} onClose={() => setSelected(null)} />}
|
||||
{showSubscribe && <SubscribeModal url={subscribeUrl} onClose={() => setShowSubscribe(false)} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function EventDetail({ ev, onClose }: { ev: CalEvent["extendedProps"] & { title: string; start: string }; onClose: () => void }) {
|
||||
const m = TYPE_META[ev.type]
|
||||
const dateLabel = new Date(ev.start + "T12:00:00").toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", year: "numeric" })
|
||||
return (
|
||||
<div className="fixed inset-0 z-[300] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm" onClick={onClose}>
|
||||
<div className="w-full max-w-sm rounded-2xl border border-white/10 bg-[#16161f] p-5" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="mb-4 flex items-start justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-9 w-9 items-center justify-center rounded-xl border" style={{ borderColor: m.color + "33", background: m.color + "1a", color: m.color }}>
|
||||
<m.Icon className="h-4 w-4" />
|
||||
</div>
|
||||
))}
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-white">{ev.title}</p>
|
||||
<p className="text-xs text-white/40">{m.label}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={onClose} className="text-white/30 transition hover:text-white"><X className="h-4 w-4" /></button>
|
||||
</div>
|
||||
<dl className="space-y-2 text-sm">
|
||||
<div className="flex justify-between gap-4"><dt className="text-white/40">Date</dt><dd className="text-white/80">{dateLabel}</dd></div>
|
||||
{ev.subtitle && <div className="flex justify-between gap-4"><dt className="text-white/40">Details</dt><dd className="text-right text-white/80">{ev.subtitle}</dd></div>}
|
||||
{ev.status && <div className="flex justify-between gap-4"><dt className="text-white/40">Status</dt><dd className="capitalize text-white/80">{ev.status}</dd></div>}
|
||||
</dl>
|
||||
<Link href={ev.href} className="mt-5 flex items-center justify-center gap-1.5 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-indigo-500">
|
||||
Open {m.label.toLowerCase()} <ArrowRight className="h-3.5 w-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SubscribeModal({ url, onClose }: { url: string; onClose: () => void }) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const webcal = url.replace(/^https?:\/\//, "webcal://")
|
||||
return (
|
||||
<div className="fixed inset-0 z-[300] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm" onClick={onClose}>
|
||||
<div className="w-full max-w-lg rounded-2xl border border-white/10 bg-[#16161f] p-6" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="mb-4 flex items-start justify-between">
|
||||
<div>
|
||||
<h3 className="text-base font-bold text-white">Subscribe to your calendar</h3>
|
||||
<p className="mt-1 text-xs text-white/45">One-way sync — new rent, lease, and inspection dates appear automatically in your calendar app.</p>
|
||||
</div>
|
||||
<button onClick={onClose} className="text-white/30 transition hover:text-white"><X className="h-4 w-4" /></button>
|
||||
</div>
|
||||
|
||||
{url ? (
|
||||
<>
|
||||
<div className="flex items-center gap-2 rounded-lg border border-white/10 bg-white/[0.03] p-2">
|
||||
<input readOnly value={url} className="flex-1 bg-transparent px-2 text-xs text-white/70 outline-none" onFocus={(e) => e.currentTarget.select()} />
|
||||
<button
|
||||
onClick={() => { navigator.clipboard.writeText(url).catch(() => {}); setCopied(true); setTimeout(() => setCopied(false), 2000) }}
|
||||
className="flex items-center gap-1 rounded-md bg-indigo-600 px-2.5 py-1.5 text-xs font-semibold text-white transition hover:bg-indigo-500"
|
||||
>
|
||||
{copied ? <><Check className="h-3 w-3" /> Copied</> : <><Copy className="h-3 w-3" /> Copy</>}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 space-y-2.5 text-xs text-white/55">
|
||||
<p><strong className="text-white/80">Google Calendar:</strong> Settings → Add calendar → <em>From URL</em> → paste the link.</p>
|
||||
<p><strong className="text-white/80">Apple Calendar:</strong> File → New Calendar Subscription → paste, or open <a href={webcal} className="text-indigo-400 hover:text-indigo-300">this webcal link</a>.</p>
|
||||
<p><strong className="text-white/80">Outlook:</strong> Add calendar → Subscribe from web → paste the link.</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex items-center justify-between border-t border-white/[0.06] pt-4">
|
||||
<p className="text-[11px] text-white/30">Keep this link private — anyone with it can view your dates.</p>
|
||||
<a href={url} download className="rounded-lg border border-white/10 px-3 py-1.5 text-xs font-medium text-white/70 transition hover:bg-white/[0.06]">Download .ics</a>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-sm text-white/50">Your feed link isn't available yet. Refresh the page and try again.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
/* Dark theme for FullCalendar, scoped to .fc-dark to match the app's aesthetic. */
|
||||
.fc-dark {
|
||||
--fc-border-color: rgba(255, 255, 255, 0.06);
|
||||
--fc-page-bg-color: transparent;
|
||||
--fc-neutral-bg-color: rgba(255, 255, 255, 0.02);
|
||||
--fc-neutral-text-color: rgba(255, 255, 255, 0.5);
|
||||
--fc-today-bg-color: rgba(99, 102, 241, 0.1);
|
||||
--fc-now-indicator-color: #6366f1;
|
||||
--fc-list-event-hover-bg-color: rgba(255, 255, 255, 0.04);
|
||||
--fc-highlight-color: rgba(99, 102, 241, 0.15);
|
||||
}
|
||||
|
||||
.fc-dark .fc {
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
/* Toolbar */
|
||||
.fc-dark .fc .fc-toolbar.fc-header-toolbar {
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.fc-dark .fc .fc-toolbar-title {
|
||||
font-size: 1.05rem;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
}
|
||||
.fc-dark .fc .fc-button {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
box-shadow: none;
|
||||
text-transform: none;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 500;
|
||||
padding: 0.35rem 0.7rem;
|
||||
border-radius: 0.55rem;
|
||||
}
|
||||
.fc-dark .fc .fc-button:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: #fff;
|
||||
border-color: rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
.fc-dark .fc .fc-button:focus,
|
||||
.fc-dark .fc .fc-button:active {
|
||||
box-shadow: none !important;
|
||||
outline: none;
|
||||
}
|
||||
.fc-dark .fc .fc-button-primary:not(:disabled).fc-button-active,
|
||||
.fc-dark .fc .fc-button-primary:not(:disabled):active {
|
||||
background: #4f46e5;
|
||||
border-color: #4f46e5;
|
||||
color: #fff;
|
||||
}
|
||||
.fc-dark .fc .fc-button:disabled {
|
||||
opacity: 0.4;
|
||||
}
|
||||
.fc-dark .fc .fc-button-group > .fc-button {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Grid headers + cells */
|
||||
.fc-dark .fc .fc-col-header-cell-cushion {
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
font-size: 0.68rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
padding: 0.6rem 0.4rem;
|
||||
}
|
||||
.fc-dark .fc .fc-daygrid-day-number {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 0.78rem;
|
||||
padding: 0.4rem 0.5rem;
|
||||
}
|
||||
.fc-dark .fc .fc-day-today .fc-daygrid-day-number {
|
||||
color: #a5b4fc;
|
||||
font-weight: 700;
|
||||
}
|
||||
.fc-dark .fc .fc-daygrid-day.fc-day-other {
|
||||
background: rgba(255, 255, 255, 0.012);
|
||||
}
|
||||
.fc-dark .fc .fc-daygrid-day.fc-day-other .fc-daygrid-day-number {
|
||||
opacity: 0.35;
|
||||
}
|
||||
|
||||
/* Events */
|
||||
.fc-dark .fc .fc-event {
|
||||
border-radius: 6px;
|
||||
border: none;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 500;
|
||||
padding: 1px 5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.fc-dark .fc .fc-event:hover {
|
||||
filter: brightness(1.12);
|
||||
}
|
||||
.fc-dark .fc .fc-daygrid-event .fc-event-title {
|
||||
font-weight: 500;
|
||||
}
|
||||
.fc-dark .fc .fc-daygrid-more-link {
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
font-size: 0.68rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.fc-dark .fc .fc-daygrid-more-link:hover {
|
||||
color: #fff;
|
||||
}
|
||||
.fc-dark .fc .fc-popover {
|
||||
background: #16161f;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
.fc-dark .fc .fc-popover-header {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* Time grid (week/day) */
|
||||
.fc-dark .fc .fc-timegrid-slot-label-cushion,
|
||||
.fc-dark .fc .fc-timegrid-axis-cushion {
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
font-size: 0.68rem;
|
||||
}
|
||||
|
||||
/* List / agenda view */
|
||||
.fc-dark .fc .fc-list {
|
||||
border-color: var(--fc-border-color);
|
||||
}
|
||||
.fc-dark .fc .fc-list-day-cushion {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
color: #fff;
|
||||
}
|
||||
.fc-dark .fc .fc-list-event:hover td {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
.fc-dark .fc .fc-list-event-title,
|
||||
.fc-dark .fc .fc-list-event-time {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
.fc-dark .fc .fc-list-empty {
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
@@ -1,52 +1,125 @@
|
||||
import { redirect } from "next/navigation"
|
||||
import { and, eq, gte, lte } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { rent_payments, leases } from "@/lib/db/schema"
|
||||
import { profiles, rent_payments, leases, inspections } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { CalendarClient } from "./calendar-client"
|
||||
import { getAccountContext } from "@/lib/account"
|
||||
import { CalendarClient, type CalEvent } from "./calendar-client"
|
||||
|
||||
export const metadata = { title: "Calendar" }
|
||||
|
||||
const RENT_COLOR = (s: string) =>
|
||||
s === "paid" ? "#10b981" : s === "overdue" ? "#ef4444" : "#6366f1"
|
||||
const LEASE_COLOR = "#f59e0b"
|
||||
const INSPECTION_COLOR = "#14b8a6"
|
||||
|
||||
export default async function CalendarPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const now = new Date()
|
||||
const rangeStart = new Date(now.getFullYear(), now.getMonth() - 1, 1)
|
||||
const rangeEnd = new Date(now.getFullYear(), now.getMonth() + 3, 0)
|
||||
const ctx = await getAccountContext(user.id)
|
||||
const ownerId = ctx.ownerId
|
||||
|
||||
const [payments, leaseList] = await Promise.all([
|
||||
const now = new Date()
|
||||
const rangeStart = new Date(now.getFullYear(), now.getMonth() - 3, 1)
|
||||
const rangeEnd = new Date(now.getFullYear(), now.getMonth() + 12, 0)
|
||||
const iso = (d: Date) => d.toISOString().slice(0, 10)
|
||||
|
||||
const [payments, leaseList, inspectionList, profile] = await Promise.all([
|
||||
db.query.rent_payments.findMany({
|
||||
where: and(
|
||||
eq(rent_payments.user_id, user.id),
|
||||
gte(rent_payments.due_date, rangeStart.toISOString().slice(0, 10)),
|
||||
lte(rent_payments.due_date, rangeEnd.toISOString().slice(0, 10))
|
||||
eq(rent_payments.user_id, ownerId),
|
||||
gte(rent_payments.due_date, iso(rangeStart)),
|
||||
lte(rent_payments.due_date, iso(rangeEnd))
|
||||
),
|
||||
columns: { id: true, due_date: true, amount: true, status: true },
|
||||
with: {
|
||||
tenant: { columns: { first_name: true, last_name: true } },
|
||||
},
|
||||
with: { tenant: { columns: { first_name: true, last_name: true } }, property: { columns: { name: true } }, unit: { columns: { unit_number: true } } },
|
||||
}),
|
||||
db.query.leases.findMany({
|
||||
where: and(
|
||||
eq(leases.user_id, user.id),
|
||||
gte(leases.lease_end, new Date().toISOString().slice(0, 10))
|
||||
),
|
||||
where: and(eq(leases.user_id, ownerId), eq(leases.status, "active")),
|
||||
columns: { id: true, lease_end: true },
|
||||
with: {
|
||||
tenant: { columns: { first_name: true, last_name: true } },
|
||||
property: { columns: { name: true } },
|
||||
},
|
||||
with: { tenant: { columns: { first_name: true, last_name: true } }, property: { columns: { name: true } } },
|
||||
}),
|
||||
db.query.inspections.findMany({
|
||||
where: and(eq(inspections.user_id, ownerId), gte(inspections.date, iso(rangeStart)), lte(inspections.date, iso(rangeEnd))),
|
||||
columns: { id: true, date: true, type: true, status: true },
|
||||
with: { property: { columns: { name: true } }, unit: { columns: { unit_number: true } } },
|
||||
}),
|
||||
db.query.profiles.findFirst({ where: eq(profiles.id, ownerId), columns: { calendar_token: true } }),
|
||||
])
|
||||
|
||||
const events: CalEvent[] = [
|
||||
...payments.map((p) => {
|
||||
const who = `${p.tenant?.first_name ?? ""} ${p.tenant?.last_name ?? ""}`.trim() || "Tenant"
|
||||
const color = RENT_COLOR(p.status)
|
||||
return {
|
||||
id: `rent-${p.id}`,
|
||||
title: `${who} · $${Number(p.amount).toLocaleString("en-US")}`,
|
||||
start: p.due_date!,
|
||||
allDay: true,
|
||||
backgroundColor: color,
|
||||
borderColor: color,
|
||||
editable: ctx.canWrite,
|
||||
extendedProps: {
|
||||
type: "rent" as const,
|
||||
entityId: p.id,
|
||||
status: p.status,
|
||||
subtitle: `${p.property?.name ?? ""}${p.unit ? ` · Unit ${p.unit.unit_number}` : ""}`,
|
||||
href: "/rent",
|
||||
},
|
||||
}
|
||||
}),
|
||||
...leaseList.map((l) => {
|
||||
const who = `${l.tenant?.first_name ?? ""} ${l.tenant?.last_name ?? ""}`.trim() || "Tenant"
|
||||
return {
|
||||
id: `lease-${l.id}`,
|
||||
title: `Lease ends: ${who}`,
|
||||
start: l.lease_end!,
|
||||
allDay: true,
|
||||
backgroundColor: LEASE_COLOR,
|
||||
borderColor: LEASE_COLOR,
|
||||
editable: false,
|
||||
extendedProps: {
|
||||
type: "lease" as const,
|
||||
entityId: l.id,
|
||||
subtitle: l.property?.name ?? "",
|
||||
href: `/leases/${l.id}`,
|
||||
},
|
||||
}
|
||||
}),
|
||||
...inspectionList.map((ins) => {
|
||||
const label = ins.type.replace("_", "-")
|
||||
return {
|
||||
id: `insp-${ins.id}`,
|
||||
title: `${label} inspection`,
|
||||
start: ins.date!,
|
||||
allDay: true,
|
||||
backgroundColor: INSPECTION_COLOR,
|
||||
borderColor: INSPECTION_COLOR,
|
||||
editable: ctx.canWrite,
|
||||
extendedProps: {
|
||||
type: "inspection" as const,
|
||||
entityId: ins.id,
|
||||
status: ins.status,
|
||||
subtitle: `${ins.property?.name ?? ""}${ins.unit ? ` · Unit ${ins.unit.unit_number}` : ""}`,
|
||||
href: "/inspections",
|
||||
},
|
||||
}
|
||||
}),
|
||||
]
|
||||
|
||||
const base = process.env.NEXT_PUBLIC_APP_URL ?? ""
|
||||
const subscribeUrl = profile?.calendar_token ? `${base}/api/calendar/${profile.calendar_token}.ics` : ""
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<div className="mb-6">
|
||||
<h2 className="text-lg font-bold text-white">Calendar</h2>
|
||||
<p className="text-sm text-white/40 mt-0.5">Rent due dates and lease expirations at a glance</p>
|
||||
<p className="text-sm text-white/40 mt-0.5">
|
||||
Rent due dates, lease expirations, and inspections — subscribe to sync with Google, Apple, or Outlook.
|
||||
</p>
|
||||
</div>
|
||||
<CalendarClient payments={payments ?? []} leases={leaseList ?? []} />
|
||||
<CalendarClient events={events} canWrite={ctx.canWrite} subscribeUrl={subscribeUrl} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { profiles } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import {
|
||||
getDashboardStats,
|
||||
getRecentRentPayments,
|
||||
@@ -33,20 +34,11 @@ function GreetingBanner({ name }: { name: string }) {
|
||||
const dateStr = now.toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", year: "numeric" })
|
||||
|
||||
return (
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-8">
|
||||
<div>
|
||||
<h2 className="text-xl font-bold text-white">
|
||||
{greeting}, {name?.split(" ")[0] ?? "there"} 👋
|
||||
</h2>
|
||||
<p className="text-sm text-white/40 mt-0.5">{dateStr}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 rounded-xl border border-emerald-500/20 bg-emerald-500/5 px-4 py-2">
|
||||
<div className="relative flex h-2 w-2">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
|
||||
<span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-400" />
|
||||
</div>
|
||||
<span className="text-xs font-medium text-emerald-400">All systems operational</span>
|
||||
</div>
|
||||
<div className="mb-8">
|
||||
<h2 className="text-xl font-bold text-white">
|
||||
{greeting}, {name?.split(" ")[0] ?? "there"} 👋
|
||||
</h2>
|
||||
<p className="text-sm text-white/40 mt-0.5">{dateStr}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -96,23 +88,32 @@ export default async function DashboardPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
// Fetch profile for greeting
|
||||
// Data is scoped to the effective owner's portfolio (team access).
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
// Fetch profile for greeting (the logged-in user's own name / onboarding state).
|
||||
const profile = await db.query.profiles.findFirst({
|
||||
where: eq(profiles.id, user.id),
|
||||
columns: { full_name: true },
|
||||
columns: { full_name: true, onboarding_completed: true },
|
||||
})
|
||||
|
||||
const [stats, recentPayments, openMaintenance, expiringLeases, monthlyRevenue, expenseBreakdown] = await Promise.all([
|
||||
getDashboardStats(user.id),
|
||||
getRecentRentPayments(user.id),
|
||||
getOpenMaintenanceRequests(user.id),
|
||||
getExpiringLeases(user.id),
|
||||
getMonthlyRevenue(user.id),
|
||||
getExpenseBreakdown(user.id),
|
||||
getDashboardStats(ownerId),
|
||||
getRecentRentPayments(ownerId),
|
||||
getOpenMaintenanceRequests(ownerId),
|
||||
getExpiringLeases(ownerId),
|
||||
getMonthlyRevenue(ownerId),
|
||||
getExpenseBreakdown(ownerId),
|
||||
])
|
||||
|
||||
const hasData = stats.totalProperties > 0
|
||||
|
||||
// New users who haven't finished onboarding and have no data go through the
|
||||
// dedicated onboarding flow first.
|
||||
if (!(profile as { onboarding_completed?: boolean })?.onboarding_completed && !hasData) {
|
||||
redirect("/onboarding")
|
||||
}
|
||||
|
||||
const rentTrendPct = stats.rentCollectedLastMonth > 0
|
||||
? Math.round(((stats.rentCollectedThisMonth - stats.rentCollectedLastMonth) / stats.rentCollectedLastMonth) * 100)
|
||||
: null
|
||||
|
||||
@@ -3,6 +3,7 @@ import { asc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { ExpenseForm } from "@/components/forms/expense-form"
|
||||
import { BackButton } from "@/components/ui/back-button"
|
||||
|
||||
@@ -12,8 +13,10 @@ export default async function NewExpensePage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const propertyList = await db.query.properties.findMany({
|
||||
where: eq(properties.user_id, user.id),
|
||||
where: eq(properties.user_id, ownerId),
|
||||
columns: { id: true, name: true },
|
||||
with: {
|
||||
units: { columns: { id: true, unit_number: true } },
|
||||
|
||||
@@ -3,6 +3,7 @@ import { asc, desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { expenses, properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { ExpensesClient } from "./expenses-client"
|
||||
|
||||
export const metadata = { title: "Expenses" }
|
||||
@@ -11,9 +12,11 @@ export default async function ExpensesPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const [expenseList, propertyList] = await Promise.all([
|
||||
db.query.expenses.findMany({
|
||||
where: eq(expenses.user_id, user.id),
|
||||
where: eq(expenses.user_id, ownerId),
|
||||
with: {
|
||||
property: { columns: { name: true } },
|
||||
unit: { columns: { unit_number: true } },
|
||||
@@ -23,7 +26,7 @@ export default async function ExpensesPage() {
|
||||
db
|
||||
.select({ id: properties.id, name: properties.name })
|
||||
.from(properties)
|
||||
.where(eq(properties.user_id, user.id))
|
||||
.where(eq(properties.user_id, ownerId))
|
||||
.orderBy(asc(properties.name)),
|
||||
])
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { asc, desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { follow_up_rules, follow_up_log } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { FollowUpsClient } from "./follow-ups-client"
|
||||
|
||||
export const metadata = { title: "Automated Follow-ups" }
|
||||
@@ -11,16 +12,18 @@ export default async function FollowUpsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const [rules, logs] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(follow_up_rules)
|
||||
.where(eq(follow_up_rules.user_id, user.id))
|
||||
.where(eq(follow_up_rules.user_id, ownerId))
|
||||
.orderBy(asc(follow_up_rules.created_at)),
|
||||
db
|
||||
.select()
|
||||
.from(follow_up_log)
|
||||
.where(eq(follow_up_log.user_id, user.id))
|
||||
.where(eq(follow_up_log.user_id, ownerId))
|
||||
.orderBy(desc(follow_up_log.created_at))
|
||||
.limit(30),
|
||||
])
|
||||
|
||||
@@ -3,6 +3,7 @@ import { and, desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { ai_recommendations, activity_log } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { ImpactClient } from "./impact-client"
|
||||
|
||||
export const metadata = { title: "AI Impact" }
|
||||
@@ -11,15 +12,17 @@ export default async function ImpactPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const [recs, activityRows] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(ai_recommendations)
|
||||
.where(eq(ai_recommendations.user_id, user.id)),
|
||||
.where(eq(ai_recommendations.user_id, ownerId)),
|
||||
db
|
||||
.select()
|
||||
.from(activity_log)
|
||||
.where(and(eq(activity_log.user_id, user.id), eq(activity_log.type, "ai_action")))
|
||||
.where(and(eq(activity_log.user_id, ownerId), eq(activity_log.type, "ai_action")))
|
||||
.orderBy(desc(activity_log.created_at))
|
||||
.limit(20),
|
||||
])
|
||||
|
||||
@@ -19,8 +19,8 @@ const typeColors: Record<string, string> = {
|
||||
}
|
||||
|
||||
const statusIcon: Record<string, React.ElementType> = {
|
||||
draft: Clock,
|
||||
completed: CheckCircle2,
|
||||
draft: Clock,
|
||||
complete: CheckCircle2,
|
||||
}
|
||||
|
||||
export function InspectionManager({ inspections: initial, properties }: { inspections: any[]; properties: any[] }) {
|
||||
@@ -44,7 +44,7 @@ export function InspectionManager({ inspections: initial, properties }: { inspec
|
||||
const cls = "w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2.5 text-sm text-white placeholder-white/30 outline-none focus:border-indigo-500/50 focus:ring-1 focus:ring-indigo-500 transition"
|
||||
|
||||
async function toggleStatus(id: string, current: string) {
|
||||
const next = current === "completed" ? "draft" : "completed"
|
||||
const next = current === "complete" ? "draft" : "complete"
|
||||
const res = await fetch(`/api/inspections/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -52,7 +52,7 @@ export function InspectionManager({ inspections: initial, properties }: { inspec
|
||||
})
|
||||
if (res.ok) {
|
||||
setInspections(v => v.map(i => i.id === id ? { ...i, status: next } : i))
|
||||
toast.success(next === "completed" ? "Marked complete" : "Marked draft")
|
||||
toast.success(next === "complete" ? "Marked complete" : "Marked draft")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,9 +161,9 @@ export function InspectionManager({ inspections: initial, properties }: { inspec
|
||||
<button
|
||||
onClick={() => toggleStatus(ins.id, ins.status)}
|
||||
className="flex items-center gap-1 text-xs hover:opacity-80 transition"
|
||||
title={ins.status === "completed" ? "Mark as draft" : "Mark as complete"}
|
||||
title={ins.status === "complete" ? "Mark as draft" : "Mark as complete"}
|
||||
>
|
||||
<StatusIcon className={`h-3.5 w-3.5 ${ins.status === "completed" ? "text-emerald-400" : "text-white/30"}`} />
|
||||
<StatusIcon className={`h-3.5 w-3.5 ${ins.status === "complete" ? "text-emerald-400" : "text-white/30"}`} />
|
||||
<span className="text-white/30 capitalize">{ins.status}</span>
|
||||
</button>
|
||||
<button
|
||||
|
||||
@@ -3,6 +3,7 @@ import { desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { inspections, properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { InspectionManager } from "./inspection-manager"
|
||||
|
||||
export const metadata = { title: "Inspections" }
|
||||
@@ -11,9 +12,11 @@ export default async function InspectionsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const [inspectionList, propertyList] = await Promise.all([
|
||||
db.query.inspections.findMany({
|
||||
where: eq(inspections.user_id, user.id),
|
||||
where: eq(inspections.user_id, ownerId),
|
||||
with: {
|
||||
property: { columns: { name: true } },
|
||||
unit: { columns: { unit_number: true } },
|
||||
@@ -21,7 +24,7 @@ export default async function InspectionsPage() {
|
||||
orderBy: desc(inspections.created_at),
|
||||
}),
|
||||
db.query.properties.findMany({
|
||||
where: eq(properties.user_id, user.id),
|
||||
where: eq(properties.user_id, ownerId),
|
||||
columns: { id: true, name: true },
|
||||
with: {
|
||||
units: { columns: { id: true, unit_number: true } },
|
||||
|
||||
@@ -2,7 +2,9 @@ import { redirect } from "next/navigation"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { profiles } from "@/lib/db/schema"
|
||||
import { getSession } from "@/lib/session"
|
||||
import { getSession, isAdminUser } from "@/lib/session"
|
||||
import { getMaintenanceMode } from "@/lib/settings"
|
||||
import { MaintenanceScreen } from "@/components/shared/maintenance-screen"
|
||||
import { Sidebar } from "@/components/dashboard/sidebar"
|
||||
import { Header } from "@/components/dashboard/header"
|
||||
import { CommandPalette } from "@/components/dashboard/command-palette"
|
||||
@@ -19,6 +21,12 @@ export default async function DashboardLayout({ children }: { children: React.Re
|
||||
redirect("/login")
|
||||
}
|
||||
|
||||
// Site maintenance mode: everyone except admins sees the maintenance screen.
|
||||
const maintenance = await getMaintenanceMode()
|
||||
if (maintenance.enabled && !isAdminUser(user)) {
|
||||
return <MaintenanceScreen message={maintenance.message} />
|
||||
}
|
||||
|
||||
const profile = await db.query.profiles.findFirst({
|
||||
where: eq(profiles.id, user.id),
|
||||
})
|
||||
@@ -30,7 +38,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
|
||||
<div className="flex h-screen flex-col bg-[#09090b] overflow-hidden">
|
||||
{impersonating && <ImpersonationBanner label={profile?.email ?? user.email} />}
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
<Sidebar profile={profile ?? null} />
|
||||
<Sidebar profile={profile ?? null} isAdmin={isAdminUser(user)} />
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
<Header />
|
||||
<main id="main-scroll" className="flex-1 overflow-y-auto p-4 sm:p-6">
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
import { and, asc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { tenants as tenantsTable, properties, leases as leasesTable } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { LeaseForm } from "@/components/forms/lease-form"
|
||||
import { BackButton } from "@/components/ui/back-button"
|
||||
|
||||
export const metadata = { title: "Edit Lease" }
|
||||
|
||||
export default async function EditLeasePage({ params }: { params: Promise<{ leaseId: string }> }) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const { leaseId } = await params
|
||||
|
||||
const [lease, tenants, properties_] = await Promise.all([
|
||||
db.query.leases.findFirst({
|
||||
where: and(eq(leasesTable.id, leaseId), eq(leasesTable.user_id, ownerId)),
|
||||
with: {
|
||||
tenant: { columns: { id: true, first_name: true, last_name: true } },
|
||||
},
|
||||
}),
|
||||
db
|
||||
.select({
|
||||
id: tenantsTable.id,
|
||||
first_name: tenantsTable.first_name,
|
||||
last_name: tenantsTable.last_name,
|
||||
unit_id: tenantsTable.unit_id,
|
||||
property_id: tenantsTable.property_id,
|
||||
})
|
||||
.from(tenantsTable)
|
||||
.where(and(eq(tenantsTable.user_id, ownerId), eq(tenantsTable.status, "active")))
|
||||
.orderBy(asc(tenantsTable.first_name)),
|
||||
db.query.properties.findMany({
|
||||
where: eq(properties.user_id, ownerId),
|
||||
columns: { id: true, name: true },
|
||||
with: {
|
||||
units: { columns: { id: true, unit_number: true } },
|
||||
},
|
||||
orderBy: asc(properties.name),
|
||||
}),
|
||||
])
|
||||
|
||||
if (!lease) notFound()
|
||||
|
||||
// Ensure the lease's own tenant is selectable even if now inactive.
|
||||
const tenantList = tenants.some((t) => t.id === lease.tenant_id)
|
||||
? tenants
|
||||
: [
|
||||
{
|
||||
id: lease.tenant_id,
|
||||
first_name: lease.tenant?.first_name ?? "",
|
||||
last_name: lease.tenant?.last_name ?? "",
|
||||
unit_id: lease.unit_id,
|
||||
property_id: lease.property_id,
|
||||
},
|
||||
...tenants,
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl space-y-6">
|
||||
<BackButton href={`/leases/${leaseId}`} />
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-white">Edit Lease</h2>
|
||||
<p className="text-sm text-white/40">
|
||||
{lease.tenant?.first_name} {lease.tenant?.last_name}
|
||||
</p>
|
||||
</div>
|
||||
<LeaseForm tenants={tenantList} properties={properties_ ?? []} lease={lease} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { leases as leasesTable } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getAccountContext } from "@/lib/account"
|
||||
import { listAdapters, listRequestsForLease } from "@/lib/esign"
|
||||
import Link from "next/link"
|
||||
import { FileText, ExternalLink } from "lucide-react"
|
||||
import { formatCurrency, formatDate, daysUntil } from "@/lib/utils"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { LeaseActions } from "@/components/forms/lease-actions"
|
||||
import { EsignLease } from "@/components/forms/esign-lease"
|
||||
|
||||
export const metadata = { title: "Lease" }
|
||||
|
||||
const statusColors: Record<string, string> = {
|
||||
active: "text-emerald-400 bg-emerald-500/10 border-emerald-500/20",
|
||||
expired: "text-red-400 bg-red-500/10 border-red-500/20",
|
||||
terminated: "text-white/40 bg-white/5 border-white/10",
|
||||
renewed: "text-blue-400 bg-blue-500/10 border-blue-500/20",
|
||||
}
|
||||
|
||||
const leaseTypeLabels: Record<string, string> = {
|
||||
fixed: "Fixed Term",
|
||||
month_to_month: "Month-to-Month",
|
||||
}
|
||||
|
||||
function InfoRow({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-4 py-3">
|
||||
<span className="text-sm text-white/40">{label}</span>
|
||||
<span className="text-right text-sm font-medium text-white">{children}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default async function LeaseDetailPage({ params }: { params: Promise<{ leaseId: string }> }) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ctx = await getAccountContext(user.id)
|
||||
const ownerId = ctx.ownerId
|
||||
|
||||
const { leaseId } = await params
|
||||
|
||||
const lease = await db.query.leases.findFirst({
|
||||
where: and(eq(leasesTable.id, leaseId), eq(leasesTable.user_id, ownerId)),
|
||||
with: {
|
||||
tenant: { columns: { id: true, first_name: true, last_name: true, email: true } },
|
||||
property: { columns: { name: true } },
|
||||
unit: { columns: { unit_number: true } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!lease) notFound()
|
||||
|
||||
const esignRequests = await listRequestsForLease(ownerId, leaseId)
|
||||
const esignProviders = listAdapters()
|
||||
const canSendEsign = ctx.canWrite && !!lease.document_url && !!lease.tenant?.email
|
||||
const esignDisabledReason = !ctx.canWrite
|
||||
? "You have read-only access."
|
||||
: !lease.document_url
|
||||
? "Upload a lease document to enable e-signature."
|
||||
: !lease.tenant?.email
|
||||
? "The tenant has no email address on file."
|
||||
: ""
|
||||
|
||||
const days = daysUntil(lease.lease_end)
|
||||
const totalDays = Math.max(
|
||||
0,
|
||||
Math.round(
|
||||
(new Date(lease.lease_end).getTime() - new Date(lease.lease_start).getTime()) /
|
||||
(1000 * 60 * 60 * 24)
|
||||
)
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl space-y-6">
|
||||
{/* Breadcrumb */}
|
||||
<div className="flex items-center gap-2 text-sm text-white/40">
|
||||
<Link href="/leases" className="hover:text-white transition">Leases</Link>
|
||||
<span>/</span>
|
||||
<span className="text-white/70">
|
||||
{lease.tenant?.first_name} {lease.tenant?.last_name}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex h-14 w-14 items-center justify-center rounded-2xl border border-indigo-500/20 bg-indigo-600/20 text-indigo-400">
|
||||
<FileText className="h-6 w-6" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="text-xl font-bold text-white">
|
||||
{lease.tenant?.first_name} {lease.tenant?.last_name}
|
||||
</h2>
|
||||
<span className={cn("rounded-md border px-2 py-0.5 text-xs font-medium capitalize", statusColors[lease.status] ?? statusColors.active)}>
|
||||
{lease.status}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-white/50">
|
||||
{lease.property?.name} · Unit {lease.unit?.unit_number ?? "—"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LeaseActions lease={lease} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
{/* Main */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
{/* Term */}
|
||||
<div className="rounded-xl border border-white/[0.06] bg-[#16161f]">
|
||||
<div className="border-b border-white/[0.06] px-5 py-4">
|
||||
<h3 className="text-sm font-semibold text-white">Lease Term</h3>
|
||||
</div>
|
||||
<div className="divide-y divide-white/[0.04] px-5">
|
||||
<InfoRow label="Start date">{formatDate(lease.lease_start)}</InfoRow>
|
||||
<InfoRow label="End date">{formatDate(lease.lease_end)}</InfoRow>
|
||||
<InfoRow label="Duration">{totalDays} days</InfoRow>
|
||||
<InfoRow label={days <= 0 ? "Expired" : "Ends in"}>
|
||||
{lease.status === "active"
|
||||
? days <= 0
|
||||
? <span className="text-red-400">{Math.abs(days)} days ago</span>
|
||||
: <span className={days <= 30 ? "text-amber-400" : "text-white"}>{days} days</span>
|
||||
: <span className="text-white/40">—</span>}
|
||||
</InfoRow>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Financials */}
|
||||
<div className="rounded-xl border border-white/[0.06] bg-[#16161f]">
|
||||
<div className="border-b border-white/[0.06] px-5 py-4">
|
||||
<h3 className="text-sm font-semibold text-white">Financials</h3>
|
||||
</div>
|
||||
<div className="divide-y divide-white/[0.04] px-5">
|
||||
<InfoRow label="Monthly rent">
|
||||
{formatCurrency(lease.rent_amount)}<span className="text-xs text-white/30">/mo</span>
|
||||
</InfoRow>
|
||||
<InfoRow label="Security deposit">
|
||||
{lease.security_deposit != null ? formatCurrency(lease.security_deposit) : <span className="text-white/40">—</span>}
|
||||
</InfoRow>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Notes */}
|
||||
{lease.notes && (
|
||||
<div className="rounded-xl border border-white/[0.06] bg-[#16161f]">
|
||||
<div className="border-b border-white/[0.06] px-5 py-4">
|
||||
<h3 className="text-sm font-semibold text-white">Notes</h3>
|
||||
</div>
|
||||
<p className="whitespace-pre-wrap px-5 py-4 text-sm text-white/60">{lease.notes}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Sidebar */}
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-xl border border-white/[0.06] bg-[#16161f] p-5 space-y-3">
|
||||
<h3 className="text-xs font-medium uppercase tracking-wider text-white/30">Details</h3>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-white/40">Tenant</span>
|
||||
{lease.tenant?.id ? (
|
||||
<Link href={`/tenants/${lease.tenant.id}`} className="text-sm font-medium text-indigo-400 hover:text-indigo-300 transition">
|
||||
{lease.tenant.first_name} {lease.tenant.last_name}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-sm font-medium text-white">
|
||||
{lease.tenant?.first_name} {lease.tenant?.last_name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-white/40">Property</span>
|
||||
<span className="text-sm font-medium text-white">{lease.property?.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-white/40">Unit</span>
|
||||
<span className="text-sm font-medium text-white">{lease.unit?.unit_number ?? "—"}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-white/40">Type</span>
|
||||
<span className="text-sm font-medium text-white">{leaseTypeLabels[lease.lease_type] ?? lease.lease_type}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-white/40">Auto-renew</span>
|
||||
<span className={cn("text-sm font-medium", lease.auto_renew ? "text-emerald-400" : "text-white/40")}>
|
||||
{lease.auto_renew ? "Enabled" : "Disabled"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{lease.document_url && (
|
||||
<a
|
||||
href={lease.document_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center justify-between rounded-xl border border-white/[0.06] bg-[#16161f] p-5 transition hover:border-white/15"
|
||||
>
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-white">
|
||||
<FileText className="h-4 w-4 text-indigo-400" />
|
||||
Lease document
|
||||
</div>
|
||||
<ExternalLink className="h-4 w-4 text-white/40" />
|
||||
</a>
|
||||
)}
|
||||
|
||||
<EsignLease
|
||||
leaseId={leaseId}
|
||||
providers={esignProviders}
|
||||
requests={esignRequests}
|
||||
canSend={canSendEsign}
|
||||
disabledReason={esignDisabledReason}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { and, asc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { tenants as tenantsTable, properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { LeaseForm } from "@/components/forms/lease-form"
|
||||
import { BackButton } from "@/components/ui/back-button"
|
||||
|
||||
@@ -12,6 +13,8 @@ export default async function NewLeasePage({ searchParams }: { searchParams: Pro
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const params = await searchParams
|
||||
const prefill = {
|
||||
tenant_id: params.tenant_id ?? "",
|
||||
@@ -30,10 +33,10 @@ export default async function NewLeasePage({ searchParams }: { searchParams: Pro
|
||||
property_id: tenantsTable.property_id,
|
||||
})
|
||||
.from(tenantsTable)
|
||||
.where(and(eq(tenantsTable.user_id, user.id), eq(tenantsTable.status, "active")))
|
||||
.where(and(eq(tenantsTable.user_id, ownerId), eq(tenantsTable.status, "active")))
|
||||
.orderBy(asc(tenantsTable.first_name)),
|
||||
db.query.properties.findMany({
|
||||
where: eq(properties.user_id, user.id),
|
||||
where: eq(properties.user_id, ownerId),
|
||||
columns: { id: true, name: true },
|
||||
with: {
|
||||
units: { columns: { id: true, unit_number: true } },
|
||||
|
||||
@@ -3,6 +3,7 @@ import { eq, asc } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { leases as leasesTable } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import Link from "next/link"
|
||||
import { FileText, AlertTriangle, ArrowRight } from "lucide-react"
|
||||
import { EmptyState } from "@/components/shared/empty-state"
|
||||
@@ -34,8 +35,10 @@ export default async function LeasesPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const leases = await db.query.leases.findMany({
|
||||
where: eq(leasesTable.user_id, user.id),
|
||||
where: eq(leasesTable.user_id, ownerId),
|
||||
with: {
|
||||
tenant: { columns: { first_name: true, last_name: true } },
|
||||
property: { columns: { name: true } },
|
||||
@@ -90,9 +93,9 @@ export default async function LeasesPage() {
|
||||
return (
|
||||
<tr key={lease.id} className="group hover:bg-white/[0.02] transition">
|
||||
<td className="px-5 py-3.5">
|
||||
<p className="text-sm font-medium text-white">
|
||||
<Link href={`/leases/${lease.id}`} className="text-sm font-medium text-white hover:text-indigo-300 transition">
|
||||
{lease.tenant?.first_name} {lease.tenant?.last_name}
|
||||
</p>
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-5 py-3.5">
|
||||
<p className="text-sm text-white/70">{lease.property?.name}</p>
|
||||
@@ -114,14 +117,22 @@ export default async function LeasesPage() {
|
||||
<DaysChip days={days} status={lease.status} />
|
||||
</td>
|
||||
<td className="px-5 py-3.5 text-right">
|
||||
{canRenew && (
|
||||
<div className="flex items-center justify-end gap-4">
|
||||
{canRenew && (
|
||||
<Link
|
||||
href={`/leases/new?tenant_id=${lease.tenant_id}&property_id=${lease.property_id}&unit_id=${lease.unit_id ?? ""}&rent_amount=${lease.rent_amount}`}
|
||||
className="inline-flex items-center gap-1 text-xs font-medium text-indigo-400 hover:text-indigo-300 transition"
|
||||
>
|
||||
Renew <ArrowRight className="h-3 w-3" />
|
||||
</Link>
|
||||
)}
|
||||
<Link
|
||||
href={`/leases/new?tenant_id=${lease.tenant_id}&property_id=${lease.property_id}&unit_id=${lease.unit_id ?? ""}&rent_amount=${lease.rent_amount}`}
|
||||
className="inline-flex items-center gap-1 text-xs font-medium text-indigo-400 hover:text-indigo-300 transition"
|
||||
href={`/leases/${lease.id}`}
|
||||
className="inline-flex items-center gap-1 text-xs font-medium text-white/50 hover:text-white transition"
|
||||
>
|
||||
Renew <ArrowRight className="h-3 w-3" />
|
||||
View <ArrowRight className="h-3 w-3" />
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
@@ -138,14 +149,14 @@ export default async function LeasesPage() {
|
||||
return (
|
||||
<div key={lease.id} className="rounded-xl border border-white/[0.06] bg-[#16161f] p-4 space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<Link href={`/leases/${lease.id}`} className="min-w-0">
|
||||
<p className="text-sm font-semibold text-white">
|
||||
{lease.tenant?.first_name} {lease.tenant?.last_name}
|
||||
</p>
|
||||
<p className="text-xs text-white/40 mt-0.5">
|
||||
{lease.property?.name} · Unit {lease.unit?.unit_number ?? "—"}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
<span className={cn("shrink-0 rounded-md border px-2 py-0.5 text-xs font-medium capitalize", statusColors[lease.status] ?? statusColors.active)}>
|
||||
{lease.status}
|
||||
</span>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { maintenance_requests } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import Link from "next/link"
|
||||
import { formatCurrency, formatDate } from "@/lib/utils"
|
||||
import { MaintenanceStatusBadge, PriorityBadge } from "@/components/dashboard/maintenance-status-badge"
|
||||
@@ -12,12 +13,14 @@ export default async function MaintenanceDetailPage({ params }: { params: Promis
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const { requestId } = await params
|
||||
|
||||
const req = await db.query.maintenance_requests.findFirst({
|
||||
where: and(
|
||||
eq(maintenance_requests.id, requestId),
|
||||
eq(maintenance_requests.user_id, user.id)
|
||||
eq(maintenance_requests.user_id, ownerId)
|
||||
),
|
||||
with: {
|
||||
property: { columns: { name: true, address_line1: true, city: true } },
|
||||
|
||||
@@ -3,6 +3,7 @@ import { and, asc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { properties, tenants } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { MaintenanceForm } from "@/components/forms/maintenance-form"
|
||||
import { BackButton } from "@/components/ui/back-button"
|
||||
|
||||
@@ -12,9 +13,11 @@ export default async function NewMaintenancePage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const [propertyList, tenantList] = await Promise.all([
|
||||
db.query.properties.findMany({
|
||||
where: eq(properties.user_id, user.id),
|
||||
where: eq(properties.user_id, ownerId),
|
||||
columns: { id: true, name: true },
|
||||
with: {
|
||||
units: { columns: { id: true, unit_number: true } },
|
||||
@@ -29,7 +32,7 @@ export default async function NewMaintenancePage() {
|
||||
unit_id: tenants.unit_id,
|
||||
})
|
||||
.from(tenants)
|
||||
.where(and(eq(tenants.user_id, user.id), eq(tenants.status, "active"))),
|
||||
.where(and(eq(tenants.user_id, ownerId), eq(tenants.status, "active"))),
|
||||
])
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,6 +3,7 @@ import { asc, desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { maintenance_requests, properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import Link from "next/link"
|
||||
import { Plus } from "lucide-react"
|
||||
import { MaintenanceList } from "./maintenance-list"
|
||||
@@ -13,9 +14,11 @@ export default async function MaintenancePage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const [requests, propertyList] = await Promise.all([
|
||||
db.query.maintenance_requests.findMany({
|
||||
where: eq(maintenance_requests.user_id, user.id),
|
||||
where: eq(maintenance_requests.user_id, ownerId),
|
||||
with: {
|
||||
property: { columns: { name: true } },
|
||||
unit: { columns: { unit_number: true } },
|
||||
@@ -26,7 +29,7 @@ export default async function MaintenancePage() {
|
||||
db
|
||||
.select({ id: properties.id, name: properties.name })
|
||||
.from(properties)
|
||||
.where(eq(properties.user_id, user.id))
|
||||
.where(eq(properties.user_id, ownerId))
|
||||
.orderBy(asc(properties.name)),
|
||||
])
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { redirect } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
import { eq, sql } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { profiles, properties, tenants, leases, rent_payments } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { completeOnboarding } from "@/app/actions/onboarding"
|
||||
import { Building2, Users, FileText, CreditCard, CheckCircle2, ArrowRight, Sparkles } from "lucide-react"
|
||||
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
async function count(table: typeof properties | typeof tenants | typeof leases | typeof rent_payments, userId: string) {
|
||||
const [row] = await db.select({ c: sql<number>`count(*)::int` }).from(table).where(eq(table.user_id, userId))
|
||||
return row?.c ?? 0
|
||||
}
|
||||
|
||||
export default async function OnboardingPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const profile = await db.query.profiles.findFirst({
|
||||
where: eq(profiles.id, user.id),
|
||||
columns: { onboarding_completed: true, full_name: true },
|
||||
})
|
||||
|
||||
// Users who already finished onboarding don't need this screen.
|
||||
if (profile?.onboarding_completed) redirect("/dashboard")
|
||||
|
||||
const [propCount, tenantCount, leaseCount, rentCount] = await Promise.all([
|
||||
count(properties, user.id),
|
||||
count(tenants, user.id),
|
||||
count(leases, user.id),
|
||||
count(rent_payments, user.id),
|
||||
])
|
||||
|
||||
const steps = [
|
||||
{ label: "Add your first property", desc: "Create a building or unit to manage.", href: "/properties/new", icon: Building2, done: propCount > 0 },
|
||||
{ label: "Add a tenant", desc: "Record who's renting from you.", href: "/tenants/new", icon: Users, done: tenantCount > 0 },
|
||||
{ label: "Set up a lease", desc: "Track term, rent, and deposit.", href: "/leases/new", icon: FileText, done: leaseCount > 0 },
|
||||
{ label: "Record a rent payment", desc: "Log or generate the first payment.", href: "/rent/new", icon: CreditCard, done: rentCount > 0 },
|
||||
]
|
||||
const doneCount = steps.filter((s) => s.done).length
|
||||
const firstName = profile?.full_name?.split(" ")[0]
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl py-4">
|
||||
<div className="mb-6 flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-indigo-600 shadow-lg shadow-indigo-500/25">
|
||||
<Sparkles className="h-5 w-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-white">
|
||||
Welcome{firstName ? `, ${firstName}` : ""} 👋
|
||||
</h1>
|
||||
<p className="text-sm text-white/50">Let's get your portfolio set up in four quick steps.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Progress */}
|
||||
<div className="mb-6">
|
||||
<div className="mb-1.5 flex items-center justify-between text-xs text-white/50">
|
||||
<span>{doneCount} of {steps.length} complete</span>
|
||||
<span>{Math.round((doneCount / steps.length) * 100)}%</span>
|
||||
</div>
|
||||
<div className="h-1.5 w-full overflow-hidden rounded-full bg-white/[0.06]">
|
||||
<div
|
||||
className="h-full rounded-full bg-gradient-to-r from-indigo-500 to-violet-500 transition-all"
|
||||
style={{ width: `${(doneCount / steps.length) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Steps */}
|
||||
<ol className="space-y-3">
|
||||
{steps.map((step, i) => (
|
||||
<li
|
||||
key={step.label}
|
||||
className={`flex items-center gap-4 rounded-2xl border p-4 transition-colors ${
|
||||
step.done
|
||||
? "border-emerald-500/20 bg-emerald-500/[0.04]"
|
||||
: "border-white/[0.06] bg-[#16161f]"
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-xl ${
|
||||
step.done ? "bg-emerald-500/15 text-emerald-400" : "bg-white/[0.04] text-white/50"
|
||||
}`}
|
||||
>
|
||||
{step.done ? <CheckCircle2 className="h-5 w-5" /> : <step.icon className="h-5 w-5" />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className={`text-sm font-semibold ${step.done ? "text-white/60 line-through" : "text-white"}`}>
|
||||
{i + 1}. {step.label}
|
||||
</p>
|
||||
<p className="text-xs text-white/40">{step.desc}</p>
|
||||
</div>
|
||||
{step.done ? (
|
||||
<span className="shrink-0 text-xs font-medium text-emerald-400">Done</span>
|
||||
) : (
|
||||
<Link
|
||||
href={step.href}
|
||||
className="flex shrink-0 items-center gap-1 rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-indigo-500"
|
||||
>
|
||||
Add <ArrowRight className="h-3.5 w-3.5" />
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
{/* Finish */}
|
||||
<form action={completeOnboarding} className="mt-6 flex items-center justify-between gap-3">
|
||||
<p className="text-xs text-white/40">You can always finish these later from the dashboard.</p>
|
||||
<button
|
||||
type="submit"
|
||||
className="shrink-0 rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/10"
|
||||
>
|
||||
{doneCount === steps.length ? "Finish setup" : "Skip to dashboard"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { ai_predictions } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { PredictionsClient } from "./predictions-client"
|
||||
|
||||
export const metadata = { title: "Predictive Analytics" }
|
||||
@@ -11,10 +12,12 @@ export default async function PredictionsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const predictions = await db
|
||||
.select()
|
||||
.from(ai_predictions)
|
||||
.where(eq(ai_predictions.user_id, user.id))
|
||||
.where(eq(ai_predictions.user_id, ownerId))
|
||||
.orderBy(desc(ai_predictions.created_at))
|
||||
|
||||
return <PredictionsClient predictions={predictions ?? []} />
|
||||
|
||||
@@ -3,15 +3,18 @@ import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
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 ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const { propertyId } = await params
|
||||
const property = await db.query.properties.findFirst({
|
||||
where: and(eq(properties.id, propertyId), eq(properties.user_id, user.id)),
|
||||
where: and(eq(properties.id, propertyId), eq(properties.user_id, ownerId)),
|
||||
})
|
||||
|
||||
if (!property) notFound()
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 { getEffectiveOwnerId } from "@/lib/account"
|
||||
import Link from "next/link"
|
||||
import { MapPin, Plus, BedDouble, Bath, Edit } from "lucide-react"
|
||||
import { formatCurrency, getOccupancyRate } from "@/lib/utils"
|
||||
@@ -10,11 +11,15 @@ 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"
|
||||
import { UnitActions } from "@/components/forms/unit-actions"
|
||||
import { PropertyMap } from "@/components/maps/property-map"
|
||||
|
||||
export default async function PropertyDetailPage({ params }: { params: Promise<{ propertyId: string }> }) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const { propertyId } = await params
|
||||
|
||||
const sixMonthsAgo = new Date()
|
||||
@@ -24,7 +29,7 @@ export default async function PropertyDetailPage({ params }: { params: Promise<{
|
||||
|
||||
const [property, payments, expenses] = await Promise.all([
|
||||
db.query.properties.findFirst({
|
||||
where: and(eq(propertiesTable.id, propertyId), eq(propertiesTable.user_id, user.id)),
|
||||
where: and(eq(propertiesTable.id, propertyId), eq(propertiesTable.user_id, ownerId)),
|
||||
with: {
|
||||
units: {
|
||||
with: {
|
||||
@@ -38,7 +43,7 @@ export default async function PropertyDetailPage({ params }: { params: Promise<{
|
||||
.from(rent_payments)
|
||||
.where(
|
||||
and(
|
||||
eq(rent_payments.user_id, user.id),
|
||||
eq(rent_payments.user_id, ownerId),
|
||||
eq(rent_payments.property_id, propertyId),
|
||||
gte(rent_payments.due_date, rangeStart)
|
||||
)
|
||||
@@ -48,7 +53,7 @@ export default async function PropertyDetailPage({ params }: { params: Promise<{
|
||||
.from(expensesTable)
|
||||
.where(
|
||||
and(
|
||||
eq(expensesTable.user_id, user.id),
|
||||
eq(expensesTable.user_id, ownerId),
|
||||
eq(expensesTable.property_id, propertyId),
|
||||
gte(expensesTable.expense_date, rangeStart)
|
||||
)
|
||||
@@ -167,8 +172,11 @@ export default async function PropertyDetailPage({ params }: { params: Promise<{
|
||||
)}
|
||||
</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 className="flex items-center gap-4">
|
||||
<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>
|
||||
<UnitActions propertyId={propertyId} unitId={unit.id} unitNumber={unit.unit_number} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
@@ -176,6 +184,28 @@ export default async function PropertyDetailPage({ params }: { params: Promise<{
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Location */}
|
||||
{property.latitude != null && property.longitude != null && (
|
||||
<div className="rounded-xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
|
||||
<div className="flex items-center gap-2 border-b border-white/[0.06] px-5 py-4">
|
||||
<MapPin className="h-4 w-4 text-indigo-400" />
|
||||
<h3 className="text-sm font-semibold text-white">Location</h3>
|
||||
</div>
|
||||
<PropertyMap
|
||||
className="h-72 w-full"
|
||||
markers={[
|
||||
{
|
||||
id: property.id,
|
||||
name: property.name,
|
||||
lat: property.latitude,
|
||||
lng: property.longitude,
|
||||
subtitle: `${property.address_line1}, ${property.city}${property.state ? `, ${property.state}` : ""}`,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Revenue chart */}
|
||||
<PropertyRevenueChart data={chartData} />
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { redirect } from "next/navigation"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { properties, units } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { BackButton } from "@/components/ui/back-button"
|
||||
import { UnitForm } from "@/components/forms/unit-form"
|
||||
|
||||
export const metadata = { title: "Edit Unit" }
|
||||
|
||||
export default async function EditUnitPage({ params }: { params: Promise<{ propertyId: string; unitId: string }> }) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const { propertyId, unitId } = await params
|
||||
|
||||
const [property, unit] = await Promise.all([
|
||||
db.query.properties.findFirst({
|
||||
where: and(eq(properties.id, propertyId), eq(properties.user_id, ownerId)),
|
||||
columns: { id: true, name: true },
|
||||
}),
|
||||
db.query.units.findFirst({
|
||||
where: and(eq(units.id, unitId), eq(units.property_id, propertyId), eq(units.user_id, ownerId)),
|
||||
}),
|
||||
])
|
||||
|
||||
if (!property || !unit) redirect(`/properties/${propertyId}`)
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl space-y-6">
|
||||
<BackButton href={`/properties/${propertyId}`} />
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-white">Edit Unit {unit.unit_number}</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} unit={unit} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { BackButton } from "@/components/ui/back-button"
|
||||
import { UnitForm } from "@/components/forms/unit-form"
|
||||
|
||||
@@ -12,10 +13,12 @@ export default async function NewUnitPage({ params }: { params: Promise<{ proper
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const { propertyId } = await params
|
||||
|
||||
const property = await db.query.properties.findFirst({
|
||||
where: and(eq(properties.id, propertyId), eq(properties.user_id, user.id)),
|
||||
where: and(eq(properties.id, propertyId), eq(properties.user_id, ownerId)),
|
||||
columns: { id: true, name: true },
|
||||
})
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@ 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 { getEffectiveOwnerId } from "@/lib/account"
|
||||
import Link from "next/link"
|
||||
import { Building2, MapPin, BedDouble, ArrowRight, TrendingUp } from "lucide-react"
|
||||
import { EmptyState } from "@/components/shared/empty-state"
|
||||
import { PropertyMap } from "@/components/maps/property-map"
|
||||
import { formatCurrency, getOccupancyRate } from "@/lib/utils"
|
||||
|
||||
export const metadata = { title: "Properties" }
|
||||
@@ -14,8 +16,10 @@ export default async function PropertiesPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const properties = await db.query.properties.findMany({
|
||||
where: eq(propertiesTable.user_id, user.id),
|
||||
where: eq(propertiesTable.user_id, ownerId),
|
||||
with: {
|
||||
units: { columns: { id: true, status: true, rent_amount: true } },
|
||||
},
|
||||
@@ -26,6 +30,17 @@ export default async function PropertiesPage() {
|
||||
return sum + (p.units ?? []).filter((u: any) => u.status === "occupied").reduce((s: number, u: any) => s + Number(u.rent_amount), 0)
|
||||
}, 0)
|
||||
|
||||
const mapMarkers = (properties ?? [])
|
||||
.filter((p: any) => p.latitude != null && p.longitude != null)
|
||||
.map((p: any) => ({
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
lat: p.latitude as number,
|
||||
lng: p.longitude as number,
|
||||
subtitle: `${p.address_line1 ? `${p.address_line1}, ` : ""}${p.city}${p.state ? `, ${p.state}` : ""}`,
|
||||
href: `/properties/${p.id}`,
|
||||
}))
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Page header */}
|
||||
@@ -39,6 +54,12 @@ export default async function PropertiesPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{mapMarkers.length > 0 && (
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
|
||||
<PropertyMap className="h-80 w-full" markers={mapMarkers} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!properties?.length ? (
|
||||
<EmptyState
|
||||
icon={Building2}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { ai_recommendations } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { RecommendationsClient } from "./recommendations-client"
|
||||
|
||||
export const metadata = { title: "AI Recommendations" }
|
||||
@@ -11,10 +12,12 @@ export default async function RecommendationsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const recommendations = await db
|
||||
.select()
|
||||
.from(ai_recommendations)
|
||||
.where(eq(ai_recommendations.user_id, user.id))
|
||||
.where(eq(ai_recommendations.user_id, ownerId))
|
||||
.orderBy(desc(ai_recommendations.created_at))
|
||||
|
||||
return <RecommendationsClient recommendations={recommendations ?? []} />
|
||||
|
||||
@@ -3,6 +3,7 @@ import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { leases as leasesTable } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { BulkGenerateForm } from "./bulk-generate-form"
|
||||
|
||||
export const metadata = { title: "Generate Rent" }
|
||||
@@ -11,8 +12,10 @@ export default async function GenerateRentPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const leases = await db.query.leases.findMany({
|
||||
where: and(eq(leasesTable.user_id, user.id), eq(leasesTable.status, "active")),
|
||||
where: and(eq(leasesTable.user_id, ownerId), eq(leasesTable.status, "active")),
|
||||
columns: { id: true, rent_amount: true },
|
||||
with: {
|
||||
tenant: { columns: { first_name: true, last_name: true } },
|
||||
|
||||
@@ -3,6 +3,7 @@ import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { tenants as tenantsTable, properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { BackButton } from "@/components/ui/back-button"
|
||||
import { RentCsvImport } from "./rent-csv-import"
|
||||
|
||||
@@ -12,8 +13,10 @@ export default async function ImportRentPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const tenants = await db.query.tenants.findMany({
|
||||
where: and(eq(tenantsTable.user_id, user.id), eq(tenantsTable.status, "active")),
|
||||
where: and(eq(tenantsTable.user_id, ownerId), eq(tenantsTable.status, "active")),
|
||||
columns: { id: true, first_name: true, last_name: true },
|
||||
with: {
|
||||
unit: { columns: { unit_number: true } },
|
||||
@@ -24,7 +27,7 @@ export default async function ImportRentPage() {
|
||||
const properties_ = await db
|
||||
.select({ id: properties.id, name: properties.name })
|
||||
.from(properties)
|
||||
.where(eq(properties.user_id, user.id))
|
||||
.where(eq(properties.user_id, ownerId))
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl space-y-6">
|
||||
|
||||
@@ -3,6 +3,7 @@ import { and, asc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { tenants as tenantsTable } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { RentPaymentForm } from "@/components/forms/rent-payment-form"
|
||||
import { BackButton } from "@/components/ui/back-button"
|
||||
|
||||
@@ -12,8 +13,10 @@ export default async function NewRentPaymentPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const tenants = await db.query.tenants.findMany({
|
||||
where: and(eq(tenantsTable.user_id, user.id), eq(tenantsTable.status, "active")),
|
||||
where: and(eq(tenantsTable.user_id, ownerId), eq(tenantsTable.status, "active")),
|
||||
columns: { id: true, first_name: true, last_name: true, property_id: true, unit_id: true },
|
||||
with: {
|
||||
unit: { columns: { unit_number: true, rent_amount: true } },
|
||||
|
||||
@@ -3,6 +3,7 @@ import { eq, desc } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { rent_payments } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import Link from "next/link"
|
||||
import { CreditCard, Plus, Upload } from "lucide-react"
|
||||
import { EmptyState } from "@/components/shared/empty-state"
|
||||
@@ -15,8 +16,10 @@ export default async function RentPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const payments = await db.query.rent_payments.findMany({
|
||||
where: eq(rent_payments.user_id, user.id),
|
||||
where: eq(rent_payments.user_id, ownerId),
|
||||
with: {
|
||||
tenant: { columns: { first_name: true, last_name: true } },
|
||||
property: { columns: { name: true } },
|
||||
|
||||
@@ -3,9 +3,11 @@ 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 { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { formatCurrency } from "@/lib/utils"
|
||||
import { TrendingUp, TrendingDown, Building2, DollarSign, Receipt, BarChart3 } from "lucide-react"
|
||||
import { ReportsClient } from "./reports-client"
|
||||
import { CsvExportButton } from "@/components/forms/csv-export-button"
|
||||
|
||||
export const metadata = { title: "Reports" }
|
||||
|
||||
@@ -13,6 +15,8 @@ export default async function ReportsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
// Last 6 months range
|
||||
const sixMonthsAgo = new Date()
|
||||
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 5)
|
||||
@@ -23,7 +27,7 @@ export default async function ReportsPage() {
|
||||
db
|
||||
.select({ id: propertiesTable.id, name: propertiesTable.name })
|
||||
.from(propertiesTable)
|
||||
.where(eq(propertiesTable.user_id, user.id)),
|
||||
.where(eq(propertiesTable.user_id, ownerId)),
|
||||
db
|
||||
.select({
|
||||
amount: rent_payments.amount,
|
||||
@@ -32,7 +36,7 @@ export default async function ReportsPage() {
|
||||
property_id: rent_payments.property_id,
|
||||
})
|
||||
.from(rent_payments)
|
||||
.where(and(eq(rent_payments.user_id, user.id), gte(rent_payments.due_date, rangeStart))),
|
||||
.where(and(eq(rent_payments.user_id, ownerId), gte(rent_payments.due_date, rangeStart))),
|
||||
db
|
||||
.select({
|
||||
amount: expensesTable.amount,
|
||||
@@ -41,7 +45,7 @@ export default async function ReportsPage() {
|
||||
category: expensesTable.category,
|
||||
})
|
||||
.from(expensesTable)
|
||||
.where(and(eq(expensesTable.user_id, user.id), gte(expensesTable.expense_date, rangeStart))),
|
||||
.where(and(eq(expensesTable.user_id, ownerId), gte(expensesTable.expense_date, rangeStart))),
|
||||
])
|
||||
|
||||
// Build monthly buckets for last 6 months
|
||||
@@ -79,6 +83,19 @@ export default async function ReportsPage() {
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header + CSV exports */}
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-white">Reports</h2>
|
||||
<p className="text-sm text-white/40">Revenue, expenses & profit — last 6 months</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<CsvExportButton endpoint="/api/export/rent" filename="rent-payments.csv" label="Rent CSV" />
|
||||
<CsvExportButton endpoint="/api/export/tenants" filename="tenants.csv" label="Tenants CSV" />
|
||||
<CsvExportButton endpoint="/api/expenses/export" filename="expenses.csv" label="Expenses CSV" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Summary KPI cards */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
||||
{[
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { redirect } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
import { desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { api_keys } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { ApiKeyManager, type ApiKeyRow } from "@/components/dashboard/api-key-manager"
|
||||
|
||||
export const metadata = { title: "API Keys" }
|
||||
|
||||
export default async function ApiKeysSettingsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: api_keys.id,
|
||||
name: api_keys.name,
|
||||
key_prefix: api_keys.key_prefix,
|
||||
created_at: api_keys.created_at,
|
||||
last_used_at: api_keys.last_used_at,
|
||||
revoked_at: api_keys.revoked_at,
|
||||
})
|
||||
.from(api_keys)
|
||||
.where(eq(api_keys.user_id, user.id))
|
||||
.orderBy(desc(api_keys.created_at))
|
||||
|
||||
const keys: ApiKeyRow[] = rows
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl space-y-6">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-white">API Keys</h2>
|
||||
<p className="text-sm text-white/40">
|
||||
Create keys to authenticate with the public REST API. See the{" "}
|
||||
<Link
|
||||
href="/api-docs"
|
||||
className="text-indigo-400 underline underline-offset-2 transition hover:text-indigo-300"
|
||||
>
|
||||
API documentation
|
||||
</Link>{" "}
|
||||
for available endpoints.
|
||||
</p>
|
||||
</div>
|
||||
<ApiKeyManager initialKeys={keys} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -5,7 +5,9 @@ import { profiles, properties, tenants } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { CheckoutButton } from "@/components/forms/checkout-button"
|
||||
import { PortalButton } from "@/components/forms/portal-button"
|
||||
import { getPlanLabel, PLAN_LIMITS } from "@/lib/stripe/plans"
|
||||
import { PaypalCancelButton } from "@/components/forms/paypal-cancel-button"
|
||||
import { getPlanLabel, PLAN_LIMITS, annualEnabled } from "@/lib/stripe/plans"
|
||||
import { paypalConfigured } from "@/lib/paypal/client"
|
||||
import { Check } from "lucide-react"
|
||||
import type { Plan } from "@/types"
|
||||
|
||||
@@ -57,7 +59,7 @@ const PLANS = [
|
||||
export default async function BillingPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ success?: string; canceled?: string }>
|
||||
searchParams: Promise<{ success?: string; canceled?: string; error?: string }>
|
||||
}) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
@@ -70,13 +72,18 @@ export default async function BillingPage({
|
||||
plan_expires_at: true,
|
||||
stripe_customer_id: true,
|
||||
stripe_subscription_id: true,
|
||||
paypal_subscription_id: true,
|
||||
billing_provider: true,
|
||||
},
|
||||
})
|
||||
|
||||
const params = await searchParams
|
||||
const currentPlan = (profile?.plan ?? "starter") as Plan
|
||||
const hasStripeAccount = !!profile?.stripe_customer_id
|
||||
const isPaypal = profile?.billing_provider === "paypal" || !!profile?.paypal_subscription_id
|
||||
const paypalEnabled = paypalConfigured()
|
||||
const limits = PLAN_LIMITS[currentPlan]
|
||||
const canBillAnnually = annualEnabled()
|
||||
|
||||
const [[{ count: propertiesUsed }], [{ count: tenantsUsed }]] = await Promise.all([
|
||||
db
|
||||
@@ -106,6 +113,11 @@ export default async function BillingPage({
|
||||
Checkout canceled — no charge was made.
|
||||
</div>
|
||||
)}
|
||||
{params.error === "paypal" && (
|
||||
<div className="rounded-xl border border-red-500/20 bg-red-500/10 px-5 py-4 text-sm text-red-400">
|
||||
We couldn't complete your PayPal payment. No charge was made — please try again.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Current plan */}
|
||||
<div className="rounded-xl border border-white/[0.06] bg-[#16161f] p-5">
|
||||
@@ -117,9 +129,12 @@ export default async function BillingPage({
|
||||
<p className="mt-0.5 text-xs text-white/40 capitalize">Status: {profile.subscription_status}</p>
|
||||
)}
|
||||
</div>
|
||||
{hasStripeAccount && currentPlan !== "starter" && currentPlan !== "lifetime" && (
|
||||
<PortalButton />
|
||||
)}
|
||||
{currentPlan !== "starter" && currentPlan !== "lifetime" &&
|
||||
(isPaypal ? (
|
||||
<PaypalCancelButton />
|
||||
) : hasStripeAccount ? (
|
||||
<PortalButton />
|
||||
) : null)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -177,7 +192,13 @@ export default async function BillingPage({
|
||||
{plan.key === "starter" ? "Free" : "Downgrade via portal"}
|
||||
</div>
|
||||
) : (
|
||||
<CheckoutButton plan={plan.key} label={plan.cta} highlight={plan.highlight} />
|
||||
<CheckoutButton
|
||||
plan={plan.key}
|
||||
label={plan.cta}
|
||||
highlight={plan.highlight}
|
||||
annualAvailable={canBillAnnually && plan.key !== "lifetime"}
|
||||
paypalEnabled={paypalEnabled}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import Link from "next/link"
|
||||
import { redirect } from "next/navigation"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { profiles } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { PLAN_LIMITS } from "@/lib/stripe/plans"
|
||||
import { BrandingForm } from "@/components/forms/branding-form"
|
||||
import { Sparkles, ArrowRight } from "lucide-react"
|
||||
import type { Plan } from "@/types"
|
||||
|
||||
export const metadata = { title: "White-Label Branding" }
|
||||
|
||||
export default async function BrandingSettingsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const profile = await db.query.profiles.findFirst({
|
||||
where: eq(profiles.id, user.id),
|
||||
columns: {
|
||||
plan: true,
|
||||
brand_name: true,
|
||||
brand_logo_url: true,
|
||||
brand_color: true,
|
||||
hide_powered_by: true,
|
||||
},
|
||||
})
|
||||
|
||||
const plan = (profile?.plan ?? "starter") as Plan
|
||||
const hasWhiteLabel = PLAN_LIMITS[plan]?.hasWhiteLabel === true
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl space-y-6">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-white">White-Label Branding</h2>
|
||||
<p className="text-sm text-white/40">
|
||||
Customize how the tenant portal looks with your own brand.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{hasWhiteLabel ? (
|
||||
<BrandingForm
|
||||
brandName={profile?.brand_name ?? null}
|
||||
brandLogoUrl={profile?.brand_logo_url ?? null}
|
||||
brandColor={profile?.brand_color ?? null}
|
||||
hidePoweredBy={profile?.hide_powered_by ?? false}
|
||||
/>
|
||||
) : (
|
||||
<div className="rounded-xl border border-indigo-500/20 bg-indigo-600/5 p-8 text-center">
|
||||
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-indigo-600">
|
||||
<Sparkles className="h-6 w-6 text-white" />
|
||||
</div>
|
||||
<h3 className="text-base font-semibold text-white">White-label is a Landlord feature</h3>
|
||||
<p className="mx-auto mt-2 max-w-md text-sm text-white/50">
|
||||
Put your own brand name, logo, and accent color on the tenant portal — and remove the
|
||||
“Powered by” line. Available on the Landlord and Lifetime plans.
|
||||
</p>
|
||||
<Link
|
||||
href="/settings/billing"
|
||||
className="mt-6 inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-indigo-500"
|
||||
>
|
||||
Upgrade to unlock
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { seedDemoData, clearDemoData, setTestPlan } from "@/app/actions/seed-dem
|
||||
import { eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { profiles } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getSessionUser, isAdminUser } from "@/lib/session"
|
||||
import { redirect, notFound } from "next/navigation"
|
||||
import {
|
||||
Building2, Users, CreditCard, Wrench,
|
||||
@@ -30,7 +30,8 @@ export default async function DemoDataPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
if (process.env.NODE_ENV === "production") notFound()
|
||||
// Admin-only testing tool — regular users get a 404 (and never see the nav link).
|
||||
if (!isAdminUser(user)) notFound()
|
||||
|
||||
const profile = await db.query.profiles.findFirst({
|
||||
where: eq(profiles.id, user.id),
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { redirect } from "next/navigation"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getAccountContext } from "@/lib/account"
|
||||
import { listProviders, listConnections } from "@/lib/accounting"
|
||||
import { AccountingIntegrations } from "@/components/dashboard/accounting-integrations"
|
||||
|
||||
export const metadata = { title: "Integrations" }
|
||||
export const dynamic = "force-dynamic"
|
||||
|
||||
export default async function IntegrationsPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ connected?: string; error?: string }>
|
||||
}) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
const ctx = await getAccountContext(user.id)
|
||||
const sp = await searchParams
|
||||
|
||||
const providers = listProviders()
|
||||
const connections = ctx.isOwner ? await listConnections(ctx.ownerId) : []
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto space-y-6">
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-white">Integrations</h2>
|
||||
<p className="text-sm text-white/40 mt-0.5">
|
||||
Connect your accounting software to automatically push rent income and expenses into your books.
|
||||
</p>
|
||||
</div>
|
||||
<AccountingIntegrations
|
||||
providers={providers}
|
||||
connections={connections}
|
||||
isOwner={ctx.isOwner}
|
||||
flash={{ connected: sp.connected, error: sp.error }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import Link from "next/link"
|
||||
import { redirect } from "next/navigation"
|
||||
import { and, desc, eq, ne } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { account_members, profiles } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getAccountContext } from "@/lib/account"
|
||||
import { PLAN_LIMITS } from "@/lib/stripe/plans"
|
||||
import { TeamManager, type TeamMember } from "@/components/dashboard/team-manager"
|
||||
import { Users } from "lucide-react"
|
||||
import type { Plan } from "@/types"
|
||||
|
||||
export const metadata = { title: "Team Access" }
|
||||
|
||||
export default async function TeamSettingsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ctx = await getAccountContext(user.id)
|
||||
|
||||
// If the user is a MEMBER of someone else's account, show a read-only note
|
||||
// instead of management UI — they can't manage the owner's team.
|
||||
if (!ctx.isOwner) {
|
||||
const owner = await db.query.profiles.findFirst({
|
||||
where: eq(profiles.id, ctx.ownerId),
|
||||
columns: { full_name: true, company_name: true, email: true },
|
||||
})
|
||||
const ownerName =
|
||||
owner?.company_name || owner?.full_name || owner?.email || "another landlord"
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl space-y-6">
|
||||
<PageHeader />
|
||||
<div className="rounded-xl border border-white/[0.06] bg-[#16161f] p-6">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="rounded-lg bg-indigo-600/10 p-2">
|
||||
<Users className="h-5 w-5 text-indigo-400" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">
|
||||
You're a {ctx.role} of {ownerName}'s account
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-white/50">
|
||||
You're working inside {ownerName}'s portfolio.{" "}
|
||||
{ctx.canWrite
|
||||
? "You can view and edit their data."
|
||||
: "You have read-only access to their data."}{" "}
|
||||
Only the account owner can manage team members.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Owner: gate on their plan.
|
||||
const profile = await db.query.profiles.findFirst({
|
||||
where: eq(profiles.id, user.id),
|
||||
columns: { plan: true },
|
||||
})
|
||||
const plan = (profile?.plan ?? "starter") as Plan
|
||||
const hasTeamAccess = PLAN_LIMITS[plan].hasTeamAccess
|
||||
|
||||
if (!hasTeamAccess) {
|
||||
return (
|
||||
<div className="max-w-2xl space-y-6">
|
||||
<PageHeader />
|
||||
<div className="rounded-xl border border-indigo-500/20 bg-indigo-600/5 p-8 text-center">
|
||||
<div className="mx-auto mb-4 w-fit rounded-xl bg-indigo-600/10 p-3">
|
||||
<Users className="h-6 w-6 text-indigo-400" />
|
||||
</div>
|
||||
<h3 className="text-base font-semibold text-white">Team access is a paid feature</h3>
|
||||
<p className="mx-auto mt-2 max-w-md text-sm text-white/50">
|
||||
Invite staff or co-managers to access your portfolio with the Landlord
|
||||
or Lifetime plan. Members can help manage your properties, and viewers
|
||||
get read-only access.
|
||||
</p>
|
||||
<Link
|
||||
href="/settings/billing"
|
||||
className="mt-6 inline-flex items-center justify-center rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-indigo-500"
|
||||
>
|
||||
Upgrade your plan
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: account_members.id,
|
||||
email: account_members.email,
|
||||
role: account_members.role,
|
||||
status: account_members.status,
|
||||
})
|
||||
.from(account_members)
|
||||
.where(and(eq(account_members.owner_id, user.id), ne(account_members.status, "revoked")))
|
||||
.orderBy(desc(account_members.created_at))
|
||||
|
||||
const members: TeamMember[] = rows
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl space-y-6">
|
||||
<PageHeader />
|
||||
<TeamManager initialMembers={members} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PageHeader() {
|
||||
return (
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-white">Team Access</h2>
|
||||
<p className="text-sm text-white/40">
|
||||
Invite people to help manage your property portfolio
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { redirect } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
import { desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { webhook_endpoints } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { WebhookManager } from "@/components/dashboard/webhook-manager"
|
||||
import type { WebhookEndpointDTO } from "@/app/actions/webhooks"
|
||||
|
||||
export const metadata = { title: "Webhooks" }
|
||||
|
||||
export default async function WebhooksSettingsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
// Endpoints belong to the account owner (team-aware) so every portfolio event
|
||||
// is delivered regardless of which member triggered it.
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(webhook_endpoints)
|
||||
.where(eq(webhook_endpoints.user_id, ownerId))
|
||||
.orderBy(desc(webhook_endpoints.created_at))
|
||||
|
||||
const endpoints: WebhookEndpointDTO[] = rows.map((row) => ({
|
||||
id: row.id,
|
||||
url: row.url,
|
||||
description: row.description,
|
||||
events: row.events,
|
||||
secret: row.secret,
|
||||
status: row.status,
|
||||
source: row.source,
|
||||
last_success_at: row.last_success_at,
|
||||
last_error_at: row.last_error_at,
|
||||
last_error: row.last_error,
|
||||
failure_count: row.failure_count,
|
||||
created_at: row.created_at,
|
||||
}))
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl space-y-6">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-white">Webhooks</h2>
|
||||
<p className="text-sm text-white/40">
|
||||
Send real-time events to Zapier, Make, or your own server. Each delivery is signed with the
|
||||
endpoint's secret so you can verify it's from us. See the{" "}
|
||||
<Link
|
||||
href="/api-docs#webhooks"
|
||||
className="text-indigo-400 underline underline-offset-2 transition hover:text-indigo-300"
|
||||
>
|
||||
webhook documentation
|
||||
</Link>{" "}
|
||||
for the payload format and signature scheme.
|
||||
</p>
|
||||
</div>
|
||||
<WebhookManager initialEndpoints={endpoints} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { and, asc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { tenants as tenantsTable, properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { TenantForm } from "@/components/forms/tenant-form"
|
||||
import { BackButton } from "@/components/ui/back-button"
|
||||
|
||||
@@ -12,14 +13,16 @@ export default async function EditTenantPage({ params }: { params: Promise<{ ten
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const { tenantId } = await params
|
||||
|
||||
const [tenant, properties_] = await Promise.all([
|
||||
db.query.tenants.findFirst({
|
||||
where: and(eq(tenantsTable.id, tenantId), eq(tenantsTable.user_id, user.id)),
|
||||
where: and(eq(tenantsTable.id, tenantId), eq(tenantsTable.user_id, ownerId)),
|
||||
}),
|
||||
db.query.properties.findMany({
|
||||
where: eq(properties.user_id, user.id),
|
||||
where: eq(properties.user_id, ownerId),
|
||||
columns: { id: true, name: true },
|
||||
with: {
|
||||
units: { columns: { id: true, unit_number: true, status: true } },
|
||||
|
||||
@@ -3,6 +3,7 @@ import { and, eq, desc } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { tenants as tenantsTable, rent_payments, maintenance_requests, leases as leasesTable } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import Link from "next/link"
|
||||
import { formatCurrency, formatDate } from "@/lib/utils"
|
||||
import { RentStatusBadge } from "@/components/dashboard/rent-status-badge"
|
||||
@@ -10,15 +11,18 @@ import { MaintenanceStatusBadge, PriorityBadge } from "@/components/dashboard/ma
|
||||
import { Mail, Phone } from "lucide-react"
|
||||
import { CopyButton } from "@/components/shared/copy-button"
|
||||
import { SendReminderButton } from "@/components/shared/send-reminder-button"
|
||||
import { DeleteTenantButton } from "@/components/forms/delete-tenant-button"
|
||||
|
||||
export default async function TenantDetailPage({ params }: { params: Promise<{ tenantId: string }> }) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const { tenantId } = await params
|
||||
|
||||
const tenant = await db.query.tenants.findFirst({
|
||||
where: and(eq(tenantsTable.id, tenantId), eq(tenantsTable.user_id, user.id)),
|
||||
where: and(eq(tenantsTable.id, tenantId), eq(tenantsTable.user_id, ownerId)),
|
||||
with: {
|
||||
unit: { columns: { unit_number: true, rent_amount: true, bedrooms: true, bathrooms: true } },
|
||||
property: { columns: { name: true, address_line1: true, city: true, state: true } },
|
||||
@@ -31,19 +35,19 @@ export default async function TenantDetailPage({ params }: { params: Promise<{ t
|
||||
db
|
||||
.select()
|
||||
.from(rent_payments)
|
||||
.where(and(eq(rent_payments.user_id, user.id), eq(rent_payments.tenant_id, tenantId)))
|
||||
.where(and(eq(rent_payments.user_id, ownerId), eq(rent_payments.tenant_id, tenantId)))
|
||||
.orderBy(desc(rent_payments.due_date))
|
||||
.limit(6),
|
||||
db
|
||||
.select()
|
||||
.from(maintenance_requests)
|
||||
.where(and(eq(maintenance_requests.user_id, user.id), eq(maintenance_requests.tenant_id, tenantId)))
|
||||
.where(and(eq(maintenance_requests.user_id, ownerId), eq(maintenance_requests.tenant_id, tenantId)))
|
||||
.orderBy(desc(maintenance_requests.created_at))
|
||||
.limit(5),
|
||||
db
|
||||
.select()
|
||||
.from(leasesTable)
|
||||
.where(and(eq(leasesTable.user_id, user.id), eq(leasesTable.tenant_id, tenantId)))
|
||||
.where(and(eq(leasesTable.user_id, ownerId), eq(leasesTable.tenant_id, tenantId)))
|
||||
.orderBy(desc(leasesTable.created_at))
|
||||
.limit(1),
|
||||
])
|
||||
@@ -74,12 +78,18 @@ export default async function TenantDetailPage({ params }: { params: Promise<{ t
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Link
|
||||
href={`/tenants/${tenantId}/edit`}
|
||||
className="rounded-lg border border-white/10 px-4 py-2 text-sm text-white/60 hover:border-white/20 hover:text-white transition"
|
||||
>
|
||||
Edit
|
||||
</Link>
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
href={`/tenants/${tenantId}/edit`}
|
||||
className="rounded-lg border border-white/10 px-4 py-2 text-sm text-white/60 hover:border-white/20 hover:text-white transition"
|
||||
>
|
||||
Edit
|
||||
</Link>
|
||||
<DeleteTenantButton
|
||||
tenantId={tenantId}
|
||||
tenantName={`${tenant.first_name} ${tenant.last_name}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
|
||||
@@ -3,6 +3,7 @@ import { asc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { TenantForm } from "@/components/forms/tenant-form"
|
||||
import { BackButton } from "@/components/ui/back-button"
|
||||
|
||||
@@ -12,8 +13,10 @@ export default async function NewTenantPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const properties_ = await db.query.properties.findMany({
|
||||
where: eq(properties.user_id, user.id),
|
||||
where: eq(properties.user_id, ownerId),
|
||||
columns: { id: true, name: true },
|
||||
with: {
|
||||
units: { columns: { id: true, unit_number: true, status: true } },
|
||||
|
||||
@@ -3,6 +3,7 @@ import { and, eq, desc } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { tenants as tenantsTable } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { Users, Plus } from "lucide-react"
|
||||
import { EmptyState } from "@/components/shared/empty-state"
|
||||
import Link from "next/link"
|
||||
@@ -15,8 +16,10 @@ export default async function TenantsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const tenants = await db.query.tenants.findMany({
|
||||
where: and(eq(tenantsTable.user_id, user.id), eq(tenantsTable.status, "active")),
|
||||
where: and(eq(tenantsTable.user_id, ownerId), eq(tenantsTable.status, "active")),
|
||||
with: {
|
||||
unit: { columns: { unit_number: true, rent_amount: true } },
|
||||
property: { columns: { name: true } },
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { Mail, Search, ArrowRight, ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react"
|
||||
import { formatDate, formatCurrency } from "@/lib/utils"
|
||||
import { DeleteTenantButton } from "@/components/forms/delete-tenant-button"
|
||||
|
||||
type SortKey = "name" | "property" | "move_in" | "rent"
|
||||
type SortDir = "asc" | "desc"
|
||||
@@ -121,12 +122,20 @@ export function TenantsTable({ tenants }: { tenants: any[] }) {
|
||||
</p>
|
||||
</td>
|
||||
<td className="px-5 py-4 text-right">
|
||||
<Link
|
||||
href={`/tenants/${tenant.id}`}
|
||||
className="inline-flex items-center gap-1 text-xs text-white/30 transition group-hover:text-indigo-400"
|
||||
>
|
||||
View <ArrowRight className="h-3 w-3" />
|
||||
</Link>
|
||||
<div className="flex items-center justify-end gap-3">
|
||||
<Link
|
||||
href={`/tenants/${tenant.id}`}
|
||||
className="inline-flex items-center gap-1 text-xs text-white/30 transition group-hover:text-indigo-400"
|
||||
>
|
||||
View <ArrowRight className="h-3 w-3" />
|
||||
</Link>
|
||||
<DeleteTenantButton
|
||||
tenantId={tenant.id}
|
||||
tenantName={`${tenant.first_name} ${tenant.last_name}`}
|
||||
refreshOnly
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
|
||||
Vendored
+5
-2
@@ -3,6 +3,7 @@ import { asc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { vendors, properties } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getEffectiveOwnerId } from "@/lib/account"
|
||||
import { VendorManager } from "./vendor-manager"
|
||||
|
||||
export const metadata = { title: "Vendors" }
|
||||
@@ -11,16 +12,18 @@ export default async function VendorsPage() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
const ownerId = await getEffectiveOwnerId(user.id)
|
||||
|
||||
const [vendorList, propertyList] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(vendors)
|
||||
.where(eq(vendors.user_id, user.id))
|
||||
.where(eq(vendors.user_id, ownerId))
|
||||
.orderBy(asc(vendors.name)),
|
||||
db
|
||||
.select({ id: properties.id, name: properties.name })
|
||||
.from(properties)
|
||||
.where(eq(properties.user_id, user.id)),
|
||||
.where(eq(properties.user_id, ownerId)),
|
||||
])
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user