@zeyolabs/shopping 2026.11.7 → 2026.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.
@@ -0,0 +1,52 @@
1
+ <script lang="ts">
2
+ import { getStock } from '../remote/admin-stock.remote';
3
+ import StockRow from './StockRow.svelte';
4
+ import Badge from '@zeyolabs/ui/badge/Badge.svelte';
5
+ import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
6
+ </script>
7
+
8
+ <svelte:head><title>Stock</title></svelte:head>
9
+
10
+ <h1 class="text-2xl font-semibold">Stock</h1>
11
+ <p class="mt-1 text-sm text-[var(--ink-muted)]">
12
+ Setting a sold-out product above 0 emails the customers waiting for it, up to 50 a minute, and
13
+ removes them from the list.
14
+ </p>
15
+
16
+ <Boundary message="Could not load stock.">
17
+ {let rows = $derived(await getStock())}
18
+ <div class="mt-4 overflow-x-auto rounded-xl border border-[var(--line)] bg-white">
19
+ <table class="w-full text-left text-sm">
20
+ <thead class="border-b border-[var(--line)] text-[var(--ink-muted)]">
21
+ <tr>
22
+ <th class="px-4 py-2 font-medium">Product</th>
23
+ <th class="px-4 py-2 font-medium">SKU</th>
24
+ <th class="px-4 py-2 text-right font-medium">Waiting</th>
25
+ <th class="px-4 py-2 text-right font-medium">Stock</th>
26
+ </tr>
27
+ </thead>
28
+ <tbody class="divide-y divide-[var(--line)]">
29
+ {#each rows as row (row.id)}
30
+ <tr>
31
+ <td class="px-4 py-2 font-medium">
32
+ {row.name}{row.variationLabel ? ` · ${row.variationLabel}` : ''}
33
+ {#if !row.active}<Badge color="neutral">inactive</Badge>{/if}
34
+ </td>
35
+ <td class="px-4 py-2 whitespace-nowrap">{row.sku}</td>
36
+ <td class="px-4 py-2 text-right">{row.waiting}</td>
37
+ <td class="px-4 py-2"
38
+ ><StockRow
39
+ id={row.id}
40
+ name={`${row.name}${row.variationLabel ? ` ${row.variationLabel}` : ''} (${row.sku})`}
41
+ stock={row.stock}
42
+ /></td
43
+ >
44
+ </tr>
45
+ {/each}
46
+ </tbody>
47
+ </table>
48
+ </div>
49
+ {#snippet pending()}
50
+ <p class="mt-6 text-[var(--ink-muted)]">Loading…</p>
51
+ {/snippet}
52
+ </Boundary>
@@ -0,0 +1,26 @@
1
+ <script lang="ts">
2
+ import { setStockForm } from '../remote/admin-stock.remote';
3
+ import { StockSchema } from './stock.schema';
4
+ import { Form, NumberField } from '@zeyolabs/ui/form';
5
+ import Button from '@zeyolabs/ui/form/Button.svelte';
6
+ import Span from '@zeyolabs/ui/text/Span.svelte';
7
+
8
+ let { id, name, stock }: { id: number; name: string; stock: number } = $props();
9
+
10
+ const form = $derived(setStockForm.for(id));
11
+ </script>
12
+
13
+ <Form
14
+ class="flex items-end justify-end gap-2"
15
+ defaults={{ stock }}
16
+ {form}
17
+ hidden={{ productId: id }}
18
+ reset={false}
19
+ schema={StockSchema}
20
+ >
21
+ <!-- The column header says "Stock"; the label names the product for screen readers. -->
22
+ <NumberField name="stock" {form} inputmode="numeric">
23
+ <Span class="sr-only">Stock for {name}</Span>
24
+ </NumberField>
25
+ <Button {form}>Save</Button>
26
+ </Form>
@@ -0,0 +1,6 @@
1
+ import { z } from 'zod';
2
+
3
+ export const StockSchema = z.object({
4
+ productId: z.number().int().positive(),
5
+ stock: z.number().int().min(0, 'stock cannot be negative').max(100_000),
6
+ });
package/config.ts CHANGED
@@ -3,6 +3,7 @@ import type { EmailBrand } from '@zeyolabs/kit/utils/email';
3
3
  import { envStore } from '@zeyolabs/kit/utils/env';
4
4
 
5
5
  import type { ShopDb } from './db';
6
+ import type { BackInStockEmailData } from './emails/back-in-stock';
6
7
  import type { DispatchEmailData } from './emails/dispatch';
7
8
  import type { OrderEmailData } from './emails/order';
8
9
 
@@ -33,6 +34,11 @@ export type ShippingRules = {
33
34
  * (`@zeyolabs/shopping/server/mail`) is the package's own wording; a site can use it or write its own.
34
35
  */
35
36
  export type ShopMail = {
37
+ /**
38
+ * Tells a customer that a sold-out product they asked about is available again. Optional so shops
39
+ * that predate it keep working; without it the back-in-stock job sends nothing.
40
+ */
41
+ backInStock?: (alert: BackInStockEmailData) => Promise<void>;
36
42
  /** The shop's own heads-up that an order was paid. */
37
43
  newOrderAlert: (order: OrderEmailData) => Promise<void>;
38
44
  /** The customer's receipt. */
@@ -0,0 +1,36 @@
1
+ import type { EmailParams } from '@zeyolabs/kit/utils/email';
2
+
3
+ import { shopping } from '../config';
4
+ import { formatMoney } from '../money';
5
+
6
+ export type BackInStockEmailData = {
7
+ email: string;
8
+ pricePence: number;
9
+ productName: string;
10
+ slug: string;
11
+ };
12
+
13
+ /** The product page the customer lands on from the email. */
14
+ export const productUrl = (slug: string): string => `${shopping().siteUrl}/product/${slug}`;
15
+
16
+ /** Sent once to each customer who asked to be told when a sold-out product is back. */
17
+ export function backInStockEmail(data: BackInStockEmailData): EmailParams {
18
+ const { brand } = shopping();
19
+ const url = productUrl(data.slug);
20
+ return {
21
+ badge: 'Back in stock',
22
+ brand,
23
+ cta: { href: url, label: 'View product' },
24
+ eyebrow: 'Back in stock',
25
+ footnote:
26
+ 'You are getting this one email because you asked us to tell you. We will not send another about this product.',
27
+ heading: `${data.productName} is back`,
28
+ intro: [
29
+ `Good news: ${data.productName} (${formatMoney(data.pricePence)}) is back in stock at ${brand.name}.`,
30
+ 'Stock is limited, so if you want it, do not wait too long.',
31
+ `You can see it here: ${url}`,
32
+ ],
33
+ preheader: `${data.productName} is back in stock. Stock is limited.`,
34
+ sections: [],
35
+ };
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeyolabs/shopping",
3
- "version": "2026.11.7",
3
+ "version": "2026.11.9",
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",
@@ -0,0 +1,13 @@
1
+ import { Remote } from '@zeyolabs/kit/server/remote-functions';
2
+ import { FormResult } from '@zeyolabs/kit/utils/form';
3
+
4
+ import { StockSchema } from '../admin/stock.schema';
5
+ import { listStock, setStock } from '../server/admin-stock';
6
+
7
+ export const getStock = Remote.Query(() => listStock());
8
+
9
+ export const setStockForm = Remote.Form(StockSchema, async ({ productId, stock }) => {
10
+ await setStock(productId, stock);
11
+ await getStock().refresh();
12
+ return FormResult.ok('Stock saved.');
13
+ });
@@ -0,0 +1,33 @@
1
+ import { Error404 } from '@zeyolabs/kit/utils/errors';
2
+ import { asc, count, eq, sql } from 'drizzle-orm';
3
+
4
+ import { shopping } from '../config';
5
+ import { products, stockAlerts } from '../db/schema';
6
+
7
+ const getDb = () => shopping().db();
8
+
9
+ /** Every product with its stock and how many customers are waiting for it, sold-out first. */
10
+ export async function listStock() {
11
+ return getDb()
12
+ .select({
13
+ active: products.active,
14
+ id: products.id,
15
+ name: products.name,
16
+ sku: products.sku,
17
+ stock: products.stock,
18
+ variationLabel: products.variationLabel,
19
+ waiting: sql<number>`(select ${count()} from ${stockAlerts} where ${stockAlerts.productId} = ${products.id})`,
20
+ })
21
+ .from(products)
22
+ .orderBy(asc(sql`${products.stock} > 0`), asc(products.name), asc(products.id));
23
+ }
24
+
25
+ /** Sets a product's stock. Customers waiting on it are emailed by the stock-alerts cron, not here. */
26
+ export async function setStock(productId: number, stock: number) {
27
+ const updated = await getDb()
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.');
33
+ }
package/server/mail.ts CHANGED
@@ -3,6 +3,7 @@ import { renderEmail, renderEmailText } from '@zeyolabs/kit/utils/email';
3
3
  import type { ShopMail } from '../config';
4
4
 
5
5
  import { shopping } from '../config';
6
+ import { backInStockEmail } from '../emails/back-in-stock';
6
7
  import { dispatchEmail } from '../emails/dispatch';
7
8
  import { customerOrderEmail, shopOrderEmail } from '../emails/order';
8
9
  import { formatMoney } from '../money';
@@ -29,6 +30,17 @@ export function defaultShopMail({
29
30
  send: (message: Message) => Promise<void>;
30
31
  }): ShopMail {
31
32
  return {
33
+ backInStock: async (alert) => {
34
+ const { brand } = shopping();
35
+ const email = backInStockEmail(alert);
36
+ await send({
37
+ from: { email: brand.supportEmail, name: brand.name },
38
+ html: renderEmail(email),
39
+ subject: `${alert.productName} is back in stock`,
40
+ text: renderEmailText(email),
41
+ to: alert.email,
42
+ });
43
+ },
32
44
  newOrderAlert: async (order) => {
33
45
  const { brand } = shopping();
34
46
  const email = shopOrderEmail(order);
@@ -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
+ }
@@ -0,0 +1,104 @@
1
+ import { logger } from '@zeyolabs/kit/server/logger';
2
+ import { and, asc, eq, gt, isNull } from 'drizzle-orm';
3
+
4
+ import type { BackInStockEmailData } from '../emails/back-in-stock';
5
+
6
+ import { shopping } from '../config';
7
+ import { products, stockAlerts } from '../db/schema';
8
+
9
+ /** How many back-in-stock emails go out per run. The worker runs once a minute. */
10
+ export const BACK_IN_STOCK_BATCH = 50;
11
+
12
+ /** An SMTP error can carry the recipient's address, so logs get the failure's kind, not its text. */
13
+ const safeError = (what: string, error: unknown) =>
14
+ new Error(`${what}: ${error instanceof Error ? error.name : 'unknown error'}`);
15
+
16
+ export type PendingAlert = BackInStockEmailData & {
17
+ createdAt: number;
18
+ id: number;
19
+ productId: number;
20
+ };
21
+
22
+ /** Signups waiting on a product that has stock again, oldest first. Rows already marked notified are skipped. */
23
+ export async function pendingAlerts(limit = BACK_IN_STOCK_BATCH): Promise<PendingAlert[]> {
24
+ return shopping()
25
+ .db()
26
+ .select({
27
+ createdAt: stockAlerts.createdAt,
28
+ email: stockAlerts.email,
29
+ id: stockAlerts.id,
30
+ pricePence: products.pricePence,
31
+ productId: stockAlerts.productId,
32
+ productName: products.name,
33
+ slug: products.slug,
34
+ })
35
+ .from(stockAlerts)
36
+ .innerJoin(products, eq(products.id, stockAlerts.productId))
37
+ .where(and(gt(products.stock, 0), eq(products.active, true), isNull(stockAlerts.notifiedAt)))
38
+ .orderBy(asc(stockAlerts.id))
39
+ .limit(limit);
40
+ }
41
+
42
+ /**
43
+ * Emails each alert once. A signup is claimed (deleted) before the send, so two overlapping runs
44
+ * can't both email the same person: only the run whose delete took the row sends. If the send
45
+ * fails the signup is put back and tried again on the next run; one failure never stops the rest.
46
+ * The cost of claiming first: a Worker killed between the delete and the send loses that signup.
47
+ */
48
+ export async function deliverAlerts(
49
+ alerts: PendingAlert[],
50
+ send: (alert: BackInStockEmailData) => Promise<void>,
51
+ claim: (id: number) => Promise<boolean>,
52
+ restore: (alert: PendingAlert) => Promise<void>
53
+ ): Promise<{ failed: number; sent: number }> {
54
+ let sent = 0;
55
+ let failed = 0;
56
+ for (const alert of alerts) {
57
+ try {
58
+ if (!(await claim(alert.id))) continue; // another run already took it
59
+ } catch (error) {
60
+ failed++;
61
+ logger.error(error, { alertId: alert.id, op: 'backInStockClaim' });
62
+ continue;
63
+ }
64
+ try {
65
+ await send(alert);
66
+ sent++;
67
+ } catch (error) {
68
+ failed++;
69
+ logger.error(safeError('Back-in-stock send failed', error), {
70
+ alertId: alert.id,
71
+ op: 'backInStockEmail',
72
+ });
73
+ try {
74
+ await restore(alert);
75
+ } catch (restoreError) {
76
+ logger.error(restoreError, { alertId: alert.id, op: 'backInStockRestore' });
77
+ }
78
+ }
79
+ }
80
+ return { failed, sent };
81
+ }
82
+
83
+ /** One run of the cron: email up to a batch of waiting customers and delete their signups. */
84
+ export async function sendBackInStockBatch(limit = BACK_IN_STOCK_BATCH) {
85
+ const db = shopping().db();
86
+ const { backInStock } = shopping().mail;
87
+ // A shop without a back-in-stock email sends nothing and leaves the signups alone.
88
+ if (!backInStock) return { failed: 0, sent: 0 };
89
+ return deliverAlerts(
90
+ await pendingAlerts(limit),
91
+ ({ email, pricePence, productName, slug }) =>
92
+ backInStock({ email, pricePence, productName, slug }),
93
+ async (id) => {
94
+ const taken = await db
95
+ .delete(stockAlerts)
96
+ .where(eq(stockAlerts.id, id))
97
+ .returning({ id: stockAlerts.id });
98
+ return taken.length > 0;
99
+ },
100
+ async ({ createdAt, email, productId }) => {
101
+ await db.insert(stockAlerts).values({ createdAt, email, productId }).onConflictDoNothing();
102
+ }
103
+ );
104
+ }