@tokenoftrust/storefront-runner 7.8.10 → 7.9.0

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.8.10",
3
+ "version": "7.9.0",
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",
@@ -16,6 +16,17 @@ import type { ShipDestination } from "./evaluate.js";
16
16
 
17
17
  export const PACT_REPORT_RECORD_VERSION = 1;
18
18
 
19
+ /**
20
+ * A closed refusal: PACT evidence that cannot be reported. `reason` is fixed copy written at the
21
+ * throw site, safe to show a person; callers branch on the class, never on the message text.
22
+ */
23
+ export class PactRefusal extends Error {
24
+ constructor(readonly stage: "reconciliation" | "reporting", readonly reason: string) {
25
+ super(`PACT ${stage}: ${reason}`);
26
+ this.name = "PactRefusal";
27
+ }
28
+ }
29
+
19
30
  /** One shipped regulated line, as the PACT report enumerates it. */
20
31
  export interface PactReportLine {
21
32
  sku: string;
@@ -25,6 +36,8 @@ export interface PactReportLine {
25
36
  quantity: number;
26
37
  /** Per-unit volume in millilitres when known. */
27
38
  volumeMl?: number;
39
+ /** Per-unit weight in grams when known. */
40
+ unitWeightGrams?: number;
28
41
  }
29
42
 
30
43
  /** The buyer identity a PACT filing needs (captured to the compliance sink only). */
@@ -92,6 +105,8 @@ export interface PactReportShipmentRecord extends PactReportOrderRecord {
92
105
  lines: PactReportShipmentLine[];
93
106
  /** Sum of known shipped volumes. Omitted when all volumes are unknown. */
94
107
  totalVolumeMl?: number;
108
+ /** SKUs shipped with no recorded unit volume (zero for a product with no contained liquid). Omitted when every line is measured. */
109
+ unmeasuredSkus?: string[];
95
110
  }
96
111
 
97
112
  interface PactReportMonth {
@@ -143,7 +158,7 @@ export function buildPactReportRecord(
143
158
  function reportRegion(value: string | undefined): string {
144
159
  const region = value?.trim().toUpperCase();
145
160
  if (!region || !/^[A-Z]{2}$/.test(region)) {
146
- throw new Error("PACT reporting: a two-letter region is required");
161
+ throw new PactRefusal("reporting", "a two-letter region is required");
147
162
  }
148
163
  return region;
149
164
  }
@@ -154,7 +169,7 @@ function knownVolumeTotal(lines: readonly { totalVolumeMl?: number }[]): number
154
169
  undefined,
155
170
  );
156
171
  if (total !== undefined && (!Number.isFinite(total) || total < 0)) {
157
- throw new Error("PACT reporting: invalid total shipped volume");
172
+ throw new PactRefusal("reporting", "invalid total shipped volume");
158
173
  }
159
174
  return total;
160
175
  }
@@ -167,18 +182,24 @@ function parcelLines(
167
182
  for (const { sku, quantity } of shipment.lines) {
168
183
  if (!ordered.has(sku)) continue;
169
184
  if (!Number.isSafeInteger(quantity) || quantity <= 0) {
170
- throw new Error("PACT reporting: invalid shipped quantity");
185
+ throw new PactRefusal("reporting", "invalid shipped quantity");
171
186
  }
172
187
  quantities.set(sku, (quantities.get(sku) ?? 0) + quantity);
173
188
  }
174
189
 
175
190
  return [...quantities.keys()].sort().map((sku) => {
176
- const { productName, category, volumeMl } = ordered.get(sku)!;
191
+ const { productName, category, volumeMl, unitWeightGrams } = ordered.get(sku)!;
177
192
  const quantity = quantities.get(sku)!;
178
- const line = { sku, productName, category, quantity };
193
+ const line: PactReportShipmentLine = { sku, productName, category, quantity };
194
+ if (unitWeightGrams !== undefined) {
195
+ if (!Number.isFinite(unitWeightGrams) || unitWeightGrams < 0) {
196
+ throw new PactRefusal("reporting", "invalid per-unit weight");
197
+ }
198
+ line.unitWeightGrams = unitWeightGrams;
199
+ }
179
200
  if (volumeMl === undefined) return line;
180
201
  if (!Number.isFinite(volumeMl) || volumeMl < 0) {
181
- throw new Error("PACT reporting: invalid per-unit volume");
202
+ throw new PactRefusal("reporting", "invalid per-unit volume");
182
203
  }
183
204
  return { ...line, volumeMl, totalVolumeMl: volumeMl * quantity };
184
205
  });
@@ -192,16 +213,23 @@ export function reconcilePactShipmentRecords(
192
213
  const ordered = new Map<string, PactReportLine>();
193
214
  for (const line of order.lines) {
194
215
  if (ordered.has(line.sku) || !Number.isSafeInteger(line.quantity) || line.quantity <= 0) {
195
- throw new Error("PACT reporting: invalid ordered SKU quantities");
216
+ throw new PactRefusal("reporting", "invalid ordered SKU quantities");
196
217
  }
197
218
  ordered.set(line.sku, line);
198
219
  }
199
220
 
200
- const results: PactReportShipmentRecord[] = [];
221
+ type Parcel = {
222
+ shipmentId: string; carrier: string; service: string | undefined; trackingNumber: string;
223
+ shippedAt: string; adultSignature: PactAdultSignature; lines: PactReportShipmentLine[];
224
+ };
201
225
  const shipped = new Map<string, number>();
202
226
  const parcels = new Map<string, string>();
203
- for (const shipment of shipments) {
204
- if (shipment.state !== "confirmed") continue;
227
+ const byTracking = new Map<string, Parcel>();
228
+ const contributions = new Map<string, Set<string>>();
229
+ const confirmed = shipments
230
+ .filter((shipment) => shipment.state === "confirmed")
231
+ .sort((a, b) => a.shipmentId.localeCompare(b.shipmentId));
232
+ for (const shipment of confirmed) {
205
233
  const lines = parcelLines(shipment, ordered);
206
234
  if (lines.length === 0) continue;
207
235
 
@@ -210,41 +238,67 @@ export function reconcilePactShipmentRecords(
210
238
  const service = shipment.service?.trim() || undefined;
211
239
  const trackingNumber = shipment.trackingNumber?.trim();
212
240
  const { shippedAt, adultSignature = "absent" } = shipment;
213
- if (!shipmentId) throw new Error("PACT reporting: shipment ID is required");
214
- if (!carrier) throw new Error("PACT reporting: carrier is required");
215
- if (!trackingNumber) throw new Error("PACT reporting: tracking number is required");
241
+ if (!shipmentId) throw new PactRefusal("reporting", "shipment ID is required");
242
+ if (!carrier) throw new PactRefusal("reporting", "carrier is required");
243
+ if (!trackingNumber) throw new PactRefusal("reporting", "tracking number is required");
216
244
  if (!shippedAt || !/(?:Z|[+-]\d{2}:\d{2})$/.test(shippedAt) || !Number.isFinite(Date.parse(shippedAt))) {
217
- throw new Error("PACT reporting: shipment timestamp is required");
245
+ throw new PactRefusal("reporting", "shipment timestamp is required");
218
246
  }
219
247
  if (order.adultSignatureRequired && adultSignature === "refused") {
220
- throw new Error("PACT reporting: required adult signature was refused");
248
+ throw new PactRefusal("reporting", "required adult signature was refused");
221
249
  }
222
250
 
223
- const parcel = { shipmentId, carrier, service, trackingNumber, shippedAt, adultSignature, lines };
251
+ const parcel: Parcel = { shipmentId, carrier, service, trackingNumber, shippedAt, adultSignature, lines };
224
252
  const fingerprint = JSON.stringify(parcel);
225
253
  const prior = parcels.get(shipmentId);
226
254
  if (prior === fingerprint) continue;
227
- if (prior !== undefined) throw new Error("PACT reporting: conflicting facts for a shipment");
255
+ if (prior !== undefined) throw new PactRefusal("reporting", "conflicting facts for a shipment");
228
256
  parcels.set(shipmentId, fingerprint);
229
257
 
230
258
  for (const { sku, quantity } of lines) {
231
259
  const total = (shipped.get(sku) ?? 0) + quantity;
232
260
  if (total > ordered.get(sku)!.quantity) {
233
- throw new Error("PACT reporting: shipped quantity exceeds ordered quantity");
261
+ throw new PactRefusal("reporting", "shipped quantity exceeds ordered quantity");
234
262
  }
235
263
  shipped.set(sku, total);
236
264
  }
237
265
 
238
- const { line1, line2, city, country, postalCode } = order.buyer.shipTo;
239
- const region = reportRegion(order.buyer.shipTo.region);
266
+ // One tracking number is one physical parcel: rows sharing it merge into a single record
267
+ // under the smallest shipment id, and rows that disagree on the parcel's facts conflict.
268
+ const trackingKey = `${carrier.toUpperCase()}\u0000${trackingNumber.toUpperCase()}`;
269
+ const contents = JSON.stringify(lines);
270
+ const same = byTracking.get(trackingKey);
271
+ if (!same) {
272
+ byTracking.set(trackingKey, parcel);
273
+ contributions.set(trackingKey, new Set([contents]));
274
+ continue;
275
+ }
276
+ if (same.service !== service || same.shippedAt !== shippedAt || same.adultSignature !== adultSignature) {
277
+ throw new PactRefusal("reporting", "conflicting facts for a tracking number");
278
+ }
279
+ // Rows under one tracking number that each list identical contents cannot be told apart from
280
+ // one box recorded twice, so adding them would over-count and dropping one would under-count.
281
+ const seen = contributions.get(trackingKey)!;
282
+ if (seen.has(contents)) throw new PactRefusal("reporting", "overlapping facts for a tracking number");
283
+ seen.add(contents);
284
+ same.lines = parcelLines({ shipmentId, state: "confirmed", source: "split-shipment", lines: [...same.lines, ...lines] }, ordered);
285
+ }
286
+
287
+ const { line1, line2, city, country, postalCode } = order.buyer.shipTo;
288
+ return [...byTracking.values()].map(({ lines, ...parcel }) => {
240
289
  const record = buildPactReportRecord({
241
290
  ...order,
242
- buyer: { name: order.buyer.name, shipTo: { line1, line2, city, region, country, postalCode } },
291
+ buyer: { name: order.buyer.name, shipTo: { line1, line2, city, region: reportRegion(order.buyer.shipTo.region), country, postalCode } },
243
292
  lines,
244
293
  });
245
- results.push({ ...record, ...parcel, totalVolumeMl: knownVolumeTotal(lines) });
246
- }
247
- return results;
294
+ const unmeasuredSkus = lines
295
+ .filter((line) => line.volumeMl === undefined)
296
+ .map(({ sku }) => sku);
297
+ return {
298
+ ...record, ...parcel, lines, totalVolumeMl: knownVolumeTotal(lines),
299
+ ...(unmeasuredSkus.length > 0 ? { unmeasuredSkus } : {}),
300
+ };
301
+ });
248
302
  }
249
303
 
250
304
  /** Aggregate the reconciled parcels for one tenant, destination and UTC shipment month. */
@@ -255,7 +309,7 @@ export function buildPactMonthlyReport(
255
309
  const { tenantId, month } = period;
256
310
  const region = reportRegion(period.region);
257
311
  if (!/^\d{4}-(?:0[1-9]|1[0-2])$/.test(month)) {
258
- throw new Error("PACT reporting: month must be YYYY-MM");
312
+ throw new PactRefusal("reporting", "month must be YYYY-MM");
259
313
  }
260
314
 
261
315
  const shipments = records