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

294 lines
11 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, ChoiceList, IndexTable } 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 { getShopTier } from "../services/billing.server";
import { tierAtLeast } from "../lib/billing-plans";
import { UpsellState } from "../components/UpsellState";
// Product/collection/vendor/type/tag-scoped delivery rules (PRODUCT_STRATEGY.md
// §2 — previously unimplemented; see product-rules.server.ts). Tier-gated at
// Growth, same as Zones/Rates, since scoping rules is an "advanced operator"
// feature, not core parity every merchant needs on day one.
const SCOPE_TYPES = [
{ label: "Product", value: "product" },
{ label: "Collection", value: "collection" },
{ label: "Vendor", value: "vendor" },
{ label: "Product type", value: "type" },
{ label: "Tag", value: "tag" },
];
const METHOD_OPTIONS: Array<{ label: string; value: Method }> = [
{ label: "Shipping", value: "SHIPPING" },
{ label: "Local delivery", value: "LOCAL_DELIVERY" },
{ label: "Pickup", value: "PICKUP" },
];
const SCOPE_LABELS: Record<string, string> = {
product: "Product ID",
collection: "Collection ID",
vendor: "Vendor",
type: "Product type",
tag: "Tag",
};
/** "09:00, 13:30" -> [540, 810]; ignores blank/garbage entries. */
function parseBlockedStartMins(raw: string): number[] {
return [
...new Set(
raw
.split(",")
.map((s) => s.trim())
.filter(Boolean)
.map((s) => {
const [h, m] = s.split(":").map(Number);
return Number.isFinite(h) && Number.isFinite(m) ? h * 60 + m : NaN;
})
.filter((n) => Number.isFinite(n) && n >= 0 && n < 24 * 60),
),
].sort((a, b) => a - b);
}
function formatBlockedStartMins(mins: number[]): string {
return mins
.map((n) => `${String(Math.floor(n / 60)).padStart(2, "0")}:${String(n % 60).padStart(2, "0")}`)
.join(", ");
}
export const loader = async ({ request }: LoaderFunctionArgs) => {
const { session } = await authenticate.admin(request);
const tier = await getShopTier(session.shop);
if (!tierAtLeast(tier, "growth")) {
return { gated: true as const, tier };
}
const [rules, locations] = await Promise.all([
db.productRule.findMany({ where: { shopDomain: session.shop }, orderBy: { createdAt: "asc" } }),
db.location.findMany({ where: { shopDomain: session.shop }, orderBy: { createdAt: "asc" } }),
]);
return { gated: false as const, rules, locations };
};
export const action = async ({ request }: ActionFunctionArgs) => {
const { session } = await authenticate.admin(request);
const tier = await getShopTier(session.shop);
if (!tierAtLeast(tier, "growth")) {
return data({ errors: { scopeValue: "Product rules need the Growth plan or higher." } }, { status: 403 });
}
const formData = await request.formData();
const intent = formData.get("intent");
if (intent === "delete") {
const id = String(formData.get("id") || "");
await db.productRule.deleteMany({ where: { id, shopDomain: session.shop } });
return data({ ok: true });
}
const scopeType = String(formData.get("scopeType") || "product");
const scopeValue = String(formData.get("scopeValue") || "").trim();
const allowedMethods = formData.getAll("allowedMethods").map(String) as Method[];
const allowedLocationIds = formData.getAll("allowedLocationIds").map(String);
const leadTimeMinRaw = String(formData.get("leadTimeMin") || "");
const blockedStartMins = parseBlockedStartMins(String(formData.get("blockedStartMins") || ""));
const errors: Record<string, string> = {};
if (!scopeValue) errors.scopeValue = "This field is required";
if (Object.keys(errors).length > 0) {
return data({ errors });
}
await db.productRule.create({
data: {
shopDomain: session.shop,
scopeType,
scopeValue,
allowedMethods,
allowedLocationIds,
leadTimeMin: leadTimeMinRaw ? Number(leadTimeMinRaw) : null,
blockedStartMins,
},
});
return data({ ok: true });
};
export default function ProductRulesIndex() {
const loaderData = useLoaderData<typeof loader>();
const navigation = useNavigation();
const isSubmitting = navigation.state === "submitting";
if (loaderData.gated) {
return (
<Page>
<TitleBar title="Product rules" />
<UpsellState
requiredTier="growth"
currentTier={loaderData.tier}
feature="Product rules"
description="Scope prep time, allowed methods, and allowed locations to specific products, collections, vendors, types, or tags."
/>
</Page>
);
}
const { rules, locations } = loaderData;
const locationNameById = new Map(locations.map((l) => [l.id, l.name]));
return (
<Page>
<TitleBar title="Product rules" />
<BlockStack gap="400">
<Card padding="0">
{rules.length === 0 ? (
<div style={{ padding: 16 }}>
<Text as="p" tone="subdued">
No product rules yet. Without one, every product uses the same lead time and is available via any
method/location your slots allow.
</Text>
</div>
) : (
<IndexTable
itemCount={rules.length}
headings={[
{ title: "Scope" },
{ title: "Extra lead time" },
{ title: "Allowed methods" },
{ title: "Allowed locations" },
{ title: "Blocked slots" },
{ title: "" },
]}
selectable={false}
>
{rules.map((rule, index) => (
<IndexTable.Row id={rule.id} key={rule.id} position={index}>
<IndexTable.Cell>
{SCOPE_LABELS[rule.scopeType] ?? rule.scopeType}: {rule.scopeValue}
</IndexTable.Cell>
<IndexTable.Cell>{rule.leadTimeMin ? `${rule.leadTimeMin} min` : "—"}</IndexTable.Cell>
<IndexTable.Cell>{rule.allowedMethods.length > 0 ? rule.allowedMethods.join(", ") : "Any"}</IndexTable.Cell>
<IndexTable.Cell>
{rule.allowedLocationIds.length > 0
? rule.allowedLocationIds.map((id) => locationNameById.get(id) ?? id).join(", ")
: "Any"}
</IndexTable.Cell>
<IndexTable.Cell>
{rule.blockedStartMins.length > 0 ? formatBlockedStartMins(rule.blockedStartMins) : "—"}
</IndexTable.Cell>
<IndexTable.Cell>
<Form method="post">
<input type="hidden" name="intent" value="delete" />
<input type="hidden" name="id" value={rule.id} />
<Button submit variant="plain" tone="critical">
Remove
</Button>
</Form>
</IndexTable.Cell>
</IndexTable.Row>
))}
</IndexTable>
)}
</Card>
<AddRuleForm locations={locations} isSubmitting={isSubmitting} />
</BlockStack>
</Page>
);
}
function AddRuleForm({
locations,
isSubmitting,
}: {
locations: Array<{ id: string; name: string }>;
isSubmitting: boolean;
}) {
const [scopeType, setScopeType] = useState("vendor");
const [scopeValue, setScopeValue] = useState("");
const [leadTimeMin, setLeadTimeMin] = useState("");
const [blockedStartMins, setBlockedStartMins] = useState("");
const [allowedMethods, setAllowedMethods] = useState<string[]>([]);
const [allowedLocationIds, setAllowedLocationIds] = useState<string[]>([]);
return (
<Card>
<Form method="post">
{allowedMethods.map((m) => (
<input key={m} type="hidden" name="allowedMethods" value={m} />
))}
{allowedLocationIds.map((id) => (
<input key={id} type="hidden" name="allowedLocationIds" value={id} />
))}
<BlockStack gap="300">
<Text as="h3" variant="headingSm">
Add a product rule
</Text>
<InlineStack gap="300" wrap>
<Select label="Scope" name="scopeType" options={SCOPE_TYPES} value={scopeType} onChange={setScopeType} />
<TextField
label={SCOPE_LABELS[scopeType] ?? "Value"}
name="scopeValue"
autoComplete="off"
value={scopeValue}
onChange={setScopeValue}
helpText={
scopeType === "product" || scopeType === "collection"
? "The Shopify GID, e.g. gid://shopify/Product/123456789"
: undefined
}
/>
<TextField
label="Extra prep time (minutes, optional)"
name="leadTimeMin"
type="number"
autoComplete="off"
value={leadTimeMin}
onChange={setLeadTimeMin}
helpText="Added on top of the slot's own lead time when this rule matches something in the cart."
/>
<TextField
label="Blocked time slots (optional)"
name="blockedStartMins"
autoComplete="off"
value={blockedStartMins}
onChange={setBlockedStartMins}
helpText="Comma-separated start times (e.g. 09:00, 13:30) this cart's contents can't be scheduled into — the earliest run, say, for a fragile item."
/>
</InlineStack>
<InlineStack gap="400" wrap>
<ChoiceList
title="Allowed methods (leave blank for any)"
allowMultiple
choices={METHOD_OPTIONS}
selected={allowedMethods}
onChange={setAllowedMethods}
/>
{locations.length > 0 && (
<ChoiceList
title="Allowed locations (leave blank for any)"
allowMultiple
choices={locations.map((l) => ({ label: l.name, value: l.id }))}
selected={allowedLocationIds}
onChange={setAllowedLocationIds}
/>
)}
</InlineStack>
<div>
<Button submit variant="primary" loading={isSubmitting}>
Add rule
</Button>
</div>
</BlockStack>
</Form>
</Card>
);
}