- 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>
90 lines
3.1 KiB
TypeScript
90 lines
3.1 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;
|
|
note_attributes?: OrderNoteAttribute[];
|
|
}
|
|
|
|
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,
|
|
},
|
|
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,
|
|
);
|
|
}
|
|
}
|