metatrondelivery/app/routes/app.blackouts._index.tsx
metatroncubeswdev a2c78d703f
Some checks failed
CI / Lint, Unit & Integration Tests (push) Has been cancelled
feat: close DS study coverage gaps (inventory exclusion, live checkout re-validation, per-day cap, payment fn, checkout ext)
Audited the implementation against DS_Delivery_Date_Time_App_Study.docx and
closed the actionable gaps (see IMPLEMENTATION_REVIEW_2026-09-04.md).

Core (code + unit tests, 156 green):
- Wire excludeLocationsWithoutStock into resolveAvailabilityRequest; widget
  now sends variantIds so inventory-based location exclusion actually runs.
- Live slot re-validation at checkout: new checkout-snapshot.server.ts writes
  a shop-metafield capacity snapshot; validation-slot's evaluateCheckout
  rejects a complete selection that has since filled / blacked out / closed /
  hit the daily cap / left the schedule. Refreshed on order webhooks and
  slot/blackout/location/enforcement edits.
- Scopable checkout enforcement: Shop.enforcementMode (all|tagged|off) +
  enforcementTag, new app.settings.tsx admin page, honoured via the snapshot.
- Per-day order cap: Location.dailyOrderCap threaded through getAvailability
  (dailyCap + consumedPerDate); admin field on the location screen.
- Product-rule slot blocking: ProductRule.blockedStartMins, unioned in
  resolveProductRuleConstraints, enforced in the engine and resolveHoldRequest;
  admin field on the product rules screen.
- Product-page placement: product-availability.liquid block + widget
  data-mode="preview" (read-only earliest-date line).
- Second locale: datetime-widget fr.json / fr.schema.json.
- Migration 20260904120000_review_gaps (apply with prisma migrate deploy).

New Functions (source + unit tests; need `shopify app deploy` to ship):
- extensions/payment-customization: cart.payment-methods.transform.run — hides
  cash-on-delivery / pay-in-store gateways on SHIPPING orders.
- extensions/checkout-datetime/src: restored from a gitignored dist-only state
  — Plus native picker + Thank you / Order status confirmation blocks, all
  calling the existing checkout.scheduling.* routes (one capacity pool).
  tsconfig ships checkJs:false pending reconciliation with live checkout types.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-04 01:31:02 -04:00

177 lines
5.9 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,
Card,
BlockStack,
InlineStack,
Text,
Button,
Select,
TextField,
IndexTable,
EmptyState,
} from "@shopify/polaris";
import { TitleBar } from "@shopify/app-bridge-react";
import type { Method } from "@prisma/client";
import { authenticate } from "../shopify.server";
import db from "../db.server";
import { writeCheckoutSnapshot } from "../services/checkout-snapshot.server";
const METHODS: Method[] = ["SHIPPING", "LOCAL_DELIVERY", "PICKUP"];
export const loader = async ({ request }: LoaderFunctionArgs) => {
const { session } = await authenticate.admin(request);
const [locations, blackouts] = await Promise.all([
db.location.findMany({ where: { shopDomain: session.shop }, orderBy: { createdAt: "asc" } }),
db.blackoutDate.findMany({
where: { shopDomain: session.shop },
include: { location: true },
orderBy: { date: "asc" },
}),
]);
return { locations, blackouts };
};
export const action = async ({ request }: ActionFunctionArgs) => {
const { session, admin } = await authenticate.admin(request);
const formData = await request.formData();
const intent = formData.get("intent");
if (intent === "delete") {
const id = String(formData.get("id") || "");
await db.blackoutDate.deleteMany({ where: { id, shopDomain: session.shop } });
await writeCheckoutSnapshot(admin, session.shop);
return data({ ok: true });
}
const date = String(formData.get("date") || "");
const locationId = String(formData.get("locationId") || "") || null;
const method = (String(formData.get("method") || "") || null) as Method | null;
const reason = String(formData.get("reason") || "").trim() || null;
if (!date) {
return data({ errors: { date: "Date is required" } });
}
await db.blackoutDate.create({
data: {
shopDomain: session.shop,
date: new Date(`${date}T00:00:00.000Z`),
locationId,
method,
reason,
},
});
await writeCheckoutSnapshot(admin, session.shop);
return data({ ok: true });
};
export default function BlackoutsIndex() {
const { locations, blackouts } = useLoaderData<typeof loader>();
const navigation = useNavigation();
const isSubmitting = navigation.state === "submitting";
const [date, setDate] = useState("");
const [reason, setReason] = useState("");
if (locations.length === 0) {
return (
<Page>
<TitleBar title="Blackout dates" />
<Card>
<EmptyState
heading="Add a location first"
action={{ content: "Add location", url: "/app/locations/new" }}
image="https://cdn.shopify.com/s/files/1/0757/9955/files/empty-state.svg"
>
<Text as="p">Blackout dates can be scoped to one location, or left blank for all locations.</Text>
</EmptyState>
</Card>
</Page>
);
}
return (
<Page>
<TitleBar title="Blackout dates" />
<BlockStack gap="400">
<Card padding="0">
{blackouts.length === 0 ? (
<div style={{ padding: 16 }}>
<Text as="p" tone="subdued">
No blackout dates yet.
</Text>
</div>
) : (
<IndexTable
itemCount={blackouts.length}
headings={[
{ title: "Date" },
{ title: "Location" },
{ title: "Method" },
{ title: "Reason" },
{ title: "" },
]}
selectable={false}
>
{blackouts.map((b, index) => (
<IndexTable.Row id={b.id} key={b.id} position={index}>
<IndexTable.Cell>{b.date.slice(0, 10)}</IndexTable.Cell>
<IndexTable.Cell>{b.location?.name ?? "All locations"}</IndexTable.Cell>
<IndexTable.Cell>{b.method?.replace("_", " ") ?? "All methods"}</IndexTable.Cell>
<IndexTable.Cell>{b.reason ?? "—"}</IndexTable.Cell>
<IndexTable.Cell>
<Form method="post">
<input type="hidden" name="intent" value="delete" />
<input type="hidden" name="id" value={b.id} />
<Button submit variant="plain" tone="critical">
Remove
</Button>
</Form>
</IndexTable.Cell>
</IndexTable.Row>
))}
</IndexTable>
)}
</Card>
<Card>
<Form method="post">
<BlockStack gap="300">
<Text as="h3" variant="headingSm">
Add a blackout date
</Text>
<InlineStack gap="300" wrap>
<TextField label="Date" name="date" type="date" autoComplete="off" value={date} onChange={setDate} />
<Select
label="Location"
name="locationId"
options={[{ label: "All locations", value: "" }, ...locations.map((l) => ({ label: l.name, value: l.id }))]}
/>
<Select
label="Method"
name="method"
options={[
{ label: "All methods", value: "" },
...METHODS.map((m) => ({ label: m.replace("_", " "), value: m })),
]}
/>
<TextField label="Reason (optional)" name="reason" autoComplete="off" value={reason} onChange={setReason} />
</InlineStack>
<div>
<Button submit variant="primary" loading={isSubmitting}>
Add blackout date
</Button>
</div>
</BlockStack>
</Form>
</Card>
</BlockStack>
</Page>
);
}