@tokenoftrust/storefront-runner 6.11.5 → 6.11.7
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/apps/storefront/src/components/assets/storefront/Img.astro +28 -4
- package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +6 -1
- package/apps/storefront/src/components/catalog/storefront/islands/ImageGallery.tsx +28 -6
- package/apps/storefront/src/lib/assets/captured-original-serve.ts +16 -1
- package/apps/storefront/src/lib/assets/shared/imageAttrs.ts +101 -1
- package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +16 -23
- package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +32 -17
- package/apps/storefront/src/lib/integrations/webhooks/emit.ts +16 -2
- package/apps/storefront/src/lib/inventory/allocations.ts +22 -41
- package/apps/storefront/src/lib/inventory/mirrorStock.ts +92 -80
- package/package.json +1 -1
|
@@ -14,7 +14,12 @@
|
|
|
14
14
|
* the storefront is served by Cloudflare or CloudFront, so this component never
|
|
15
15
|
* routes them through a provider-specific transformation path.
|
|
16
16
|
*/
|
|
17
|
-
import {
|
|
17
|
+
import {
|
|
18
|
+
isCapturedPoolRaster,
|
|
19
|
+
resolveImage,
|
|
20
|
+
type CapturedImageVariant,
|
|
21
|
+
type CapturedVariantManifest,
|
|
22
|
+
} from "@/lib/assets/shared/imageAttrs";
|
|
18
23
|
|
|
19
24
|
interface Props {
|
|
20
25
|
src?: string;
|
|
@@ -26,6 +31,10 @@ interface Props {
|
|
|
26
31
|
/** Short label drawn into the placeholder (e.g. product title). */
|
|
27
32
|
label?: string;
|
|
28
33
|
rehosted?: boolean;
|
|
34
|
+
/** Captured width variants from the revision manifest, when present. */
|
|
35
|
+
variants?: readonly CapturedImageVariant[];
|
|
36
|
+
/** Optional manifest mapping source URLs or `/_a/<address>` entries to width variants. */
|
|
37
|
+
manifest?: CapturedVariantManifest | null;
|
|
29
38
|
/** LCP hint: eager + high priority + no lazy. */
|
|
30
39
|
priority?: boolean;
|
|
31
40
|
sizes?: string;
|
|
@@ -41,15 +50,30 @@ const {
|
|
|
41
50
|
seed,
|
|
42
51
|
label,
|
|
43
52
|
rehosted = false,
|
|
53
|
+
variants,
|
|
54
|
+
manifest,
|
|
44
55
|
priority = false,
|
|
45
56
|
sizes,
|
|
46
57
|
class: className,
|
|
47
58
|
loading,
|
|
48
59
|
} = Astro.props;
|
|
49
60
|
|
|
50
|
-
// Render decision (placeholder / direct rehost / Shopify ?width=) lives in
|
|
61
|
+
// Render decision (placeholder / captured variants / direct rehost / Shopify ?width=) lives in
|
|
51
62
|
// lib/assets/shared/imageAttrs.ts so it's unit-testable without rendering this component.
|
|
52
|
-
const { src: resolvedSrc, srcset } = resolveImage({
|
|
63
|
+
const { src: resolvedSrc, srcset } = resolveImage({
|
|
64
|
+
src,
|
|
65
|
+
rehosted,
|
|
66
|
+
width,
|
|
67
|
+
height,
|
|
68
|
+
seed,
|
|
69
|
+
label,
|
|
70
|
+
variants,
|
|
71
|
+
manifest,
|
|
72
|
+
});
|
|
73
|
+
const resolvedSizes =
|
|
74
|
+
srcset || isCapturedPoolRaster(resolvedSrc)
|
|
75
|
+
? (sizes ?? "(min-width: 768px) 50vw, 100vw")
|
|
76
|
+
: undefined;
|
|
53
77
|
|
|
54
78
|
const loadingAttr = loading ?? (priority ? "eager" : "lazy");
|
|
55
79
|
---
|
|
@@ -57,7 +81,7 @@ const loadingAttr = loading ?? (priority ? "eager" : "lazy");
|
|
|
57
81
|
<img
|
|
58
82
|
src={resolvedSrc}
|
|
59
83
|
srcset={srcset}
|
|
60
|
-
sizes={
|
|
84
|
+
sizes={resolvedSizes}
|
|
61
85
|
alt={alt}
|
|
62
86
|
width={width}
|
|
63
87
|
height={height}
|
|
@@ -10,6 +10,7 @@ import type { CatalogProduct } from "@tot/public-runtime";
|
|
|
10
10
|
import { discountPercent, truncate } from "@/lib/content/shared/format";
|
|
11
11
|
import { isOnSale, isNew, isAvailable, fromPrice } from "@/lib/catalog/tot/query";
|
|
12
12
|
import { colorOptionValues, resolveSwatch, isLightFill } from "@/lib/content/shared/colors";
|
|
13
|
+
import type { ComponentProps } from "astro/types";
|
|
13
14
|
import Img from "@/components/assets/storefront/Img.astro";
|
|
14
15
|
import Badge from "@/components/content/storefront/Badge.astro";
|
|
15
16
|
import PriceDisplay from "@/components/catalog/storefront/commerce/PriceDisplay.astro";
|
|
@@ -28,9 +29,11 @@ interface Props {
|
|
|
28
29
|
rating?: number;
|
|
29
30
|
/** Optional review count shown with the stars. */
|
|
30
31
|
reviewCount?: number;
|
|
32
|
+
/** Optional captured width-variant manifest for product card images. */
|
|
33
|
+
variantManifest?: ComponentProps<typeof Img>["manifest"];
|
|
31
34
|
}
|
|
32
35
|
|
|
33
|
-
const { product, priority = false, rating, reviewCount } = Astro.props;
|
|
36
|
+
const { product, priority = false, rating, reviewCount, variantManifest = null } = Astro.props;
|
|
34
37
|
const { tenant, basePath, features, commerce, apiBasePath, browserEnvironment, contentVersionId } = Astro.locals;
|
|
35
38
|
const showBadges = features.productBadges;
|
|
36
39
|
|
|
@@ -124,6 +127,7 @@ const quickview = {
|
|
|
124
127
|
<Img
|
|
125
128
|
src={primary.url}
|
|
126
129
|
rehosted={primary.rehosted}
|
|
130
|
+
manifest={variantManifest}
|
|
127
131
|
seed={primary.id ?? product.handle}
|
|
128
132
|
label={product.title}
|
|
129
133
|
alt={primary.alt ?? product.title}
|
|
@@ -151,6 +155,7 @@ const quickview = {
|
|
|
151
155
|
<Img
|
|
152
156
|
src={secondary.url}
|
|
153
157
|
rehosted={secondary.rehosted}
|
|
158
|
+
manifest={variantManifest}
|
|
154
159
|
seed={secondary.id ?? `${product.handle}-2`}
|
|
155
160
|
label={product.title}
|
|
156
161
|
alt=""
|
|
@@ -16,13 +16,22 @@
|
|
|
16
16
|
import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
|
|
17
17
|
import type { CatalogImage } from "@tot/public-runtime";
|
|
18
18
|
import { placeholderDataUri, isUsableImageUrl } from "@/lib/content/shared/placeholder";
|
|
19
|
-
import {
|
|
19
|
+
import {
|
|
20
|
+
isCapturedPoolRaster,
|
|
21
|
+
resolveImage,
|
|
22
|
+
type CapturedImageVariant,
|
|
23
|
+
type CapturedVariantManifest,
|
|
24
|
+
} from "@/lib/assets/shared/imageAttrs";
|
|
20
25
|
|
|
21
26
|
export type PublicGalleryImage = Pick<CatalogImage,
|
|
22
|
-
"id" | "url" | "alt" | "position" | "width" | "height" | "variant_ids" | "rehosted"
|
|
27
|
+
"id" | "url" | "alt" | "position" | "width" | "height" | "variant_ids" | "rehosted"> & {
|
|
28
|
+
variants?: readonly CapturedImageVariant[];
|
|
29
|
+
};
|
|
23
30
|
|
|
24
31
|
/** Project before Astro serializes props; private provenance stays in the catalog. */
|
|
25
|
-
export function publicGalleryImages(
|
|
32
|
+
export function publicGalleryImages(
|
|
33
|
+
images: readonly (CatalogImage & { variants?: readonly CapturedImageVariant[] })[],
|
|
34
|
+
): PublicGalleryImage[] {
|
|
26
35
|
return images.map((image) => ({
|
|
27
36
|
id: image.id,
|
|
28
37
|
url: image.url,
|
|
@@ -32,6 +41,7 @@ export function publicGalleryImages(images: readonly CatalogImage[]): PublicGall
|
|
|
32
41
|
...(image.height !== undefined ? { height: image.height } : {}),
|
|
33
42
|
...(image.variant_ids !== undefined ? { variant_ids: [...image.variant_ids] } : {}),
|
|
34
43
|
...(image.rehosted !== undefined ? { rehosted: image.rehosted } : {}),
|
|
44
|
+
...(image.variants !== undefined ? { variants: [...image.variants] } : {}),
|
|
35
45
|
}));
|
|
36
46
|
}
|
|
37
47
|
|
|
@@ -40,6 +50,7 @@ interface Props {
|
|
|
40
50
|
title: string;
|
|
41
51
|
productHandle: string;
|
|
42
52
|
activeImageId?: string;
|
|
53
|
+
manifest?: CapturedVariantManifest | null;
|
|
43
54
|
}
|
|
44
55
|
|
|
45
56
|
const FALLBACK_W = 1000;
|
|
@@ -53,7 +64,11 @@ const isShopifyCdnUrl = (url: string): boolean =>
|
|
|
53
64
|
* decision (same as <Img> on the PLP) so rehosted images use the same
|
|
54
65
|
* provider-neutral shared-CDN URL on Cloudflare and CloudFront.
|
|
55
66
|
*/
|
|
56
|
-
function mainImage(
|
|
67
|
+
function mainImage(
|
|
68
|
+
img: PublicGalleryImage,
|
|
69
|
+
title: string,
|
|
70
|
+
manifest?: CapturedVariantManifest | null,
|
|
71
|
+
): { src: string; srcset?: string } {
|
|
57
72
|
return resolveImage({
|
|
58
73
|
src: img.url,
|
|
59
74
|
rehosted: img.rehosted,
|
|
@@ -61,6 +76,8 @@ function mainImage(img: PublicGalleryImage, title: string): { src: string; srcse
|
|
|
61
76
|
height: img.height ?? FALLBACK_H,
|
|
62
77
|
seed: img.id || title,
|
|
63
78
|
label: title,
|
|
79
|
+
variants: img.variants,
|
|
80
|
+
manifest,
|
|
64
81
|
});
|
|
65
82
|
}
|
|
66
83
|
|
|
@@ -99,6 +116,7 @@ export default function ImageGallery({
|
|
|
99
116
|
title,
|
|
100
117
|
productHandle,
|
|
101
118
|
activeImageId,
|
|
119
|
+
manifest,
|
|
102
120
|
}: Props) {
|
|
103
121
|
const ordered = useMemo(
|
|
104
122
|
() => [...images].sort((a, b) => a.position - b.position),
|
|
@@ -192,7 +210,11 @@ export default function ImageGallery({
|
|
|
192
210
|
const w = current.width ?? FALLBACK_W;
|
|
193
211
|
const h = current.height ?? FALLBACK_H;
|
|
194
212
|
const isLcp = index === 0 && !interacted;
|
|
195
|
-
const main = mainImage(current, title);
|
|
213
|
+
const main = mainImage(current, title, manifest);
|
|
214
|
+
const mainSizes =
|
|
215
|
+
main.srcset || isCapturedPoolRaster(main.src)
|
|
216
|
+
? "(min-width: 768px) 45vw, 100vw"
|
|
217
|
+
: undefined;
|
|
196
218
|
|
|
197
219
|
return (
|
|
198
220
|
<div class="flex flex-col gap-3 md:flex-row-reverse md:gap-4">
|
|
@@ -211,7 +233,7 @@ export default function ImageGallery({
|
|
|
211
233
|
<img
|
|
212
234
|
src={main.src}
|
|
213
235
|
srcset={main.srcset}
|
|
214
|
-
sizes={
|
|
236
|
+
sizes={mainSizes}
|
|
215
237
|
alt={current.alt ?? title}
|
|
216
238
|
width={w}
|
|
217
239
|
height={h}
|
|
@@ -88,7 +88,7 @@ async function readManifestEntries(
|
|
|
88
88
|
const entries: ManifestEntry[] = [];
|
|
89
89
|
for (const raw of parsed.entries) {
|
|
90
90
|
if (!raw || typeof raw !== "object") return null;
|
|
91
|
-
const entry = raw as Partial<ManifestEntry
|
|
91
|
+
const entry = raw as Partial<ManifestEntry> & { variants?: unknown };
|
|
92
92
|
if (typeof entry.address !== "string" || !ADDRESS_RE.test(entry.address)) return null;
|
|
93
93
|
if (!Number.isSafeInteger(entry.byteLength) || entry.byteLength! < 1 || entry.byteLength! > maxEntryBytes ||
|
|
94
94
|
!sealedOriginalEntryAllowed(entry.provenance?.kind, entry.mediaType, entry.sanitized)) return null;
|
|
@@ -100,6 +100,21 @@ async function readManifestEntries(
|
|
|
100
100
|
provenance: entry.provenance,
|
|
101
101
|
...(sanitized ? { sanitized } : {}),
|
|
102
102
|
});
|
|
103
|
+
if (Array.isArray(entry.variants)) {
|
|
104
|
+
for (const rawVariant of entry.variants) {
|
|
105
|
+
if (!rawVariant || typeof rawVariant !== "object") return null;
|
|
106
|
+
const v = rawVariant as { address?: unknown; byteLength?: unknown; mediaType?: unknown };
|
|
107
|
+
if (typeof v.address !== "string" || !ADDRESS_RE.test(v.address)) return null;
|
|
108
|
+
if (!Number.isSafeInteger(v.byteLength) || (v.byteLength as number) < 1 || (v.byteLength as number) > maxEntryBytes) return null;
|
|
109
|
+
if (v.mediaType !== "image/webp") return null;
|
|
110
|
+
entries.push({
|
|
111
|
+
address: v.address,
|
|
112
|
+
byteLength: v.byteLength as number,
|
|
113
|
+
mediaType: "image/webp",
|
|
114
|
+
provenance: entry.provenance,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
103
118
|
}
|
|
104
119
|
return entries;
|
|
105
120
|
} catch {
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* Picks the `src` + responsive `srcset` for a catalog image, factored out of
|
|
5
5
|
* Img.astro so the branching is unit-testable without rendering the component:
|
|
6
6
|
* - unusable/missing URL -> deterministic placeholder data URI
|
|
7
|
+
* - captured/rehosted asset with manifest variants -> shared CDN URL + variant `srcset`
|
|
7
8
|
* - rehosted asset -> shared CDN URL as-is (Cloudflare + CloudFront safe)
|
|
8
9
|
* - referenced Shopify CDN -> Shopify's native ?width= scheme
|
|
9
10
|
* - anything else usable -> the URL as-is, no srcset
|
|
@@ -11,6 +12,93 @@
|
|
|
11
12
|
import { placeholderDataUri, isUsableImageUrl } from "../../content/shared/placeholder.js";
|
|
12
13
|
|
|
13
14
|
const RESPONSIVE_IMAGE_WIDTHS = [320, 480, 640, 960, 1280, 1600] as const;
|
|
15
|
+
const CAPTURED_POOL_RASTER_RE = /^((?:\/[A-Za-z0-9._~%-]+)*)\/_a\/([0-9a-f]{64})(\.(?:jpe?g|png|webp))?$/i;
|
|
16
|
+
|
|
17
|
+
export interface CapturedImageVariant {
|
|
18
|
+
width: number;
|
|
19
|
+
/** Content address (`<64-hex>`) in the shared `/_a/` asset pool. */
|
|
20
|
+
address?: string;
|
|
21
|
+
/** Pool entry filename (`<64-hex>.webp`). */
|
|
22
|
+
entry?: string;
|
|
23
|
+
/** Explicit URL override when already formatted. */
|
|
24
|
+
url?: string;
|
|
25
|
+
mediaType?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type CapturedVariantManifest =
|
|
29
|
+
| Readonly<Record<string, readonly CapturedImageVariant[]>>
|
|
30
|
+
| ReadonlyMap<string, readonly CapturedImageVariant[]>;
|
|
31
|
+
|
|
32
|
+
let activeCapturedVariantManifest: CapturedVariantManifest | null = null;
|
|
33
|
+
|
|
34
|
+
/** Bind a request/render-scoped captured variant manifest for `<Img>` and `<ImageGallery>`. */
|
|
35
|
+
export function setCapturedVariantManifest(manifest: CapturedVariantManifest | null): void {
|
|
36
|
+
activeCapturedVariantManifest = manifest;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function getCapturedVariantManifest(): CapturedVariantManifest | null {
|
|
40
|
+
return activeCapturedVariantManifest;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function isCapturedPoolRaster(url: string | undefined): boolean {
|
|
44
|
+
if (!url) return false;
|
|
45
|
+
const match = CAPTURED_POOL_RASTER_RE.exec(url);
|
|
46
|
+
if (!match) return false;
|
|
47
|
+
const ext = (match[3] ?? "").toLowerCase();
|
|
48
|
+
return ext === "" || ext === ".jpg" || ext === ".jpeg" || ext === ".png" || ext === ".webp";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function lookupManifestVariants(
|
|
52
|
+
manifest: CapturedVariantManifest | null | undefined,
|
|
53
|
+
url: string,
|
|
54
|
+
): readonly CapturedImageVariant[] | undefined {
|
|
55
|
+
if (!manifest) return undefined;
|
|
56
|
+
const isMap = (
|
|
57
|
+
value: CapturedVariantManifest,
|
|
58
|
+
): value is ReadonlyMap<string, readonly CapturedImageVariant[]> =>
|
|
59
|
+
typeof (value as ReadonlyMap<string, readonly CapturedImageVariant[]>).get === "function";
|
|
60
|
+
const get = (key: string): readonly CapturedImageVariant[] | undefined =>
|
|
61
|
+
isMap(manifest) ? manifest.get(key) : manifest[key];
|
|
62
|
+
const direct = get(url);
|
|
63
|
+
if (direct?.length) return direct;
|
|
64
|
+
const match = CAPTURED_POOL_RASTER_RE.exec(url);
|
|
65
|
+
if (!match) return undefined;
|
|
66
|
+
const address = match[2]!.toLowerCase();
|
|
67
|
+
const ext = match[3] ?? "";
|
|
68
|
+
return (
|
|
69
|
+
(ext ? get(`/_a/${address}${ext}`) ?? get(`${address}${ext}`) : undefined) ??
|
|
70
|
+
get(`/_a/${address}`) ??
|
|
71
|
+
get(address)
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function formatCapturedVariantSrcset(
|
|
76
|
+
url: string,
|
|
77
|
+
variants: readonly CapturedImageVariant[],
|
|
78
|
+
): string | undefined {
|
|
79
|
+
const prefix = CAPTURED_POOL_RASTER_RE.exec(url)?.[1] ?? "";
|
|
80
|
+
const parts: { width: number; candidate: string }[] = [];
|
|
81
|
+
for (const variant of variants) {
|
|
82
|
+
if (!Number.isSafeInteger(variant.width) || variant.width < 1) continue;
|
|
83
|
+
let candidateUrl = variant.url;
|
|
84
|
+
if (!candidateUrl) {
|
|
85
|
+
if (variant.entry) {
|
|
86
|
+
candidateUrl = `${prefix}/_a/${variant.entry}`;
|
|
87
|
+
} else if (variant.address) {
|
|
88
|
+
const ext = variant.mediaType === "image/png"
|
|
89
|
+
? ".png"
|
|
90
|
+
: variant.mediaType === "image/jpeg"
|
|
91
|
+
? ".jpg"
|
|
92
|
+
: ".webp";
|
|
93
|
+
candidateUrl = `${prefix}/_a/${variant.address}${ext}`;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (candidateUrl) parts.push({ width: variant.width, candidate: `${candidateUrl} ${variant.width}w` });
|
|
97
|
+
}
|
|
98
|
+
if (parts.length === 0) return undefined;
|
|
99
|
+
parts.sort((a, b) => a.width - b.width);
|
|
100
|
+
return parts.map((p) => p.candidate).join(", ");
|
|
101
|
+
}
|
|
14
102
|
|
|
15
103
|
export interface ResolveImageInput {
|
|
16
104
|
src?: string;
|
|
@@ -20,6 +108,10 @@ export interface ResolveImageInput {
|
|
|
20
108
|
/** Placeholder seed (image id / product handle). */
|
|
21
109
|
seed: string;
|
|
22
110
|
label?: string;
|
|
111
|
+
/** Captured width variants from the revision manifest, when present. */
|
|
112
|
+
variants?: readonly CapturedImageVariant[];
|
|
113
|
+
/** Optional manifest mapping source URLs or `/_a/<address>` entries to width variants. */
|
|
114
|
+
manifest?: CapturedVariantManifest | null;
|
|
23
115
|
}
|
|
24
116
|
|
|
25
117
|
export interface ResolvedImage {
|
|
@@ -31,13 +123,21 @@ const isShopifyCdnUrl = (url: string): boolean =>
|
|
|
31
123
|
/\/\/cdn\.shopify\.com\//.test(url) || /\/cdn\/shop\//.test(url);
|
|
32
124
|
|
|
33
125
|
export function resolveImage(input: ResolveImageInput): ResolvedImage {
|
|
34
|
-
const { src, rehosted = false, width, height, seed, label } = input;
|
|
126
|
+
const { src, rehosted = false, width, height, seed, label, variants, manifest } = input;
|
|
35
127
|
|
|
36
128
|
if (!isUsableImageUrl(src, rehosted)) {
|
|
37
129
|
return { src: placeholderDataUri({ seed, width, height, label }) };
|
|
38
130
|
}
|
|
39
131
|
const url = src!;
|
|
40
132
|
|
|
133
|
+
const resolvedVariants = variants?.length
|
|
134
|
+
? variants
|
|
135
|
+
: lookupManifestVariants(manifest ?? activeCapturedVariantManifest, url);
|
|
136
|
+
if (resolvedVariants?.length) {
|
|
137
|
+
const srcset = formatCapturedVariantSrcset(url, resolvedVariants);
|
|
138
|
+
if (srcset) return { src: url, srcset };
|
|
139
|
+
}
|
|
140
|
+
|
|
41
141
|
// Rehosted assets live behind the shared asset CDN. Serve that URL directly:
|
|
42
142
|
// `/cdn-cgi/image` exists only on zones configured for Cloudflare Image
|
|
43
143
|
// Resizing and is not a CloudFront contract. The original URL is the one
|
|
@@ -6,7 +6,11 @@ import { admissionBindsOrder, currentCartEvent, readCommerceAdmission } from "..
|
|
|
6
6
|
import { FulfillmentService } from "./fulfillmentService.js";
|
|
7
7
|
import { fulfillmentDbFromQueryable } from "./store.js";
|
|
8
8
|
import { dispatchCommerceDeliveries } from "./commerceRuntime.js";
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
ORDER_DECREMENT_SOURCE,
|
|
11
|
+
readEffectiveMirrorBalance,
|
|
12
|
+
recordMirrorInventoryChanged,
|
|
13
|
+
} from "../inventory/mirrorStock.js";
|
|
10
14
|
const UNKNOWN: CommerceEvidence = { verification: "UNKNOWN", tax: "UNKNOWN", risk: "UNKNOWN", stock: "UNKNOWN" };
|
|
11
15
|
|
|
12
16
|
export async function projectCommerceOrder(
|
|
@@ -83,35 +87,24 @@ export async function projectCommerceOrder(
|
|
|
83
87
|
input.orderId,
|
|
84
88
|
],
|
|
85
89
|
},
|
|
90
|
+
{
|
|
91
|
+
sql: `SELECT DISTINCT sku, location_id FROM scrappy_allocations
|
|
92
|
+
WHERE tenant_id=? AND stage=? AND order_id=? AND state='confirmed'`,
|
|
93
|
+
params: [input.tenantId, input.stage, input.orderId],
|
|
94
|
+
},
|
|
86
95
|
]);
|
|
87
96
|
trusted = Boolean(results[0]?.results.length);
|
|
88
|
-
const confirmedAllocations = results[
|
|
97
|
+
const confirmedAllocations = trusted ? (results[3]?.results ?? []) : [];
|
|
89
98
|
for (const row of confirmedAllocations) {
|
|
90
99
|
const sku = typeof row.sku === "string" ? row.sku : "";
|
|
91
100
|
const locationId = typeof row.location_id === "string" && row.location_id ? row.location_id : "unspecified";
|
|
92
101
|
if (!sku) continue;
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS ledger_sum,
|
|
97
|
-
(SELECT COUNT(*) FROM commerce_inventory_movements
|
|
98
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS ledger_count,
|
|
99
|
-
(SELECT COALESCE(SUM(quantity), 0) FROM scrappy_allocations
|
|
100
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed') AS confirmed_sum`,
|
|
101
|
-
input.tenantId,
|
|
102
|
-
input.stage,
|
|
103
|
-
sku,
|
|
104
|
-
locationId,
|
|
105
|
-
input.tenantId,
|
|
106
|
-
input.stage,
|
|
107
|
-
sku,
|
|
108
|
-
locationId,
|
|
109
|
-
input.tenantId,
|
|
110
|
-
input.stage,
|
|
102
|
+
const reading = await readEffectiveMirrorBalance(db, {
|
|
103
|
+
tenantId: input.tenantId,
|
|
104
|
+
stage: input.stage,
|
|
111
105
|
sku,
|
|
112
106
|
locationId,
|
|
113
|
-
);
|
|
114
|
-
const balance = Number(stat?.ledger_count ?? 0) > 0 ? Number(stat?.ledger_sum ?? 0) - Number(stat?.confirmed_sum ?? 0) : 0;
|
|
107
|
+
});
|
|
115
108
|
await recordMirrorInventoryChanged(db, {
|
|
116
109
|
tenantId: input.tenantId,
|
|
117
110
|
stage: input.stage,
|
|
@@ -119,7 +112,7 @@ export async function projectCommerceOrder(
|
|
|
119
112
|
sourceEventId: input.orderId,
|
|
120
113
|
sku,
|
|
121
114
|
locationId,
|
|
122
|
-
balance,
|
|
115
|
+
balance: reading.balance,
|
|
123
116
|
asOf: input.now,
|
|
124
117
|
notify: dispatchCommerceDeliveries,
|
|
125
118
|
gate: {
|
|
@@ -178,6 +178,27 @@ async function priorAnswer(db: Queryable, installId: string, key: string, bodyHa
|
|
|
178
178
|
return receiptFrom(check.responseBody) ?? inventoryRefusal("idempotency-conflict");
|
|
179
179
|
}
|
|
180
180
|
|
|
181
|
+
async function ensureReceiptEmitted(
|
|
182
|
+
db: Queryable,
|
|
183
|
+
actor: InventoryWriteActor,
|
|
184
|
+
answer: InventoryWriteResponse,
|
|
185
|
+
): Promise<InventoryWriteResponse> {
|
|
186
|
+
if ("receiptId" in answer.body) {
|
|
187
|
+
const source = await appSource(actor.appId);
|
|
188
|
+
await emitInventoryChanged(db, {
|
|
189
|
+
tenantId: actor.tenantId,
|
|
190
|
+
stage: actor.stage,
|
|
191
|
+
source,
|
|
192
|
+
sourceEventId: answer.body.receiptId,
|
|
193
|
+
sku: answer.body.sku,
|
|
194
|
+
locationId: answer.body.locationId,
|
|
195
|
+
balance: answer.body.balance,
|
|
196
|
+
asOf: answer.body.asOf,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
return answer;
|
|
200
|
+
}
|
|
201
|
+
|
|
181
202
|
export interface InventoryWriteRequest {
|
|
182
203
|
actor: InventoryWriteActor;
|
|
183
204
|
idempotencyKey: string;
|
|
@@ -195,7 +216,7 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
195
216
|
const key = namespacedKey(actor, request.idempotencyKey);
|
|
196
217
|
const bodyHash = await computeBodyHash({ operation: "inventory.write", ...delta });
|
|
197
218
|
const prior = await priorAnswer(db, actor.installId, key, bodyHash);
|
|
198
|
-
if (prior) return prior;
|
|
219
|
+
if (prior) return ensureReceiptEmitted(db, actor, prior);
|
|
199
220
|
|
|
200
221
|
const sku = await request.resolveSku(delta.sku);
|
|
201
222
|
if (sku === null || !isStoredSku(sku)) return inventoryRefusal("unknown-sku");
|
|
@@ -229,8 +250,10 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
229
250
|
sql: `INSERT INTO idempotency_keys (install_id, idempotency_key, body_hash, response_body, created_at)
|
|
230
251
|
SELECT ?, ?, ?, json_object('status', 201, 'body', json_object(
|
|
231
252
|
'receiptId', ?, 'sku', ?, 'locationId', ?, 'quantityDelta', CAST(? AS INTEGER), 'asOf', ?,
|
|
232
|
-
'balance', (SELECT SUM(quantity_delta) FROM commerce_inventory_movements
|
|
233
|
-
|
|
253
|
+
'balance', COALESCE((SELECT SUM(quantity_delta) FROM commerce_inventory_movements
|
|
254
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?), 0)
|
|
255
|
+
- COALESCE((SELECT SUM(quantity) FROM scrappy_allocations
|
|
256
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed'), 0))), ?
|
|
234
257
|
WHERE changes() = 1`,
|
|
235
258
|
params: [
|
|
236
259
|
actor.installId,
|
|
@@ -245,6 +268,10 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
245
268
|
actor.stage,
|
|
246
269
|
sku,
|
|
247
270
|
delta.locationId,
|
|
271
|
+
actor.tenantId,
|
|
272
|
+
actor.stage,
|
|
273
|
+
sku,
|
|
274
|
+
delta.locationId,
|
|
248
275
|
asOf,
|
|
249
276
|
],
|
|
250
277
|
},
|
|
@@ -252,19 +279,7 @@ export async function applyAppInventoryDelta(db: Queryable, request: InventoryWr
|
|
|
252
279
|
if ((changes[0] ?? 0) === 1 && (changes[2] ?? 0) === 1) {
|
|
253
280
|
const answer = await priorAnswer(db, actor.installId, key, bodyHash);
|
|
254
281
|
if (!answer) return inventoryRefusal("unavailable");
|
|
255
|
-
|
|
256
|
-
await emitInventoryChanged(db, {
|
|
257
|
-
tenantId: actor.tenantId,
|
|
258
|
-
stage: actor.stage,
|
|
259
|
-
source,
|
|
260
|
-
sourceEventId: receiptId,
|
|
261
|
-
sku: answer.body.sku,
|
|
262
|
-
locationId: answer.body.locationId,
|
|
263
|
-
balance: answer.body.balance,
|
|
264
|
-
asOf: answer.body.asOf,
|
|
265
|
-
});
|
|
266
|
-
}
|
|
267
|
-
return answer;
|
|
282
|
+
return ensureReceiptEmitted(db, actor, answer);
|
|
268
283
|
}
|
|
269
284
|
return classifyRefused(db, actor, delta, key, bodyHash);
|
|
270
285
|
}
|
|
@@ -278,7 +293,7 @@ async function classifyRefused(
|
|
|
278
293
|
bodyHash: string,
|
|
279
294
|
): Promise<InventoryWriteResponse> {
|
|
280
295
|
const prior = await priorAnswer(db, actor.installId, key, bodyHash);
|
|
281
|
-
if (prior) return prior;
|
|
296
|
+
if (prior) return ensureReceiptEmitted(db, actor, prior);
|
|
282
297
|
const install = await db.first<{ tenant_id: string; env: string; status: string; scopes: string }>(
|
|
283
298
|
`SELECT tenant_id, env, status, scopes FROM app_installs WHERE install_id = ?`,
|
|
284
299
|
actor.installId,
|
|
@@ -273,6 +273,19 @@ export async function emitInventoryChanged(
|
|
|
273
273
|
deliveryId: await inventoryDeliveryId(eventId, row.install_id),
|
|
274
274
|
})),
|
|
275
275
|
);
|
|
276
|
+
const existingEvent = await db.first<{ ok: number }>(`SELECT 1 AS ok FROM webhook_events WHERE id = ?`, eventId);
|
|
277
|
+
const existingDeliveries =
|
|
278
|
+
targets.length > 0
|
|
279
|
+
? await db.all<{ delivery_id: string }>(
|
|
280
|
+
`SELECT delivery_id FROM webhook_deliveries WHERE event_id = ?`,
|
|
281
|
+
eventId,
|
|
282
|
+
)
|
|
283
|
+
: [];
|
|
284
|
+
const existingDeliveryIds = new Set(existingDeliveries.map((row) => row.delivery_id));
|
|
285
|
+
const missingTargets = targets.filter((target) => !existingDeliveryIds.has(target.deliveryId));
|
|
286
|
+
if (existingEvent && missingTargets.length === 0) {
|
|
287
|
+
return { eventId, deliveryIds: targets.map((target) => target.deliveryId) };
|
|
288
|
+
}
|
|
276
289
|
const baseGate: CommerceEventStatement = input.gate ?? {
|
|
277
290
|
sql: `EXISTS (
|
|
278
291
|
SELECT 1 FROM commerce_inventory_movements
|
|
@@ -308,10 +321,11 @@ export async function emitInventoryChanged(
|
|
|
308
321
|
)
|
|
309
322
|
: [];
|
|
310
323
|
const deliveryIds = committed.map((row) => row.delivery_id);
|
|
311
|
-
|
|
324
|
+
const newDeliveryIds = deliveryIds.filter((id) => !existingDeliveryIds.has(id));
|
|
325
|
+
if (newDeliveryIds.length > 0) {
|
|
312
326
|
const notify = input.notify ?? dispatchInventoryDeliveries;
|
|
313
327
|
try {
|
|
314
|
-
await notify(input.tenantId,
|
|
328
|
+
await notify(input.tenantId, newDeliveryIds);
|
|
315
329
|
} catch {
|
|
316
330
|
// Pending rows remain durable in webhook_deliveries.
|
|
317
331
|
}
|
|
@@ -656,6 +656,7 @@ import {
|
|
|
656
656
|
mirrorMovementDeliveryId,
|
|
657
657
|
mirrorMovementEventId,
|
|
658
658
|
ORDER_DECREMENT_SOURCE,
|
|
659
|
+
readEffectiveMirrorBalance,
|
|
659
660
|
recordMirrorInventoryChanged,
|
|
660
661
|
} from "./mirrorStock.js";
|
|
661
662
|
|
|
@@ -712,13 +713,22 @@ export async function confirmHoldOnce(
|
|
|
712
713
|
params: [...scope, ...scope],
|
|
713
714
|
},
|
|
714
715
|
{
|
|
715
|
-
sql: `SELECT state FROM scrappy_allocations
|
|
716
|
+
sql: `SELECT state, sku, location_id FROM scrappy_allocations
|
|
716
717
|
WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
|
|
717
718
|
params: scope,
|
|
718
719
|
},
|
|
719
720
|
]);
|
|
720
721
|
const confirmedRows = results[0] ?? [];
|
|
721
|
-
|
|
722
|
+
const allAllocations = results[3] ?? [];
|
|
723
|
+
const confirmedTargets = new Map<string, { sku: string; locationId: string }>();
|
|
724
|
+
for (const row of allAllocations) {
|
|
725
|
+
if (text(row, "state") !== "confirmed") continue;
|
|
726
|
+
const sku = text(row, "sku");
|
|
727
|
+
const locationId = text(row, "location_id") || "unspecified";
|
|
728
|
+
if (!sku) continue;
|
|
729
|
+
confirmedTargets.set(`${sku}\n${locationId}`, { sku, locationId });
|
|
730
|
+
}
|
|
731
|
+
if (confirmedTargets.size > 0) {
|
|
722
732
|
const orderRows = await runner.all(
|
|
723
733
|
`SELECT placed_at FROM scrappy_commerce_orders WHERE tenant_id = ? AND stage = ? AND order_id = ?`,
|
|
724
734
|
scope,
|
|
@@ -735,43 +745,14 @@ export async function confirmHoldOnce(
|
|
|
735
745
|
await runner.batch(statements);
|
|
736
746
|
},
|
|
737
747
|
};
|
|
738
|
-
for (const
|
|
739
|
-
const
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
(SELECT COUNT(*) FROM commerce_inventory_movements
|
|
747
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS ledger_count,
|
|
748
|
-
(SELECT MAX(as_of) FROM commerce_inventory_movements
|
|
749
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS max_as_of,
|
|
750
|
-
(SELECT COALESCE(SUM(quantity), 0) FROM scrappy_allocations
|
|
751
|
-
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed') AS confirmed_sum`,
|
|
752
|
-
[
|
|
753
|
-
input.tenantId,
|
|
754
|
-
input.stage,
|
|
755
|
-
sku,
|
|
756
|
-
locationId,
|
|
757
|
-
input.tenantId,
|
|
758
|
-
input.stage,
|
|
759
|
-
sku,
|
|
760
|
-
locationId,
|
|
761
|
-
input.tenantId,
|
|
762
|
-
input.stage,
|
|
763
|
-
sku,
|
|
764
|
-
locationId,
|
|
765
|
-
input.tenantId,
|
|
766
|
-
input.stage,
|
|
767
|
-
sku,
|
|
768
|
-
locationId,
|
|
769
|
-
],
|
|
770
|
-
);
|
|
771
|
-
const stat = stats[0] ?? {};
|
|
772
|
-
const ledgerCount = Number(stat.ledger_count ?? 0);
|
|
773
|
-
const balance = ledgerCount > 0 ? Number(stat.ledger_sum ?? 0) - Number(stat.confirmed_sum ?? 0) : 0;
|
|
774
|
-
const asOf = text(stat, "max_as_of") || placedAt;
|
|
748
|
+
for (const { sku, locationId } of confirmedTargets.values()) {
|
|
749
|
+
const reading = await readEffectiveMirrorBalance(runnerQueryable, {
|
|
750
|
+
tenantId: input.tenantId,
|
|
751
|
+
stage: input.stage,
|
|
752
|
+
sku,
|
|
753
|
+
locationId,
|
|
754
|
+
});
|
|
755
|
+
const asOf = reading.asOf && reading.asOf > placedAt ? reading.asOf : placedAt;
|
|
775
756
|
await recordMirrorInventoryChanged(runnerQueryable, {
|
|
776
757
|
tenantId: input.tenantId,
|
|
777
758
|
stage: input.stage,
|
|
@@ -779,7 +760,7 @@ export async function confirmHoldOnce(
|
|
|
779
760
|
sourceEventId: input.orderId,
|
|
780
761
|
sku,
|
|
781
762
|
locationId,
|
|
782
|
-
balance,
|
|
763
|
+
balance: reading.balance,
|
|
783
764
|
asOf,
|
|
784
765
|
gate: {
|
|
785
766
|
sql: `EXISTS (
|
|
@@ -793,7 +774,7 @@ export async function confirmHoldOnce(
|
|
|
793
774
|
}
|
|
794
775
|
return {
|
|
795
776
|
decremented: sumQuantity(confirmedRows),
|
|
796
|
-
states:
|
|
777
|
+
states: allAllocations.map((row) => text(row, "state")),
|
|
797
778
|
};
|
|
798
779
|
}
|
|
799
780
|
|
|
@@ -82,6 +82,19 @@ export async function recordMirrorInventoryChanged(
|
|
|
82
82
|
deliveryId: await mirrorMovementDeliveryId(eventId, row.install_id),
|
|
83
83
|
})),
|
|
84
84
|
);
|
|
85
|
+
const existingEvent = await db.first<{ ok: number }>(`SELECT 1 AS ok FROM webhook_events WHERE id = ?`, eventId);
|
|
86
|
+
const existingDeliveries =
|
|
87
|
+
targets.length > 0
|
|
88
|
+
? await db.all<{ delivery_id: string }>(
|
|
89
|
+
`SELECT delivery_id FROM webhook_deliveries WHERE event_id = ?`,
|
|
90
|
+
eventId,
|
|
91
|
+
)
|
|
92
|
+
: [];
|
|
93
|
+
const existingDeliveryIds = new Set(existingDeliveries.map((row) => row.delivery_id));
|
|
94
|
+
const missingTargets = targets.filter((target) => !existingDeliveryIds.has(target.deliveryId));
|
|
95
|
+
if (existingEvent && missingTargets.length === 0) {
|
|
96
|
+
return { eventId, deliveryIds: targets.map((target) => target.deliveryId) };
|
|
97
|
+
}
|
|
85
98
|
const baseGate: SqlCondition = input.gate ?? {
|
|
86
99
|
sql: `EXISTS (
|
|
87
100
|
SELECT 1 FROM commerce_inventory_movements
|
|
@@ -133,10 +146,11 @@ export async function recordMirrorInventoryChanged(
|
|
|
133
146
|
)
|
|
134
147
|
: [];
|
|
135
148
|
const deliveryIds = committed.map((row) => row.delivery_id);
|
|
149
|
+
const newDeliveryIds = deliveryIds.filter((id) => !existingDeliveryIds.has(id));
|
|
136
150
|
const notify = input.notify ?? defaultInventoryNotify;
|
|
137
|
-
if (
|
|
151
|
+
if (newDeliveryIds.length > 0 && notify) {
|
|
138
152
|
try {
|
|
139
|
-
await notify(input.tenantId,
|
|
153
|
+
await notify(input.tenantId, newDeliveryIds);
|
|
140
154
|
} catch {
|
|
141
155
|
// Pending rows remain in webhook_deliveries for the commerce alarm.
|
|
142
156
|
}
|
|
@@ -220,24 +234,22 @@ export async function appendMirrorMovement(db: Queryable, input: MirrorMovement)
|
|
|
220
234
|
actual.actor_id !== input.actorId
|
|
221
235
|
)
|
|
222
236
|
throw new InventoryMovementError("conflict");
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
});
|
|
240
|
-
}
|
|
237
|
+
const reading = await readEffectiveMirrorBalance(db, {
|
|
238
|
+
tenantId: input.tenantId,
|
|
239
|
+
stage: input.stage,
|
|
240
|
+
sku: input.sku,
|
|
241
|
+
locationId: input.locationId,
|
|
242
|
+
});
|
|
243
|
+
await recordMirrorInventoryChanged(db, {
|
|
244
|
+
tenantId: input.tenantId,
|
|
245
|
+
stage: input.stage,
|
|
246
|
+
source: input.source,
|
|
247
|
+
sourceEventId: input.sourceEventId,
|
|
248
|
+
sku: input.sku,
|
|
249
|
+
locationId: input.locationId,
|
|
250
|
+
balance: reading.balance,
|
|
251
|
+
asOf: actual.as_of,
|
|
252
|
+
});
|
|
241
253
|
}
|
|
242
254
|
export async function readMirrorStock(
|
|
243
255
|
db: Queryable,
|
|
@@ -283,36 +295,6 @@ export const MIRROR_LOCATION_UNSPECIFIED = "unspecified";
|
|
|
283
295
|
export const CATALOG_IMPORT_ACTOR_ID = "catalog-import";
|
|
284
296
|
export const CATALOG_IMPORT_SOURCE = "catalog-import";
|
|
285
297
|
export const ORDER_DECREMENT_SOURCE = "order-decrement";
|
|
286
|
-
export const ORDER_DECREMENT_ACTOR_ID = "commerce-order";
|
|
287
|
-
|
|
288
|
-
/** Records an order stock decrement in the mirror ledger and emits `inventory.changed` once. */
|
|
289
|
-
export async function appendOrderDecrement(
|
|
290
|
-
db: Queryable,
|
|
291
|
-
input: {
|
|
292
|
-
tenantId: string;
|
|
293
|
-
stage: CommerceStage;
|
|
294
|
-
orderId: string;
|
|
295
|
-
sku: string;
|
|
296
|
-
locationId?: string;
|
|
297
|
-
quantity: number;
|
|
298
|
-
asOf: string;
|
|
299
|
-
},
|
|
300
|
-
): Promise<void> {
|
|
301
|
-
if (!Number.isSafeInteger(input.quantity) || input.quantity <= 0) {
|
|
302
|
-
throw new InventoryMovementError("invalid-movement");
|
|
303
|
-
}
|
|
304
|
-
await appendMirrorMovement(db, {
|
|
305
|
-
tenantId: input.tenantId,
|
|
306
|
-
stage: input.stage,
|
|
307
|
-
source: ORDER_DECREMENT_SOURCE,
|
|
308
|
-
sourceEventId: input.orderId,
|
|
309
|
-
sku: input.sku,
|
|
310
|
-
locationId: input.locationId ?? MIRROR_LOCATION_UNSPECIFIED,
|
|
311
|
-
quantityDelta: -input.quantity,
|
|
312
|
-
asOf: input.asOf,
|
|
313
|
-
actorId: ORDER_DECREMENT_ACTOR_ID,
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
298
|
|
|
317
299
|
export interface MirrorBalance {
|
|
318
300
|
balance: number;
|
|
@@ -332,6 +314,40 @@ interface BalanceKey {
|
|
|
332
314
|
locationId: string;
|
|
333
315
|
}
|
|
334
316
|
|
|
317
|
+
/**
|
|
318
|
+
* Net mirror balance for `inventory.changed` and app inventory receipts:
|
|
319
|
+
* summed ledger movements (`commerce_inventory_movements`) minus confirmed order
|
|
320
|
+
* allocations (`scrappy_allocations WHERE state = 'confirmed'`) for the same key.
|
|
321
|
+
*/
|
|
322
|
+
export async function readEffectiveMirrorBalance(
|
|
323
|
+
db: Queryable,
|
|
324
|
+
input: BalanceKey,
|
|
325
|
+
): Promise<{ balance: number; asOf: string | null }> {
|
|
326
|
+
const row = await db.first<{ ledger_sum: number; confirmed_sum: number; as_of: string | null }>(
|
|
327
|
+
`SELECT
|
|
328
|
+
COALESCE((SELECT SUM(quantity_delta) FROM commerce_inventory_movements
|
|
329
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?), 0) AS ledger_sum,
|
|
330
|
+
COALESCE((SELECT SUM(quantity) FROM scrappy_allocations
|
|
331
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ? AND state = 'confirmed'), 0) AS confirmed_sum,
|
|
332
|
+
(SELECT MAX(as_of) FROM commerce_inventory_movements
|
|
333
|
+
WHERE tenant_id = ? AND stage = ? AND sku = ? AND location_id = ?) AS as_of`,
|
|
334
|
+
input.tenantId,
|
|
335
|
+
input.stage,
|
|
336
|
+
input.sku,
|
|
337
|
+
input.locationId,
|
|
338
|
+
input.tenantId,
|
|
339
|
+
input.stage,
|
|
340
|
+
input.sku,
|
|
341
|
+
input.locationId,
|
|
342
|
+
input.tenantId,
|
|
343
|
+
input.stage,
|
|
344
|
+
input.sku,
|
|
345
|
+
input.locationId,
|
|
346
|
+
);
|
|
347
|
+
const balance = Number(row?.ledger_sum ?? 0) - Number(row?.confirmed_sum ?? 0);
|
|
348
|
+
return { balance: Number.isSafeInteger(balance) ? balance : 0, asOf: row?.as_of ?? null };
|
|
349
|
+
}
|
|
350
|
+
|
|
335
351
|
/** Sum of movements, including a non-positive or stale balance. No rows is null, not zero. */
|
|
336
352
|
export async function readMirrorBalance(db: Queryable, input: BalanceKey): Promise<MirrorBalance | null> {
|
|
337
353
|
const row = await db.first<{ balance: number | null; as_of: string | null }>(
|
|
@@ -388,16 +404,6 @@ export async function appendSourceOnHand(
|
|
|
388
404
|
!["preview", "publication"].includes(input.stage)
|
|
389
405
|
)
|
|
390
406
|
throw new InventoryMovementError("invalid-movement");
|
|
391
|
-
const prior = await db.first<{ one: number }>(
|
|
392
|
-
`SELECT 1 AS one FROM commerce_inventory_movements
|
|
393
|
-
WHERE tenant_id=? AND stage=? AND source=? AND source_event_id=? AND sku=? AND location_id=?`,
|
|
394
|
-
input.tenantId,
|
|
395
|
-
input.stage,
|
|
396
|
-
input.source,
|
|
397
|
-
input.sourceEventId,
|
|
398
|
-
input.sku,
|
|
399
|
-
input.locationId,
|
|
400
|
-
);
|
|
401
407
|
const others = [input.tenantId, input.stage, input.sku, input.locationId, input.source, input.sourceEventId];
|
|
402
408
|
await db.run(
|
|
403
409
|
`INSERT INTO commerce_inventory_movements
|
|
@@ -435,24 +441,22 @@ export async function appendSourceOnHand(
|
|
|
435
441
|
actual.actor_id !== input.actorId
|
|
436
442
|
)
|
|
437
443
|
throw new InventoryMovementError("conflict");
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
});
|
|
455
|
-
}
|
|
444
|
+
const reading = await readEffectiveMirrorBalance(db, {
|
|
445
|
+
tenantId: input.tenantId,
|
|
446
|
+
stage: input.stage,
|
|
447
|
+
sku: input.sku,
|
|
448
|
+
locationId: input.locationId,
|
|
449
|
+
});
|
|
450
|
+
await recordMirrorInventoryChanged(db, {
|
|
451
|
+
tenantId: input.tenantId,
|
|
452
|
+
stage: input.stage,
|
|
453
|
+
source: input.source,
|
|
454
|
+
sourceEventId: input.sourceEventId,
|
|
455
|
+
sku: input.sku,
|
|
456
|
+
locationId: input.locationId,
|
|
457
|
+
balance: reading.balance,
|
|
458
|
+
asOf: actual.as_of,
|
|
459
|
+
});
|
|
456
460
|
}
|
|
457
461
|
|
|
458
462
|
/** The largest balance a key may hold: the mirror ledger never stores or reports an unsafe integer. */
|
|
@@ -488,8 +492,12 @@ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlC
|
|
|
488
492
|
sql: `INSERT INTO commerce_inventory_movements
|
|
489
493
|
(tenant_id,stage,source,source_event_id,sku,location_id,quantity_delta,as_of,actor_id)
|
|
490
494
|
SELECT ?,?,?,?,?,?,CAST(? AS INTEGER),?,?
|
|
491
|
-
FROM (
|
|
492
|
-
|
|
495
|
+
FROM (
|
|
496
|
+
SELECT COALESCE((SELECT SUM(quantity_delta) FROM commerce_inventory_movements
|
|
497
|
+
WHERE tenant_id=? AND stage=? AND sku=? AND location_id=?), 0)
|
|
498
|
+
- COALESCE((SELECT SUM(quantity) FROM scrappy_allocations
|
|
499
|
+
WHERE tenant_id=? AND stage=? AND sku=? AND location_id=? AND state='confirmed'), 0) AS balance
|
|
500
|
+
) AS current
|
|
493
501
|
WHERE current.balance + CAST(? AS INTEGER) <= ${MIRROR_BALANCE_MAX}
|
|
494
502
|
AND (current.balance + CAST(? AS INTEGER) >= 0 OR CAST(? AS INTEGER) > 0)
|
|
495
503
|
AND (? = '${MIRROR_LOCATION_UNSPECIFIED}' OR EXISTS (
|
|
@@ -510,6 +518,10 @@ export function guardedCorrectionStatement(movement: MirrorMovement, guard: SqlC
|
|
|
510
518
|
movement.stage,
|
|
511
519
|
movement.sku,
|
|
512
520
|
movement.locationId,
|
|
521
|
+
movement.tenantId,
|
|
522
|
+
movement.stage,
|
|
523
|
+
movement.sku,
|
|
524
|
+
movement.locationId,
|
|
513
525
|
delta,
|
|
514
526
|
delta,
|
|
515
527
|
delta,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "6.11.
|
|
3
|
+
"version": "6.11.7",
|
|
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",
|