metatrondelivery/app/routes/app.settings.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

121 lines
5.0 KiB
TypeScript

import { useState } from "react";
import { type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/node";
import { Form, useActionData, useLoaderData, useNavigation } from "@remix-run/react";
import { Page, Card, BlockStack, Text, Button, ChoiceList, TextField, Banner } from "@shopify/polaris";
import { TitleBar } from "@shopify/app-bridge-react";
import { authenticate } from "../shopify.server";
import db from "../db.server";
import { writeCheckoutSnapshot } from "../services/checkout-snapshot.server";
// Checkout enforcement scope for the Cart/Checkout Validation Function
// (study §3.5 — enforcement should be scopable, not all-or-nothing). The
// Function can't read this DB, so every save re-writes the shop-metafield
// snapshot it does read (checkout-snapshot.server.ts).
const MODE_CHOICES = [
{ label: "Every order must pick a slot", value: "all" },
{ label: "Only orders containing a tagged product", value: "tagged" },
{ label: "Never block checkout (widget still collects)", value: "off" },
];
export const loader = async ({ request }: LoaderFunctionArgs) => {
const { session } = await authenticate.admin(request);
const shop = await db.shop.findUnique({
where: { shopDomain: session.shop },
select: { enforcementMode: true, enforcementTag: true },
});
return { mode: shop?.enforcementMode ?? "all", tag: shop?.enforcementTag ?? "" };
};
export const action = async ({ request }: ActionFunctionArgs) => {
const { session, admin } = await authenticate.admin(request);
const formData = await request.formData();
const mode = String(formData.get("mode") || "all");
const tag = String(formData.get("enforcementTag") || "").trim() || null;
const errors: Record<string, string> = {};
if (!["all", "tagged", "off"].includes(mode)) errors.mode = "Pick a valid option";
if (mode === "tagged" && !tag) errors.enforcementTag = "Enter the product tag that requires scheduling";
if (Object.keys(errors).length > 0) {
return { ok: false as const, errors };
}
await db.shop.upsert({
where: { shopDomain: session.shop },
create: { shopDomain: session.shop, enforcementMode: mode, enforcementTag: tag },
update: { enforcementMode: mode, enforcementTag: tag },
});
// Push the new config straight into the metafield the Function reads.
await writeCheckoutSnapshot(admin, session.shop);
return { ok: true as const, errors: {} as Record<string, string> };
};
export default function EnforcementSettings() {
const { mode: initialMode, tag: initialTag } = useLoaderData<typeof loader>();
const actionData = useActionData<typeof action>();
const navigation = useNavigation();
const isSubmitting = navigation.state === "submitting";
const [mode, setMode] = useState<string>(initialMode);
const [tag, setTag] = useState(initialTag);
return (
<Page>
<TitleBar title="Checkout enforcement" />
<BlockStack gap="400">
{actionData?.ok && (
<Banner tone="success" title="Saved — the checkout snapshot has been refreshed." />
)}
<Card>
<Form method="post">
<BlockStack gap="400">
<Text as="p" tone="subdued">
The storefront widget only <em>collects</em> a slot. The Cart &amp; Checkout Validation Function is what
actually blocks an order from completing without a valid one. This controls when it blocks.
</Text>
<ChoiceList
title="When should checkout be blocked without a slot?"
choices={MODE_CHOICES}
selected={[mode]}
onChange={(v) => setMode(v[0])}
/>
<input type="hidden" name="mode" value={mode} />
{mode === "tagged" && (
<TextField
label="Product tag that requires scheduling"
name="enforcementTag"
autoComplete="off"
value={tag}
onChange={setTag}
error={actionData?.errors?.enforcementTag}
helpText="Orders are only blocked when a cart line's product carries this tag. Others check out normally."
/>
)}
<div>
<Button submit variant="primary" loading={isSubmitting}>
Save
</Button>
</div>
</BlockStack>
</Form>
</Card>
<Card>
<BlockStack gap="200">
<Text as="h3" variant="headingSm">
Live slot re-validation
</Text>
<Text as="p" tone="subdued">
Every save here, plus every order and every slot/blackout edit, refreshes a capacity snapshot the Function
reads at checkout. If a slot has filled up or been blacked out since the shopper picked it, checkout is
blocked with a "no longer available" message not just when the slot attribute is missing.
</Text>
</BlockStack>
</Card>
</BlockStack>
</Page>
);
}