@zeyolabs/shopping 2026.11.8 → 2026.11.10
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/components/ProductCard.svelte +10 -1
- package/db/schema.ts +28 -0
- package/package.json +5 -4
- package/pages/Product.svelte +6 -1
- package/server/admin-stock.ts +4 -9
- package/server/basket.ts +9 -5
- package/server/catalogue.ts +9 -2
- package/server/orders.ts +11 -10
- package/server/stock-alert-service.ts +30 -0
- package/server/stock-alerts.ts +4 -3
- package/server/stock-service.ts +192 -0
|
@@ -3,10 +3,13 @@
|
|
|
3
3
|
import { shoppingClient } from '../client';
|
|
4
4
|
import { productImageUrl } from '../images';
|
|
5
5
|
import { formatMoney } from '../money';
|
|
6
|
+
import { Stock } from '../stock';
|
|
6
7
|
|
|
7
8
|
type Product = {
|
|
8
9
|
comparePricePence: null | number;
|
|
9
10
|
cover?: { alt: string; src: string };
|
|
11
|
+
/** Show "Only N left" when the sellable stock is at or below this. */
|
|
12
|
+
lowStockThreshold?: null | number;
|
|
10
13
|
name: string;
|
|
11
14
|
pricePence: number;
|
|
12
15
|
slug: string;
|
|
@@ -17,6 +20,7 @@
|
|
|
17
20
|
|
|
18
21
|
const client = shoppingClient();
|
|
19
22
|
|
|
23
|
+
const badge = $derived(Stock.badge(product.stock, product.lowStockThreshold));
|
|
20
24
|
const onSale = $derived(
|
|
21
25
|
product.comparePricePence !== null && product.comparePricePence > product.pricePence
|
|
22
26
|
);
|
|
@@ -42,11 +46,16 @@
|
|
|
42
46
|
src={productImageUrl(client.imageBaseUrl, product.cover.src)}
|
|
43
47
|
/>
|
|
44
48
|
{/if}
|
|
45
|
-
{#if
|
|
49
|
+
{#if badge.kind === 'out'}
|
|
46
50
|
<span
|
|
47
51
|
class="absolute top-2 left-2 rounded-full bg-white/95 px-2.5 py-1 text-xs font-medium text-[var(--txs)] shadow-sm"
|
|
48
52
|
>Out of stock</span
|
|
49
53
|
>
|
|
54
|
+
{:else if badge.kind === 'low'}
|
|
55
|
+
<span
|
|
56
|
+
class="absolute top-2 left-2 rounded-full bg-white/95 px-2.5 py-1 text-xs font-medium text-[var(--txs)] shadow-sm"
|
|
57
|
+
>Only {badge.count} left</span
|
|
58
|
+
>
|
|
50
59
|
{:else if onSale}
|
|
51
60
|
<span
|
|
52
61
|
class="absolute top-2 left-2 rounded-full bg-[var(--primary-strong)] px-2.5 py-1 text-xs font-medium text-white"
|
package/db/schema.ts
CHANGED
|
@@ -33,20 +33,48 @@ export const products = sqliteTable('products', {
|
|
|
33
33
|
createdAt: integer('created_at').notNull(),
|
|
34
34
|
description: text('description').notNull().default(''),
|
|
35
35
|
id: integer('id').primaryKey({ autoIncrement: true }),
|
|
36
|
+
/** Show "only N left" when the sellable count is at or below this. Null: never. */
|
|
37
|
+
lowStockThreshold: integer('low_stock_threshold'),
|
|
36
38
|
massGrams: integer('mass_grams').notNull().default(0),
|
|
37
39
|
maxPerOrder: integer('max_per_order').notNull().default(10),
|
|
38
40
|
name: text('name').notNull(),
|
|
41
|
+
/** Single units sold together as one purchase; `stock` is held in single units. */
|
|
42
|
+
packSize: integer('pack_size').notNull().default(1),
|
|
39
43
|
pricePence: integer('price_pence').notNull(),
|
|
44
|
+
/** When the product last went from not sellable to sellable (set by `StockService.setStock`). */
|
|
45
|
+
restockedAt: integer('restocked_at'),
|
|
40
46
|
shortDescription: text('short_description').notNull().default(''),
|
|
41
47
|
sku: text('sku').notNull().unique(),
|
|
42
48
|
slug: text('slug').notNull().unique(),
|
|
49
|
+
/** Purchases counted when an order is paid. */
|
|
50
|
+
sold: integer('sold').notNull().default(0),
|
|
43
51
|
sortOrder: integer('sort_order').notNull().default(0),
|
|
52
|
+
/** Units in stock, in single units (a product sold in packs of 10 with 30 in stock sells 3). */
|
|
44
53
|
stock: integer('stock').notNull().default(0),
|
|
45
54
|
variationGroupId: integer('variation_group_id').references(() => variationGroups.id),
|
|
46
55
|
/** This product's option within its variation group, e.g. "Black". */
|
|
47
56
|
variationLabel: text('variation_label'),
|
|
48
57
|
});
|
|
49
58
|
|
|
59
|
+
/**
|
|
60
|
+
* A combined product is made of other products: it has no stock of its own, and what can be sold is
|
|
61
|
+
* the fewest complete sets the components allow. Paying for it decrements the components.
|
|
62
|
+
*/
|
|
63
|
+
export const productComponents = sqliteTable(
|
|
64
|
+
'product_components',
|
|
65
|
+
{
|
|
66
|
+
componentId: integer('component_id')
|
|
67
|
+
.notNull()
|
|
68
|
+
.references(() => products.id, { onDelete: 'restrict' }),
|
|
69
|
+
productId: integer('product_id')
|
|
70
|
+
.notNull()
|
|
71
|
+
.references(() => products.id, { onDelete: 'cascade' }),
|
|
72
|
+
/** How many of the component one set takes. */
|
|
73
|
+
quantity: integer('quantity').notNull().default(1),
|
|
74
|
+
},
|
|
75
|
+
(t) => [primaryKey({ columns: [t.productId, t.componentId] })]
|
|
76
|
+
);
|
|
77
|
+
|
|
50
78
|
/** Slugs the legacy site used, so old links and search results 301 to the product's current URL. */
|
|
51
79
|
export const productSlugAliases = sqliteTable('product_slug_aliases', {
|
|
52
80
|
productId: integer('product_id')
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zeyolabs/shopping",
|
|
3
|
-
"version": "2026.11.
|
|
3
|
+
"version": "2026.11.10",
|
|
4
4
|
"description": "Shop and order fulfilment for SvelteKit 3 on Cloudflare: catalogue, basket, Stripe Checkout, orders, Royal Mail Click & Drop, order emails, packing, pages and admin.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -65,9 +65,9 @@
|
|
|
65
65
|
"svelte-sonner": "1.2.1"
|
|
66
66
|
},
|
|
67
67
|
"peerDependencies": {
|
|
68
|
+
"@sveltejs/kit": "^3.1.1",
|
|
68
69
|
"@zeyolabs/kit": ">=2026.11.5",
|
|
69
70
|
"@zeyolabs/ui": ">=2026.11.5",
|
|
70
|
-
"@sveltejs/kit": "^3.1.1",
|
|
71
71
|
"drizzle-orm": "^0.45.3",
|
|
72
72
|
"svelte": "^5.57.3",
|
|
73
73
|
"zod": "^4.6.5"
|
|
@@ -76,9 +76,9 @@
|
|
|
76
76
|
"@cloudflare/workers-types": "5.20261005.1",
|
|
77
77
|
"@eslint/compat": "2.1.1",
|
|
78
78
|
"@eslint/js": "9.39.4",
|
|
79
|
-
"@zeyolabs/kit": "2026.11.6",
|
|
80
|
-
"@zeyolabs/ui": "2026.1106.0",
|
|
81
79
|
"@sveltejs/kit": "3.1.1",
|
|
80
|
+
"@zeyolabs/kit": "2026.11.11",
|
|
81
|
+
"@zeyolabs/ui": "2026.1106.0",
|
|
82
82
|
"drizzle-orm": "0.45.3",
|
|
83
83
|
"eslint": "9.39.4",
|
|
84
84
|
"eslint-config-prettier": "10.1.8",
|
|
@@ -86,6 +86,7 @@
|
|
|
86
86
|
"eslint-plugin-perfectionist": "5.9.1",
|
|
87
87
|
"eslint-plugin-svelte": "3.24.0",
|
|
88
88
|
"globals": "17.13.0",
|
|
89
|
+
"miniflare": "4.20260730.0",
|
|
89
90
|
"prettier": "3.9.9",
|
|
90
91
|
"prettier-plugin-svelte": "4.1.1",
|
|
91
92
|
"svelte": "5.57.3",
|
package/pages/Product.svelte
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
import { shoppingClient } from '../client';
|
|
10
10
|
import { productImageUrl } from '../images';
|
|
11
11
|
import { formatMoney } from '../money';
|
|
12
|
+
import { Stock } from '../stock';
|
|
12
13
|
import { toast } from 'svelte-sonner';
|
|
13
14
|
import Button from '@zeyolabs/ui/form/Button.svelte';
|
|
14
15
|
import ImageGallery from '@zeyolabs/ui/gallery/ImageGallery.svelte';
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
</script>
|
|
37
38
|
|
|
38
39
|
{let product = $derived(data.product)}
|
|
40
|
+
{let stockBadge = $derived(Stock.badge(product.stock, product.lowStockThreshold))}
|
|
39
41
|
|
|
40
42
|
<PageTitle
|
|
41
43
|
description={(product.shortDescription || product.description).slice(0, 160)}
|
|
@@ -75,7 +77,10 @@
|
|
|
75
77
|
{/if}
|
|
76
78
|
{#if product.shortDescription}<p class="mt-4">{product.shortDescription}</p>{/if}
|
|
77
79
|
<p class="mt-4 whitespace-pre-line">{product.description}</p>
|
|
78
|
-
<p class="mt-4">
|
|
80
|
+
<p class="mt-4">
|
|
81
|
+
{#if stockBadge.kind === 'out'}Out of stock{:else if stockBadge.kind === 'low'}Only {stockBadge.count}
|
|
82
|
+
left{:else}In stock{/if}
|
|
83
|
+
</p>
|
|
79
84
|
{#if product.stock > 0}
|
|
80
85
|
<Button class="mt-4" onclick={() => add(product.id)} size="lg">
|
|
81
86
|
<ShoppingBasket size={18} />
|
package/server/admin-stock.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { asc, count, eq, sql } from 'drizzle-orm';
|
|
1
|
+
import { asc, count, sql } from 'drizzle-orm';
|
|
3
2
|
|
|
4
3
|
import { shopping } from '../config';
|
|
5
4
|
import { products, stockAlerts } from '../db/schema';
|
|
5
|
+
import { StockService } from './stock-service';
|
|
6
6
|
|
|
7
7
|
const getDb = () => shopping().db();
|
|
8
8
|
|
|
@@ -22,12 +22,7 @@ export async function listStock() {
|
|
|
22
22
|
.orderBy(asc(sql`${products.stock} > 0`), asc(products.name), asc(products.id));
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
/** Sets a product's stock. Customers waiting on it are emailed by the stock-alerts cron, not here. */
|
|
25
|
+
/** Sets a product's stock in single units. Customers waiting on it are emailed by the stock-alerts cron, not here. */
|
|
26
26
|
export async function setStock(productId: number, stock: number) {
|
|
27
|
-
|
|
28
|
-
.update(products)
|
|
29
|
-
.set({ stock })
|
|
30
|
-
.where(eq(products.id, productId))
|
|
31
|
-
.returning({ id: products.id });
|
|
32
|
-
if (updated.length === 0) throw Error404('Product not found.');
|
|
27
|
+
await new StockService(getDb()).setStock(productId, stock);
|
|
33
28
|
}
|
package/server/basket.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type { ShopDb } from '../db';
|
|
|
7
7
|
import { shopping } from '../config';
|
|
8
8
|
import { productImages, products } from '../db/schema';
|
|
9
9
|
import { quoteShipping, type ShippingQuote } from './shipping';
|
|
10
|
+
import { StockService } from './stock-service';
|
|
10
11
|
|
|
11
12
|
/** The basket lives in a cookie as `{ [productId]: quantity }`; prices always come from D1. */
|
|
12
13
|
const COOKIE = 'basket';
|
|
@@ -16,11 +17,11 @@ const MAX_LINES = 30;
|
|
|
16
17
|
export type Basket = Record<number, number>;
|
|
17
18
|
|
|
18
19
|
export type BasketLine = {
|
|
19
|
-
/** What the customer can actually buy right now: min(requested,
|
|
20
|
+
/** What the customer can actually buy right now: min(requested, sellable, max per order). */
|
|
20
21
|
available: number;
|
|
21
22
|
cover: null | { alt: string; src: string };
|
|
22
23
|
id: number;
|
|
23
|
-
/** The most of this product one order can hold: min(
|
|
24
|
+
/** The most of this product one order can hold: min(sellable, max per order). */
|
|
24
25
|
limit: number;
|
|
25
26
|
lineTotalPence: number;
|
|
26
27
|
massGrams: number;
|
|
@@ -29,6 +30,7 @@ export type BasketLine = {
|
|
|
29
30
|
quantity: number;
|
|
30
31
|
sku: string;
|
|
31
32
|
slug: string;
|
|
33
|
+
/** Units that can be sold now (whole packs, or complete sets), not the raw stock count. */
|
|
32
34
|
stock: number;
|
|
33
35
|
};
|
|
34
36
|
|
|
@@ -131,6 +133,7 @@ export async function summariseBasket(
|
|
|
131
133
|
.from(products)
|
|
132
134
|
.where(and(inArray(products.id, ids), eq(products.active, true)))
|
|
133
135
|
.orderBy(asc(products.name));
|
|
136
|
+
const sellable = await new StockService(db).availableMany(rows.map((p) => p.id));
|
|
134
137
|
const images = await db
|
|
135
138
|
.select()
|
|
136
139
|
.from(productImages)
|
|
@@ -146,13 +149,14 @@ export async function summariseBasket(
|
|
|
146
149
|
|
|
147
150
|
const lines = rows.map((product): BasketLine => {
|
|
148
151
|
const quantity = basket[product.id];
|
|
149
|
-
const
|
|
152
|
+
const inStock = sellable.get(product.id) ?? 0;
|
|
153
|
+
const available = Math.max(0, Math.min(quantity, inStock, product.maxPerOrder));
|
|
150
154
|
const image = cover.get(product.id);
|
|
151
155
|
return {
|
|
152
156
|
available,
|
|
153
157
|
cover: image ? { alt: image.alt, src: image.src } : null,
|
|
154
158
|
id: product.id,
|
|
155
|
-
limit: Math.max(0, Math.min(
|
|
159
|
+
limit: Math.max(0, Math.min(inStock, product.maxPerOrder)),
|
|
156
160
|
lineTotalPence: available * product.pricePence,
|
|
157
161
|
massGrams: product.massGrams,
|
|
158
162
|
name: product.name,
|
|
@@ -160,7 +164,7 @@ export async function summariseBasket(
|
|
|
160
164
|
quantity,
|
|
161
165
|
sku: product.sku,
|
|
162
166
|
slug: product.slug,
|
|
163
|
-
stock:
|
|
167
|
+
stock: inStock,
|
|
164
168
|
};
|
|
165
169
|
});
|
|
166
170
|
|
package/server/catalogue.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
products,
|
|
10
10
|
productSlugAliases,
|
|
11
11
|
} from '../db/schema';
|
|
12
|
+
import { StockService } from './stock-service';
|
|
12
13
|
|
|
13
14
|
export async function getCategory(db: ShopDb, slug: string) {
|
|
14
15
|
return db.query.categories.findFirst({ where: eq(categories.slug, slug) });
|
|
@@ -20,7 +21,7 @@ export async function listCategories(db: ShopDb) {
|
|
|
20
21
|
|
|
21
22
|
type Product = typeof products.$inferSelect;
|
|
22
23
|
|
|
23
|
-
/** Adds each product's cover image (lowest position), if it has one. */
|
|
24
|
+
/** Adds each product's cover image (lowest position), if it has one. `stock` is what can be sold now. */
|
|
24
25
|
async function withCovers(db: ShopDb, list: Product[]) {
|
|
25
26
|
if (list.length === 0) return [];
|
|
26
27
|
const images = await db
|
|
@@ -35,7 +36,12 @@ async function withCovers(db: ShopDb, list: Product[]) {
|
|
|
35
36
|
.orderBy(asc(productImages.position));
|
|
36
37
|
const cover = new Map<number, (typeof images)[number]>();
|
|
37
38
|
for (const image of images) if (!cover.has(image.productId)) cover.set(image.productId, image);
|
|
38
|
-
|
|
39
|
+
const sellable = await new StockService(db).availableMany(list.map((p) => p.id));
|
|
40
|
+
return list.map((product) => ({
|
|
41
|
+
...product,
|
|
42
|
+
cover: cover.get(product.id),
|
|
43
|
+
stock: sellable.get(product.id) ?? 0,
|
|
44
|
+
}));
|
|
39
45
|
}
|
|
40
46
|
|
|
41
47
|
/** Active products in a category, each with its cover image, if any. */
|
|
@@ -66,6 +72,7 @@ export async function getProduct(db: ShopDb, slug: string) {
|
|
|
66
72
|
with: { images: { orderBy: asc(productImages.position) }, variationGroup: true },
|
|
67
73
|
});
|
|
68
74
|
if (!product) return undefined;
|
|
75
|
+
product.stock = await new StockService(db).available(product.id);
|
|
69
76
|
|
|
70
77
|
const options = product.variationGroupId
|
|
71
78
|
? await db
|
package/server/orders.ts
CHANGED
|
@@ -2,15 +2,16 @@ import type Stripe from 'stripe';
|
|
|
2
2
|
|
|
3
3
|
import { logger } from '@zeyolabs/kit/server/logger';
|
|
4
4
|
import { Crypto } from '@zeyolabs/kit/utils/crypto';
|
|
5
|
-
import { eq
|
|
5
|
+
import { eq } from 'drizzle-orm';
|
|
6
6
|
|
|
7
7
|
import type { ShopDb } from '../db';
|
|
8
8
|
|
|
9
9
|
import { secret, shopping } from '../config';
|
|
10
|
-
import { addresses, orderItems, orders
|
|
10
|
+
import { addresses, orderItems, orders } from '../db/schema';
|
|
11
11
|
import { orderUrl } from '../order-links';
|
|
12
12
|
import { createClickAndDropOrder } from '../royalmail';
|
|
13
13
|
import { quoteServiceCode } from './shipping';
|
|
14
|
+
import { StockService } from './stock-service';
|
|
14
15
|
import { getStripe } from './stripe';
|
|
15
16
|
|
|
16
17
|
// No 0/O/1/I: the number is read out over the phone.
|
|
@@ -121,17 +122,17 @@ export async function fulfilCheckoutSession(db: ShopDb, sessionId: string): Prom
|
|
|
121
122
|
};
|
|
122
123
|
});
|
|
123
124
|
|
|
125
|
+
// Read before the batch: the stock statements depend on pack sizes and components, and the batch
|
|
126
|
+
// itself stays one atomic write of the items and the stock (a double delivery sees the items).
|
|
127
|
+
const stockStatements = await new StockService(db).paidStatements(
|
|
128
|
+
items.flatMap((item) =>
|
|
129
|
+
item.productId === null ? [] : [{ productId: item.productId, quantity: item.quantity }]
|
|
130
|
+
)
|
|
131
|
+
);
|
|
124
132
|
try {
|
|
125
133
|
await db.batch([
|
|
126
134
|
db.insert(orderItems).values(items.map((item) => ({ ...item, orderId }))),
|
|
127
|
-
...
|
|
128
|
-
.filter((item) => item.productId !== null)
|
|
129
|
-
.map((item) =>
|
|
130
|
-
db
|
|
131
|
-
.update(products)
|
|
132
|
-
.set({ stock: sql`max(${products.stock} - ${item.quantity}, 0)` })
|
|
133
|
-
.where(eq(products.id, item.productId!))
|
|
134
|
-
),
|
|
135
|
+
...stockStatements,
|
|
135
136
|
]);
|
|
136
137
|
} catch (error) {
|
|
137
138
|
// The batch is atomic, so if the items exist another delivery already wrote them and the stock.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { and, eq } from 'drizzle-orm';
|
|
2
|
+
|
|
3
|
+
import type { ShopDb } from '../db';
|
|
4
|
+
|
|
5
|
+
import { products, stockAlerts } from '../db/schema';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Data access for "tell me when it's back" signups. It takes the db it works on; it checks no
|
|
9
|
+
* permissions and sends nothing (the back-in-stock job in `stock-alerts.ts` does the sending).
|
|
10
|
+
*/
|
|
11
|
+
export class StockAlertService {
|
|
12
|
+
constructor(private readonly db: ShopDb) {}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Adds a signup for an active product and returns the product's name, or null when there is no
|
|
16
|
+
* such active product. Signing up twice is fine and is not reported, so a caller cannot tell
|
|
17
|
+
* whether an address was already on the list.
|
|
18
|
+
*/
|
|
19
|
+
async subscribe(email: string, productId: number): Promise<null | { productName: string }> {
|
|
20
|
+
const product = await this.db.query.products.findFirst({
|
|
21
|
+
where: and(eq(products.id, productId), eq(products.active, true)),
|
|
22
|
+
});
|
|
23
|
+
if (!product) return null;
|
|
24
|
+
await this.db
|
|
25
|
+
.insert(stockAlerts)
|
|
26
|
+
.values({ createdAt: Date.now(), email: email.toLowerCase(), productId })
|
|
27
|
+
.onConflictDoNothing();
|
|
28
|
+
return { productName: product.name };
|
|
29
|
+
}
|
|
30
|
+
}
|
package/server/stock-alerts.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { logger } from '@zeyolabs/kit/server/logger';
|
|
2
|
-
import { and, asc, eq,
|
|
2
|
+
import { and, asc, eq, isNull } from 'drizzle-orm';
|
|
3
3
|
|
|
4
4
|
import type { BackInStockEmailData } from '../emails/back-in-stock';
|
|
5
5
|
|
|
6
6
|
import { shopping } from '../config';
|
|
7
7
|
import { products, stockAlerts } from '../db/schema';
|
|
8
|
+
import { sellableSql } from './stock-service';
|
|
8
9
|
|
|
9
10
|
/** How many back-in-stock emails go out per run. The worker runs once a minute. */
|
|
10
11
|
export const BACK_IN_STOCK_BATCH = 50;
|
|
@@ -19,7 +20,7 @@ export type PendingAlert = BackInStockEmailData & {
|
|
|
19
20
|
productId: number;
|
|
20
21
|
};
|
|
21
22
|
|
|
22
|
-
/** Signups waiting on a product that
|
|
23
|
+
/** Signups waiting on a product that is sellable again (a whole pack, or every component of a set), oldest first. Rows already marked notified are skipped. */
|
|
23
24
|
export async function pendingAlerts(limit = BACK_IN_STOCK_BATCH): Promise<PendingAlert[]> {
|
|
24
25
|
return shopping()
|
|
25
26
|
.db()
|
|
@@ -34,7 +35,7 @@ export async function pendingAlerts(limit = BACK_IN_STOCK_BATCH): Promise<Pendin
|
|
|
34
35
|
})
|
|
35
36
|
.from(stockAlerts)
|
|
36
37
|
.innerJoin(products, eq(products.id, stockAlerts.productId))
|
|
37
|
-
.where(and(
|
|
38
|
+
.where(and(sellableSql, eq(products.active, true), isNull(stockAlerts.notifiedAt)))
|
|
38
39
|
.orderBy(asc(stockAlerts.id))
|
|
39
40
|
.limit(limit);
|
|
40
41
|
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { Error400, Error404 } from '@zeyolabs/kit/utils/errors';
|
|
2
|
+
import { eq, inArray, sql } from 'drizzle-orm';
|
|
3
|
+
|
|
4
|
+
import type { ShopDb } from '../db';
|
|
5
|
+
|
|
6
|
+
import { productComponents, products } from '../db/schema';
|
|
7
|
+
import { Stock, type StockComponent } from '../stock';
|
|
8
|
+
|
|
9
|
+
/** A combined product takes at most this many components (keeps every statement well under D1's limits). */
|
|
10
|
+
export const MAX_COMPONENTS = 10;
|
|
11
|
+
|
|
12
|
+
type ComponentRow = StockComponent & { componentId: number };
|
|
13
|
+
|
|
14
|
+
/** The part of a paid order line the stock cares about. */
|
|
15
|
+
export type PaidLine = { productId: number; quantity: number };
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* SQL for "this product can be bought right now": a plain product has at least one whole pack, a
|
|
19
|
+
* combined product has every component stocked for one set. Used where a query filters on it.
|
|
20
|
+
*/
|
|
21
|
+
export const sellableSql = sql`(case when exists (select 1 from ${productComponents} pc where pc.product_id = ${products.id})
|
|
22
|
+
then not exists (select 1 from ${productComponents} pc join ${products} c on c.id = pc.component_id
|
|
23
|
+
where pc.product_id = ${products.id} and c.stock < pc.quantity * c.pack_size)
|
|
24
|
+
else ${products.stock} >= ${products.packSize} end)`;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Stock data access: what can be sold, the decrement when an order is paid, and the one write path
|
|
28
|
+
* for stock edits. It takes the db it works on, checks no permissions and sends nothing.
|
|
29
|
+
*/
|
|
30
|
+
export class StockService {
|
|
31
|
+
constructor(private readonly db: ShopDb) {}
|
|
32
|
+
|
|
33
|
+
/** What can be sold of one product right now (whole packs, or complete sets if it is combined). */
|
|
34
|
+
async available(productId: number): Promise<number> {
|
|
35
|
+
return (await this.availableMany([productId])).get(productId) ?? 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Sellable count per product id. Unknown ids are left out. */
|
|
39
|
+
async availableMany(ids: readonly number[]): Promise<Map<number, number>> {
|
|
40
|
+
const result = new Map<number, number>();
|
|
41
|
+
if (ids.length === 0) return result;
|
|
42
|
+
const rows = await this.db
|
|
43
|
+
.select({ id: products.id, packSize: products.packSize, stock: products.stock })
|
|
44
|
+
.from(products)
|
|
45
|
+
.where(inArray(products.id, [...ids]));
|
|
46
|
+
const components = await this.componentsOf(rows.map((r) => r.id));
|
|
47
|
+
for (const row of rows) {
|
|
48
|
+
const parts = components.get(row.id);
|
|
49
|
+
result.set(
|
|
50
|
+
row.id,
|
|
51
|
+
parts ? Stock.combinedAvailable(parts) : Stock.sellable(row.stock, row.packSize)
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The components of a combined product, or an empty list for a plain one. */
|
|
58
|
+
async components(productId: number): Promise<ComponentRow[]> {
|
|
59
|
+
return (await this.componentsOf([productId])).get(productId) ?? [];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The statements that take a paid order's stock: each line's product (or, for a combined product,
|
|
64
|
+
* its components) loses stock, floored at 0, and the product's `sold` goes up. They are returned
|
|
65
|
+
* rather than run, so the caller writes them in the same atomic `db.batch` as the order items.
|
|
66
|
+
*/
|
|
67
|
+
async paidStatements(lines: readonly PaidLine[]) {
|
|
68
|
+
const ids = lines.map((l) => l.productId);
|
|
69
|
+
const [rows, components] = await Promise.all([
|
|
70
|
+
ids.length > 0
|
|
71
|
+
? this.db
|
|
72
|
+
.select({ id: products.id, packSize: products.packSize })
|
|
73
|
+
.from(products)
|
|
74
|
+
.where(inArray(products.id, ids))
|
|
75
|
+
: [],
|
|
76
|
+
this.componentsOf(ids),
|
|
77
|
+
]);
|
|
78
|
+
const packSize = new Map(rows.map((r) => [r.id, r.packSize]));
|
|
79
|
+
const statements = [];
|
|
80
|
+
for (const line of lines) {
|
|
81
|
+
const parts = components.get(line.productId);
|
|
82
|
+
if (parts) {
|
|
83
|
+
for (const part of parts) {
|
|
84
|
+
statements.push(
|
|
85
|
+
this.decrement(part.componentId, line.quantity * part.quantity * part.packSize)
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
} else {
|
|
89
|
+
statements.push(
|
|
90
|
+
this.decrement(line.productId, line.quantity * (packSize.get(line.productId) ?? 1))
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
statements.push(
|
|
94
|
+
this.db
|
|
95
|
+
.update(products)
|
|
96
|
+
.set({ sold: sql`${products.sold} + ${line.quantity}` })
|
|
97
|
+
.where(eq(products.id, line.productId))
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
return statements;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Replaces a combined product's components. At most `MAX_COMPONENTS`, no repeats, and a product
|
|
105
|
+
* cannot contain itself or another combined product. An empty list makes it a plain product again.
|
|
106
|
+
*/
|
|
107
|
+
async setComponents(
|
|
108
|
+
productId: number,
|
|
109
|
+
components: readonly { componentId: number; quantity: number }[]
|
|
110
|
+
) {
|
|
111
|
+
if (components.length > MAX_COMPONENTS) {
|
|
112
|
+
throw Error400(`A combined product has at most ${MAX_COMPONENTS} components.`);
|
|
113
|
+
}
|
|
114
|
+
const ids = components.map((c) => c.componentId);
|
|
115
|
+
if (new Set(ids).size !== ids.length) throw Error400('A component can only be listed once.');
|
|
116
|
+
if (ids.includes(productId)) throw Error400('A product cannot contain itself.');
|
|
117
|
+
if (components.some((c) => !Number.isInteger(c.quantity) || c.quantity < 1)) {
|
|
118
|
+
throw Error400('Each component quantity must be a whole number of at least 1.');
|
|
119
|
+
}
|
|
120
|
+
if (ids.length > 0) {
|
|
121
|
+
const nested = await this.componentsOf(ids);
|
|
122
|
+
if (nested.size > 0) throw Error400('A component cannot itself be a combined product.');
|
|
123
|
+
}
|
|
124
|
+
if (components.length > 0) {
|
|
125
|
+
const usedAsComponent = await this.db
|
|
126
|
+
.select({ productId: productComponents.productId })
|
|
127
|
+
.from(productComponents)
|
|
128
|
+
.where(eq(productComponents.componentId, productId))
|
|
129
|
+
.limit(1);
|
|
130
|
+
if (usedAsComponent.length > 0) {
|
|
131
|
+
throw Error400('A product that is a component of another set cannot be combined itself.');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
await this.db.batch([
|
|
135
|
+
this.db.delete(productComponents).where(eq(productComponents.productId, productId)),
|
|
136
|
+
...(components.length > 0
|
|
137
|
+
? [this.db.insert(productComponents).values(components.map((c) => ({ ...c, productId })))]
|
|
138
|
+
: []),
|
|
139
|
+
]);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Sets a product's stock in single units. This is the only write path for stock edits (the admin
|
|
144
|
+
* page and imports go through it): `restockedAt` is set in the same statement when the product
|
|
145
|
+
* goes from not sellable to sellable, so it cannot drift.
|
|
146
|
+
*/
|
|
147
|
+
async setStock(productId: number, units: number, now = Date.now()): Promise<void> {
|
|
148
|
+
const updated = await this.db
|
|
149
|
+
.update(products)
|
|
150
|
+
.set({
|
|
151
|
+
restockedAt: sql`case when ${products.stock} < ${products.packSize} and ${units} >= ${products.packSize} then ${now} else ${products.restockedAt} end`,
|
|
152
|
+
stock: units,
|
|
153
|
+
})
|
|
154
|
+
.where(eq(products.id, productId))
|
|
155
|
+
.returning({ id: products.id });
|
|
156
|
+
if (updated.length === 0) throw Error404('Product not found.');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
private async componentsOf(ids: readonly number[]): Promise<Map<number, ComponentRow[]>> {
|
|
160
|
+
const map = new Map<number, ComponentRow[]>();
|
|
161
|
+
if (ids.length === 0) return map;
|
|
162
|
+
const rows = await this.db
|
|
163
|
+
.select({
|
|
164
|
+
componentId: productComponents.componentId,
|
|
165
|
+
packSize: products.packSize,
|
|
166
|
+
productId: productComponents.productId,
|
|
167
|
+
quantity: productComponents.quantity,
|
|
168
|
+
stock: products.stock,
|
|
169
|
+
})
|
|
170
|
+
.from(productComponents)
|
|
171
|
+
.innerJoin(products, eq(products.id, productComponents.componentId))
|
|
172
|
+
.where(inArray(productComponents.productId, [...ids]));
|
|
173
|
+
for (const row of rows) {
|
|
174
|
+
const list = map.get(row.productId) ?? [];
|
|
175
|
+
list.push({
|
|
176
|
+
componentId: row.componentId,
|
|
177
|
+
packSize: row.packSize,
|
|
178
|
+
quantity: row.quantity,
|
|
179
|
+
stock: row.stock,
|
|
180
|
+
});
|
|
181
|
+
map.set(row.productId, list);
|
|
182
|
+
}
|
|
183
|
+
return map;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
private decrement(productId: number, units: number) {
|
|
187
|
+
return this.db
|
|
188
|
+
.update(products)
|
|
189
|
+
.set({ stock: sql`max(${products.stock} - ${units}, 0)` })
|
|
190
|
+
.where(eq(products.id, productId));
|
|
191
|
+
}
|
|
192
|
+
}
|