metatrondelivery/app/services/booking.server.ts
metatroncubeswdev c5ec8f368c feat: Phase 6 — ops/dispatch dashboard
- Prisma: Booking.totalPriceCents (parsed from the order webhook's
  total_price string), populated in booking.server.ts so "revenue by
  method" is real data, not a placeholder.
- app/services/dashboard.server.ts: pure aggregation over injected booking
  data (CLAUDE.md — no DB calls in the math) — bucketByLocalDate (each
  booking grouped under its own location's local calendar day, not a
  shared UTC day), revenueByMethod (confirmed/fulfilled only),
  utilizationByDateLocation (booked vs. summed SlotTemplate capacity for
  that weekday, capped at 100%), upcomingFulfillments, and a CSV
  writer/formatter with proper quote-escaping.
- /app/dashboard: filterable (date range, location, method, status) view
  with revenue-by-method cards, a capacity-utilization list (color-coded
  by load), an upcoming-fulfillments table with one-click
  confirmed->fulfilled/no_show status transitions, and a full by-day
  booking list.
- /app/dashboard/export: a resource route (loader only, no component)
  streaming the same filtered bookings as a downloadable CSV — kept
  separate from the dashboard route specifically so it can import
  dashboard.server.ts freely without the client-bundling constraint the
  main route has to respect (see below).

Fixed the same class of server/client bundling bug from the Phase 5 commit
before it could ship, this time by construction: dashboard.server.ts's
aggregation functions are called only inside app.dashboard.tsx's `loader`,
never referenced by the default-exported component (which only reads
useLoaderData() output) — verified this holds by actually running
`npm run build`, not just tsc/vitest, which both stay silent about this
class of error. Also hit (and fixed) the same "loader Dates arrive as
strings on the client" issue from Phase 1: swapped DateTime.fromJSDate for
DateTime.fromISO in the two places the component formats a booking's
slotStart.

Verified: lint, typecheck, 102 unit tests (+16 new for dashboard.server.ts,
+2 new for totalPriceCents parsing), 18 integration tests, both builds, and
a live script exercising the full aggregation pipeline (revenue exclusion
of cancelled bookings, utilization math, CSV output) against the Postgres
container.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 03:33:21 -04:00

98 lines
3.5 KiB
TypeScript

import type { Method } from "@prisma/client";
import db from "../db.server";
import { slotDateTime } from "../lib/time";
import { releaseHold } from "./holds.server";
const VALID_METHODS = new Set<Method>(["SHIPPING", "LOCAL_DELIVERY", "PICKUP"]);
export interface OrderNoteAttribute {
name: string;
value: string;
}
export interface OrderWebhookPayload {
admin_graphql_api_id: string;
name?: string;
cart_token?: string | null;
email?: string | null;
phone?: string | null;
total_price?: string | null; // e.g. "49.99" — Shopify sends this as a decimal string, not cents
note_attributes?: OrderNoteAttribute[];
}
function parsePriceCents(totalPrice: string | null | undefined): number | undefined {
if (!totalPrice) return undefined;
const value = Number(totalPrice);
return Number.isFinite(value) ? Math.round(value * 100) : undefined;
}
function readAttr(attrs: OrderNoteAttribute[], key: string): string | undefined {
return attrs.find((a) => a.name === key)?.value;
}
/**
* Converts a completed order's dd_* cart attributes (written by the
* storefront widget, see extensions/datetime-widget) into a confirmed
* Booking, and releases the Redis hold that reserved its capacity.
*
* Idempotent on orderId — webhooks can and do redeliver, so this must be
* safe to run twice for the same order without double-booking capacity.
*
* Deliberately does NOT re-check capacity here and reject the order if
* over budget: by the time an order exists, payment has been taken and the
* Validation Function already had its chance to block checkout with a
* fresh capacity snapshot. This function's job is to record what happened,
* not to re-litigate it.
*/
export async function createBookingFromOrder(shopDomain: string, order: OrderWebhookPayload): Promise<void> {
const attrs = order.note_attributes ?? [];
const method = readAttr(attrs, "dd_method");
const date = readAttr(attrs, "dd_date");
const startMinRaw = readAttr(attrs, "dd_start_min");
const endMinRaw = readAttr(attrs, "dd_end_min");
const locationId = readAttr(attrs, "dd_location_id");
const zoneId = readAttr(attrs, "dd_zone_id") || null; // LOCAL_DELIVERY orders matched by zones.server.ts; absent for PICKUP/SHIPPING
if (!method || !VALID_METHODS.has(method as Method) || !date || !startMinRaw || !endMinRaw || !locationId) {
return; // no scheduling selection on this order — nothing to book
}
const location = await db.location.findFirst({ where: { id: locationId, shopDomain } });
if (!location) return;
const startMin = Number(startMinRaw);
const endMin = Number(endMinRaw);
const slotStart = slotDateTime(date, startMin, location.timezone);
const slotEnd = slotDateTime(date, endMin, location.timezone);
await db.booking.upsert({
where: { orderId: order.admin_graphql_api_id },
create: {
shopDomain,
orderId: order.admin_graphql_api_id,
orderName: order.name,
locationId: location.id,
zoneId,
method: method as Method,
slotStart: slotStart.toJSDate(),
slotEnd: slotEnd.toJSDate(),
customerEmail: order.email ?? undefined,
customerPhone: order.phone ?? undefined,
totalPriceCents: parsePriceCents(order.total_price),
},
update: {}, // redelivered webhook — the booking already exists, nothing to change
});
if (order.cart_token) {
await releaseHold(
{
shopDomain,
locationId: location.id,
method: method as Method,
slotStartIso: slotStart.toUTC().toISO()!,
},
order.cart_token,
);
}
}