Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 62,765 Bytes
8133df9 f462120 07a68d0 f462120 8133df9 07a68d0 f462120 8133df9 07a68d0 8133df9 07a68d0 f462120 07a68d0 f462120 07a68d0 f462120 8133df9 f462120 8133df9 f462120 07a68d0 8873406 07a68d0 8873406 07a68d0 f462120 07a68d0 8133df9 07a68d0 8133df9 07a68d0 8873406 07a68d0 f462120 07a68d0 f462120 07a68d0 8133df9 8873406 07a68d0 f462120 07a68d0 8873406 07a68d0 8873406 07a68d0 f462120 8133df9 f462120 8133df9 f462120 07a68d0 f462120 8133df9 07a68d0 f462120 8133df9 07a68d0 f462120 07a68d0 8133df9 07a68d0 8873406 07a68d0 f462120 8133df9 07a68d0 8873406 07a68d0 8873406 07a68d0 8873406 07a68d0 f462120 07a68d0 f462120 07a68d0 8133df9 07a68d0 f462120 07a68d0 f462120 07a68d0 f462120 07a68d0 f462120 8133df9 f462120 07a68d0 8133df9 07a68d0 f462120 07a68d0 8873406 07a68d0 8873406 07a68d0 8873406 07a68d0 8873406 07a68d0 8873406 07a68d0 8133df9 07a68d0 f462120 8133df9 07a68d0 f462120 8133df9 07a68d0 f462120 07a68d0 8133df9 07a68d0 8873406 07a68d0 8133df9 07a68d0 8133df9 07a68d0 8133df9 07a68d0 8133df9 07a68d0 8133df9 07a68d0 8133df9 07a68d0 8133df9 07a68d0 8873406 f462120 8133df9 8873406 07a68d0 8133df9 07a68d0 8133df9 07a68d0 8133df9 f462120 07a68d0 8133df9 f462120 8133df9 07a68d0 8133df9 f462120 8133df9 07a68d0 8133df9 07a68d0 f462120 8133df9 07a68d0 f462120 8133df9 f462120 07a68d0 8133df9 07a68d0 8133df9 07a68d0 8133df9 07a68d0 f462120 07a68d0 8133df9 07a68d0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 | import { useCallback, useEffect, useRef, useState, type ComponentType } from "react";
import { Dashboard } from "./Dashboard";
import type { DashboardKit } from "./Dashboard";
import { API_V1, CREDENTIALS } from "../../apiContract";
import { ConfirmDialog } from "../../ui/ConfirmDialog";
import { AppGrid } from "../AppGrid";
import { ActionCadence } from "../actions/ActionCadence";
import { SkuActions } from "../actions/SkuActions";
import { Kpi, KpiStrip } from "../../viz/kit/Kpi";
import type { KpiProps } from "../../viz/kit/Kpi";
import "../../styles/sdlc79/restock-planner.css";
import "../../styles/sdlc81/restock-loop.css";
import "../../styles/sdlc81/restock-reorder.css";
import "../../styles/sdlc82/restock-grid.css";
// The App frame owns navigation. This view shares Dashboard, the SKU Grid and the SKU drawer.
/** C2: the App as the dispatcher passes it. Structurally equal to lane A's TemplateApplication. */
interface RestockApplication {
id: string;
name: string;
templateKind?: string;
templateView?: string;
templateMark?: string;
templateConnector?: string;
capabilities?: Record<string, boolean>;
}
interface RestockAppViewProps { application: RestockApplication; canEdit: boolean }
// C6 fixture compilers replace this glob with injected module loaders, never substitute the inbound UI kit.
const dashboardModules = import.meta.glob("../App{Tabs,Dashboard}.tsx");
function useDashboardKit() {
const [kit, setKit] = useState<DashboardKit | null | undefined>(undefined);
useEffect(() => {
let alive = true;
const tabs = dashboardModules["../AppTabs.tsx"];
const dashboard = dashboardModules["../AppDashboard.tsx"];
if (!tabs || !dashboard) { setKit(null); return; }
void Promise.all([tabs(), dashboard()]).then(([tabModule, dashboardModule]) => {
const t = tabModule as { AppTabs?: DashboardKit["AppTabs"]; default?: DashboardKit["AppTabs"] };
const d = dashboardModule as { AppDashboard?: DashboardKit["AppDashboard"]; default?: DashboardKit["AppDashboard"] };
const AppTabs = t.AppTabs ?? t.default;
const AppDashboard = d.AppDashboard ?? d.default;
if (alive) setKit(AppTabs && AppDashboard ? { AppTabs, AppDashboard } : null);
}).catch(() => { if (alive) setKit(null); });
return () => { alive = false; };
}, []);
return kit;
}
interface Item {
id: string;
sku: string;
asin: string;
title: string;
band: string;
reason: string;
status: string;
owner: string;
due: string;
fbaAvailable: number | null;
daysOfSupply: number | null;
units30d: number | null;
recommendedQty: number | null;
recommendedShipDate: string;
odooOnHand: number | null;
odooFba: number | null;
odooNote: string;
openPurchaseQty: number | null;
inReport: boolean;
label_owner: string;
prep_owner: string;
amazonRecommendedQty: number | null;
odooNonFbaOnHand: number | null;
sentQty: number | null;
inboundPlanId: string;
sendToAmazonUrl: string;
inboundState: string;
inboundReason: string;
cancelledPlanId: string;
cancelledBy: string;
cancelledAt: string;
}
interface Warehouse { warehouse: string; fba: boolean; onHand: number | null }
interface PurchaseOrder { order: string; vendor: string; openQty: number | null; expected: string }
interface Point {
date: string; fbaAvailable: number | null; daysOfSupply: number | null; units30d: number | null;
inbound: number | null; band: string;
}
/** The two band thresholds in days of supply, from the App settings (R49). */
interface Thresholds { sendToFbaDays: number; overstockDays: number }
type InboundOwner = "Seller" | "Amazon";
interface ShipFromAddress {
name: string; addressLine1: string; addressLine2: string; city: string;
stateOrProvinceCode: string; postalCode: string; countryCode: string; phoneNumber: string;
}
interface RestockSettings extends Thresholds {
label_owner: InboundOwner; prep_owner: InboundOwner; ship_from: ShipFromAddress;
fba_capacity: { value: number; unit: string } | null;
}
interface CapacityCause { cause: string; count: number; skus: string[] }
interface CapacitySummary {
unit: string | null; fba_capacity: RestockSettings["fba_capacity"]; remaining: number | null;
storageVolume: number | null; plannedVolume: number | null; plannedSkuCount: number;
capacityReason: string; quantityBasis: string; storageCauses: CapacityCause[]; plannedCauses: CapacityCause[];
}
interface FeeCoverage { coverage: string; basis: string; source: string }
type AppUrl = (path: string, params?: Record<string, string>) => string;
interface Detail {
item: Item; warehouses: Warehouse[]; openPurchaseOrders: PurchaseOrder[]; points: Point[]; thresholds: Thresholds | null;
offset: number; limit: number; total: number;
totals: Record<string, number>;
}
interface ListPage {
items: Item[];
cursor: string | null;
previousCursor: string | null;
offset: number;
total: number;
ready: boolean;
message: string;
notices: string[];
refreshedAt: string;
lastError: string;
statuses: string[];
owners: string[];
thresholds: Thresholds | null;
canEdit: boolean;
lowInventoryFee: FeeCoverage | null;
}
type Load<T> = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T };
interface RestockTile extends KpiProps { id: string; trend: number[] }
// C4: lane C adds the optional trend prop. The current kit still shows value and change.
const RestockKpi: ComponentType<KpiProps & { trend?: number[] }> = Kpi;
function RestockTiles({ url, revision }: { url: AppUrl; revision: unknown }) {
const [state, setState] = useState<Load<RestockTile[]>>({ phase: "loading" });
const [attempt, setAttempt] = useState(0);
useEffect(() => {
const controller = new AbortController();
setState({ phase: "loading" });
void fetch(url("/tiles"), { credentials: CREDENTIALS, signal: controller.signal })
.then((response) => readJson(response, "Restock tiles could not be loaded"))
.then((body) => {
const entries = list((body as { tiles?: unknown } | null)?.tiles);
const tiles = entries.map((entry): RestockTile => {
const tile = entry as RestockTile;
return { id: text(tile.id), label: text(tile.label), value: num(tile.value), unit: text(tile.unit),
validated: tile.validated === true, reason: text(tile.reason),
trend: list(tile.trend).filter((point): point is number => num(point) !== null),
change: tile.change };
});
if (tiles.length !== 3 || new Set(tiles.map((tile) => tile.id)).size !== 3) {
throw new Error("Restock tiles could not be loaded");
}
if (!controller.signal.aborted) setState({ phase: "ready", value: tiles });
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) setState({ phase: "error", message: failure(reason, "Restock tiles could not be loaded") });
});
return () => controller.abort();
}, [url, revision, attempt]);
if (state.phase === "loading") return <p className="rp-muted" role="status">Loading restock tiles</p>;
if (state.phase === "error") return <Failed message={state.message} onRetry={() => setAttempt((n) => n + 1)} />;
return <KpiStrip label="Restock figures">
{state.value.map((tile) => <RestockKpi key={tile.id} {...tile} />)}
</KpiStrip>;
}
/** S82-T26: the work tab lists every SKU in this module table. Band and Status are pill columns there. */
const RESTOCK_TABLE = "ut_amazon_restock";
const WORK_TAB = "skus";
const STATUSES = ["Open", "Accepted", "Ordered", "Sent to FBA", "Watching", "Done", "Dismissed"];
/** The server's page bound. A SKU lookup follows the cursor past it, so no SKU is out of reach (rule 1). */
const LOOKUP_PAGE = 200;
const EMPTY_PLAN = "Nothing to restock";
/** Used only when an answer carries no thresholds; the server's settings win. */
const FALLBACK_THRESHOLDS: Thresholds = { sendToFbaDays: 30, overstockDays: 90 };
const text = (value: unknown) => (typeof value === "string" ? value : "");
const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null);
const list = (value: unknown) => (Array.isArray(value) ? value : []);
const words = (value: unknown) => list(value).map(text).filter(Boolean);
const pageButtonStyle = (disabled: boolean) => disabled
? { opacity: "var(--lp-home-disabled-opacity)", cursor: "not-allowed" } : undefined;
async function readJson(response: Response, fallback: string): Promise<unknown> {
const body: unknown = await response.json().catch(() => null);
if (response.ok) return body;
// The server sends a refusal as top-level {error}; a bare router sends it under {detail: {error}}.
const shaped = body as { error?: { message?: unknown }; detail?: { error?: { message?: unknown } } } | null;
throw new Error(text(shaped?.error?.message) || text(shaped?.detail?.error?.message) || fallback);
}
const failure = (reason: unknown, fallback: string) => (reason instanceof Error && reason.message
? reason.message : fallback);
function parseItem(raw: unknown): Item | null {
const row = (raw ?? {}) as Record<string, unknown>;
const id = text(row.id);
if (!id) return null;
return {
id, sku: text(row.sku), asin: text(row.asin), title: text(row.title) || text(row.sku), band: text(row.band),
reason: text(row.reason), status: text(row.status), owner: text(row.owner), due: text(row.due),
fbaAvailable: num(row.fbaAvailable), daysOfSupply: num(row.daysOfSupply), units30d: num(row.units30d),
recommendedQty: num(row.recommendedQty), recommendedShipDate: text(row.recommendedShipDate),
odooOnHand: num(row.odooOnHand), odooFba: num(row.odooFba), odooNote: text(row.odooNote),
openPurchaseQty: num(row.openPurchaseQty), inReport: row.inReport !== false,
label_owner: text(row.label_owner), prep_owner: text(row.prep_owner),
amazonRecommendedQty: num(row.amazonRecommendedQty), odooNonFbaOnHand: num(row.odooNonFbaOnHand),
sentQty: num(row.sentQty), inboundPlanId: text(row.inboundPlanId), sendToAmazonUrl: text(row.sendToAmazonUrl),
inboundState: text(row.inboundState), inboundReason: text(row.inboundReason),
cancelledPlanId: text(row.cancelledPlanId), cancelledBy: text(row.cancelledBy), cancelledAt: text(row.cancelledAt),
};
}
function parseThresholds(raw: unknown): Thresholds | null {
const body = (raw ?? {}) as Record<string, unknown>;
const send = num(body.sendToFbaDays);
const over = num(body.overstockDays);
return send !== null && over !== null && send > 0 && over > send ? { sendToFbaDays: send, overstockDays: over } : null;
}
function parseSettings(raw: unknown): RestockSettings {
const body = (raw ?? {}) as Record<string, unknown>;
const thresholds = parseThresholds(body);
if (!thresholds || !["Seller", "Amazon"].includes(text(body.label_owner))
|| !["Seller", "Amazon"].includes(text(body.prep_owner))) throw new Error("Restock settings could not be loaded.");
const address = (body.ship_from ?? {}) as Record<string, unknown>;
const capacity = body.fba_capacity as { value?: unknown; unit?: unknown } | null | undefined;
if (capacity && (num(capacity.value) === null || !["cu ft", "cu m"].includes(text(capacity.unit)))) {
throw new Error("FBA capacity needs a value and volume unit.");
}
return { ...thresholds, label_owner: body.label_owner as InboundOwner, prep_owner: body.prep_owner as InboundOwner,
fba_capacity: capacity ? { value: Number(capacity.value), unit: text(capacity.unit) } : null,
ship_from: { name: text(address.name), addressLine1: text(address.addressLine1), addressLine2: text(address.addressLine2),
city: text(address.city), stateOrProvinceCode: text(address.stateOrProvinceCode), postalCode: text(address.postalCode),
countryCode: text(address.countryCode), phoneNumber: text(address.phoneNumber) } };
}
function parsePage(raw: unknown): ListPage {
const body = (raw ?? {}) as Record<string, unknown>;
const statuses = words(body.statuses);
return {
items: list(body.items).map(parseItem).filter((row): row is Item => row !== null),
cursor: text(body.cursor) || null, ready: body.ready === true, message: text(body.message),
previousCursor: text(body.previousCursor) || null, offset: num(body.offset) ?? 0, total: num(body.total) ?? 0,
notices: words(body.notices), refreshedAt: text(body.refreshedAt), lastError: text(body.lastError),
statuses: statuses.length ? statuses : STATUSES, owners: words(body.owners),
thresholds: parseThresholds(body.thresholds), canEdit: body.canEdit === true,
lowInventoryFee: body.lowInventoryFee ? body.lowInventoryFee as FeeCoverage : null,
};
}
function parseDetail(raw: unknown, fallback: Item): Detail {
const body = (raw ?? {}) as Record<string, unknown>;
const rawTotals = (body.detailTotals ?? {}) as Record<string, unknown>;
const totals: Record<string, number> = {};
for (const field of ["warehouses", "openPurchaseOrders", "events", "points"]) totals[field] = num(rawTotals[field]) ?? 0;
return {
item: parseItem(body) ?? fallback,
thresholds: parseThresholds(body.thresholds),
offset: num(body.detailOffset) ?? 0, limit: num(body.detailLimit) ?? 50, total: num(body.detailTotal) ?? 0,
totals,
warehouses: list(body.warehouses).map((entry) => {
const row = (entry ?? {}) as Record<string, unknown>;
return { warehouse: text(row.warehouse), fba: row.fba === true, onHand: num(row.onHand) };
}),
openPurchaseOrders: list(body.openPurchaseOrders).map((entry) => {
const row = (entry ?? {}) as Record<string, unknown>;
return { order: text(row.order), vendor: text(row.vendor), openQty: num(row.openQty), expected: text(row.expected) };
}),
points: list(body.points).map((entry) => {
const row = (entry ?? {}) as Record<string, unknown>;
return { date: text(row.date), fbaAvailable: num(row.fbaAvailable), daysOfSupply: num(row.daysOfSupply),
units30d: num(row.units30d), inbound: num(row.inbound), band: text(row.band) };
}),
};
}
/** A quantity with at most one decimal, or nothing when the source does not know it. */
const qty = (value: number | null) => (value === null ? ""
: value.toLocaleString(undefined, { maximumFractionDigits: 1 }));
/** "Oct 24" from an ISO day. A calendar day is read in UTC. */
function day(iso: string) {
if (!iso) return "";
const date = new Date(iso.length === 10 ? iso + "T00:00:00Z" : iso);
return Number.isNaN(date.getTime()) ? iso
: date.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" });
}
const statusTone = (status: string) => status.toLowerCase().replace(/[^a-z]+/g, "-");
type Zone = "critical" | "healthy" | "overstock";
/** The zone of a days of supply value, by the same rule the module bands with. */
function zoneOf(days: number, t: Thresholds): Zone {
if (days < t.sendToFbaDays) return "critical";
if (days > t.overstockDays) return "overstock";
return "healthy";
}
/** The meter's words: its aria-label and title. */
function meterWords(days: number, t: Thresholds): string {
const zone = zoneOf(days, t);
if (zone === "critical") return `${qty(days)} days of supply, under the ${qty(t.sendToFbaDays)} day Send to FBA threshold`;
if (zone === "overstock") return `${qty(days)} days of supply, over the ${qty(t.overstockDays)} day Overstock threshold`;
return `${qty(days)} days of supply, inside the ${qty(t.sendToFbaDays)} to ${qty(t.overstockDays)} day range`;
}
/** The three levels, named once, from the server's thresholds. */
function levelLabels(t: Thresholds): [Zone, string][] {
return [["critical", `Under ${qty(t.sendToFbaDays)} days`],
["healthy", `${qty(t.sendToFbaDays)} to ${qty(t.overstockDays)} days`],
["overstock", `Over ${qty(t.overstockDays)} days`]];
}
/** Piecewise position in percent: 0 to send fills 40, send to overstock the next 40, overstock to twice overstock 20. */
function meterPosition(days: number, t: Thresholds): number {
const send = t.sendToFbaDays;
const over = t.overstockDays;
if (days <= 0) return 0;
if (days <= send) return (days / send) * 40;
if (days <= over) return 40 + ((days - send) / (over - send)) * 40;
if (days <= over * 2) return 80 + ((days - over) / over) * 20;
return 100;
}
/** A bar meter for days of supply over a track zoned at the server thresholds, with a tick at each threshold. */
function DaysMeter({ days, thresholds, size, labels = false }: {
days: number | null; thresholds: Thresholds; size: "cell" | "wide" | "mini"; labels?: boolean;
}) {
if (days === null) return null;
const at = (value: number) => `${meterPosition(value, thresholds)}%`;
const sendAt = meterPosition(thresholds.sendToFbaDays, thresholds);
const overAt = meterPosition(thresholds.overstockDays, thresholds);
const zone = zoneOf(days, thresholds);
const words = meterWords(days, thresholds);
return <span className={`rp-meter is-${size} is-${zone}${days > thresholds.overstockDays * 2 ? " is-past" : ""}`}
role="img" aria-label={words} title={words}>
<span className="rp-meter-track">
<span className="rp-meter-zone is-critical" style={{ width: `${sendAt}%` }} />
<span className="rp-meter-zone is-healthy" style={{ width: `${overAt - sendAt}%` }} />
<span className="rp-meter-zone is-overstock" style={{ width: `${100 - overAt}%` }} />
<span className="rp-meter-bar" style={{ width: at(days) }} />
<span className="rp-meter-tick" style={{ left: at(thresholds.sendToFbaDays) }} />
<span className="rp-meter-tick" style={{ left: at(thresholds.overstockDays) }} />
</span>
{labels && <span className="rp-meter-labels" aria-hidden="true">
<span style={{ left: at(thresholds.sendToFbaDays) }}>{qty(thresholds.sendToFbaDays)}</span>
<span style={{ left: at(thresholds.overstockDays) }}>{qty(thresholds.overstockDays)}</span>
</span>}
</span>;
}
/** The number and its meter in one cell. A critical number reads red and heavier, so it stands out without colour. */
function DaysCell({ days, units, thresholds, size }: {
days: number | null; units: number | null; thresholds: Thresholds; size: "cell" | "mini";
}) {
if (days === null && units === 0) return <span className="rp-days"><span className="rp-days-none">No sales</span></span>;
const zone = days === null ? "" : zoneOf(days, thresholds);
return <span className="rp-days">
<DaysMeter days={days} thresholds={thresholds} size={size} />
<span className={zone === "critical" ? "rp-days-num is-critical" : "rp-days-num"}>{qty(days)}</span>
</span>;
}
function Legend({ thresholds }: { thresholds: Thresholds }) {
return <ul className="rp-legend" aria-label="Days of supply levels">
{levelLabels(thresholds).map(([zone, label]) => <li key={zone} className={`rp-legend-item is-${zone}`}>
<span className="rp-legend-swatch" aria-hidden="true" />{label}
</li>)}
</ul>;
}
function Skeleton({ rows = 4 }: { rows?: number }) {
return <div className="rp-skeleton-rows" aria-busy="true" aria-label="Loading">
{Array.from({ length: rows }, (_v, index) => <div key={index} className="rp-skeleton" />)}
</div>;
}
function Failed({ message, onRetry }: { message: string; onRetry: () => void }) {
return <p className="rp-error" role="alert">{message}{" "}
<button type="button" className="rp-link" onClick={onRetry}>Retry</button></p>;
}
const ADDRESS_FIELDS: { key: keyof ShipFromAddress; label: string; wide?: boolean }[] = [
{ key: "name", label: "Name", wide: true },
{ key: "addressLine1", label: "Street address", wide: true },
{ key: "addressLine2", label: "Address line 2", wide: true },
{ key: "city", label: "City" }, { key: "stateOrProvinceCode", label: "State or province" },
{ key: "postalCode", label: "Postal code" }, { key: "countryCode", label: "Country code" },
{ key: "phoneNumber", label: "Phone", wide: true },
];
function CapacityHeader({ url, revision }: { url: AppUrl; revision: unknown }) {
const [state, setState] = useState<Load<CapacitySummary>>({ phase: "loading" });
const [retry, setRetry] = useState(0);
useEffect(() => {
const controller = new AbortController();
setState({ phase: "loading" });
void fetch(url("/capacity"), { credentials: CREDENTIALS, signal: controller.signal })
.then((response) => readJson(response, "FBA capacity could not be loaded."))
.then((body) => { if (!controller.signal.aborted) setState({ phase: "ready", value: body as CapacitySummary }); })
.catch((reason: unknown) => {
if (!controller.signal.aborted) setState({ phase: "error", message: failure(reason, "FBA capacity could not be loaded.") });
});
return () => controller.abort();
}, [url, revision, retry]);
if (state.phase === "loading") return <p className="rp-muted" role="status">Loading FBA capacity</p>;
if (state.phase === "error") return <Failed message={state.message} onRetry={() => setRetry((value) => value + 1)} />;
const value = state.value;
const causes = new Map<string, CapacityCause>();
for (const group of [...value.storageCauses, ...value.plannedCauses]) {
const skus = [...new Set([...(causes.get(group.cause)?.skus ?? []), ...group.skus])];
causes.set(group.cause, { cause: group.cause, count: skus.length, skus });
}
const volume = (number: number | null) => number === null || !value.unit ? "Not known" : `${qty(number)} ${value.unit}`;
return <section className="rp-bar" aria-label="FBA capacity">
<dl className="rp-settings-read">
<Fact label="Remaining FBA capacity" value={volume(value.remaining)} numeric />
<div className="rp-fact" title={value.quantityBasis}><dt>Planned Send to FBA</dt>
<dd className="is-num">{volume(value.plannedVolume)}</dd></div>
<Fact label="Capacity source" value="Typed" />
<Fact label="Current storage" value={volume(value.storageVolume)} numeric />
</dl>
{value.capacityReason && <p className="rp-muted" role="status">{value.capacityReason}</p>}
{causes.size > 0 && <div className="rp-notices">
{[...causes.values()].map(({ cause, count, skus }) => <div key={cause}>
<p role="status">{count > 0 ? `${qty(count)} ${count === 1 ? "SKU has" : "SKUs have"} ${cause}` : cause}</p>
{skus.length > 0 && <details>
<summary>Show SKUs</summary>
<ul aria-label={`SKUs with ${cause}`} tabIndex={0}
style={{ maxHeight: "40vh", overflowY: "auto", overflowWrap: "anywhere" }}>
{skus.map((sku) => <li key={sku}>{sku}</li>)}
</ul>
</details>}
</div>)}
<p>Enter carton size and CBM in Command Center Data Entry.</p>
</div>}
</section>;
}
function RestockSettingsFields({ value, editable, saving, onChange }: {
value: RestockSettings; editable: boolean; saving: boolean; onChange: (value: RestockSettings) => void;
}) {
const [capacityUnit, setCapacityUnit] = useState(value.fba_capacity?.unit ?? "cu ft");
if (!editable) return <dl className="rp-settings-read">
<Fact label="Send to FBA days" value={qty(value.sendToFbaDays)} numeric />
<Fact label="Overstock days" value={qty(value.overstockDays)} numeric />
<Fact label="Label owner" value={value.label_owner} />
<Fact label="Prep owner" value={value.prep_owner} />
<Fact label="FBA capacity (Typed)" value={value.fba_capacity
? `${qty(value.fba_capacity.value)} ${value.fba_capacity.unit}` : "Enter FBA capacity in Restock settings"} />
<div className="rp-fact rp-ship-from-read"><dt>Ship from</dt>
<dd>{Object.values(value.ship_from).some(Boolean)
? <address>{[value.ship_from.name, value.ship_from.addressLine1, value.ship_from.addressLine2,
[value.ship_from.city, value.ship_from.stateOrProvinceCode, value.ship_from.postalCode].filter(Boolean).join(", "),
value.ship_from.countryCode, value.ship_from.phoneNumber].filter(Boolean)
.map((line, index) => <span key={index}>{line}</span>)}</address>
: "No address"}</dd>
</div>
</dl>;
return <fieldset className="rp-settings-fields" disabled={saving}>
<div className="rp-settings-grid">
<label className="rp-field"><span className="rp-field-label">FBA capacity (Typed)</span>
<input className="rp-input" aria-label="FBA capacity (Typed)" type="number" min="0" step="any" value={value.fba_capacity?.value ?? ""}
onChange={(event) => onChange({ ...value, fba_capacity: event.target.value === "" ? null
: { value: event.target.valueAsNumber, unit: value.fba_capacity?.unit ?? capacityUnit } })} />
</label>
<label className="rp-field"><span className="rp-field-label">Capacity unit</span>
<select className="rp-select" aria-label="Capacity unit" value={value.fba_capacity?.unit ?? capacityUnit}
onChange={(event) => {
setCapacityUnit(event.target.value);
if (value.fba_capacity) onChange({ ...value, fba_capacity: { ...value.fba_capacity, unit: event.target.value } });
}}>
<option value="cu ft">cu ft</option><option value="cu m">cu m</option>
</select>
</label>
{(["sendToFbaDays", "overstockDays"] as const).map((field) => <label className="rp-field" key={field}>
<span className="rp-field-label">{field === "sendToFbaDays" ? "Send to FBA days" : "Overstock days"}</span>
<input className="rp-input" type="number" min="1" max="3650" step="any" required value={value[field]}
onChange={(event) => onChange({ ...value, [field]: event.target.valueAsNumber })} />
</label>)}
{(["label_owner", "prep_owner"] as const).map((field) => <label className="rp-field" key={field}>
<span className="rp-field-label">{field === "label_owner" ? "Label owner" : "Prep owner"}</span>
<select className="rp-select" value={value[field]}
onChange={(event) => onChange({ ...value, [field]: event.target.value as InboundOwner })}>
<option value="Seller">Seller</option><option value="Amazon">Amazon</option>
</select>
</label>)}
</div>
<fieldset className="rp-ship-from">
<legend className="rp-heading">Ship from</legend>
<div className="rp-settings-grid">
{ADDRESS_FIELDS.map(({ key, label, wide }) => <label key={key} className={wide ? "rp-field rp-address-wide" : "rp-field"}>
<span className="rp-field-label">{label}</span>
<input className="rp-input" type={key === "phoneNumber" ? "tel" : "text"} value={value.ship_from[key]}
maxLength={key === "countryCode" ? 2 : undefined}
onChange={(event) => onChange({ ...value, ship_from: { ...value.ship_from, [key]: event.target.value } })} />
</label>)}
</div>
</fieldset>
</fieldset>;
}
function RestockSettingsPanel({ url, editable, onSaved }: {
url: AppUrl; editable: boolean; onSaved: (value: RestockSettings) => void;
}) {
const [loaded, setLoaded] = useState<Load<RestockSettings>>({ phase: "loading" });
const [draft, setDraft] = useState<RestockSettings | null>(null);
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
const [message, setMessage] = useState("");
const [saveError, setSaveError] = useState("");
const [attempt, setAttempt] = useState(0);
const saveRequest = useRef<AbortController | null>(null);
useEffect(() => {
const controller = new AbortController();
void fetch(url("/settings"), { credentials: CREDENTIALS, signal: controller.signal })
.then((response) => readJson(response, "Restock settings could not be loaded."))
.then((body) => {
if (controller.signal.aborted) return;
const value = parseSettings(body);
setLoaded({ phase: "ready", value });
onSaved(value);
}).catch((reason: unknown) => {
if (!controller.signal.aborted) setLoaded({ phase: "error", message: failure(reason, "Restock settings could not be loaded.") });
});
return () => { controller.abort(); saveRequest.current?.abort(); };
}, [url, onSaved, attempt]);
const save = async () => {
if (!editable || !draft || saving) return;
const controller = new AbortController();
saveRequest.current = controller;
setSaving(true);
setMessage("");
setSaveError("");
try {
const response = await fetch(url("/settings"), { method: "PATCH", credentials: CREDENTIALS,
signal: controller.signal, headers: { "Content-Type": "application/json" }, body: JSON.stringify(draft) });
const value = parseSettings(await readJson(response, "Restock settings were not saved."));
if (controller.signal.aborted) return;
setLoaded({ phase: "ready", value });
setEditing(false);
setDraft(null);
setMessage("Settings saved");
onSaved(value);
} catch (reason) {
if (!controller.signal.aborted) setSaveError(failure(reason, "Restock settings were not saved."));
} finally {
if (!controller.signal.aborted) setSaving(false);
}
};
return <details className="rp-settings">
<summary className="rp-heading">Settings</summary>
<div className="rp-settings-body">
{loaded.phase === "loading" && <Skeleton rows={2} />}
{loaded.phase === "error" && <Failed message={loaded.message} onRetry={() => {
setLoaded({ phase: "loading" }); setAttempt((count) => count + 1);
}} />}
{loaded.phase === "ready" && <>
{editable && editing && draft
? <form className="rp-settings-form" onSubmit={(event) => { event.preventDefault(); void save(); }}>
<RestockSettingsFields value={draft} editable={editable} saving={saving} onChange={setDraft} />
<div className="rp-bar">
<button type="submit" className="rp-button is-primary" disabled={saving}>{saving ? "Saving" : "Save"}</button>
<button type="button" className="rp-button is-quiet" disabled={saving}
onClick={() => { setEditing(false); setDraft(null); setSaveError(""); }}>Cancel</button>
</div>
</form>
: <RestockSettingsFields value={loaded.value} editable={false} saving={false} onChange={setDraft} />}
{editable && !editing && <button type="button" className="rp-button" onClick={() => {
setDraft(loaded.value); setEditing(true); setMessage(""); setSaveError("");
}}>Edit settings</button>}
</>}
{saveError && <p className="rp-error" role="alert">{saveError}</p>}
{message && <p className="rp-muted" role="status">{message}</p>}
</div>
</details>;
}
function StatusPill({ status }: { status: string }) {
return status ? <span className={`rp-pill is-${statusTone(status)}`}>{status}</span> : null;
}
function Fact({ label, value, numeric = false }: { label: string; value: string; numeric?: boolean }) {
return <div className="rp-fact">
<dt>{label}</dt><dd className={numeric ? "is-num" : undefined}>{value || "Not known"}</dd>
</div>;
}
interface Reorder {
quantityUnit: string; dailySalesUnit: string; product: string; unitsPerSku: number | null;
dailySales: { amazon: number | null; odoo: number | null; total: number | null };
leadTimeDays: number | null; purchaseOrderCount: number | null; coverDays: number | null;
onHand: number | null; openOrders: number | null; suggestedQuantity: number | null;
cause: string; fix: string;
}
function parseReorder(raw: unknown): Reorder {
const body = (raw ?? {}) as Record<string, unknown>;
const sales = (body.daily_sales ?? {}) as Record<string, unknown>;
if (body.state !== "ready" && body.state !== "unavailable") throw new Error("Reorder could not be loaded.");
const quantityUnit = text(body.quantity_unit);
const dailySalesUnit = text(body.daily_sales_unit);
if (body.state === "ready" && (!quantityUnit || !dailySalesUnit || num(body.suggested_quantity) === null)) {
throw new Error("Reorder units or quantity are missing. Retry after syncing.");
}
return {
quantityUnit, dailySalesUnit, product: text(body.odoo_product), unitsPerSku: num(body.units_per_sku),
dailySales: { amazon: num(sales.amazon), odoo: num(sales.odoo), total: num(sales.total) },
leadTimeDays: num(body.lead_time_days), purchaseOrderCount: num(body.purchase_order_count),
coverDays: num(body.cover_days), onHand: num(body.on_hand), openOrders: num(body.open_order_quantity),
suggestedQuantity: body.state === "ready" ? num(body.suggested_quantity) : null,
cause: text(body.cause), fix: text(body.fix) || text(body.message),
};
}
function SupplierReorder({ itemId, url }: { itemId: string; url: AppUrl }) {
const [state, setState] = useState<Load<Reorder>>({ phase: "loading" });
const [coverDays, setCoverDays] = useState<string | null>(null);
const [defaultCover, setDefaultCover] = useState("");
const [attempt, setAttempt] = useState(0);
const validCover = coverDays === null || (coverDays.trim() !== "" && Number.isFinite(Number(coverDays)) && Number(coverDays) >= 0);
useEffect(() => {
const controller = new AbortController();
setState({ phase: "loading" });
if (!validCover) return () => controller.abort();
const params: Record<string, string> = coverDays === null ? {} : { cover_days: coverDays };
void fetch(url(`/items/${encodeURIComponent(itemId)}/reorder`, params),
{ credentials: CREDENTIALS, signal: controller.signal })
.then((response) => readJson(response, "Reorder could not be loaded."))
.then((body) => {
if (controller.signal.aborted) return;
const value = parseReorder(body);
if (coverDays === null) setDefaultCover(value.coverDays === null ? "" : String(value.coverDays));
setState({ phase: "ready", value });
}).catch((reason: unknown) => {
if (!controller.signal.aborted) setState({ phase: "error", message: failure(reason, "Reorder could not be loaded.") });
});
return () => controller.abort();
}, [itemId, url, coverDays, validCover, attempt]);
const value = state.phase === "ready" ? state.value : null;
const amount = (quantity: number | null) => quantity === null || !value?.quantityUnit
? "Not known" : `${qty(quantity)} ${value.quantityUnit}`;
return <section className="rp-section rp-reorder" aria-label="Reorder from supplier">
<h3 className="rp-heading">Reorder from supplier</h3>
<label className="rp-field rp-reorder-cover">
<span className="rp-field-label">Cover days</span>
<input className="rp-input" type="number" min="0" step="any" required
value={coverDays ?? defaultCover} aria-invalid={!validCover}
onChange={(event) => setCoverDays(event.target.value)} />
</label>
{!validCover ? <p className="rp-error" role="alert">Enter cover days at or above 0.</p>
: state.phase === "loading" ? <Skeleton rows={2} />
: state.phase === "error" ? <Failed message={state.message} onRetry={() => setAttempt((count) => count + 1)} />
: value && <div className="rp-reorder-result" aria-live="polite">
{value.fix && <p className="rp-notice" role="status" title={value.cause}>{value.fix}</p>}
{value.quantityUnit && <>
<dl className="rp-facts">
<Fact label="Product" value={value.product} />
<Fact label="Per Amazon SKU" value={amount(value.unitsPerSku)} numeric />
</dl>
<table className="rp-mini">
<caption>Daily sales ({value.dailySalesUnit || "Unit not known"})</caption>
<thead><tr><th scope="col">Channel</th><th scope="col" className="is-num">Daily sales</th></tr></thead>
<tbody>{([["Amazon", value.dailySales.amazon], ["Odoo", value.dailySales.odoo], ["Total", value.dailySales.total]] as const)
.map(([channel, daily]) => <tr key={channel}><th scope="row">{channel}</th>
<td className="is-num">{daily === null || !value.dailySalesUnit ? "Not known" : qty(daily)}</td></tr>)}</tbody>
</table>
<dl className="rp-facts">
<Fact label="Lead time" value={value.leadTimeDays === null ? "Not known" : `${qty(value.leadTimeDays)} days`} numeric />
<Fact label="Purchase orders" value={qty(value.purchaseOrderCount)} numeric />
<Fact label="On hand" value={amount(value.onHand)} numeric />
<Fact label="Open purchases" value={amount(value.openOrders)} numeric />
</dl>
<p className="rp-reorder-suggestion"><span>Suggested quantity</span>
<output aria-label="Suggested quantity">{amount(value.suggestedQuantity)}</output></p>
</>}
</div>}
</section>;
}
function InboundPlan({ item, editable, busy, onCancel }: {
item: Item; editable: boolean; busy: boolean; onCancel: () => void;
}) {
if (!item.inboundState && !item.inboundPlanId && !item.cancelledPlanId) return null;
const cancelled = item.inboundState === "cancelled";
const title = cancelled ? "Plan cancelled" : item.inboundState === "sent" ? "Sent to FBA"
: item.inboundState.startsWith("cancel_") ? "Cancellation unconfirmed"
: item.inboundState === "held" ? "Held back"
: (item.inboundState === "failed" || item.inboundState === "refused") ? "Plan refused" : "Plan unconfirmed";
return <section className="rp-section rp-inbound-plan" aria-label="Inbound plan">
<h3 className="rp-heading">{title}</h3>
<dl className="rp-facts">
<Fact label="Plan" value={cancelled ? item.cancelledPlanId : item.inboundPlanId} />
<Fact label="Amazon quantity" value={qty(item.amazonRecommendedQty)} numeric />
<Fact label="Odoo on hand at send" value={qty(item.odooNonFbaOnHand)} numeric />
<Fact label="Sent quantity" value={qty(item.sentQty)} numeric />
{cancelled && <>
<Fact label="Cancelled by" value={item.cancelledBy} />
<Fact label="Cancelled on" value={day(item.cancelledAt)} />
</>}
</dl>
{item.inboundReason && <p className="rp-notice" role="status">{item.inboundReason}</p>}
{!cancelled && item.sendToAmazonUrl && <a className="rp-link" href={item.sendToAmazonUrl}
target="_blank" rel="noopener noreferrer">Open in Send to Amazon</a>}
{editable && !cancelled && item.inboundPlanId && <button type="button" className="rp-button"
disabled={busy} onClick={onCancel}>Cancel plan</button>}
</section>;
}
/** One SKU from the plan by its exact SKU. It follows every cursor, so a large plan never hides a SKU (rule 1). */
async function findItem(url: AppUrl, sku: string, signal: AbortSignal): Promise<Item | null> {
const wanted = sku.trim();
const seen = new Set<string>();
let cursor: string | null = null;
do {
const params: Record<string, string> = { q: wanted, limit: String(LOOKUP_PAGE) };
if (cursor) params.cursor = cursor;
const response = await fetch(url("/items", params), { credentials: CREDENTIALS, signal });
const page = parsePage(await readJson(response, "This SKU could not be loaded."));
const hit = page.items.find((item) => item.sku.trim() === wanted);
if (hit) return hit;
cursor = page.cursor && !seen.has(page.cursor) ? page.cursor : null;
if (cursor) seen.add(cursor);
} while (cursor);
return null;
}
interface DetailProps {
editable: boolean;
owners: string[];
statuses: string[];
thresholds: Thresholds;
inboundSettings: RestockSettings | null;
url: AppUrl;
onSaved: (item: Item) => void;
onPlanSaved: (items: Item[]) => Promise<void>;
}
interface DrawerProps extends DetailProps { appId: string; sku: string; title: string; onClose: () => void }
/** D-12058: the Restock drawer is the shared SkuActions drawer. Its body holds the reorder and inbound sections. */
function Drawer({ appId, sku, title, onClose, ...detail }: DrawerProps) {
// Set while a plan cancellation is in flight, so Close and Escape keep the drawer open.
const lock = useRef(false);
const [found, setFound] = useState<Load<Item>>({ phase: "loading" });
const [attempt, setAttempt] = useState(0);
const { url } = detail;
useEffect(() => {
const controller = new AbortController();
setFound({ phase: "loading" });
void findItem(url, sku, controller.signal)
.then((item) => {
if (!controller.signal.aborted) setFound(item ? { phase: "ready", value: item }
: { phase: "error", message: "This SKU is not in the plan. Refresh the plan." });
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) setFound({ phase: "error", message: failure(reason, "This SKU could not be loaded.") });
});
return () => controller.abort();
}, [url, sku, attempt]);
return <SkuActions appId={appId} appKind="restock_planner" grain="sku" entityKey={sku}
title={found.phase === "ready" ? found.value.title : title} canEdit={detail.editable} canRead
onClose={() => { if (!lock.current) onClose(); }}>
{found.phase === "loading" && <Skeleton rows={3} />}
{found.phase === "error" && <Failed message={found.message} onRetry={() => setAttempt((count) => count + 1)} />}
{found.phase === "ready" && <SkuDetail key={found.value.id} row={found.value} lock={lock} {...detail} />}
</SkuActions>;
}
function SkuDetail({ row, lock, editable, owners, statuses, thresholds: listThresholds, inboundSettings, url, onSaved, onPlanSaved }:
DetailProps & { row: Item; lock: { current: boolean } }) {
const [detail, setDetail] = useState<Load<Detail>>({ phase: "loading" });
const [attempt, setAttempt] = useState(0);
const [offset, setOffset] = useState(0);
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState("");
const [confirmCancel, setConfirmCancel] = useState(false);
const [cancelling, setCancelling] = useState(false);
const [cancelMessage, setCancelMessage] = useState("");
const cancelRequest = lock;
// The row object changes after a save. Only a different SKU reloads the detail.
const latest = useRef(row);
latest.current = row;
useEffect(() => {
const controller = new AbortController();
setDetail({ phase: "loading" });
void fetch(url(`/items/${encodeURIComponent(row.id)}`, { offset: String(offset) }), { credentials: CREDENTIALS, signal: controller.signal })
.then((response) => readJson(response, "This SKU could not be loaded."))
.then((body) => {
if (controller.signal.aborted) return;
const value = parseDetail(body, latest.current);
setOffset(value.offset);
setDetail({ phase: "ready", value });
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) setDetail({ phase: "error", message: failure(reason, "This SKU could not be loaded.") });
});
return () => controller.abort();
}, [url, row.id, attempt, offset]);
/** Store one change, then show the value the server answered. */
const save = async (change: { owner?: string; status?: string; label_owner?: string; prep_owner?: string }) => {
if (!editable || saving || cancelRequest.current || confirmCancel) return;
setSaving(true);
setSaveError("");
try {
const response = await fetch(url(`/items/${encodeURIComponent(row.id)}`), {
method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
body: JSON.stringify(change),
});
const stored = parseItem(await readJson(response, "The change was not saved."));
if (!stored) throw new Error("The change was not saved.");
onSaved(stored);
setDetail((current) => current.phase !== "ready" ? current
: { phase: "ready", value: { ...current.value, item: { ...current.value.item, ...stored } } });
} catch (reason) {
setSaveError(failure(reason, "The change was not saved."));
} finally {
setSaving(false);
}
};
const item = detail.phase === "ready" ? detail.value.item : row;
const cancelPlan = async () => {
if (!editable || !confirmCancel || !item.inboundPlanId || saving || cancelRequest.current) return;
cancelRequest.current = true;
setCancelling(true);
setCancelMessage("");
try {
const response = await fetch(url(`/items/${encodeURIComponent(item.id)}/cancel-plan`), {
method: "POST", credentials: CREDENTIALS,
});
const result = await readJson(response, "Cancellation is unconfirmed. Check Send to Amazon.") as {
state?: string; message?: string; items?: unknown[];
} | null;
const items = list(result?.items).map(parseItem).filter((entry): entry is Item => entry !== null);
const stored = items.find((entry) => entry.id === item.id);
if (!stored) throw new Error(text(result?.message) || "Cancellation is unconfirmed. Check Send to Amazon.");
if (result?.state === "cancelled") {
if (stored.inboundState !== "cancelled" || stored.status !== "Open" || !stored.cancelledPlanId
|| stored.inboundPlanId || stored.sendToAmazonUrl) throw new Error("Cancellation is unconfirmed. Reload this item.");
} else if (stored.inboundState === "cancelled" || stored.inboundPlanId !== item.inboundPlanId
|| stored.sendToAmazonUrl !== item.sendToAmazonUrl
|| (item.status === "Sent to FBA" && stored.status !== "Sent to FBA")) {
throw new Error("Cancellation is unconfirmed. Reload this item.");
}
setDetail((current) => current.phase !== "ready" ? current
: { phase: "ready", value: { ...current.value, item: stored } });
setCancelMessage(text(result?.message) || (result?.state === "cancelled"
? "Amazon cancelled this plan." : "Cancellation is unconfirmed. Check Send to Amazon."));
await onPlanSaved(items);
} catch (reason) {
setCancelMessage(failure(reason, "Cancellation is unconfirmed. Check Send to Amazon."));
} finally {
cancelRequest.current = false;
setCancelling(false);
setConfirmCancel(false);
}
};
const busy = saving || cancelling || confirmCancel;
const thresholds = (detail.phase === "ready" ? detail.value.thresholds : null) ?? listThresholds;
const ownerOptions = item.owner && !owners.includes(item.owner) ? [item.owner, ...owners] : owners;
return <div className="rp-drawer" aria-label="Restock detail">
{item.asin && <span className="rp-drawer-sub">{item.asin}</span>}
<p className="rp-reason">{item.reason}</p>
<div className="rp-controls">
<label className="rp-field">
<span className="rp-field-label">Status</span>
{editable
? <select className="rp-select" value={item.status} disabled={busy}
onChange={(event) => void save({ status: event.target.value })}>
{(statuses.includes(item.status) || !item.status ? statuses : [item.status, ...statuses])
.map((status) => <option key={status} value={status}>{status}</option>)}
</select>
: <StatusPill status={item.status} />}
</label>
<label className="rp-field">
<span className="rp-field-label">Owner</span>
{editable
? <select className="rp-select" value={item.owner} disabled={busy}
onChange={(event) => void save({ owner: event.target.value })}>
{ownerOptions.map((owner) => <option key={owner} value={owner}>{owner}</option>)}
</select>
: <span className="rp-field-value">{item.owner || "Nobody"}</span>}
</label>
{(["label_owner", "prep_owner"] as const).map((field) => <label className="rp-field" key={field}>
<span className="rp-field-label">{field === "label_owner" ? "Label owner" : "Prep owner"}</span>
{editable
? <select className="rp-select" value={item[field]} disabled={busy}
onChange={(event) => void save({ [field]: event.target.value })}>
<option value="">{inboundSettings ? `Use setting (${inboundSettings[field]})` : "Use setting"}</option>
<option value="Seller">Seller</option><option value="Amazon">Amazon</option>
</select>
: <span className="rp-field-value">{item[field] || inboundSettings?.[field] || "Not known"}</span>}
</label>)}
{saveError && <p className="rp-error" role="alert">{saveError}</p>}
</div>
<InboundPlan item={item} editable={editable} busy={busy || detail.phase !== "ready"}
onCancel={() => setConfirmCancel(true)} />
{cancelMessage && cancelMessage !== item.inboundReason && <p className="rp-notice" role="status">{cancelMessage}</p>}
{editable && <ConfirmDialog open={confirmCancel} title="Cancel plan" tone="destructive"
body={<p>Cancel this plan for every SKU it contains? Items return to Open after Amazon confirms.</p>}
confirmLabel={cancelling ? "Cancelling" : "Cancel plan"} cancelLabel="Keep plan" busy={cancelling}
onConfirm={() => void cancelPlan()} onCancel={() => setConfirmCancel(false)} />}
<dl className="rp-facts">
<Fact label="FBA available" value={qty(item.fbaAvailable)} numeric />
<div className="rp-fact rp-fact-meter">
<dt>Days of supply</dt>
<dd className={item.daysOfSupply !== null && zoneOf(item.daysOfSupply, thresholds) === "critical"
? "is-num rp-days-num is-critical" : "is-num"}>{item.daysOfSupply === null ? "Not known" : qty(item.daysOfSupply)}</dd>
{item.daysOfSupply !== null && <DaysMeter days={item.daysOfSupply} thresholds={thresholds} size="wide" labels />}
<Legend thresholds={thresholds} />
</div>
<Fact label="30-day units" value={qty(item.units30d)} numeric />
<Fact label="Recommended" value={qty(item.recommendedQty)} numeric />
<Fact label="Ship date" value={day(item.recommendedShipDate)} numeric />
<Fact label="Odoo on hand" value={qty(item.odooOnHand)} numeric />
<Fact label="Odoo in FBA" value={qty(item.odooFba)} numeric />
<Fact label="Open purchases" value={qty(item.openPurchaseQty)} numeric />
<Fact label="Due" value={day(item.due)} numeric />
</dl>
{item.odooNote && <p className="rp-notice" role="status">{item.odooNote}</p>}
{detail.phase === "loading" && <Skeleton rows={3} />}
{detail.phase === "error" && <Failed message={detail.message} onRetry={() => setAttempt((count) => count + 1)} />}
{detail.phase === "ready" && <>
<SupplierReorder key={row.id} itemId={row.id} url={url} />
<section className="rp-section" aria-label="Warehouses">
<h3 className="rp-heading">Warehouses</h3>
{detail.value.warehouses.length === 0
? <p className="rp-muted">{detail.value.totals.warehouses ? "No warehouses on this page" : "No Odoo stock"}</p>
: <table className="rp-mini">
<thead><tr><th scope="col">Warehouse</th><th scope="col" className="is-num">On hand</th></tr></thead>
<tbody>{detail.value.warehouses.map((row) => <tr key={`${row.warehouse}:${row.fba}`}>
<td>{row.warehouse}{row.fba && !/fba/i.test(row.warehouse) && <span className="rp-tag">FBA</span>}</td>
<td className="is-num">{qty(row.onHand)}</td>
</tr>)}</tbody>
</table>}
</section>
<section className="rp-section" aria-label="Open purchase orders">
<h3 className="rp-heading">Open purchase orders</h3>
{detail.value.openPurchaseOrders.length === 0
? <p className="rp-muted">{detail.value.totals.openPurchaseOrders ? "No orders on this page" : "No open orders"}</p>
: <table className="rp-mini">
<thead><tr><th scope="col">Order</th><th scope="col">Vendor</th>
<th scope="col" className="is-num">Open</th><th scope="col" className="is-num">Expected</th></tr></thead>
<tbody>{detail.value.openPurchaseOrders.map((row, index) => <tr key={`${row.order}:${index}`}>
<td>{row.order}</td><td>{row.vendor}</td>
<td className="is-num">{qty(row.openQty)}</td><td className="is-num">{day(row.expected)}</td>
</tr>)}</tbody>
</table>}
</section>
<section className="rp-section" aria-label="History">
<h3 className="rp-heading">History</h3>
{detail.value.points.length === 0
? <p className="rp-muted">{detail.value.totals.points ? "No history on this page" : "No history yet"}</p>
: <table className="rp-mini rp-history">
<thead><tr><th scope="col">Day</th><th scope="col" className="is-num">FBA</th>
<th scope="col" className="is-num rp-h-days">Days</th><th scope="col" className="is-num">30-day</th>
<th scope="col" className="rp-h-band">Band</th></tr></thead>
<tbody>{detail.value.points.map((point) => <tr key={point.date}>
<td className="rp-nowrap">{day(point.date)}</td>
<td className="is-num">{qty(point.fbaAvailable)}</td>
<td className="is-num rp-h-days">
<DaysCell days={point.daysOfSupply} units={point.units30d} thresholds={thresholds} size="mini" />
</td>
<td className="is-num">{qty(point.units30d)}</td>
<td className="rp-h-band">{point.band}</td>
</tr>)}</tbody>
</table>}
</section>
</>}
<nav className="rp-more rp-bar" aria-label="Detail pages">
<button type="button" className="rp-button" aria-disabled={detail.phase !== "ready" || offset === 0}
style={pageButtonStyle(detail.phase !== "ready" || offset === 0)}
onClick={() => { if (detail.phase === "ready" && offset > 0) setOffset(Math.max(0, offset - detail.value.limit)); }}>Previous</button>
<span className="rp-muted" role="status">{detail.phase === "ready"
? `Page ${Math.floor(offset / detail.value.limit) + 1} of ${Math.max(1, Math.ceil(detail.value.total / detail.value.limit))}` : "Loading"}</span>
<button type="button" className="rp-button" aria-disabled={detail.phase !== "ready" || offset + detail.value.limit >= detail.value.total}
style={pageButtonStyle(detail.phase !== "ready" || offset + detail.value.limit >= detail.value.total)}
onClick={() => { if (detail.phase === "ready" && offset + detail.value.limit < detail.value.total) setOffset(offset + detail.value.limit); }}>Next</button>
</nav>
</div>;
}
/** A Grid row as the host passes it: the module table's cells by field key. */
type GridRow = Record<string, unknown>;
export default function RestockPlannerView({ application, canEdit }: RestockAppViewProps) {
const appId = application.id;
const kit = useDashboardKit();
const [tab, setTab] = useState(WORK_TAB);
const url = useCallback((path: string, params: Record<string, string> = {}) => {
const query = new URLSearchParams({ app: appId, ...params });
return `${API_V1}/app-kinds/restock_planner${path}?${query.toString()}`;
}, [appId]);
const [capacityRevision, setCapacityRevision] = useState(0);
const [status, setStatus] = useState<Load<ListPage>>({ phase: "loading" });
const [attempt, setAttempt] = useState(0);
const [serverThresholds, setServerThresholds] = useState<Thresholds | null>(null);
const [inboundSettings, setInboundSettings] = useState<RestockSettings | null>(null);
const settingsSaved = useCallback((value: RestockSettings) => {
setInboundSettings(value);
setCapacityRevision((revision) => revision + 1);
setServerThresholds({ sendToFbaDays: value.sendToFbaDays, overstockDays: value.overstockDays });
}, []);
const [refreshing, setRefreshing] = useState(false);
const [refreshError, setRefreshError] = useState("");
const [opened, setOpened] = useState<{ sku: string; title: string } | null>(null);
// A drawer save changes table cells. The Grid remounts on close so it reads them.
const [gridRevision, setGridRevision] = useState(0);
const changed = useRef(false);
const alive = useRef(true);
useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
// D-12043: the Grid's Filter, Sort and Group replace the list query. This one read carries the refresh time,
// notices, people and the edit grant, and adopts every Status set in the Grid before it answers.
useEffect(() => {
const controller = new AbortController();
void fetch(url("/items", { limit: "1" }), { credentials: CREDENTIALS, signal: controller.signal })
.then((response) => readJson(response, "The restock plan could not be loaded."))
.then((body) => {
if (controller.signal.aborted) return;
const value = parsePage(body);
setStatus({ phase: "ready", value });
if (value.thresholds) setServerThresholds(value.thresholds);
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) setStatus({ phase: "error", message: failure(reason, "The restock plan could not be loaded.") });
});
return () => controller.abort();
}, [url, attempt]);
const screen = status.phase === "ready" ? status.value : null;
const editable = canEdit === true && screen?.canEdit === true;
const refresh = async () => {
setRefreshing(true);
setRefreshError("");
try {
const response = await fetch(url("/refresh"), { method: "POST", credentials: CREDENTIALS });
const queued = await readJson(response, "The restock plan could not be refreshed.") as { requestId?: string };
const deadline = Date.now() + 120000;
while (alive.current) {
if (Date.now() >= deadline) throw new Error("The refresh is still running. Try again shortly.");
await new Promise((resolve) => window.setTimeout(resolve, 1000));
if (!alive.current) return;
const state = await readJson(await fetch(url("/refresh"), { credentials: CREDENTIALS }),
"The refresh status could not be read.") as { state?: string; requestId?: string; message?: string; result?: { message?: string } };
if (state.requestId !== queued.requestId) throw new Error("Another refresh started. Reload the plan.");
if (state.state === "failed") throw new Error(state.message || state.result?.message || "The restock plan could not be refreshed.");
if (state.state === "done") {
setAttempt((count) => count + 1);
setCapacityRevision((revision) => revision + 1);
setGridRevision((revision) => revision + 1);
break;
}
}
} catch (reason) {
if (alive.current) setRefreshError(failure(reason, "The restock plan could not be refreshed."));
} finally {
if (alive.current) setRefreshing(false);
}
};
const openRow = useCallback((row: GridRow) => {
const sku = typeof row.sku === "number" ? String(row.sku) : text(row.sku).trim();
if (sku) setOpened({ sku, title: text(row.product) || sku });
}, []);
const closeRow = useCallback(() => {
setOpened(null);
if (changed.current) {
changed.current = false;
setGridRevision((revision) => revision + 1);
}
}, []);
const saved = useCallback((_item: Item) => {
changed.current = true;
setCapacityRevision((revision) => revision + 1);
}, []);
// A plan change moves sibling SKUs too, so the Grid reads them at once.
const planSaved = useCallback(async (_items: Item[]) => {
setCapacityRevision((revision) => revision + 1);
setAttempt((count) => count + 1);
setGridRevision((revision) => revision + 1);
}, []);
const pickTab = (next: string) => {
setTab(next);
setOpened(null);
};
const statuses = screen?.statuses ?? STATUSES;
const thresholds = serverThresholds ?? FALLBACK_THRESHOLDS;
const tabs = [{ id: WORK_TAB, label: "SKUs", count: screen ? screen.total : null }, { id: "dashboard", label: "Dashboard" }];
return <div className="rp-app">
<div className="rp-scroll">
<CapacityHeader url={url} revision={capacityRevision} />
{kit ? <kit.AppTabs tabs={tabs} value={tab} onChange={pickTab} /> : <div className="rp-tabs" role="tablist" aria-label="Restock tabs">
{tabs.map((entry) => <button key={entry.id} type="button" role="tab" aria-selected={tab === entry.id}
className={tab === entry.id ? "rp-tab is-active" : "rp-tab"} onClick={() => pickTab(entry.id)}>
{entry.label}{entry.count != null && <span className="rp-count">{qty(entry.count)}</span>}
</button>)}
</div>}
{tab === "dashboard" ? <div className="rp-body" role="tabpanel" aria-label="Dashboard">
<Dashboard key={appId} url={url} kit={kit} attempt={attempt + capacityRevision} />
<ActionCadence appId={appId} appKind="restock_planner" canRead />
</div> : <>
<RestockSettingsPanel key={appId} url={url} editable={editable} onSaved={settingsSaved} />
<div className="rp-bar">
<div className="rp-bar-end">
{screen?.refreshedAt && <span className="rp-muted rp-nowrap">Updated {day(screen.refreshedAt)}</span>}
{editable && screen?.ready && <button type="button" className="rp-button" disabled={refreshing}
onClick={() => void refresh()}>{refreshing ? "Refreshing" : "Refresh"}</button>}
</div>
</div>
<div className="rp-body rp-grid-body" role="tabpanel" aria-label="SKUs">
<RestockTiles url={url} revision={capacityRevision} />
{refreshError && <p className="rp-error" role="alert">{refreshError}</p>}
{screen?.lastError && <p className="rp-error" role="alert">{screen.lastError}</p>}
{screen && screen.notices.length > 0 && <ul className="rp-notices" role="status">
{screen.notices.map((notice) => <li key={notice}>{notice}</li>)}
</ul>}
{status.phase === "loading" && <Skeleton />}
{status.phase === "error" && <Failed message={status.message} onRetry={() => setAttempt((count) => count + 1)} />}
{screen && !screen.ready && screen.total === 0 ? <div className="rp-waiting" role="status">
<p className="rp-empty">{screen.message}</p>
{editable && <button type="button" className="rp-button is-primary" disabled={refreshing}
onClick={() => void refresh()}>{refreshing ? "Refreshing" : "Refresh"}</button>}
</div> : screen && <div className="rp-grid">
<AppGrid key={gridRevision} table={RESTOCK_TABLE} onOpenRow={openRow}
empty={<p className="rp-empty" role="status">{EMPTY_PLAN}</p>} />
</div>}
</div>
</>}
</div>
{opened && <Drawer key={opened.sku} appId={appId} sku={opened.sku} title={opened.title} editable={editable}
owners={screen?.owners ?? []} statuses={statuses} thresholds={thresholds} inboundSettings={inboundSettings}
url={url} onSaved={saved} onPlanSaved={planSaved} onClose={closeRow} />}
</div>;
}
|