metatrondelivery/app/routes/apps.scheduling.availability.tsx
metatroncubeswdev 6598691372 feat: Phase 5 — multi-location, zones, rates, auto-assignment
- Prisma: Zone (postal-code list or radius), Rate (zone- or distance-band
  keyed), GeocodeCache (permanent address->lat/lng cache per
  IMPLEMENTATION_PLAN.md §9), Location.shopifyLocationId (maps to
  Shopify's own Location resource for inventory checks), Booking.zoneId
  (needed for per-zone delivery-density counts, not just per-location).
- app/lib/geo.ts: pure haversine distance + postal-code matching, unit
  tested against known city-to-city distances.
- app/services/zones.server.ts: geocoding (Google Maps Geocoding API,
  cached — never re-geocodes the same address twice), zone eligibility,
  nearest-location auto-assignment ranked by distance, delivery-density
  threshold checks (a sparse zone doesn't unlock until minOrders bookings
  have already routed through it), and inventory-based location exclusion
  via Shopify's InventoryLevel API (locations without a mapped
  shopifyLocationId are left in rather than false-negative excluded).
- app/services/rates.server.ts: pure rate resolution by zone or distance
  band, cheapest-match-wins when bands overlap.
- apps.scheduling.availability.tsx: LOCAL_DELIVERY requests with a
  postalCode/address now auto-assign to the nearest eligible,
  density-qualified zone/location instead of the shop's default location;
  response includes the matched rate. Also fixed a real gap left over from
  Phase 4: this route never actually read Booking counts into
  getAvailability's `consumed` map, so capacity always showed as fully
  available regardless of existing bookings — now it does.
- extensions/datetime-widget: LOCAL_DELIVERY now asks for a postal code
  before showing dates; PICKUP shows a Google Maps pin for the location
  (both gated on an optional Maps API key — a block setting in the theme
  editor, since it needs to be public/client-side, not an app secret);
  confirmation display and cart attributes (dd_zone_id, dd_rate_label)
  carry the resolved zone/rate through to checkout.
- extensions/delivery-customization: now appends the resolved rate to the
  relabeled delivery option ("Local delivery — Aug 25 ($5.99)") when one's
  configured — real Cart Transform-based fee *charging* stays deferred to
  v2 per IMPLEMENTATION_PLAN.md §5.4, this is display-only.
- Admin: /app/zones and /app/rates (Polaris CRUD, mirroring Phase 1's
  patterns), plus shopifyLocationId and auto-geocode-on-save added to the
  location edit form.

Fixed one real bug caught only by `npm run build` (not tsc/vitest, which
both passed clean): app.rates._index.tsx's component called
formatPriceLabel from rates.server.ts, and Remix correctly refuses to
bundle anything imported from a .server.ts path for the client. Moved the
pure (no I/O, no Prisma) formatter to app/lib/currency.ts.

Verified: lint, typecheck, 86 unit tests (+21 new: geo, zones, rates,
delivery-customization's rate-label case with a real WASM fixture run),
16 integration tests against live Postgres (+8 new: geocode caching,
postal/radius zone matching, nearest-first ranking, density thresholds),
both builds, and a live script exercising the full
zone-match -> density-check -> rate-resolve -> availability pipeline
together against the Postgres container.

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

191 lines
7.3 KiB
TypeScript

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 { getAvailability } from "../services/scheduling.server";
import { findEligibleLocationsForDelivery, meetsDeliveryDensity } from "../services/zones.server";
import { resolveRate } from "../services/rates.server";
import { formatPriceLabel } from "../lib/currency";
// Public endpoint, reachable only through Shopify's App Proxy (signature
// verified by authenticate.public.appProxy) — this is what the storefront
// Theme App Extension calls. Requests to https://{shop}/apps/scheduling/*
// forward here because shopify.app.toml's [app_proxy].url already includes
// the /apps/scheduling prefix, so this file's path (apps.scheduling.*)
// mirrors the shop-facing URL exactly.
const VALID_METHODS = new Set<Method>(["SHIPPING", "LOCAL_DELIVERY", "PICKUP"]);
const MAX_DAYS = 60;
const DEFAULT_DAYS = 14;
function toIsoDate(date: Date): string {
return date.toISOString().slice(0, 10);
}
/** `getAvailability`'s consumed-capacity map key — must match scheduling.server.ts's slotKey() exactly. */
function slotKey(date: string, startMin: number): string {
return `${date}|${startMin}`;
}
export const loader = async ({ request }: LoaderFunctionArgs) => {
const { session } = await authenticate.public.appProxy(request);
if (!session) {
return Response.json({ error: "Shop not found" }, { status: 404 });
}
const url = new URL(request.url);
const methodParam = url.searchParams.get("method");
const locationIdParam = url.searchParams.get("locationId");
const postalCode = url.searchParams.get("postalCode") || undefined;
const address = url.searchParams.get("address") || undefined;
const daysParam = Number(url.searchParams.get("days") ?? DEFAULT_DAYS);
const days = Number.isFinite(daysParam) && daysParam > 0 ? Math.min(daysParam, MAX_DAYS) : DEFAULT_DAYS;
if (!methodParam || !VALID_METHODS.has(methodParam as Method)) {
return Response.json({ error: "Invalid or missing method" }, { status: 400 });
}
const method = methodParam as Method;
let location: Awaited<ReturnType<typeof db.location.findFirst>> = null;
let zoneId: string | null = null;
let distanceKm: number | null = null;
// Delivery-zone auto-assignment (IMPLEMENTATION_PLAN.md Phase 5): route to
// the nearest eligible, density-qualified zone for the shopper's address.
// Falls through to the plain location lookup below for PICKUP/SHIPPING,
// or when no address was supplied yet (e.g. the widget hasn't asked for
// one), so the picker can still show something before that input exists.
if (method === "LOCAL_DELIVERY" && (postalCode || address)) {
const matches = await findEligibleLocationsForDelivery(session.shop, { postalCode, address });
const zones = matches.length
? await db.zone.findMany({ where: { id: { in: matches.map((m) => m.zoneId) } } })
: [];
const zoneById = new Map(zones.map((z) => [z.id, z]));
for (const match of matches) {
if (locationIdParam && match.locationId !== locationIdParam) continue;
const zone = zoneById.get(match.zoneId);
if (!zone) continue;
// eslint-disable-next-line no-await-in-loop -- checked in nearest-first order; stop at the first that qualifies
if (!(await meetsDeliveryDensity(session.shop, zone))) continue;
zoneId = match.zoneId;
distanceKm = match.distanceKm;
location = await db.location.findFirst({ where: { id: match.locationId, shopDomain: session.shop, active: true } });
break;
}
if (!location) {
return Response.json({
locationId: null,
method,
dates: {},
zoneId: null,
rate: null,
error: "This address is outside our delivery area right now.",
});
}
} else {
location = locationIdParam
? await db.location.findFirst({
where: { id: locationIdParam, shopDomain: session.shop, active: true },
})
: await db.location.findFirst({
where: { shopDomain: session.shop, active: true },
orderBy: { createdAt: "asc" },
});
}
if (!location) {
return Response.json({ error: "No active location configured" }, { status: 404 });
}
const now = DateTime.now().setZone(location.timezone);
const startDate = now.toISODate()!;
const endDate = now.plus({ days }).toISODate()!;
const rangeStart = DateTime.fromISO(startDate, { zone: "utc" }).toJSDate();
const rangeEnd = DateTime.fromISO(endDate, { zone: "utc" }).toJSDate();
// Bookings are keyed by exact instant; widen the window by a day on each
// side so a slot near midnight UTC-offset boundaries isn't miscounted.
const bookingRangeStart = DateTime.fromISO(startDate, { zone: "utc" }).minus({ days: 1 }).toJSDate();
const bookingRangeEnd = DateTime.fromISO(endDate, { zone: "utc" }).plus({ days: 1 }).toJSDate();
const [slotTemplates, overrides, blackouts, bookings, rates] = await Promise.all([
db.slotTemplate.findMany({
where: { shopDomain: session.shop, locationId: location.id, method },
}),
db.slotOverride.findMany({
where: {
shopDomain: session.shop,
locationId: location.id,
method,
date: { gte: rangeStart, lte: rangeEnd },
},
}),
db.blackoutDate.findMany({
where: {
shopDomain: session.shop,
date: { gte: rangeStart, lte: rangeEnd },
AND: [{ OR: [{ locationId: location.id }, { locationId: null }] }, { OR: [{ method }, { method: null }] }],
},
}),
db.booking.findMany({
where: {
shopDomain: session.shop,
locationId: location.id,
method,
status: { in: ["confirmed", "fulfilled"] },
slotStart: { gte: bookingRangeStart, lte: bookingRangeEnd },
},
select: { slotStart: true },
}),
db.rate.findMany({ where: { shopDomain: session.shop, method } }),
]);
const consumed = new Map<string, number>();
for (const booking of bookings) {
const local = DateTime.fromJSDate(booking.slotStart, { zone: "utc" }).setZone(location.timezone);
const key = slotKey(local.toISODate()!, local.hour * 60 + local.minute);
consumed.set(key, (consumed.get(key) ?? 0) + 1);
}
const availability = getAvailability({
timezone: location.timezone,
dateRange: { startDate, endDate },
slotTemplates: slotTemplates.map((t) => ({
weekday: t.weekday,
startMin: t.startMin,
endMin: t.endMin,
capacity: t.capacity,
cutoffMin: t.cutoffMin,
leadTimeMin: t.leadTimeMin,
})),
overrides: overrides.map((o) => ({
date: toIsoDate(o.date),
closed: o.closed,
startMin: o.startMin,
endMin: o.endMin,
capacity: o.capacity,
})),
blackoutDates: blackouts.map((b) => ({ date: toIsoDate(b.date) })),
now,
consumed,
});
const matchedRate = resolveRate(rates, { method, zoneId: zoneId ?? undefined, distanceKm: distanceKm ?? undefined });
return Response.json({
locationId: location.id,
locationName: location.name,
locationLat: location.lat,
locationLng: location.lng,
timezone: location.timezone,
method,
dates: availability,
zoneId,
distanceKm,
rate: matchedRate ? { name: matchedRate.name, priceCents: matchedRate.priceCents, label: formatPriceLabel(matchedRate.priceCents) } : null,
});
};