2026-02-14 06:10:15 +00:00

408 lines
13 KiB
TypeScript

// routes/tenant/messages/index.tsx
import { page } from "fresh";
import { define } from "../../../utils.ts";
import { SessionCookie } from "../../auth/callback.ts";
import {
DashboardMessage,
deleteMessagesForUser,
getMessagesForUser,
markMessagesAsRead,
MessagePage,
} from "../../../services/messageService.ts";
import LandlordMessageSelection from "../../../islands/LandlordMessageSelection.tsx";
import LandlordMessageThreads from "../../../islands/LandlordMessageThreads.tsx";
import TenantMessagesFilters from "../../../islands/TenantMessagesFilters.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;
messagePage: MessagePage;
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,
): 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 `/tenant/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 filters: Filters = {
status: sanitizeEnum(
url.searchParams.get("status"),
STATUS_VALUES,
"all",
),
type: sanitizeEnum(
url.searchParams.get("type"),
TYPE_VALUES,
"all",
),
direction: sanitizeEnum(
url.searchParams.get("direction"),
DIRECTION_VALUES,
"all",
),
sort: sanitizeEnum(
url.searchParams.get("sort"),
SORT_VALUES,
"newest",
),
search: url.searchParams.get("q") || "",
pageSize,
};
const messagePage = await getMessagesForUser(user_id, {
page: pageNumber,
pageSize,
sort: filters.sort,
status: filters.status,
type: filters.type,
direction: filters.direction,
search: filters.search,
});
return page<MessagesPageData>({
stateData,
messagePage,
filters,
});
} catch (error) {
console.error("Error loading messages:", error);
return page<MessagesPageData>({
stateData: ctx.state.data as SessionCookie,
messagePage: {
messages: [],
page: 1,
pageSize: 10,
total: 0,
totalMessages: 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 { user_id } = ctx.state.data;
try {
const formData = await ctx.req.formData();
const action = formData.get("action") as string;
const message_ids_raw = formData.get("message_ids") as string;
const message_ids = message_ids_raw ? message_ids_raw.split(",") : [];
if (message_ids.length === 0) {
return new Response("", {
status: 302,
headers: { Location: "/tenant/messages" },
});
}
if (action === "mark_read") {
await markMessagesAsRead(user_id, message_ids);
} else if (action === "delete_messages") {
await deleteMessagesForUser(user_id, message_ids);
}
return new Response("", {
status: 302,
headers: { Location: "/tenant/messages" },
});
} catch (error) {
console.error("Error updating message:", error);
return new Response("Failed to update message", { status: 500 });
}
},
});
export default define.page(function TenantMessages({ data }) {
const { stateData, messagePage, filters, error } = data as MessagesPageData;
const { messages, page, total, totalPages } = messagePage;
const totalMessages = messagePage.totalMessages ?? total;
const unread = messagePage.unread ?? 0;
const MessageRow = ({ message }: { message: DashboardMessage }) => {
const isUnread = !message.is_read;
const senderName = message.sender_id === stateData.user_id
? "You"
: "Landlord";
const isReply = !!message.parent_message_id;
return (
<li
key={message.id}
class={`p-4 border-b border-gray-200 transition-colors ${
isUnread
? "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_id"
value={message.id}
class="h-4 w-4 text-blue-600 border-gray-300 rounded message-checkbox"
data-message-id={message.id}
/>
<div class="min-w-0 flex-1">
<div class="text-sm font-medium text-gray-900">
{isReply && (
<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 mr-2">
Reply
</span>
)}
{message.subject || "No Subject"}
</div>
<p class="text-sm text-gray-500 truncate">
<span class="font-semibold text-gray-700">{senderName}:</span>
{" "}
{(message.content_encrypted || message.content)?.substring(
0,
100,
) || "No content preview"}
...
</p>
</div>
</div>
<div class="flex items-center space-x-4">
<div class="text-sm text-gray-500">
{new Date(message.created_on!).toLocaleDateString()}
</div>
<a
href={`/tenant/messages/${message.id}`}
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 tenant-route">
{/* Header */}
<div class="bg-white shadow">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between items-center py-6">
<div>
<h1 class="text-3xl font-bold text-gray-900">Messages</h1>
<p class="mt-1 text-sm text-gray-500">
Communication with your landlord
</p>
</div>
<div class="flex space-x-3">
<a
href="/tenant/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>
</div>
</div>
</div>
</div>
{/* Main Content */}
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 py-8">
{error && (
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4">
<strong class="font-bold">Error:</strong>
<span class="block sm:inline">{error}</span>
</div>
)}
<div class="bg-white shadow overflow-hidden sm:rounded-lg">
{/* Filters and Search */}
<TenantMessagesFilters
status={filters.status}
sort={filters.sort}
search={filters.search}
/>
{/* Bulk Actions and Message List */}
<div class="p-4">
<div class="flex items-center justify-between mb-4">
<p class="text-sm text-gray-700">
Showing{" "}
<span class="font-medium">
{(page - 1) * filters.pageSize + 1}
</span>{" "}
to{" "}
<span class="font-medium">
{Math.min(page * filters.pageSize, totalMessages)}
</span>{" "}
of{" "}
<span class="font-medium">
{totalMessages}
</span>{" "}
results
{unread > 0 && (
<span class="ml-2 text-blue-600 font-semibold">
({unread} unread)
</span>
)}
</p>
<LandlordMessageSelection />
</div>
{messages.length > 0
? (
<ul class="divide-y divide-gray-200">
{messages.map((message) => (
<MessageRow key={message.id} message={message} />
))}
</ul>
)
: (
<div class="text-center py-12">
<svg
class="mx-auto h-12 w-12 text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
/>
</svg>
<h3 class="mt-2 text-sm font-medium text-gray-900">
No messages found
</h3>
<p class="mt-1 text-sm text-gray-500">
Try adjusting your filters or search query.
</p>
<div class="mt-6">
<a
href="/tenant/messages/new"
class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
>
Send Message
</a>
</div>
</div>
)}
</div>
{/* Pagination */}
<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>
{/* Islands for interactive features */}
<LandlordMessageThreads />
</div>
</div>
);
});