metatrondelivery/app/services/hold-request.server.ts
MOHAN 03574a4914 feat: product rules, driving-distance zones, and shipping date ranges
Closes remaining DS-parity gaps from the feature audit:

- ProductRule model (product/collection/vendor/type/tag scoping) with
  real server-side enforcement in hold-request.server.ts, plus shaped
  availability in availability-request.server.ts. Covers per-product
  prep time, cart-content-based slot blocking, and product-restricted
  locations in one mechanism. New /app/rules admin page (Growth+).
- Driving-distance delivery zones via Google's Distance Matrix API,
  cached like existing geocoding results.
- SHIPPING-only estimated arrival range (transitMinDays/transitMaxDays
  on SlotTemplate) — widget shows "Arrives Thu-Sat" instead of a
  meaningless ship-out time slot; carried through to the order
  metafield write-back.

Storefront widget and POS extension now send cart contents (vendor/
type from cart.js, product ids for Admin-API-resolved collection/tag
rules) to both availability and hold endpoints.

checkout-datetime remains excluded from this deploy pending Shopify's
Network Access approval (unrelated to this work) — re-add from
../checkout-datetime-disabled and redeploy once granted.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-26 00:28:45 +05:30

96 lines
4.3 KiB
TypeScript

import { DateTime } from "luxon";
import type { Method } from "@prisma/client";
import db from "../db.server";
import { minutesUntil, slotDateTime, weekdayOf } from "../lib/time";
import { remainingCapacity } from "./capacity.server";
import { tryCreateHold, releaseHold, countActiveHolds } from "./holds.server";
import { resolveProductRuleConstraints, productRefsFromCartLines, type ProductRef } from "./product-rules.server";
// Shared by every surface that reserves capacity — storefront widget (via
// apps.scheduling.hold.tsx) and POS (via pos.scheduling.hold.tsx). Same
// pool, same code, different auth wrapper. See holds.server.ts for why
// creating a hold has to be a single atomic Redis operation.
export interface HoldRequestParams {
intent: "create" | "release";
locationId: string;
method: Method;
date: string;
startMin: number;
cartToken: string;
/** Same ProductRule-scoping inputs as AvailabilityRequestParams — see availability-request.server.ts. */
cartLines?: Array<{ vendor?: string; productType?: string }>;
productRefs?: ProductRef[];
}
export interface HoldRequestResult {
status: number;
body: { ok?: true; success?: boolean; expiresAt?: number; remaining?: number; error?: string };
}
export async function resolveHoldRequest(shopDomain: string, params: HoldRequestParams): Promise<HoldRequestResult> {
const { intent, locationId, method, date, startMin, cartToken } = params;
const location = await db.location.findFirst({ where: { id: locationId, shopDomain, active: true } });
if (!location) {
return { status: 404, body: { error: "Location not found" } };
}
const slotStart = slotDateTime(date, startMin, location.timezone);
const slot = { shopDomain, locationId: location.id, method, slotStartIso: slotStart.toUTC().toISO()! };
if (intent === "release") {
await releaseHold(slot, cartToken);
return { status: 200, body: { ok: true } };
}
const template = await db.slotTemplate.findFirst({
where: { shopDomain, locationId: location.id, method, weekday: weekdayOf(date, location.timezone), startMin },
});
if (!template) {
return { status: 404, body: { error: "Slot not found" } };
}
// ProductRule enforcement (PRODUCT_STRATEGY.md §2) — the real, server-side
// gate for method/location/lead-time restrictions. Availability filters
// what's *shown*; this is what actually stops a hold (and therefore a
// booking) from being created against a rule, whether or not the shopper
// went through the widget to get here.
const productRules = await db.productRule.findMany({ where: { shopDomain, active: true } });
const cartProductRefs = [...(params.productRefs ?? []), ...productRefsFromCartLines(params.cartLines ?? [])];
const ruleConstraints = resolveProductRuleConstraints(productRules, cartProductRefs);
if (ruleConstraints.allowedMethods != null && !ruleConstraints.allowedMethods.includes(method)) {
return { status: 400, body: { success: false, error: "One or more items in your cart aren't available with this fulfillment method." } };
}
if (ruleConstraints.allowedLocationIds != null && !ruleConstraints.allowedLocationIds.includes(location.id)) {
return { status: 400, body: { success: false, error: "One or more items in your cart aren't available at this location." } };
}
if (ruleConstraints.minLeadTimeMin > 0) {
const now = DateTime.now().setZone(location.timezone);
if (minutesUntil(now, slotStart) < ruleConstraints.minLeadTimeMin) {
return { status: 400, body: { success: false, error: "One or more items in your cart need more preparation time than this slot allows." } };
}
}
const confirmedCount = await db.booking.count({
where: { shopDomain, locationId: location.id, method, slotStart: slotStart.toJSDate(), status: "confirmed" },
});
const capacityBudget = remainingCapacity({ capacity: template.capacity, consumed: confirmedCount });
if (capacityBudget <= 0) {
return { status: 409, body: { success: false, error: "Slot is full" } };
}
const result = await tryCreateHold(slot, cartToken, capacityBudget);
if (!result.success) {
return { status: 409, body: { success: false, error: "Slot was just taken" } };
}
const activeHolds = await countActiveHolds(slot);
return {
status: 200,
body: { success: true, expiresAt: result.expiresAt, remaining: Math.max(0, capacityBudget - activeHolds) },
};
}