@zeyolabs/shopping 2026.11.11 → 2026.11.13
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/README.md +24 -2
- package/basket/client.remote.ts +62 -0
- package/basket/cookies.server.ts +38 -0
- package/basket/library.ts +44 -0
- package/{pages → basket/pages}/Basket.svelte +31 -19
- package/basket/schema.ts +14 -0
- package/basket/service.server.ts +123 -0
- package/bundles/admin/BundleEditPage.svelte +24 -0
- package/bundles/admin/BundleForm.svelte +107 -0
- package/bundles/admin/BundlesPage.svelte +40 -0
- package/bundles/admin.remote.ts +30 -0
- package/bundles/client.remote.ts +29 -0
- package/bundles/loads.server.ts +6 -0
- package/bundles/pages/Bundle.svelte +145 -0
- package/bundles/schema.ts +82 -0
- package/bundles/service.server.ts +204 -0
- package/catalogue/admin/CategoriesPage.svelte +53 -0
- package/catalogue/admin/CategoryForm.svelte +50 -0
- package/catalogue/admin/ProductEditPage.svelte +25 -0
- package/catalogue/admin/ProductForm.svelte +249 -0
- package/catalogue/admin/ProductsPage.svelte +88 -0
- package/catalogue/admin.remote.ts +50 -0
- package/catalogue/admin.service.server.ts +239 -0
- package/catalogue/client.remote.ts +52 -0
- package/{components → catalogue/components}/ProductCard.svelte +8 -8
- package/catalogue/covers.server.ts +33 -0
- package/catalogue/library.ts +38 -0
- package/{routes/catalogue-loads.ts → catalogue/loads.server.ts} +11 -3
- package/{pages → catalogue/pages}/Category.svelte +5 -5
- package/{pages → catalogue/pages}/Product.svelte +37 -25
- package/catalogue/pages/Search.svelte +52 -0
- package/{pages → catalogue/pages}/Shop.svelte +2 -2
- package/catalogue/schema.ts +120 -0
- package/catalogue/service.server.ts +141 -0
- package/{routes/checkout-complete.ts → checkout/complete.server.ts} +6 -5
- package/checkout/manager.server.ts +127 -0
- package/{pages → checkout/pages}/CheckoutSuccess.svelte +2 -2
- package/{routes/stripe-webhook.ts → checkout/webhook.server.ts} +7 -7
- package/{royalmail.ts → clients/royalmail.ts} +30 -11
- package/clients/shop.server.ts +20 -0
- package/clients/stripe.ts +11 -0
- package/config.ts +23 -4
- package/context.ts +24 -0
- package/customers/client.remote.ts +19 -0
- package/customers/pages/Account.svelte +70 -0
- package/customers/service.server.ts +57 -0
- package/db/schema.ts +96 -0
- package/{admin → fulfilment/admin}/OrderPage.svelte +23 -16
- package/{admin → fulfilment/admin}/OrdersPage.svelte +7 -7
- package/{remote/admin-orders.remote.ts → fulfilment/admin.remote.ts} +11 -28
- package/fulfilment/dispatch-email.ts +66 -0
- package/fulfilment/invoice.server.ts +14 -0
- package/{routes/order-label.ts → fulfilment/label.server.ts} +3 -3
- package/fulfilment/library.ts +52 -0
- package/fulfilment/manager.server.ts +188 -0
- package/fulfilment/service.server.ts +155 -0
- package/{server/mail.ts → mail/default.ts} +9 -9
- package/{remote/order.remote.ts → orders/client.remote.ts} +10 -5
- package/orders/email.ts +111 -0
- package/orders/invoice.server.ts +19 -0
- package/orders/library.ts +26 -0
- package/orders/manager.server.ts +132 -0
- package/{pages → orders/pages}/Order.svelte +58 -16
- package/orders/service.server.ts +99 -0
- package/package.json +20 -32
- package/reviews/admin/ReviewsPage.svelte +95 -0
- package/reviews/admin.remote.ts +22 -0
- package/reviews/client.remote.ts +43 -0
- package/reviews/components/ReviewForm.svelte +32 -0
- package/reviews/components/Reviews.svelte +48 -0
- package/reviews/schema.ts +21 -0
- package/reviews/service.server.ts +122 -0
- package/shipping/library.ts +18 -0
- package/shipping/service.server.ts +88 -0
- package/{admin → stock/admin}/StockPage.svelte +1 -1
- package/{admin → stock/admin}/StockRow.svelte +2 -2
- package/stock/admin.remote.ts +19 -0
- package/{admin/stock.schema.ts → stock/schema.ts} +2 -1
- package/{server/stock-service.ts → stock/service.server.ts} +105 -58
- package/stock-alerts/email.ts +42 -0
- package/stock-alerts/job.server.ts +75 -0
- package/stock-alerts/service.server.ts +74 -0
- package/{components → ui}/PageTitle.svelte +5 -5
- package/ui/Stars.svelte +18 -0
- package/utils/batches.ts +21 -0
- package/utils/errors.ts +15 -0
- package/utils/form-input.ts +28 -0
- package/utils/images.ts +7 -0
- package/utils/money.ts +9 -0
- package/utils/schemas.ts +22 -0
- package/client.ts +0 -24
- package/emails/back-in-stock.ts +0 -36
- package/emails/dispatch.ts +0 -60
- package/emails/order.ts +0 -103
- package/images.ts +0 -2
- package/money.ts +0 -4
- package/order-links.ts +0 -11
- package/packing.ts +0 -49
- package/remote/admin-stock.remote.ts +0 -13
- package/remote/basket.remote.ts +0 -63
- package/remote/catalogue.remote.ts +0 -45
- package/server/admin-orders.ts +0 -304
- package/server/admin-stock.ts +0 -28
- package/server/basket.ts +0 -187
- package/server/catalogue.ts +0 -114
- package/server/checkout.ts +0 -41
- package/server/orders.ts +0 -182
- package/server/shipping.ts +0 -82
- package/server/stock-alert-service.ts +0 -30
- package/server/stock-alerts.ts +0 -105
- package/server/stripe.ts +0 -70
- package/shipping-rules.ts +0 -15
- /package/{admin → fulfilment}/filters.ts +0 -0
- /package/{admin/orders.schema.ts → fulfilment/schema.ts} +0 -0
- /package/{stock.ts → stock/library.ts} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
-
import { setStockForm } from '../
|
|
3
|
-
import { StockSchema } from '
|
|
2
|
+
import { setStockForm } from '../admin.remote';
|
|
3
|
+
import { StockSchema } from '../schema';
|
|
4
4
|
import { Form, NumberField } from '@zeyolabs/ui/form';
|
|
5
5
|
import Button from '@zeyolabs/ui/form/Button.svelte';
|
|
6
6
|
import Span from '@zeyolabs/ui/text/Span.svelte';
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Remote } from '@zeyolabs/kit/server/remote-functions';
|
|
2
|
+
import { FormResult } from '@zeyolabs/kit/utils/form';
|
|
3
|
+
|
|
4
|
+
import { shopping } from '../config';
|
|
5
|
+
import { StockSchema } from './schema';
|
|
6
|
+
import { StockService } from './service.server';
|
|
7
|
+
|
|
8
|
+
export const getStock = Remote.Query(() => {
|
|
9
|
+
const service = new StockService(shopping().db());
|
|
10
|
+
return service.list();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
/** Sets a product's stock in single units. Waiting customers are emailed by the stock-alerts job, not here. */
|
|
14
|
+
export const setStockForm = Remote.Form(StockSchema, async ({ productId, stock }) => {
|
|
15
|
+
const service = new StockService(shopping().db());
|
|
16
|
+
await service.setStock(productId, stock);
|
|
17
|
+
await getStock().refresh();
|
|
18
|
+
return FormResult.ok('Stock saved.');
|
|
19
|
+
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { Schema } from '@zeyolabs/kit/utils/schema';
|
|
1
2
|
import { z } from 'zod';
|
|
2
3
|
|
|
3
4
|
export const StockSchema = z.object({
|
|
4
|
-
productId:
|
|
5
|
+
productId: Schema.Id,
|
|
5
6
|
stock: z.number().int().min(0, 'stock cannot be negative').max(100_000),
|
|
6
7
|
});
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { Error400, Error404 } from '@zeyolabs/kit/utils/errors';
|
|
2
|
-
import { eq, inArray, sql } from 'drizzle-orm';
|
|
2
|
+
import { asc, count, eq, inArray, type SQL, sql } from 'drizzle-orm';
|
|
3
3
|
|
|
4
|
-
import type { ShopDb } from '../db';
|
|
4
|
+
import type { ShopDb } from '../db/index';
|
|
5
5
|
|
|
6
|
-
import { productComponents, products } from '../db/schema';
|
|
7
|
-
import {
|
|
6
|
+
import { productComponents, products, stockAlerts } from '../db/schema';
|
|
7
|
+
import { Batches } from '../utils/batches';
|
|
8
|
+
import { Stock, type StockComponent } from './library';
|
|
8
9
|
|
|
9
10
|
/** A combined product takes at most this many components (keeps every statement well under D1's limits). */
|
|
10
11
|
export const MAX_COMPONENTS = 10;
|
|
@@ -39,10 +40,12 @@ export class StockService {
|
|
|
39
40
|
async availableMany(ids: readonly number[]): Promise<Map<number, number>> {
|
|
40
41
|
const result = new Map<number, number>();
|
|
41
42
|
if (ids.length === 0) return result;
|
|
42
|
-
const rows = await
|
|
43
|
-
.
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
const rows = await Batches.rows(ids, (slice) =>
|
|
44
|
+
this.db
|
|
45
|
+
.select({ id: products.id, packSize: products.packSize, stock: products.stock })
|
|
46
|
+
.from(products)
|
|
47
|
+
.where(inArray(products.id, slice))
|
|
48
|
+
);
|
|
46
49
|
const components = await this.componentsOf(rows.map((r) => r.id));
|
|
47
50
|
for (const row of rows) {
|
|
48
51
|
const parts = components.get(row.id);
|
|
@@ -54,11 +57,82 @@ export class StockService {
|
|
|
54
57
|
return result;
|
|
55
58
|
}
|
|
56
59
|
|
|
60
|
+
/**
|
|
61
|
+
* Throws a 400 unless `components` is a valid set for `productId` (undefined for a product not
|
|
62
|
+
* yet saved): at most `MAX_COMPONENTS`, no repeats, not itself, no nested combined products, and
|
|
63
|
+
* a product that is already someone's component cannot become combined.
|
|
64
|
+
*/
|
|
65
|
+
async checkComponents(
|
|
66
|
+
productId: number | undefined,
|
|
67
|
+
components: readonly { componentId: number; quantity: number }[]
|
|
68
|
+
): Promise<void> {
|
|
69
|
+
if (components.length > MAX_COMPONENTS) {
|
|
70
|
+
throw Error400(`A combined product has at most ${MAX_COMPONENTS} components.`);
|
|
71
|
+
}
|
|
72
|
+
const ids = components.map((c) => c.componentId);
|
|
73
|
+
if (new Set(ids).size !== ids.length) throw Error400('A component can only be listed once.');
|
|
74
|
+
if (productId !== undefined && ids.includes(productId)) {
|
|
75
|
+
throw Error400('A product cannot contain itself.');
|
|
76
|
+
}
|
|
77
|
+
if (components.some((c) => !Number.isInteger(c.quantity) || c.quantity < 1)) {
|
|
78
|
+
throw Error400('Each component quantity must be a whole number of at least 1.');
|
|
79
|
+
}
|
|
80
|
+
if (ids.length > 0) {
|
|
81
|
+
const nested = await this.componentsOf(ids);
|
|
82
|
+
if (nested.size > 0) throw Error400('A component cannot itself be a combined product.');
|
|
83
|
+
}
|
|
84
|
+
if (components.length > 0 && productId !== undefined) {
|
|
85
|
+
const usedAsComponent = await this.db
|
|
86
|
+
.select({ productId: productComponents.productId })
|
|
87
|
+
.from(productComponents)
|
|
88
|
+
.where(eq(productComponents.componentId, productId))
|
|
89
|
+
.limit(1);
|
|
90
|
+
if (usedAsComponent.length > 0) {
|
|
91
|
+
throw Error400('A product that is a component of another set cannot be combined itself.');
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
57
96
|
/** The components of a combined product, or an empty list for a plain one. */
|
|
58
97
|
async components(productId: number): Promise<ComponentRow[]> {
|
|
59
98
|
return (await this.componentsOf([productId])).get(productId) ?? [];
|
|
60
99
|
}
|
|
61
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Statements that replace a product's components, for the caller's `db.batch`. `productId` may
|
|
103
|
+
* be a SQL expression, for a product inserted earlier in the same batch. Check them first with
|
|
104
|
+
* `checkComponents`.
|
|
105
|
+
*/
|
|
106
|
+
componentStatements(
|
|
107
|
+
productId: number | SQL,
|
|
108
|
+
components: readonly { componentId: number; quantity: number }[]
|
|
109
|
+
) {
|
|
110
|
+
return [
|
|
111
|
+
this.db.delete(productComponents).where(eq(productComponents.productId, productId)),
|
|
112
|
+
...components.map((c) =>
|
|
113
|
+
this.db
|
|
114
|
+
.insert(productComponents)
|
|
115
|
+
.values({ componentId: c.componentId, productId, quantity: c.quantity })
|
|
116
|
+
),
|
|
117
|
+
];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Every product with its stock and how many customers are waiting for it, sold-out first. */
|
|
121
|
+
async list() {
|
|
122
|
+
return this.db
|
|
123
|
+
.select({
|
|
124
|
+
active: products.active,
|
|
125
|
+
id: products.id,
|
|
126
|
+
name: products.name,
|
|
127
|
+
sku: products.sku,
|
|
128
|
+
stock: products.stock,
|
|
129
|
+
variationLabel: products.variationLabel,
|
|
130
|
+
waiting: sql<number>`(select ${count()} from ${stockAlerts} where ${stockAlerts.productId} = ${products.id})`,
|
|
131
|
+
})
|
|
132
|
+
.from(products)
|
|
133
|
+
.orderBy(asc(sql`${products.stock} > 0`), asc(products.name), asc(products.id));
|
|
134
|
+
}
|
|
135
|
+
|
|
62
136
|
/**
|
|
63
137
|
* The statements that take a paid order's stock: each line's product (or, for a combined product,
|
|
64
138
|
* its components) loses stock, floored at 0, and the product's `sold` goes up. They are returned
|
|
@@ -67,12 +141,12 @@ export class StockService {
|
|
|
67
141
|
async paidStatements(lines: readonly PaidLine[]) {
|
|
68
142
|
const ids = lines.map((l) => l.productId);
|
|
69
143
|
const [rows, components] = await Promise.all([
|
|
70
|
-
ids
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
144
|
+
Batches.rows(ids, (slice) =>
|
|
145
|
+
this.db
|
|
146
|
+
.select({ id: products.id, packSize: products.packSize })
|
|
147
|
+
.from(products)
|
|
148
|
+
.where(inArray(products.id, slice))
|
|
149
|
+
),
|
|
76
150
|
this.componentsOf(ids),
|
|
77
151
|
]);
|
|
78
152
|
const packSize = new Map(rows.map((r) => [r.id, r.packSize]));
|
|
@@ -100,43 +174,14 @@ export class StockService {
|
|
|
100
174
|
return statements;
|
|
101
175
|
}
|
|
102
176
|
|
|
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
|
-
*/
|
|
177
|
+
/** Replaces a combined product's components (checked). An empty list makes it a plain product. */
|
|
107
178
|
async setComponents(
|
|
108
179
|
productId: number,
|
|
109
180
|
components: readonly { componentId: number; quantity: number }[]
|
|
110
181
|
) {
|
|
111
|
-
|
|
112
|
-
|
|
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
|
-
]);
|
|
182
|
+
await this.checkComponents(productId, components);
|
|
183
|
+
const [first, ...rest] = this.componentStatements(productId, components);
|
|
184
|
+
await this.db.batch([first, ...rest]);
|
|
140
185
|
}
|
|
141
186
|
|
|
142
187
|
/**
|
|
@@ -159,17 +204,19 @@ export class StockService {
|
|
|
159
204
|
private async componentsOf(ids: readonly number[]): Promise<Map<number, ComponentRow[]>> {
|
|
160
205
|
const map = new Map<number, ComponentRow[]>();
|
|
161
206
|
if (ids.length === 0) return map;
|
|
162
|
-
const rows = await
|
|
163
|
-
.
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
207
|
+
const rows = await Batches.rows(ids, (slice) =>
|
|
208
|
+
this.db
|
|
209
|
+
.select({
|
|
210
|
+
componentId: productComponents.componentId,
|
|
211
|
+
packSize: products.packSize,
|
|
212
|
+
productId: productComponents.productId,
|
|
213
|
+
quantity: productComponents.quantity,
|
|
214
|
+
stock: products.stock,
|
|
215
|
+
})
|
|
216
|
+
.from(productComponents)
|
|
217
|
+
.innerJoin(products, eq(products.id, productComponents.componentId))
|
|
218
|
+
.where(inArray(productComponents.productId, slice))
|
|
219
|
+
);
|
|
173
220
|
for (const row of rows) {
|
|
174
221
|
const list = map.get(row.productId) ?? [];
|
|
175
222
|
list.push({
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { EmailParams } from '@zeyolabs/kit/utils/email';
|
|
2
|
+
|
|
3
|
+
import { shopping } from '../config';
|
|
4
|
+
import { Money } from '../utils/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
|
+
const productUrl = (slug: string): string => `${shopping().siteUrl}/product/${slug}`;
|
|
15
|
+
|
|
16
|
+
/** The back-in-stock email, as kit email params. */
|
|
17
|
+
export const BackInStockEmail = {
|
|
18
|
+
/** The product page link in the email. */
|
|
19
|
+
productUrl,
|
|
20
|
+
|
|
21
|
+
/** Sent once to each customer who asked to be told when a sold-out product is back. */
|
|
22
|
+
build(data: BackInStockEmailData): EmailParams {
|
|
23
|
+
const { brand } = shopping();
|
|
24
|
+
const url = productUrl(data.slug);
|
|
25
|
+
return {
|
|
26
|
+
badge: 'Back in stock',
|
|
27
|
+
brand,
|
|
28
|
+
cta: { href: url, label: 'View product' },
|
|
29
|
+
eyebrow: 'Back in stock',
|
|
30
|
+
footnote:
|
|
31
|
+
'You are getting this one email because you asked us to tell you. We will not send another about this product.',
|
|
32
|
+
heading: `${data.productName} is back`,
|
|
33
|
+
intro: [
|
|
34
|
+
`Good news: ${data.productName} (${Money.format(data.pricePence)}) is back in stock at ${brand.name}.`,
|
|
35
|
+
'Stock is limited, so if you want it, do not wait too long.',
|
|
36
|
+
`You can see it here: ${url}`,
|
|
37
|
+
],
|
|
38
|
+
preheader: `${data.productName} is back in stock. Stock is limited.`,
|
|
39
|
+
sections: [],
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { logger } from '@zeyolabs/kit/server/logger';
|
|
2
|
+
|
|
3
|
+
import type { BackInStockEmailData } from './email';
|
|
4
|
+
|
|
5
|
+
import { shopping } from '../config';
|
|
6
|
+
import { type PendingAlert, StockAlertService } from './service.server';
|
|
7
|
+
|
|
8
|
+
type Result = { failed: number; sent: number };
|
|
9
|
+
|
|
10
|
+
/** How many emails go out per run. */
|
|
11
|
+
const BATCH = 50;
|
|
12
|
+
|
|
13
|
+
/** An SMTP error can carry the recipient's address, so logs get the failure's kind, not its text. */
|
|
14
|
+
const safeError = (what: string, error: unknown) =>
|
|
15
|
+
new Error(`${what}: ${error instanceof Error ? error.name : 'unknown error'}`);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Emails each alert once. A signup is claimed (deleted) before the send, so two overlapping runs
|
|
19
|
+
* can't both email the same person: only the run whose delete took the row sends. If the send
|
|
20
|
+
* fails the signup is put back and tried again next run; one failure never stops the rest. The
|
|
21
|
+
* cost of claiming first: a Worker killed between the delete and the send loses that signup.
|
|
22
|
+
*/
|
|
23
|
+
async function deliver(
|
|
24
|
+
alerts: PendingAlert[],
|
|
25
|
+
send: (alert: BackInStockEmailData) => Promise<void>,
|
|
26
|
+
claim: (id: number) => Promise<boolean>,
|
|
27
|
+
restore: (alert: PendingAlert) => Promise<void>
|
|
28
|
+
): Promise<Result> {
|
|
29
|
+
let sent = 0;
|
|
30
|
+
let failed = 0;
|
|
31
|
+
for (const alert of alerts) {
|
|
32
|
+
try {
|
|
33
|
+
if (!(await claim(alert.id))) continue; // another run already took it
|
|
34
|
+
} catch (error) {
|
|
35
|
+
failed++;
|
|
36
|
+
logger.error(error, { alertId: alert.id, op: 'backInStockClaim' });
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
await send(alert);
|
|
41
|
+
sent++;
|
|
42
|
+
} catch (error) {
|
|
43
|
+
failed++;
|
|
44
|
+
logger.error(safeError('Back-in-stock send failed', error), {
|
|
45
|
+
alertId: alert.id,
|
|
46
|
+
op: 'backInStockEmail',
|
|
47
|
+
});
|
|
48
|
+
try {
|
|
49
|
+
await restore(alert);
|
|
50
|
+
} catch (restoreError) {
|
|
51
|
+
logger.error(restoreError, { alertId: alert.id, op: 'backInStockRestore' });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return { failed, sent };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** One run: email up to a batch of waiting customers and delete their signups. */
|
|
59
|
+
async function run(limit = BATCH): Promise<Result> {
|
|
60
|
+
const { db, mail } = shopping();
|
|
61
|
+
const { backInStock } = mail;
|
|
62
|
+
// A shop without a back-in-stock email sends nothing and leaves the signups alone.
|
|
63
|
+
if (!backInStock) return { failed: 0, sent: 0 };
|
|
64
|
+
const service = new StockAlertService(db());
|
|
65
|
+
return deliver(
|
|
66
|
+
await service.pending(limit),
|
|
67
|
+
({ email, pricePence, productName, slug }) =>
|
|
68
|
+
backInStock({ email, pricePence, productName, slug }),
|
|
69
|
+
(id) => service.claim(id),
|
|
70
|
+
(alert) => service.restore(alert)
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The back-in-stock cron. The app's worker calls `BackInStockJob.run()` once a minute. */
|
|
75
|
+
export const BackInStockJob = { BATCH, deliver, run };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { and, asc, eq, isNull } from 'drizzle-orm';
|
|
2
|
+
|
|
3
|
+
import type { ShopDb } from '../db/index';
|
|
4
|
+
import type { BackInStockEmailData } from './email';
|
|
5
|
+
|
|
6
|
+
import { products, stockAlerts } from '../db/schema';
|
|
7
|
+
import { sellableSql } from '../stock/service.server';
|
|
8
|
+
|
|
9
|
+
export type PendingAlert = BackInStockEmailData & {
|
|
10
|
+
createdAt: number;
|
|
11
|
+
id: number;
|
|
12
|
+
productId: number;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Data access for "tell me when it's back" signups. It checks no permissions and sends nothing
|
|
17
|
+
* (the back-in-stock job does the sending).
|
|
18
|
+
*/
|
|
19
|
+
export class StockAlertService {
|
|
20
|
+
constructor(private readonly db: ShopDb) {}
|
|
21
|
+
|
|
22
|
+
/** Takes a signup before its email is sent. False when another run already took it. */
|
|
23
|
+
async claim(id: number): Promise<boolean> {
|
|
24
|
+
const taken = await this.db
|
|
25
|
+
.delete(stockAlerts)
|
|
26
|
+
.where(eq(stockAlerts.id, id))
|
|
27
|
+
.returning({ id: stockAlerts.id });
|
|
28
|
+
return taken.length > 0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Signups waiting on a product that is sellable again (a whole pack, or every component of a
|
|
33
|
+
* set), oldest first. Rows already marked notified are skipped.
|
|
34
|
+
*/
|
|
35
|
+
async pending(limit: number): Promise<PendingAlert[]> {
|
|
36
|
+
return this.db
|
|
37
|
+
.select({
|
|
38
|
+
createdAt: stockAlerts.createdAt,
|
|
39
|
+
email: stockAlerts.email,
|
|
40
|
+
id: stockAlerts.id,
|
|
41
|
+
pricePence: products.pricePence,
|
|
42
|
+
productId: stockAlerts.productId,
|
|
43
|
+
productName: products.name,
|
|
44
|
+
slug: products.slug,
|
|
45
|
+
})
|
|
46
|
+
.from(stockAlerts)
|
|
47
|
+
.innerJoin(products, eq(products.id, stockAlerts.productId))
|
|
48
|
+
.where(and(sellableSql, eq(products.active, true), isNull(stockAlerts.notifiedAt)))
|
|
49
|
+
.orderBy(asc(stockAlerts.id))
|
|
50
|
+
.limit(limit);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Puts a claimed signup back after a failed send, so the next run tries again. */
|
|
54
|
+
async restore({ createdAt, email, productId }: PendingAlert): Promise<void> {
|
|
55
|
+
await this.db.insert(stockAlerts).values({ createdAt, email, productId }).onConflictDoNothing();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Adds a signup for an active product and returns the product's name, or null when there is no
|
|
60
|
+
* such active product. Signing up twice is fine and is not reported, so a caller cannot tell
|
|
61
|
+
* whether an address was already on the list.
|
|
62
|
+
*/
|
|
63
|
+
async subscribe(email: string, productId: number): Promise<null | { productName: string }> {
|
|
64
|
+
const product = await this.db.query.products.findFirst({
|
|
65
|
+
where: and(eq(products.id, productId), eq(products.active, true)),
|
|
66
|
+
});
|
|
67
|
+
if (!product) return null;
|
|
68
|
+
await this.db
|
|
69
|
+
.insert(stockAlerts)
|
|
70
|
+
.values({ createdAt: Date.now(), email: email.toLowerCase(), productId })
|
|
71
|
+
.onConflictDoNothing();
|
|
72
|
+
return { productName: product.name };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import { page } from '$app/state';
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { shopContext } from '../context';
|
|
5
5
|
|
|
6
6
|
let { description, title }: { description: string; title: string } = $props();
|
|
7
7
|
|
|
8
|
-
const
|
|
8
|
+
const context = shopContext();
|
|
9
9
|
// Canonical ignores the query string, so `?show=N` deep links don't count as duplicate pages.
|
|
10
|
-
const canonical = $derived(`${
|
|
10
|
+
const canonical = $derived(`${context.siteUrl}${page.url.pathname}`);
|
|
11
11
|
</script>
|
|
12
12
|
|
|
13
13
|
<svelte:head>
|
|
14
|
-
<title>{title} | {
|
|
14
|
+
<title>{title} | {context.siteName}</title>
|
|
15
15
|
<meta name="description" content={description} />
|
|
16
16
|
<link href={canonical} rel="canonical" />
|
|
17
|
-
<meta content={
|
|
17
|
+
<meta content={context.siteName} property="og:site_name" />
|
|
18
18
|
<meta content={title} property="og:title" />
|
|
19
19
|
<meta content={description} property="og:description" />
|
|
20
20
|
<meta content={canonical} property="og:url" />
|
package/ui/Stars.svelte
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
/** A read-only star rating, e.g. 4.5 shows as four and a half of five stars. */
|
|
3
|
+
let { rating, size = 'text-base' }: { rating: number; size?: string } = $props();
|
|
4
|
+
const pct = $derived(`${Math.max(0, Math.min(5, rating)) * 20}%`);
|
|
5
|
+
</script>
|
|
6
|
+
|
|
7
|
+
<span
|
|
8
|
+
class="relative inline-block leading-none {size}"
|
|
9
|
+
aria-label="{rating} out of 5 stars"
|
|
10
|
+
role="img"
|
|
11
|
+
>
|
|
12
|
+
<span class="text-[var(--bd)]" aria-hidden="true">★★★★★</span>
|
|
13
|
+
<span
|
|
14
|
+
class="absolute inset-0 overflow-hidden whitespace-nowrap text-[var(--primary-strong)]"
|
|
15
|
+
style:width={pct}
|
|
16
|
+
aria-hidden="true">★★★★★</span
|
|
17
|
+
>
|
|
18
|
+
</span>
|
package/utils/batches.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** D1 allows at most 100 bound parameters per statement; id lists are split below that. */
|
|
2
|
+
const SIZE = 90;
|
|
3
|
+
|
|
4
|
+
/** Splitting work over long id lists so each statement stays under D1's parameter limit. */
|
|
5
|
+
export const Batches = {
|
|
6
|
+
SIZE,
|
|
7
|
+
|
|
8
|
+
/** `list` in slices of at most `size`. */
|
|
9
|
+
chunks<T>(list: readonly T[], size = SIZE): T[][] {
|
|
10
|
+
const out: T[][] = [];
|
|
11
|
+
for (let i = 0; i < list.length; i += size) out.push(list.slice(i, i + size));
|
|
12
|
+
return out;
|
|
13
|
+
},
|
|
14
|
+
|
|
15
|
+
/** Runs `query` once per slice of `ids` (one after another) and joins the rows. */
|
|
16
|
+
async rows<T, R>(ids: readonly T[], query: (slice: T[]) => Promise<R[]>): Promise<R[]> {
|
|
17
|
+
const out: R[] = [];
|
|
18
|
+
for (const slice of Batches.chunks(ids)) out.push(...(await query(slice)));
|
|
19
|
+
return out;
|
|
20
|
+
},
|
|
21
|
+
};
|
package/utils/errors.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Client-side: what to tell the customer when a remote command throws. Pure. */
|
|
2
|
+
export const ErrorMessage = {
|
|
3
|
+
/**
|
|
4
|
+
* The server's message (a SvelteKit `HttpError`'s `body.message`, or an `Error`'s message), or
|
|
5
|
+
* `fallback` when there is none.
|
|
6
|
+
*/
|
|
7
|
+
from(error: unknown, fallback: string): string {
|
|
8
|
+
if (typeof error === 'object' && error !== null) {
|
|
9
|
+
const body = (error as { body?: { message?: unknown } }).body;
|
|
10
|
+
if (typeof body?.message === 'string' && body.message) return body.message;
|
|
11
|
+
if (error instanceof Error && error.message) return error.message;
|
|
12
|
+
}
|
|
13
|
+
return fallback;
|
|
14
|
+
},
|
|
15
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Turning admin form text into stored values and back. */
|
|
2
|
+
export const FormInput = {
|
|
3
|
+
/** "12.5" or "£12.50" to 1250 pence; null for blank; NaN when it is not a price. */
|
|
4
|
+
parsePounds(value: string): null | number {
|
|
5
|
+
const clean = value.replace(/[£,\s]/g, '');
|
|
6
|
+
if (clean === '') return null;
|
|
7
|
+
if (!/^\d+(\.\d{1,2})?$/.test(clean)) return Number.NaN;
|
|
8
|
+
const [whole, frac = ''] = clean.split('.');
|
|
9
|
+
return Number(whole) * 100 + Number(frac.padEnd(2, '0'));
|
|
10
|
+
},
|
|
11
|
+
|
|
12
|
+
/** 1250 pence to "12.50" for an input. */
|
|
13
|
+
penceToPounds(pence: null | number | undefined): string {
|
|
14
|
+
if (pence === null || pence === undefined) return '';
|
|
15
|
+
return `${Math.floor(pence / 100)}.${String(pence % 100).padStart(2, '0')}`;
|
|
16
|
+
},
|
|
17
|
+
|
|
18
|
+
/** A title to a URL slug: "Green Tea 100g" to "green-tea-100g". */
|
|
19
|
+
slugify(text: string): string {
|
|
20
|
+
return text
|
|
21
|
+
.toLowerCase()
|
|
22
|
+
.normalize('NFKD')
|
|
23
|
+
.replace(/[̀-ͯ]/g, '')
|
|
24
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
25
|
+
.replace(/^-+|-+$/g, '')
|
|
26
|
+
.slice(0, 120);
|
|
27
|
+
},
|
|
28
|
+
};
|
package/utils/images.ts
ADDED
package/utils/money.ts
ADDED
package/utils/schemas.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Zod pieces the shop's schemas share. Generic ones come from kit's `Schema` (`Schema.Slug`,
|
|
5
|
+
* `Schema.Id`); these are the shop's own.
|
|
6
|
+
*/
|
|
7
|
+
export const ShopSchema = {
|
|
8
|
+
/** A slug from a URL, for lookups. Not normalised: legacy slugs must match as they are. */
|
|
9
|
+
SlugParam: z.string().min(1).max(200),
|
|
10
|
+
|
|
11
|
+
/** A public order number, e.g. `PL-ABC234`. */
|
|
12
|
+
OrderNumber: z.string().min(1).max(40),
|
|
13
|
+
|
|
14
|
+
/** The secret in an order link (`/order/<number>/<token>`). */
|
|
15
|
+
OrderToken: z.string().min(1).max(200),
|
|
16
|
+
|
|
17
|
+
/** Integer pence, up to £100,000. */
|
|
18
|
+
Pence: z.number().int().min(0).max(10_000_000),
|
|
19
|
+
|
|
20
|
+
/** A text field a form may leave out: missing becomes ''. */
|
|
21
|
+
FormText: z.string().default(''),
|
|
22
|
+
};
|
package/client.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { getContext, setContext } from 'svelte';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* What pages need in the browser. The server config in `config.ts` never reaches the client, so
|
|
5
|
-
* the app hands these over once from its root layout with `setShoppingClient`.
|
|
6
|
-
*/
|
|
7
|
-
export type ShoppingClient = {
|
|
8
|
-
imageBaseUrl: string;
|
|
9
|
-
siteName: string;
|
|
10
|
-
siteUrl: string;
|
|
11
|
-
supportEmail: string;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
const KEY = Symbol('@zeyolabs/shopping-client');
|
|
15
|
-
|
|
16
|
-
export function setShoppingClient(client: ShoppingClient): void {
|
|
17
|
-
setContext(KEY, client);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export function shoppingClient(): ShoppingClient {
|
|
21
|
-
const client = getContext<ShoppingClient | undefined>(KEY);
|
|
22
|
-
if (!client) throw new Error('@zeyolabs/shopping: call setShoppingClient() in the root layout');
|
|
23
|
-
return client;
|
|
24
|
-
}
|
package/emails/back-in-stock.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
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
|
-
}
|