import type { LoaderFunctionArgs } from "@remix-run/node"; import { DateTime } from "luxon"; import type { Method } from "@prisma/client"; import { authenticate } from "../shopify.server"; import db from "../db.server"; import { bookingsToCsv, type BookingSummary } from "../services/dashboard.server"; // Resource route (no default export/component) — safe to hit directly for // a file download, and safe to import dashboard.server.ts freely since // there's no client component here for Remix to worry about bundling it into. export const loader = async ({ request }: LoaderFunctionArgs) => { const { session } = await authenticate.admin(request); const url = new URL(request.url); const locationIdFilter = url.searchParams.get("locationId") || undefined; const methodFilter = (url.searchParams.get("method") as Method | null) || undefined; const statusFilter = url.searchParams.get("status") || undefined; const startDate = url.searchParams.get("startDate") || DateTime.now().toISODate()!; const endDate = url.searchParams.get("endDate") || DateTime.now().plus({ days: 7 }).toISODate()!; const rangeStart = DateTime.fromISO(startDate, { zone: "utc" }).toJSDate(); const rangeEnd = DateTime.fromISO(endDate, { zone: "utc" }).plus({ days: 1 }).toJSDate(); const bookings = await db.booking.findMany({ where: { shopDomain: session.shop, locationId: locationIdFilter, method: methodFilter, status: statusFilter, slotStart: { gte: rangeStart, lt: rangeEnd }, }, include: { location: true }, orderBy: { slotStart: "asc" }, }); const summaries: BookingSummary[] = bookings.map((b) => ({ id: b.id, orderName: b.orderName, locationId: b.locationId, locationName: b.location.name, method: b.method, slotStart: b.slotStart, slotEnd: b.slotEnd, timezone: b.location.timezone, status: b.status, totalPriceCents: b.totalPriceCents, customerEmail: b.customerEmail, })); const csv = bookingsToCsv(summaries); return new Response(csv, { headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="dispatch-${startDate}-to-${endDate}.csv"`, }, }); };