@tokenoftrust/storefront-runner 6.11.8 → 6.11.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -72,3 +72,220 @@ export interface ProductsViewModel {
72
72
  rows: ProductRow[];
73
73
  detailsById: Record<string, ProductDetail>;
74
74
  }
75
+
76
+ /**
77
+ * Closed per-SKU outcome returned by tot-foxycart's excise SKU registration route
78
+ * (`POST /api/commerce/excise/products`).
79
+ */
80
+ export const EXCISE_SKU_OUTCOMES = [
81
+ "registered",
82
+ "already-registered",
83
+ "found",
84
+ "not-found",
85
+ "deactivated",
86
+ "refused-invalid-sku",
87
+ "refused-registry",
88
+ "refused-owned-by-other-tenant",
89
+ ] as const;
90
+
91
+ export type ExciseSkuOutcome = (typeof EXCISE_SKU_OUTCOMES)[number];
92
+
93
+ /**
94
+ * The three admin view states for a catalog SKU in the Excise tax section (`ac-1`).
95
+ */
96
+ export type ExciseSkuState = "registered" | "missing" | "refused";
97
+
98
+ export type ExciseProductType = "vape" | "nicotinePouch" | "hemp";
99
+
100
+ export type ExciseVapeSystemType =
101
+ | "open"
102
+ | "closed"
103
+ | "isLiquid"
104
+ | "isPart"
105
+ | "isOpen"
106
+ | "closedSingleUse"
107
+ | "closedCartridge"
108
+ | "batteryOnly"
109
+ | "pack";
110
+
111
+ export interface ExciseSkuAttributes {
112
+ type: ExciseProductType;
113
+ vapeSystemType: ExciseVapeSystemType;
114
+ volumeInMl: number;
115
+ wholesaleCost: number;
116
+ wholesalePrice: number;
117
+ msrp: number;
118
+ retailPrice: number;
119
+ hasNicotine: boolean;
120
+ packQuantity: number;
121
+ }
122
+
123
+ export interface ExciseCatalogSkuRow {
124
+ sku: string;
125
+ productHandle: string;
126
+ productTitle: string;
127
+ variantId: string;
128
+ variantTitle: string;
129
+ brand: string;
130
+ currency: string;
131
+ state: ExciseSkuState;
132
+ outcome: ExciseSkuOutcome | null;
133
+ message: string;
134
+ attributes: ExciseSkuAttributes;
135
+ }
136
+
137
+ export interface ExciseRegistrySkuSnapshot {
138
+ outcome: ExciseSkuOutcome;
139
+ active?: boolean;
140
+ attributes?: Partial<ExciseSkuAttributes>;
141
+ }
142
+
143
+ const CLOSED_OUTCOME_MESSAGES: Readonly<Record<ExciseSkuOutcome, string>> = Object.freeze({
144
+ registered: "Registered in the excise tax registry.",
145
+ "already-registered": "Already registered in the excise tax registry.",
146
+ found: "Registered in the excise tax registry.",
147
+ "not-found": "Not registered in the excise tax registry yet.",
148
+ deactivated: "Deactivated in the excise tax registry (exempt).",
149
+ "refused-invalid-sku": "Registration refused: invalid SKU or engine attributes.",
150
+ "refused-registry": "Registration refused: the excise tax registry could not complete this request.",
151
+ "refused-owned-by-other-tenant": "Registration refused: this SKU code is owned by another store.",
152
+ });
153
+
154
+ export function isExciseSkuOutcome(value: unknown): value is ExciseSkuOutcome {
155
+ return typeof value === "string" && (EXCISE_SKU_OUTCOMES as readonly string[]).includes(value);
156
+ }
157
+
158
+ /**
159
+ * Map a closed registry outcome into the admin SKU state (`registered`, `missing`, or `refused`).
160
+ */
161
+ export function mapExciseOutcomeToState(
162
+ outcome: ExciseSkuOutcome | null | undefined,
163
+ active?: boolean,
164
+ ): ExciseSkuState {
165
+ if (!outcome || outcome === "not-found" || outcome === "deactivated") return "missing";
166
+ if (outcome === "found") return active === false ? "missing" : "registered";
167
+ if (outcome === "registered" || outcome === "already-registered") return "registered";
168
+ return "refused";
169
+ }
170
+
171
+ /**
172
+ * Return the closed, truthful message for a SKU's registration outcome (`ac-3`).
173
+ * Upstream response bodies are never interpolated here.
174
+ */
175
+ export function exciseOutcomeMessage(
176
+ outcome: ExciseSkuOutcome | null | undefined,
177
+ active?: boolean,
178
+ ): string {
179
+ if (!outcome) return CLOSED_OUTCOME_MESSAGES["not-found"];
180
+ if (outcome === "found" && active === false) return CLOSED_OUTCOME_MESSAGES.deactivated;
181
+ return CLOSED_OUTCOME_MESSAGES[outcome] ?? CLOSED_OUTCOME_MESSAGES["refused-registry"];
182
+ }
183
+
184
+ /**
185
+ * Validate a bare catalog SKU before any U4 call: 1..200 chars, trimmed, no whitespace,
186
+ * no colon (`:`), and no wildcard (`*`).
187
+ */
188
+ export function isValidBareCatalogSku(value: unknown): value is string {
189
+ if (typeof value !== "string") return false;
190
+ const trimmed = value.trim();
191
+ if (!trimmed || trimmed !== value || trimmed.length > 200) return false;
192
+ if (/[\s:*]/.test(trimmed)) return false;
193
+ return true;
194
+ }
195
+
196
+ export interface CatalogProductLike {
197
+ handle: string;
198
+ title: string;
199
+ vendor?: string;
200
+ product_type?: string;
201
+ metafields?: ReadonlyArray<{ namespace: string; key: string; value: string }>;
202
+ variants: ReadonlyArray<{
203
+ id: string;
204
+ title: string;
205
+ sku?: string;
206
+ price: number;
207
+ compare_at_price?: number;
208
+ currency: string;
209
+ }>;
210
+ }
211
+
212
+ function positiveFinite(value: unknown, fallback: number): number {
213
+ const num = typeof value === "number" ? value : Number(value);
214
+ return Number.isFinite(num) && num >= 0 ? Number(num.toFixed(2)) : fallback;
215
+ }
216
+
217
+ function defaultAttributesForVariant(
218
+ product: CatalogProductLike,
219
+ variant: CatalogProductLike["variants"][number],
220
+ ): ExciseSkuAttributes {
221
+ const retail = positiveFinite(variant.price, 19.99);
222
+ const msrp = positiveFinite(variant.compare_at_price ?? retail, retail);
223
+ const wholesalePrice = positiveFinite(retail * 0.5, 10);
224
+ const wholesaleCost = positiveFinite(retail * 0.4, 8);
225
+ const volumeMeta = product.metafields?.find(
226
+ (m) => m.key === "volume_ml" || m.key === "volumeInMl" || m.key === "volume",
227
+ )?.value;
228
+ const parsedVolume = volumeMeta ? Number.parseFloat(volumeMeta) : NaN;
229
+ const volumeInMl = Number.isFinite(parsedVolume) && parsedVolume > 0 ? parsedVolume : 30;
230
+ const systemMeta = product.metafields?.find(
231
+ (m) => m.key === "vape_system_type" || m.key === "vapeSystemType",
232
+ )?.value;
233
+ const vapeSystemType: ExciseVapeSystemType =
234
+ systemMeta === "closed" || systemMeta === "closedSingleUse" || systemMeta === "closedCartridge"
235
+ ? systemMeta
236
+ : "open";
237
+ return {
238
+ type: "vape",
239
+ vapeSystemType,
240
+ volumeInMl,
241
+ wholesaleCost,
242
+ wholesalePrice,
243
+ msrp,
244
+ retailPrice: retail,
245
+ hasNicotine: true,
246
+ packQuantity: 1,
247
+ };
248
+ }
249
+
250
+ /**
251
+ * Build the admin excise SKU rows from the store's catalog products and optional registry read-back.
252
+ * Only variants with a valid bare SKU in the store's catalog are included.
253
+ */
254
+ export function toExciseCatalogSkuRows(
255
+ products: readonly CatalogProductLike[],
256
+ registryBySku?: ReadonlyMap<string, ExciseRegistrySkuSnapshot>,
257
+ ): ExciseCatalogSkuRow[] {
258
+ const rows: ExciseCatalogSkuRow[] = [];
259
+ const seen = new Set<string>();
260
+ const sortedProducts = [...products].sort((a, b) => a.title.localeCompare(b.title));
261
+ for (const product of sortedProducts) {
262
+ for (const variant of product.variants) {
263
+ const sku = typeof variant.sku === "string" ? variant.sku.trim() : "";
264
+ if (!isValidBareCatalogSku(sku) || seen.has(sku)) continue;
265
+ seen.add(sku);
266
+ const defaults = defaultAttributesForVariant(product, variant);
267
+ const snapshot = registryBySku?.get(sku);
268
+ const outcome = snapshot?.outcome ?? null;
269
+ const state = mapExciseOutcomeToState(outcome, snapshot?.active);
270
+ const message = exciseOutcomeMessage(outcome, snapshot?.active);
271
+ const mergedAttrs: ExciseSkuAttributes = {
272
+ ...defaults,
273
+ ...(snapshot?.attributes ?? {}),
274
+ };
275
+ rows.push({
276
+ sku,
277
+ productHandle: product.handle,
278
+ productTitle: product.title,
279
+ variantId: variant.id,
280
+ variantTitle: variant.title,
281
+ brand: (product.vendor ?? "").trim() || product.title,
282
+ currency: variant.currency || "USD",
283
+ state,
284
+ outcome,
285
+ message,
286
+ attributes: mergedAttrs,
287
+ });
288
+ }
289
+ }
290
+ return rows;
291
+ }
@@ -37,3 +37,110 @@ export function mountCheckoutExciseForm(form: HTMLElement): void {
37
37
  }
38
38
  });
39
39
  }
40
+
41
+ const SKU_CHIP_CLASSES: Record<"registered" | "missing" | "refused", string> = {
42
+ registered: "green",
43
+ missing: "amber",
44
+ refused: "red",
45
+ };
46
+
47
+ const SKU_CHIP_LABELS: Record<"registered" | "missing" | "refused", string> = {
48
+ registered: "Registered",
49
+ missing: "Missing",
50
+ refused: "Refused",
51
+ };
52
+
53
+ function readRowProduct(row: Element, sku: string, action: string): Record<string, unknown> {
54
+ if (action !== "add") return { sku };
55
+ const getVal = (name: string): string | boolean | undefined => {
56
+ const el = row.querySelector<HTMLInputElement | HTMLSelectElement>(`[data-excise-attr="${name}"]`);
57
+ if (!el) return undefined;
58
+ if (el instanceof HTMLInputElement && el.type === "checkbox") return el.checked;
59
+ return el.value;
60
+ };
61
+ return {
62
+ sku,
63
+ type: getVal("type") || "vape",
64
+ vapeSystemType: getVal("vapeSystemType") || "open",
65
+ volumeInMl: Number(getVal("volumeInMl") || 0),
66
+ wholesaleCost: Number(getVal("wholesaleCost") || 0),
67
+ wholesalePrice: Number(getVal("wholesalePrice") || 0),
68
+ msrp: Number(getVal("msrp") || 0),
69
+ retailPrice: Number(getVal("retailPrice") || 0),
70
+ packQuantity: Number.parseInt(String(getVal("packQuantity") || "1"), 10) || 1,
71
+ hasNicotine: Boolean(getVal("hasNicotine")),
72
+ };
73
+ }
74
+
75
+ function applyRowResult(
76
+ row: Element,
77
+ item: { state?: string; message?: string } | null | undefined,
78
+ ): void {
79
+ const badge = row.querySelector<HTMLElement>("[data-excise-sku-state]");
80
+ const msg = row.querySelector<HTMLElement>("[data-excise-sku-message]");
81
+ const state: "registered" | "missing" | "refused" =
82
+ item && (item.state === "registered" || item.state === "missing" || item.state === "refused")
83
+ ? item.state
84
+ : "refused";
85
+ if (badge) {
86
+ badge.setAttribute("data-excise-sku-state", state);
87
+ badge.className = `chip ${SKU_CHIP_CLASSES[state]}`;
88
+ badge.textContent = SKU_CHIP_LABELS[state];
89
+ }
90
+ if (msg && item && typeof item.message === "string") {
91
+ msg.textContent = item.message;
92
+ }
93
+ }
94
+
95
+ export function mountExciseProductsPanel(panel: HTMLElement): void {
96
+ const endpoint = panel.getAttribute("data-endpoint") || "/api/admin/excise-products";
97
+ const statusEl = panel.querySelector<HTMLElement>("[data-excise-products-status]");
98
+
99
+ panel.addEventListener("click", async (event) => {
100
+ const target = event.target instanceof Element ? event.target.closest("[data-excise-sku-action]") : null;
101
+ if (!target) return;
102
+ const action = target.getAttribute("data-excise-sku-action");
103
+ const sku = target.getAttribute("data-excise-sku");
104
+ const row = target.closest("[data-excise-sku-row]");
105
+ if (!action || !sku || !row) return;
106
+
107
+ const buttons = row.querySelectorAll<HTMLButtonElement>("button[data-excise-sku-action]");
108
+ buttons.forEach((b) => {
109
+ b.disabled = true;
110
+ });
111
+ if (statusEl) {
112
+ statusEl.textContent = action === "add" ? `Registering ${sku}...` : `Deactivating ${sku}...`;
113
+ }
114
+
115
+ try {
116
+ const product = readRowProduct(row, sku, action);
117
+ const res = await fetch(endpoint, {
118
+ method: "POST",
119
+ headers: { "content-type": "application/json" },
120
+ body: JSON.stringify({ action, products: [product] }),
121
+ });
122
+ const data = (await res.json()) as {
123
+ message?: string;
124
+ results?: Array<{ sku?: string; state?: string; message?: string }>;
125
+ };
126
+ const entry = Array.isArray(data?.results)
127
+ ? data.results.find((r) => r && r.sku === sku)
128
+ : null;
129
+ if (entry) {
130
+ applyRowResult(row, entry);
131
+ }
132
+ if (statusEl) {
133
+ statusEl.textContent =
134
+ entry?.message || data?.message || (res.ok ? "Updated." : "Request refused.");
135
+ }
136
+ } catch {
137
+ if (statusEl) {
138
+ statusEl.textContent = "Could not reach the excise registration service.";
139
+ }
140
+ } finally {
141
+ buttons.forEach((b) => {
142
+ b.disabled = false;
143
+ });
144
+ }
145
+ });
146
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.11.8",
3
+ "version": "6.11.9",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",