metatrondelivery/app/routes/app.locations._index.tsx
metatroncubeswdev 21f0ee704b feat: Phase 1 — core data model & admin CRUD
Adds the scheduling core to Prisma (Shop, Location, Method enum,
SlotTemplate, SlotOverride, BlackoutDate — IMPLEMENTATION_PLAN.md §4) and
Polaris admin screens to manage them:

- /app/locations: list/create/edit/delete locations, one-click vertical
  template seeding (bakery/florist/grocer)
- /app/slots: weekly slot template editor, scoped per location
- /app/blackouts: blackout dates, scoped to one location or all of them

services/templates.server.ts keeps the vertical presets as a pure,
unit-tested function (getVerticalTemplate) separate from the thin I/O
wrapper (seedVerticalTemplate) that does the actual Prisma writes, per
CLAUDE.md's "pure functions, inject data, no I/O in the math" rule.

Switched dev DB from SQLite to Postgres (docker-compose.yml, ports 5433/6380
to avoid clashing with other local projects already on 5432/6379): SQLite
doesn't support Prisma enums at all, and IMPLEMENTATION_PLAN.md's schema
relies on them (Method) plus Postgres-only array fields in later phases
(Zone.postalCodes, ProductRule.allowedLocationIds). Only one throwaway
migration existed, so switching now avoids compounding the rework later.

Also fixed a Remix/Polaris integration issue hit while building these forms:
this Polaris version's TextField/Checkbox are fully controlled (no
defaultValue/defaultChecked), and `data()` imported from `@remix-run/react`
(rather than `@remix-run/node`) breaks useActionData's type inference —
both are now handled correctly across the new routes.

Verified: lint, typecheck, unit tests (incl. template-seeding fixtures),
build, and a live end-to-end run of seedVerticalTemplate against the
Postgres container all pass.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 17:47:59 -04:00

153 lines
5.6 KiB
TypeScript

import { useState } from "react";
import { data, type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/node";
import { Form, useLoaderData, useNavigation } from "@remix-run/react";
import {
Page,
Layout,
Card,
BlockStack,
InlineStack,
Text,
Button,
ButtonGroup,
ResourceList,
ResourceItem,
Badge,
EmptyState,
Select,
} from "@shopify/polaris";
import { TitleBar } from "@shopify/app-bridge-react";
import { authenticate } from "../shopify.server";
import db from "../db.server";
import { listVerticalTemplates, seedVerticalTemplate, type VerticalKey } from "../services/templates.server";
export const loader = async ({ request }: LoaderFunctionArgs) => {
const { session } = await authenticate.admin(request);
const locations = await db.location.findMany({
where: { shopDomain: session.shop },
include: { _count: { select: { slotTemplates: true, blackouts: true } } },
orderBy: { createdAt: "asc" },
});
return { locations, verticals: listVerticalTemplates() };
};
export const action = async ({ request }: ActionFunctionArgs) => {
const { session } = await authenticate.admin(request);
const formData = await request.formData();
const intent = formData.get("intent");
if (intent === "seed-template") {
const vertical = formData.get("vertical") as VerticalKey;
await seedVerticalTemplate(session.shop, vertical);
return data({ ok: true });
}
if (intent === "delete-location") {
const id = formData.get("id") as string;
await db.location.deleteMany({ where: { id, shopDomain: session.shop } });
return data({ ok: true });
}
return data({ ok: false }, { status: 400 });
};
export default function LocationsIndex() {
const { locations, verticals } = useLoaderData<typeof loader>();
const navigation = useNavigation();
const isSubmitting = navigation.state === "submitting";
const [vertical, setVertical] = useState<string>(verticals[0]);
return (
<Page>
<TitleBar title="Locations" />
<BlockStack gap="500">
<Layout>
<Layout.Section>
{locations.length === 0 ? (
<Card>
<EmptyState
heading="Set up your first location"
image="https://cdn.shopify.com/s/files/1/0757/9955/files/empty-state.svg"
>
<BlockStack gap="400">
<Text as="p" variant="bodyMd">
Start from a vertical template it seeds a location with a
realistic weekly Pickup/Delivery schedule you can then edit,
or add a location from scratch.
</Text>
<InlineStack gap="300" blockAlign="center">
<div style={{ minWidth: 180 }}>
<Select
label="Vertical"
labelHidden
options={verticals.map((v) => ({ label: capitalize(v), value: v }))}
value={vertical}
onChange={setVertical}
/>
</div>
<Form method="post">
<input type="hidden" name="intent" value="seed-template" />
<input type="hidden" name="vertical" value={vertical} />
<Button submit variant="primary" loading={isSubmitting}>
Seed {capitalize(vertical)} template
</Button>
</Form>
<Button url="/app/locations/new">Add location manually</Button>
</InlineStack>
</BlockStack>
</EmptyState>
</Card>
) : (
<Card padding="0">
<ResourceList
items={locations}
resourceName={{ singular: "location", plural: "locations" }}
renderItem={(location) => (
<ResourceItem
id={location.id}
url={`/app/locations/${location.id}`}
accessibilityLabel={`View ${location.name}`}
>
<InlineStack align="space-between" blockAlign="center">
<BlockStack gap="100">
<Text as="h3" variant="bodyMd" fontWeight="bold">
{location.name}
</Text>
<Text as="span" variant="bodySm" tone="subdued">
{location.address || "No address set"} · {location.timezone}
</Text>
</BlockStack>
<InlineStack gap="200" blockAlign="center">
<Badge>{`${location._count.slotTemplates} slot templates`}</Badge>
<Badge tone={location.active ? "success" : "critical"}>
{location.active ? "Active" : "Inactive"}
</Badge>
</InlineStack>
</InlineStack>
</ResourceItem>
)}
/>
</Card>
)}
</Layout.Section>
{locations.length > 0 && (
<Layout.Section>
<ButtonGroup>
<Button url="/app/locations/new" variant="primary">
Add location
</Button>
</ButtonGroup>
</Layout.Section>
)}
</Layout>
</BlockStack>
</Page>
);
}
function capitalize(s: string) {
return s.charAt(0).toUpperCase() + s.slice(1);
}