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

142 lines
4.5 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";
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 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 };
}
await db.location.updateMany({
where: { id: params.id, shopDomain: session.shop },
data: { name, address, timezone, active },
});
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 };
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);
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} />
<TextField
label="Timezone (IANA)"
name="timezone"
autoComplete="off"
value={timezone}
onChange={setTimezone}
error={errors?.timezone}
requiredIndicator
/>
<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>
</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>
);
}