metatrondelivery/app/routes/app.locations.$id.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

187 lines
6.1 KiB
TypeScript

import { useState } from "react";
import { redirect, type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/node";
import { Form, useActionData, useLoaderData, useNavigation } from "@remix-run/react";
import {
Page,
Card,
BlockStack,
FormLayout,
TextField,
Button,
InlineStack,
Checkbox,
} from "@shopify/polaris";
import { TitleBar } from "@shopify/app-bridge-react";
import { authenticate } from "../shopify.server";
import db from "../db.server";
import { geocodeAddress } from "../services/zones.server";
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { session } = await authenticate.admin(request);
const location = await db.location.findFirst({
where: { id: params.id, shopDomain: session.shop },
});
if (!location) {
throw new Response("Not found", { status: 404 });
}
return { location };
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const { session } = await authenticate.admin(request);
const formData = await request.formData();
const intent = formData.get("intent");
if (intent === "delete") {
await db.location.deleteMany({ where: { id: params.id, shopDomain: session.shop } });
return redirect("/app/locations");
}
const name = String(formData.get("name") || "").trim();
const address = String(formData.get("address") || "").trim();
const timezone = String(formData.get("timezone") || "").trim();
const active = formData.get("active") === "true";
const shopifyLocationId = String(formData.get("shopifyLocationId") || "").trim() || null;
const errors: Record<string, string> = {};
if (!name) errors.name = "Name is required";
if (!timezone) errors.timezone = "Timezone is required";
if (Object.keys(errors).length > 0) {
return { errors };
}
// Auto-geocode on save so radius zones and the widget's pickup map have
// coordinates without a separate manual step — no-ops silently if
// GOOGLE_MAPS_API_KEY isn't configured (see zones.server.ts).
const coordinates = address ? await geocodeAddress(address) : null;
await db.location.updateMany({
where: { id: params.id, shopDomain: session.shop },
data: {
name,
address,
timezone,
active,
shopifyLocationId,
...(coordinates ? { lat: coordinates.lat, lng: coordinates.lng } : {}),
},
});
return { errors };
};
export default function EditLocation() {
const { location } = useLoaderData<typeof loader>();
const actionData = useActionData<typeof action>();
const navigation = useNavigation();
const isSubmitting = navigation.state === "submitting";
return (
<Page backAction={{ url: "/app/locations" }}>
<TitleBar title={location.name} />
<LocationForm key={location.id} location={location} errors={actionData?.errors} isSubmitting={isSubmitting} />
</Page>
);
}
function LocationForm({
location,
errors,
isSubmitting,
}: {
location: {
id: string;
name: string;
address: string;
timezone: string;
active: boolean;
shopifyLocationId: string | null;
lat: number | null;
lng: number | null;
};
errors?: Record<string, string>;
isSubmitting: boolean;
}) {
const [name, setName] = useState(location.name);
const [address, setAddress] = useState(location.address);
const [timezone, setTimezone] = useState(location.timezone);
const [active, setActive] = useState(location.active);
const [shopifyLocationId, setShopifyLocationId] = useState(location.shopifyLocationId ?? "");
return (
<BlockStack gap="400">
<Card>
<Form method="post">
<FormLayout>
<TextField
label="Location name"
name="name"
autoComplete="off"
value={name}
onChange={setName}
error={errors?.name}
requiredIndicator
/>
<TextField
label="Address"
name="address"
autoComplete="off"
multiline={2}
value={address}
onChange={setAddress}
helpText={
location.lat != null
? `Geocoded: ${location.lat.toFixed(4)}, ${location.lng?.toFixed(4)}`
: "Saved without coordinates — set GOOGLE_MAPS_API_KEY to auto-geocode on save."
}
/>
<TextField
label="Timezone (IANA)"
name="timezone"
autoComplete="off"
value={timezone}
onChange={setTimezone}
error={errors?.timezone}
requiredIndicator
/>
<TextField
label="Shopify Location ID (advanced)"
name="shopifyLocationId"
autoComplete="off"
value={shopifyLocationId}
onChange={setShopifyLocationId}
helpText="gid://shopify/Location/… — only needed for inventory-based location exclusion."
/>
<Checkbox label="Active" name="active" value="true" checked={active} onChange={setActive} />
<InlineStack gap="200">
<Button submit variant="primary" loading={isSubmitting}>
Save
</Button>
<Button url={`/app/slots?locationId=${location.id}`}>Manage weekly slots</Button>
<Button url={`/app/blackouts?locationId=${location.id}`}>Manage blackout dates</Button>
<Button url={`/app/zones?locationId=${location.id}`}>Manage delivery zones</Button>
</InlineStack>
</FormLayout>
</Form>
</Card>
<Card>
<Form method="post">
<input type="hidden" name="intent" value="delete" />
<InlineStack align="space-between" blockAlign="center">
<BlockStack gap="050">
<strong>Delete this location</strong>
<span>Removes all its slot templates and blackout dates.</span>
</BlockStack>
<Button submit tone="critical" variant="secondary">
Delete location
</Button>
</InlineStack>
</Form>
</Card>
</BlockStack>
);
}