548 lines
18 KiB
TypeScript
548 lines
18 KiB
TypeScript
// routes/landlord/messages/index.tsx
|
|
import { define } from "../../../utils.ts";
|
|
import { page } from "fresh";
|
|
import { SessionCookie } from "../../auth/callback.ts";
|
|
import {
|
|
deleteMessagesForUser,
|
|
getMessageThread,
|
|
getThreadsForUser,
|
|
ThreadPage,
|
|
ThreadSummary,
|
|
} from "../../../services/messageService.ts";
|
|
import LandlordMessageSelection from "../../../islands/LandlordMessageSelection.tsx";
|
|
import LandlordMessageThreads from "../../../islands/LandlordMessageThreads.tsx";
|
|
|
|
type FilterValue = "all" | "read" | "unread";
|
|
type TypeValue = "all" | "general" | "maintenance" | "payment" | "notice";
|
|
type DirectionValue = "all" | "sent" | "received";
|
|
type SortValue = "newest" | "oldest";
|
|
|
|
interface Filters {
|
|
status: FilterValue;
|
|
type: TypeValue;
|
|
direction: DirectionValue;
|
|
sort: SortValue;
|
|
search: string;
|
|
pageSize: number;
|
|
}
|
|
|
|
interface MessagesPageData {
|
|
stateData: SessionCookie;
|
|
threadPage: ThreadPage;
|
|
filters: Filters;
|
|
error?: string;
|
|
}
|
|
|
|
const STATUS_VALUES: FilterValue[] = ["all", "read", "unread"];
|
|
const TYPE_VALUES: TypeValue[] = [
|
|
"all",
|
|
"general",
|
|
"maintenance",
|
|
"payment",
|
|
"notice",
|
|
];
|
|
const DIRECTION_VALUES: DirectionValue[] = ["all", "sent", "received"];
|
|
const SORT_VALUES: SortValue[] = ["newest", "oldest"];
|
|
const PAGE_SIZES = [10, 20, 50];
|
|
|
|
function sanitizeEnum<T extends string>(
|
|
value: string | null,
|
|
allowed: T[],
|
|
fallback: T,
|
|
) {
|
|
if (!value) return fallback;
|
|
return allowed.includes(value as T) ? (value as T) : fallback;
|
|
}
|
|
|
|
function buildPageUrl(
|
|
filters: Filters,
|
|
pageNumber: number,
|
|
) {
|
|
const params = new URLSearchParams();
|
|
params.set("page", String(pageNumber));
|
|
params.set("page_size", String(filters.pageSize));
|
|
params.set("status", filters.status);
|
|
params.set("type", filters.type);
|
|
params.set("direction", filters.direction);
|
|
params.set("sort", filters.sort);
|
|
if (filters.search) params.set("q", filters.search);
|
|
return `/landlord/messages?${params.toString()}`;
|
|
}
|
|
|
|
export const handler = define.handlers({
|
|
async GET(ctx) {
|
|
const stateData: SessionCookie = ctx.state.data;
|
|
const { user_id } = stateData;
|
|
|
|
try {
|
|
const url = new URL(ctx.req.url);
|
|
const pageNumber = Math.max(
|
|
1,
|
|
Number(url.searchParams.get("page") || "1"),
|
|
);
|
|
const rawPageSize = Number(url.searchParams.get("page_size") || "10");
|
|
const pageSize = PAGE_SIZES.includes(rawPageSize) ? rawPageSize : 10;
|
|
|
|
const status = sanitizeEnum(
|
|
url.searchParams.get("status"),
|
|
STATUS_VALUES,
|
|
"all",
|
|
);
|
|
const type = sanitizeEnum(
|
|
url.searchParams.get("type"),
|
|
TYPE_VALUES,
|
|
"all",
|
|
);
|
|
const direction = sanitizeEnum(
|
|
url.searchParams.get("direction"),
|
|
DIRECTION_VALUES,
|
|
"all",
|
|
);
|
|
const sort = sanitizeEnum(
|
|
url.searchParams.get("sort"),
|
|
SORT_VALUES,
|
|
"newest",
|
|
);
|
|
const search = url.searchParams.get("q")?.trim() || "";
|
|
|
|
const threadPage = await getThreadsForUser(user_id, {
|
|
page: pageNumber,
|
|
pageSize,
|
|
sort,
|
|
status,
|
|
type,
|
|
direction,
|
|
search,
|
|
});
|
|
|
|
return page({
|
|
stateData,
|
|
threadPage,
|
|
filters: {
|
|
status,
|
|
type,
|
|
direction,
|
|
sort,
|
|
search,
|
|
pageSize,
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error("Error loading messages:", error);
|
|
return page({
|
|
stateData,
|
|
threadPage: {
|
|
threads: [],
|
|
page: 1,
|
|
pageSize: 10,
|
|
total: 0,
|
|
totalThreads: 0,
|
|
totalPages: 1,
|
|
unread: 0,
|
|
},
|
|
filters: {
|
|
status: "all",
|
|
type: "all",
|
|
direction: "all",
|
|
sort: "newest",
|
|
search: "",
|
|
pageSize: 10,
|
|
},
|
|
error: "Failed to load messages.",
|
|
});
|
|
}
|
|
},
|
|
async POST(ctx) {
|
|
const stateData: SessionCookie = ctx.state.data;
|
|
const { user_id } = stateData;
|
|
|
|
try {
|
|
const formData = await ctx.req.formData();
|
|
const action = formData.get("action")?.toString() || "";
|
|
const returnTo = formData.get("return_to")?.toString() ||
|
|
"/landlord/messages";
|
|
const safeReturnTo = returnTo.startsWith("/")
|
|
? returnTo
|
|
: "/landlord/messages";
|
|
const redirectUrl = new URL(safeReturnTo, ctx.req.url);
|
|
|
|
if (action !== "delete_selected") {
|
|
return Response.redirect(redirectUrl, 303);
|
|
}
|
|
|
|
const rootIds = formData.getAll("message_ids")
|
|
.map((value) => value.toString())
|
|
.filter(Boolean);
|
|
|
|
if (rootIds.length > 0) {
|
|
const messageIds: string[] = [];
|
|
for (const rootId of rootIds) {
|
|
const thread = await getMessageThread(rootId);
|
|
if (thread) {
|
|
for (const m of thread) {
|
|
if (m.sender_id === user_id || m.recipient_id === user_id) {
|
|
messageIds.push(m.id);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (messageIds.length > 0) {
|
|
await deleteMessagesForUser(user_id, messageIds);
|
|
}
|
|
}
|
|
|
|
return Response.redirect(redirectUrl, 303);
|
|
} catch (error) {
|
|
console.error("Error deleting messages:", error);
|
|
const fallbackUrl = new URL("/landlord/messages", ctx.req.url);
|
|
return Response.redirect(fallbackUrl, 303);
|
|
}
|
|
},
|
|
});
|
|
|
|
export default define.page(function LandlordMessages({ data }) {
|
|
const { stateData, threadPage, filters, error } = data as MessagesPageData;
|
|
const { threads, page, pageSize, total, totalPages } = threadPage;
|
|
const totalThreads = threadPage.totalThreads ?? total;
|
|
const unread = threadPage.unread ?? 0;
|
|
const startIndex = total === 0 ? 0 : (page - 1) * pageSize + 1;
|
|
const endIndex = Math.min(total, page * pageSize);
|
|
const returnTo = buildPageUrl(filters, page);
|
|
const hasThreads = threads.length > 0;
|
|
|
|
const ThreadRow = ({ thread }: { thread: ThreadSummary }) => {
|
|
const msg = thread.latestMessage;
|
|
const isOutbound = msg.sender_id === stateData.user_id;
|
|
const counterpart = isOutbound
|
|
? (msg.recipient_name ?? "Recipient")
|
|
: (msg.sender_name ?? "Tenant");
|
|
const contentPreview = (msg.content_encrypted || msg.content || "")
|
|
.substring(0, 100);
|
|
|
|
return (
|
|
<li
|
|
class={`p-4 border-b border-gray-200 transition-colors ${
|
|
thread.hasUnread
|
|
? "bg-blue-50 hover:bg-blue-100"
|
|
: "bg-white hover:bg-gray-50"
|
|
}`}
|
|
>
|
|
<div class="flex items-center justify-between">
|
|
<div class="flex items-center space-x-3">
|
|
<input
|
|
type="checkbox"
|
|
name="message_ids"
|
|
value={thread.rootMessageId}
|
|
form="bulk-delete-form"
|
|
class="h-4 w-4 text-blue-600 border-gray-300 rounded"
|
|
/>
|
|
<div class="min-w-0 flex-1">
|
|
<div class="text-sm font-medium text-gray-900 flex items-center gap-2 flex-wrap">
|
|
{thread.hasUnread && (
|
|
<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-semibold bg-blue-600 text-white">
|
|
New!
|
|
</span>
|
|
)}
|
|
{thread.subject}
|
|
{thread.messageCount > 1 && (
|
|
<span class="text-xs text-gray-500">
|
|
({thread.messageCount} messages)
|
|
</span>
|
|
)}
|
|
</div>
|
|
<p class="text-sm text-gray-500 truncate">
|
|
<span class="font-semibold text-gray-700">
|
|
{isOutbound ? "To" : "From"} {counterpart}:
|
|
</span>{" "}
|
|
{contentPreview || "No content preview"}
|
|
{contentPreview.length >= 100 ? "..." : ""}
|
|
</p>
|
|
{msg.property_address && (
|
|
<p class="text-xs text-gray-400 mt-0.5">
|
|
Property: {msg.property_address}
|
|
</p>
|
|
)}
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center space-x-4">
|
|
<div class="text-sm text-gray-500">
|
|
{msg.created_on
|
|
? new Date(msg.created_on).toLocaleDateString()
|
|
: "—"}
|
|
</div>
|
|
<a
|
|
href={`/landlord/messages/${thread.rootMessageId}`}
|
|
class="text-sm text-blue-600 hover:text-blue-500"
|
|
>
|
|
View Thread
|
|
</a>
|
|
</div>
|
|
</div>
|
|
</li>
|
|
);
|
|
};
|
|
|
|
return (
|
|
<div class="min-h-screen bg-gray-50 landlord-route">
|
|
<div class="bg-white shadow">
|
|
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
|
<div class="flex flex-col gap-4 py-6 sm:flex-row sm:items-center sm:justify-between">
|
|
<div>
|
|
<h1 class="text-3xl font-bold text-gray-900">
|
|
Messages
|
|
</h1>
|
|
<p class="mt-1 text-sm text-gray-500">
|
|
Review all landlord-tenant conversations in one place.
|
|
</p>
|
|
</div>
|
|
<div class="flex flex-wrap gap-3">
|
|
<a
|
|
href="/landlord/messages/new"
|
|
class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 shadow-sm"
|
|
>
|
|
New Message
|
|
</a>
|
|
<a
|
|
href="/landlord/dashboard"
|
|
class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 shadow-sm"
|
|
>
|
|
Dashboard
|
|
</a>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
|
{error && (
|
|
<div class="mb-6 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
|
|
{error}
|
|
</div>
|
|
)}
|
|
|
|
<form method="GET" class="bg-white shadow rounded-lg p-6 mb-6">
|
|
<div class="grid grid-cols-1 gap-4 lg:grid-cols-5">
|
|
<div class="lg:col-span-2">
|
|
<label class="block text-sm font-medium text-gray-700">
|
|
Search
|
|
</label>
|
|
<input
|
|
type="text"
|
|
name="q"
|
|
value={filters.search}
|
|
placeholder="Search subject or message..."
|
|
class="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
|
|
/>
|
|
</div>
|
|
<div>
|
|
<label class="block text-sm font-medium text-gray-700">
|
|
Status
|
|
</label>
|
|
<select
|
|
name="status"
|
|
class="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
|
|
>
|
|
{STATUS_VALUES.map((value) => (
|
|
<option value={value} selected={filters.status === value}>
|
|
{value === "all"
|
|
? "All"
|
|
: value === "read"
|
|
? "Read"
|
|
: "Unread"}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<label class="block text-sm font-medium text-gray-700">
|
|
Type
|
|
</label>
|
|
<select
|
|
name="type"
|
|
class="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
|
|
>
|
|
{TYPE_VALUES.map((value) => (
|
|
<option value={value} selected={filters.type === value}>
|
|
{value === "all"
|
|
? "All"
|
|
: value.charAt(0).toUpperCase() + value.slice(1)}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<label class="block text-sm font-medium text-gray-700">
|
|
Direction
|
|
</label>
|
|
<select
|
|
name="direction"
|
|
class="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
|
|
>
|
|
{DIRECTION_VALUES.map((value) => (
|
|
<option value={value} selected={filters.direction === value}>
|
|
{value === "all"
|
|
? "All"
|
|
: value === "sent"
|
|
? "Sent"
|
|
: "Received"}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
|
<div>
|
|
<label class="block text-sm font-medium text-gray-700">
|
|
Sort by
|
|
</label>
|
|
<select
|
|
name="sort"
|
|
class="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
|
|
>
|
|
{SORT_VALUES.map((value) => (
|
|
<option value={value} selected={filters.sort === value}>
|
|
{value === "newest" ? "Newest first" : "Oldest first"}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<label class="block text-sm font-medium text-gray-700">
|
|
Page size
|
|
</label>
|
|
<select
|
|
name="page_size"
|
|
class="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
|
|
>
|
|
{PAGE_SIZES.map((size) => (
|
|
<option value={size} selected={filters.pageSize === size}>
|
|
{size} per page
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
<div class="flex items-end">
|
|
<button
|
|
type="submit"
|
|
class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
|
|
>
|
|
Apply Filters
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</form>
|
|
|
|
<div
|
|
class="bg-white shadow overflow-hidden sm:rounded-lg"
|
|
data-message-form
|
|
data-status-filter={filters.status}
|
|
>
|
|
<form
|
|
method="POST"
|
|
id="bulk-delete-form"
|
|
class="px-4 py-5 sm:px-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between border-b border-gray-200"
|
|
>
|
|
<input type="hidden" name="return_to" value={returnTo} />
|
|
<div>
|
|
<h2 class="text-lg font-semibold text-gray-900">
|
|
All Messages
|
|
</h2>
|
|
<p class="text-sm text-gray-500">
|
|
Showing {startIndex}-{endIndex} of {totalThreads} threads
|
|
{unread > 0 && (
|
|
<span class="ml-2 text-blue-600 font-semibold">
|
|
({unread} unread)
|
|
</span>
|
|
)}
|
|
</p>
|
|
</div>
|
|
<div class="flex flex-wrap items-center gap-3 text-sm text-gray-500">
|
|
<label class="inline-flex items-center gap-2">
|
|
<input
|
|
type="checkbox"
|
|
class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
|
data-select-all
|
|
disabled={!hasThreads}
|
|
/>
|
|
<span>Select all</span>
|
|
</label>
|
|
<button
|
|
type="submit"
|
|
name="action"
|
|
value="delete_selected"
|
|
class="inline-flex items-center px-3 py-2 rounded-md border border-red-200 text-red-600 hover:bg-red-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
|
data-delete-button
|
|
disabled
|
|
>
|
|
Delete selected
|
|
</button>
|
|
<span>
|
|
page {page} of {totalPages}
|
|
</span>
|
|
</div>
|
|
</form>
|
|
|
|
{threads.length === 0
|
|
? (
|
|
<div class="px-6 py-12 text-center">
|
|
<p class="text-sm text-gray-500">
|
|
No threads match the selected filters.
|
|
</p>
|
|
</div>
|
|
)
|
|
: (
|
|
<ul class="divide-y divide-gray-200">
|
|
{threads.map((thread) => (
|
|
<ThreadRow key={thread.rootMessageId} thread={thread} />
|
|
))}
|
|
</ul>
|
|
)}
|
|
|
|
<div class="px-6 py-4 border-t border-gray-200 flex items-center justify-between text-sm">
|
|
<a
|
|
href={buildPageUrl(filters, Math.max(1, page - 1))}
|
|
class={`inline-flex items-center px-3 py-2 rounded-md border ${
|
|
page === 1
|
|
? "border-gray-200 text-gray-400 pointer-events-none"
|
|
: "border-gray-300 text-gray-700 hover:bg-gray-50"
|
|
}`}
|
|
>
|
|
Previous
|
|
</a>
|
|
<div class="flex gap-2">
|
|
{Array.from({ length: totalPages }, (_, index) => index + 1)
|
|
.slice(Math.max(0, page - 3), Math.min(totalPages, page + 2))
|
|
.map((pageNumber) => (
|
|
<a
|
|
key={pageNumber}
|
|
href={buildPageUrl(filters, pageNumber)}
|
|
class={`inline-flex items-center px-3 py-2 rounded-md border ${
|
|
pageNumber === page
|
|
? "border-blue-600 bg-blue-50 text-blue-700"
|
|
: "border-gray-300 text-gray-700 hover:bg-gray-50"
|
|
}`}
|
|
>
|
|
{pageNumber}
|
|
</a>
|
|
))}
|
|
</div>
|
|
<a
|
|
href={buildPageUrl(filters, Math.min(totalPages, page + 1))}
|
|
class={`inline-flex items-center px-3 py-2 rounded-md border ${
|
|
page === totalPages
|
|
? "border-gray-200 text-gray-400 pointer-events-none"
|
|
: "border-gray-300 text-gray-700 hover:bg-gray-50"
|
|
}`}
|
|
>
|
|
Next
|
|
</a>
|
|
</div>
|
|
</div>
|
|
<LandlordMessageSelection />
|
|
<LandlordMessageThreads />
|
|
</div>
|
|
</div>
|
|
);
|
|
});
|