import { and, count, desc, inArray, isNull, lte, or } from "drizzle-orm"; import Link from "next/link"; import { getTranslations } from "next-intl/server"; import { ContentCard, EmptyState } from "@/components/public/ui"; import { db, WebsitePoll, WebsitePollQuestion } from "@/lib/db"; import { excerpt } from "@/lib/format"; import { formatDate } from "@/lib/format-date"; export const metadata = { title: "Polls" }; export default async function PollsPage() { const t = await getTranslations("pages.polls"); const now = new Date(); const pollRows = await db .select() .from(WebsitePoll) .where( and( inArray(WebsitePoll.status, ["active", "closed"]), or(isNull(WebsitePoll.startsAt), lte(WebsitePoll.startsAt, now)), ), ) .orderBy(desc(WebsitePoll.createdAt)) .limit(50) .catch(() => []); const pollIds = pollRows.map((p) => p.id); const questionCounts = pollIds.length > 0 ? await db .select({ pollId: WebsitePollQuestion.pollId, value: count(), }) .from(WebsitePollQuestion) .where(inArray(WebsitePollQuestion.pollId, pollIds)) .groupBy(WebsitePollQuestion.pollId) .catch(() => []) : []; const countByPoll = new Map( questionCounts.map((r) => [r.pollId, Number(r.value)]), ); const polls = pollRows.map((poll) => ({ ...poll, _count: { questions: countByPoll.get(poll.id) ?? 0 }, })); return (
{polls.length === 0 ? ( {t("empty")} ) : (
{polls.map((poll) => { const ended = poll.status === "closed" || (poll.endsAt != null && poll.endsAt.getTime() < Date.now()); return (

{ended ? t("statusClosed") : t("statusActive")} {" ยท "} {t("questionsCount", { count: poll._count.questions })}

{poll.title}

{poll.description ? (

{excerpt(poll.description, 120)}

) : null}

{poll.endsAt ? t("ends", { date: formatDate(poll.endsAt, "datetime", ""), }) : formatDate(poll.createdAt, "date", "")}

); })}
)}
); }