@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.
Files changed (115) hide show
  1. package/README.md +24 -2
  2. package/basket/client.remote.ts +62 -0
  3. package/basket/cookies.server.ts +38 -0
  4. package/basket/library.ts +44 -0
  5. package/{pages → basket/pages}/Basket.svelte +31 -19
  6. package/basket/schema.ts +14 -0
  7. package/basket/service.server.ts +123 -0
  8. package/bundles/admin/BundleEditPage.svelte +24 -0
  9. package/bundles/admin/BundleForm.svelte +107 -0
  10. package/bundles/admin/BundlesPage.svelte +40 -0
  11. package/bundles/admin.remote.ts +30 -0
  12. package/bundles/client.remote.ts +29 -0
  13. package/bundles/loads.server.ts +6 -0
  14. package/bundles/pages/Bundle.svelte +145 -0
  15. package/bundles/schema.ts +82 -0
  16. package/bundles/service.server.ts +204 -0
  17. package/catalogue/admin/CategoriesPage.svelte +53 -0
  18. package/catalogue/admin/CategoryForm.svelte +50 -0
  19. package/catalogue/admin/ProductEditPage.svelte +25 -0
  20. package/catalogue/admin/ProductForm.svelte +249 -0
  21. package/catalogue/admin/ProductsPage.svelte +88 -0
  22. package/catalogue/admin.remote.ts +50 -0
  23. package/catalogue/admin.service.server.ts +239 -0
  24. package/catalogue/client.remote.ts +52 -0
  25. package/{components → catalogue/components}/ProductCard.svelte +8 -8
  26. package/catalogue/covers.server.ts +33 -0
  27. package/catalogue/library.ts +38 -0
  28. package/{routes/catalogue-loads.ts → catalogue/loads.server.ts} +11 -3
  29. package/{pages → catalogue/pages}/Category.svelte +5 -5
  30. package/{pages → catalogue/pages}/Product.svelte +37 -25
  31. package/catalogue/pages/Search.svelte +52 -0
  32. package/{pages → catalogue/pages}/Shop.svelte +2 -2
  33. package/catalogue/schema.ts +120 -0
  34. package/catalogue/service.server.ts +141 -0
  35. package/{routes/checkout-complete.ts → checkout/complete.server.ts} +6 -5
  36. package/checkout/manager.server.ts +127 -0
  37. package/{pages → checkout/pages}/CheckoutSuccess.svelte +2 -2
  38. package/{routes/stripe-webhook.ts → checkout/webhook.server.ts} +7 -7
  39. package/{royalmail.ts → clients/royalmail.ts} +30 -11
  40. package/clients/shop.server.ts +20 -0
  41. package/clients/stripe.ts +11 -0
  42. package/config.ts +23 -4
  43. package/context.ts +24 -0
  44. package/customers/client.remote.ts +19 -0
  45. package/customers/pages/Account.svelte +70 -0
  46. package/customers/service.server.ts +57 -0
  47. package/db/schema.ts +96 -0
  48. package/{admin → fulfilment/admin}/OrderPage.svelte +23 -16
  49. package/{admin → fulfilment/admin}/OrdersPage.svelte +7 -7
  50. package/{remote/admin-orders.remote.ts → fulfilment/admin.remote.ts} +11 -28
  51. package/fulfilment/dispatch-email.ts +66 -0
  52. package/fulfilment/invoice.server.ts +14 -0
  53. package/{routes/order-label.ts → fulfilment/label.server.ts} +3 -3
  54. package/fulfilment/library.ts +52 -0
  55. package/fulfilment/manager.server.ts +188 -0
  56. package/fulfilment/service.server.ts +155 -0
  57. package/{server/mail.ts → mail/default.ts} +9 -9
  58. package/{remote/order.remote.ts → orders/client.remote.ts} +10 -5
  59. package/orders/email.ts +111 -0
  60. package/orders/invoice.server.ts +19 -0
  61. package/orders/library.ts +26 -0
  62. package/orders/manager.server.ts +132 -0
  63. package/{pages → orders/pages}/Order.svelte +58 -16
  64. package/orders/service.server.ts +99 -0
  65. package/package.json +20 -32
  66. package/reviews/admin/ReviewsPage.svelte +95 -0
  67. package/reviews/admin.remote.ts +22 -0
  68. package/reviews/client.remote.ts +43 -0
  69. package/reviews/components/ReviewForm.svelte +32 -0
  70. package/reviews/components/Reviews.svelte +48 -0
  71. package/reviews/schema.ts +21 -0
  72. package/reviews/service.server.ts +122 -0
  73. package/shipping/library.ts +18 -0
  74. package/shipping/service.server.ts +88 -0
  75. package/{admin → stock/admin}/StockPage.svelte +1 -1
  76. package/{admin → stock/admin}/StockRow.svelte +2 -2
  77. package/stock/admin.remote.ts +19 -0
  78. package/{admin/stock.schema.ts → stock/schema.ts} +2 -1
  79. package/{server/stock-service.ts → stock/service.server.ts} +105 -58
  80. package/stock-alerts/email.ts +42 -0
  81. package/stock-alerts/job.server.ts +75 -0
  82. package/stock-alerts/service.server.ts +74 -0
  83. package/{components → ui}/PageTitle.svelte +5 -5
  84. package/ui/Stars.svelte +18 -0
  85. package/utils/batches.ts +21 -0
  86. package/utils/errors.ts +15 -0
  87. package/utils/form-input.ts +28 -0
  88. package/utils/images.ts +7 -0
  89. package/utils/money.ts +9 -0
  90. package/utils/schemas.ts +22 -0
  91. package/client.ts +0 -24
  92. package/emails/back-in-stock.ts +0 -36
  93. package/emails/dispatch.ts +0 -60
  94. package/emails/order.ts +0 -103
  95. package/images.ts +0 -2
  96. package/money.ts +0 -4
  97. package/order-links.ts +0 -11
  98. package/packing.ts +0 -49
  99. package/remote/admin-stock.remote.ts +0 -13
  100. package/remote/basket.remote.ts +0 -63
  101. package/remote/catalogue.remote.ts +0 -45
  102. package/server/admin-orders.ts +0 -304
  103. package/server/admin-stock.ts +0 -28
  104. package/server/basket.ts +0 -187
  105. package/server/catalogue.ts +0 -114
  106. package/server/checkout.ts +0 -41
  107. package/server/orders.ts +0 -182
  108. package/server/shipping.ts +0 -82
  109. package/server/stock-alert-service.ts +0 -30
  110. package/server/stock-alerts.ts +0 -105
  111. package/server/stripe.ts +0 -70
  112. package/shipping-rules.ts +0 -15
  113. /package/{admin → fulfilment}/filters.ts +0 -0
  114. /package/{admin/orders.schema.ts → fulfilment/schema.ts} +0 -0
  115. /package/{stock.ts → stock/library.ts} +0 -0
@@ -0,0 +1,249 @@
1
+ <script lang="ts">
2
+ import { goto } from '$app/navigation';
3
+ import { resolve } from '$app/paths';
4
+ import type { getAdminProduct, getProductOptions } from '../admin.remote';
5
+ import { saveProductForm } from '../admin.remote';
6
+ import { shopContext } from '../../context';
7
+ import { Images } from '../../utils/images';
8
+ import { FormInput } from '../../utils/form-input';
9
+ import { ProductFormSchema } from '../schema';
10
+ import { CheckboxField, Form, MessageField, NumberField, TextField } from '@zeyolabs/ui/form';
11
+ import Button from '@zeyolabs/ui/form/Button.svelte';
12
+
13
+ type Product = Awaited<ReturnType<typeof getAdminProduct>>;
14
+ type Options = Awaited<ReturnType<typeof getProductOptions>>;
15
+
16
+ let { options, product }: { options: Options; product: null | Product } = $props();
17
+
18
+ const context = shopContext();
19
+ // The page re-creates this component per product ({#key}), so reading the prop once is right.
20
+ // svelte-ignore state_referenced_locally
21
+ const p = product;
22
+ const form = saveProductForm.for(p?.id ?? 'new');
23
+ const { components, images } = form.fields;
24
+
25
+ const imageRows = $derived(images.value() ?? []);
26
+ const componentRows = $derived(components.value() ?? []);
27
+ const slug = $derived(form.fields.slug.value() ?? '');
28
+
29
+ /** Swaps row `i` with the one above it. */
30
+ function up<T>(rows: T[], i: number): T[] {
31
+ if (i === 0) return rows;
32
+ const next = [...rows];
33
+ [next[i - 1], next[i]] = [next[i], next[i - 1]];
34
+ return next;
35
+ }
36
+
37
+ const input = 'w-full rounded-md border border-[var(--line)] bg-white px-3 py-1.5';
38
+ const section = 'grid gap-4 rounded-xl border border-[var(--line)] bg-white p-5';
39
+ </script>
40
+
41
+ <Form
42
+ class="grid max-w-3xl gap-6"
43
+ defaults={{
44
+ active: p?.active ?? false,
45
+ categoryIds: p?.categoryIds.map(String) ?? [],
46
+ comparePrice: FormInput.penceToPounds(p?.comparePricePence),
47
+ components: p?.components ?? [],
48
+ description: p?.description ?? '',
49
+ images: p?.images ?? [],
50
+ lowStockThreshold: p?.lowStockThreshold ?? undefined,
51
+ massGrams: p?.massGrams ?? 0,
52
+ maxPerOrder: p?.maxPerOrder ?? 10,
53
+ name: p?.name ?? '',
54
+ packSize: p?.packSize ?? 1,
55
+ price: FormInput.penceToPounds(p?.pricePence),
56
+ shortDescription: p?.shortDescription ?? '',
57
+ sku: p?.sku ?? '',
58
+ slug: p?.slug ?? '',
59
+ sortOrder: p?.sortOrder ?? 0,
60
+ variationGroup: p?.variationGroup ?? '',
61
+ variationLabel: p?.variationLabel ?? '',
62
+ }}
63
+ {form}
64
+ hidden={{ id: p?.id }}
65
+ onSuccess={(data) => {
66
+ if (!p) goto(resolve('/products/[id]', { id: String(data.id) }));
67
+ }}
68
+ reset={false}
69
+ schema={ProductFormSchema}
70
+ >
71
+ <section class={section}>
72
+ <h2 class="font-semibold">Basics</h2>
73
+ <TextField name="name" {form}>Name</TextField>
74
+ <div class="grid gap-4 sm:grid-cols-2">
75
+ <TextField name="slug" {form} optional placeholder="made from the name">Slug (URL)</TextField>
76
+ <TextField name="sku" {form}>SKU</TextField>
77
+ <TextField name="price" {form} inputmode="decimal">Price (£)</TextField>
78
+ <TextField name="comparePrice" {form} inputmode="decimal" optional>Was price (£)</TextField>
79
+ </div>
80
+ <CheckboxField name="active" {form}>On sale in the shop</CheckboxField>
81
+ {#if p && slug && p.slug !== slug}
82
+ <p class="text-sm text-[var(--ink-muted)]">
83
+ The old URL /product/{p.slug} will redirect to the new one.
84
+ </p>
85
+ {/if}
86
+ </section>
87
+
88
+ <section class={section}>
89
+ <h2 class="font-semibold">Description</h2>
90
+ <TextField name="shortDescription" {form} optional>
91
+ Short description (search results, top of the page)
92
+ </TextField>
93
+ <MessageField name="description" defaultHeight={200} {form} optional
94
+ >Full description</MessageField
95
+ >
96
+ </section>
97
+
98
+ <section class={section}>
99
+ <div>
100
+ <h2 class="font-semibold">Images</h2>
101
+ <p class="text-sm text-[var(--ink-muted)]">
102
+ File names in the product image bucket. The first is the cover.
103
+ </p>
104
+ </div>
105
+ <ul class="space-y-3">
106
+ {#each imageRows as row, i (i)}
107
+ <li class="flex flex-wrap items-center gap-3">
108
+ {#if row.src}
109
+ <img
110
+ class="size-14 rounded-md border border-[var(--line)] object-cover"
111
+ alt=""
112
+ src={Images.url(context.imageBaseUrl, row.src)}
113
+ />
114
+ {/if}
115
+ <input
116
+ {...images[i].src.as('text')}
117
+ class="{input} w-56"
118
+ aria-label="Image {i + 1} file name"
119
+ placeholder="file.avif"
120
+ />
121
+ <input
122
+ {...images[i].alt.as('text')}
123
+ class="{input} flex-1"
124
+ aria-label="Image {i + 1} alt text"
125
+ placeholder="Alt text"
126
+ />
127
+ <Button onclick={() => images.set(up(imageRows, i))} size="sm" variant="secondary"
128
+ >Up</Button
129
+ >
130
+ <Button
131
+ onclick={() => images.set(imageRows.filter((_, j) => j !== i))}
132
+ size="sm"
133
+ variant="secondary">Remove</Button
134
+ >
135
+ </li>
136
+ {/each}
137
+ </ul>
138
+ <div>
139
+ <Button onclick={() => images.set([...imageRows, { alt: '', src: '' }])} variant="secondary"
140
+ >Add image</Button
141
+ >
142
+ </div>
143
+ </section>
144
+
145
+ <section class={section}>
146
+ <h2 class="font-semibold">Categories</h2>
147
+ <div class="grid gap-2 sm:grid-cols-2">
148
+ {#each options.categories as category (category.id)}
149
+ <label class="flex items-center gap-2 text-sm">
150
+ <input {...form.fields.categoryIds.as('checkbox', String(category.id))} />
151
+ {category.name}
152
+ </label>
153
+ {:else}
154
+ <p class="text-sm text-[var(--ink-muted)]">No categories yet.</p>
155
+ {/each}
156
+ </div>
157
+ </section>
158
+
159
+ <section class={section}>
160
+ <div>
161
+ <h2 class="font-semibold">Variation</h2>
162
+ <p class="text-sm text-[var(--ink-muted)]">
163
+ Products in the same group show as options of each other, e.g. group "Colour", option
164
+ "Black".
165
+ </p>
166
+ </div>
167
+ <div class="grid gap-4 sm:grid-cols-2">
168
+ <label class="text-sm font-medium">
169
+ Group
170
+ <input
171
+ {...form.fields.variationGroup.as('text')}
172
+ class="{input} mt-1"
173
+ list="variation-groups"
174
+ />
175
+ </label>
176
+ <datalist id="variation-groups">
177
+ {#each options.variationGroups as group (group)}<option value={group}></option>{/each}
178
+ </datalist>
179
+ <TextField name="variationLabel" {form} optional>This option</TextField>
180
+ </div>
181
+ </section>
182
+
183
+ <section class={section}>
184
+ <div>
185
+ <h2 class="font-semibold">Stock and shipping</h2>
186
+ <p class="text-sm text-[var(--ink-muted)]">
187
+ Stock itself is set on the Stock page{p ? ` (now ${p.stock} units)` : ''}.
188
+ </p>
189
+ </div>
190
+ <div class="grid gap-4 sm:grid-cols-3">
191
+ <NumberField name="massGrams" {form} inputmode="numeric">Weight (g)</NumberField>
192
+ <NumberField name="maxPerOrder" {form} inputmode="numeric">Max per order</NumberField>
193
+ <NumberField name="packSize" {form} inputmode="numeric">Pack size (units)</NumberField>
194
+ <NumberField name="lowStockThreshold" {form} inputmode="numeric" optional placeholder="never">
195
+ "Only N left" from
196
+ </NumberField>
197
+ <NumberField name="sortOrder" {form} inputmode="numeric">Sort order</NumberField>
198
+ </div>
199
+ </section>
200
+
201
+ <section class={section}>
202
+ <div>
203
+ <h2 class="font-semibold">Made of other products</h2>
204
+ <p class="text-sm text-[var(--ink-muted)]">
205
+ Leave empty for a normal product. A combined product has no stock of its own: it sells as
206
+ many complete sets as its parts allow, and selling one takes stock from the parts.
207
+ </p>
208
+ </div>
209
+ <ul class="space-y-2">
210
+ {#each componentRows as _, i (i)}
211
+ <li class="flex items-center gap-3">
212
+ <input
213
+ {...components[i].sku.as('text')}
214
+ class="{input} w-56"
215
+ aria-label="Part {i + 1} SKU"
216
+ placeholder="SKU"
217
+ />
218
+ <input
219
+ {...components[i].quantity.as('number')}
220
+ class="{input} w-24"
221
+ aria-label="Part {i + 1} quantity"
222
+ min="1"
223
+ />
224
+ <Button
225
+ onclick={() => components.set(componentRows.filter((_, j) => j !== i))}
226
+ size="sm"
227
+ variant="secondary">Remove</Button
228
+ >
229
+ </li>
230
+ {/each}
231
+ </ul>
232
+ {#if componentRows.length < 10}
233
+ <div>
234
+ <Button
235
+ onclick={() => components.set([...componentRows, { quantity: 1, sku: '' }])}
236
+ variant="secondary">Add part</Button
237
+ >
238
+ </div>
239
+ {/if}
240
+ </section>
241
+
242
+ <div class="flex items-center gap-4">
243
+ <Button {form} loadingMessage="Saving…">Save product</Button>
244
+ {#if p?.active}
245
+ <!-- eslint-disable-next-line svelte/no-navigation-without-resolve -- the shop's own domain -->
246
+ <a href="{context.siteUrl}/product/{p.slug}" rel="noopener" target="_blank">View in shop</a>
247
+ {/if}
248
+ </div>
249
+ </Form>
@@ -0,0 +1,88 @@
1
+ <script lang="ts">
2
+ import { goto } from '$app/navigation';
3
+ import { resolve } from '$app/paths';
4
+ import { page } from '$app/state';
5
+ import { getAdminProducts } from '../admin.remote';
6
+ import { Money } from '../../utils/money';
7
+ import Badge from '@zeyolabs/ui/badge/Badge.svelte';
8
+ import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
9
+
10
+ const q = $derived(page.url.searchParams.get('q') ?? '');
11
+ </script>
12
+
13
+ <svelte:head><title>Products · Admin</title></svelte:head>
14
+
15
+ <div class="flex flex-wrap items-center justify-between gap-3">
16
+ <h1 class="text-2xl font-semibold">Products</h1>
17
+ <div class="flex gap-2 text-sm">
18
+ <a
19
+ class="rounded-md border border-[var(--line)] bg-white px-3 py-1.5"
20
+ href={resolve('/categories')}>Categories</a
21
+ >
22
+ <a
23
+ class="rounded-md border border-[var(--line)] bg-white px-3 py-1.5"
24
+ href={resolve('/bundles')}>Bundles</a
25
+ >
26
+ <a
27
+ class="rounded-md bg-[var(--leaf-dark)] px-3 py-1.5 text-white no-underline"
28
+ href={resolve('/products/new')}>New product</a
29
+ >
30
+ </div>
31
+ </div>
32
+
33
+ <form
34
+ class="mt-4"
35
+ onsubmit={(event) => {
36
+ event.preventDefault();
37
+ const value = String(new FormData(event.currentTarget).get('q') ?? '').trim();
38
+ // eslint-disable-next-line svelte/no-navigation-without-resolve -- resolved path plus query
39
+ goto(`${resolve('/products')}${value ? `?q=${encodeURIComponent(value)}` : ''}`);
40
+ }}
41
+ role="search"
42
+ >
43
+ <label class="sr-only" for="product-q">Find a product</label>
44
+ <input
45
+ id="product-q"
46
+ name="q"
47
+ class="w-full max-w-sm rounded-md border border-[var(--line)] bg-white px-3 py-1.5"
48
+ placeholder="Name or SKU"
49
+ type="search"
50
+ value={q}
51
+ />
52
+ </form>
53
+
54
+ <Boundary message="Could not load products.">
55
+ {let rows = $derived(await getAdminProducts(q))}
56
+ <div class="mt-4 overflow-x-auto rounded-xl border border-[var(--line)] bg-white">
57
+ <table class="w-full text-left text-sm">
58
+ <thead class="border-b border-[var(--line)] text-[var(--ink-muted)]">
59
+ <tr>
60
+ <th class="px-4 py-2 font-medium">Product</th>
61
+ <th class="px-4 py-2 font-medium">SKU</th>
62
+ <th class="px-4 py-2 text-right font-medium">Price</th>
63
+ <th class="px-4 py-2 text-right font-medium">Stock</th>
64
+ </tr>
65
+ </thead>
66
+ <tbody class="divide-y divide-[var(--line)]">
67
+ {#each rows as row (row.id)}
68
+ <tr>
69
+ <td class="px-4 py-2">
70
+ <a class="font-medium" href={resolve('/products/[id]', { id: String(row.id) })}
71
+ >{row.name}{row.variationLabel ? ` · ${row.variationLabel}` : ''}</a
72
+ >
73
+ {#if !row.active}<Badge color="neutral">inactive</Badge>{/if}
74
+ </td>
75
+ <td class="px-4 py-2 whitespace-nowrap">{row.sku}</td>
76
+ <td class="px-4 py-2 text-right">{Money.format(row.pricePence)}</td>
77
+ <td class="px-4 py-2 text-right">{row.stock}</td>
78
+ </tr>
79
+ {:else}
80
+ <tr><td class="px-4 py-6 text-[var(--ink-muted)]" colspan="4">No products found.</td></tr>
81
+ {/each}
82
+ </tbody>
83
+ </table>
84
+ </div>
85
+ {#snippet pending()}
86
+ <p class="mt-6 text-[var(--ink-muted)]">Loading…</p>
87
+ {/snippet}
88
+ </Boundary>
@@ -0,0 +1,50 @@
1
+ import { Remote } from '@zeyolabs/kit/server/remote-functions';
2
+ import { Error404 } from '@zeyolabs/kit/utils/errors';
3
+ import { FormResult } from '@zeyolabs/kit/utils/form';
4
+ import { Schema } from '@zeyolabs/kit/utils/schema';
5
+ import { z } from 'zod';
6
+
7
+ import { shopping } from '../config';
8
+ import { CatalogueAdminService } from './admin.service.server';
9
+ import { CategoryFormSchema, ProductFormSchema } from './schema';
10
+
11
+ const admin = () => new CatalogueAdminService(shopping().db());
12
+
13
+ export const getAdminProducts = Remote.Query(z.string().max(100), (q) => {
14
+ const service = admin();
15
+ return service.products(q);
16
+ });
17
+
18
+ export const getAdminProduct = Remote.Query(Schema.Id, async (id) => {
19
+ const service = admin();
20
+ const product = await service.productForEdit(id);
21
+ if (!product) throw Error404('Product not found.');
22
+ return product;
23
+ });
24
+
25
+ /** Categories and variation groups, for the product editor's pickers. */
26
+ export const getProductOptions = Remote.Query(async () => {
27
+ const service = admin();
28
+ const [categories, groups] = await Promise.all([service.categories(), service.variationGroups()]);
29
+ return { categories, variationGroups: groups.map((g) => g.name) };
30
+ });
31
+
32
+ /** Saves a product; `data.id` is its id (new products get one here). */
33
+ export const saveProductForm = Remote.Form(ProductFormSchema, async (input) => {
34
+ const service = admin();
35
+ const id = await service.saveProduct(input);
36
+ await Promise.all([getAdminProduct(id).refresh(), getProductOptions().refresh()]);
37
+ return FormResult.okData({ data: { id }, message: 'Product saved.' });
38
+ });
39
+
40
+ export const getAdminCategories = Remote.Query(() => {
41
+ const service = admin();
42
+ return service.categories();
43
+ });
44
+
45
+ export const saveCategoryForm = Remote.Form(CategoryFormSchema, async (input) => {
46
+ const service = admin();
47
+ await service.saveCategory(input);
48
+ await Promise.all([getAdminCategories().refresh(), getProductOptions().refresh()]);
49
+ return FormResult.ok('Category saved.');
50
+ });
@@ -0,0 +1,239 @@
1
+ import { Error400 } from '@zeyolabs/kit/utils/errors';
2
+ import { and, asc, eq, inArray, ne, or, sql } from 'drizzle-orm';
3
+
4
+ import type { ShopDb } from '../db/index';
5
+ import type { CategoryInput, ProductInput } from './schema';
6
+
7
+ import {
8
+ categories,
9
+ productCategories,
10
+ productComponents,
11
+ productImages,
12
+ products,
13
+ productSlugAliases,
14
+ variationGroups,
15
+ } from '../db/schema';
16
+ import { StockService } from '../stock/service.server';
17
+ import { Search } from './library';
18
+
19
+ /** The admin's catalogue editing: products, categories and variation groups. */
20
+ export class CatalogueAdminService {
21
+ constructor(private readonly db: ShopDb) {}
22
+
23
+ async categories() {
24
+ return this.db
25
+ .select({
26
+ description: categories.description,
27
+ id: categories.id,
28
+ name: categories.name,
29
+ products: sql<number>`(select count(*) from ${productCategories} where ${productCategories.categoryId} = ${categories.id})`,
30
+ slug: categories.slug,
31
+ sortOrder: categories.sortOrder,
32
+ })
33
+ .from(categories)
34
+ .orderBy(asc(categories.sortOrder), asc(categories.name));
35
+ }
36
+
37
+ /** One product as the editor needs it, or undefined. */
38
+ async productForEdit(id: number) {
39
+ const db = this.db;
40
+ const product = await db.query.products.findFirst({ where: eq(products.id, id) });
41
+ if (!product) return undefined;
42
+ const [cats, images, components, group] = await Promise.all([
43
+ db
44
+ .select({ id: productCategories.categoryId })
45
+ .from(productCategories)
46
+ .where(eq(productCategories.productId, id)),
47
+ db
48
+ .select({ alt: productImages.alt, src: productImages.src })
49
+ .from(productImages)
50
+ .where(eq(productImages.productId, id))
51
+ .orderBy(asc(productImages.position)),
52
+ db
53
+ .select({ quantity: productComponents.quantity, sku: products.sku })
54
+ .from(productComponents)
55
+ .innerJoin(products, eq(products.id, productComponents.componentId))
56
+ .where(eq(productComponents.productId, id)),
57
+ product.variationGroupId
58
+ ? db.query.variationGroups.findFirst({
59
+ where: eq(variationGroups.id, product.variationGroupId),
60
+ })
61
+ : undefined,
62
+ ]);
63
+ return {
64
+ ...product,
65
+ categoryIds: cats.map((c) => c.id),
66
+ components,
67
+ images,
68
+ variationGroup: group?.name ?? null,
69
+ };
70
+ }
71
+
72
+ /** Every product for the admin list, optionally filtered by name or SKU. */
73
+ async products(q = '') {
74
+ const term = q.trim().toLowerCase();
75
+ const match = Search.pattern(term);
76
+ return this.db
77
+ .select({
78
+ active: products.active,
79
+ id: products.id,
80
+ name: products.name,
81
+ pricePence: products.pricePence,
82
+ sku: products.sku,
83
+ slug: products.slug,
84
+ stock: products.stock,
85
+ variationLabel: products.variationLabel,
86
+ })
87
+ .from(products)
88
+ .where(
89
+ term
90
+ ? or(
91
+ sql`lower(${products.name}) like ${match} escape '\\'`,
92
+ sql`lower(${products.sku}) like ${match} escape '\\'`
93
+ )
94
+ : undefined
95
+ )
96
+ .orderBy(asc(products.sortOrder), asc(products.name), asc(products.id))
97
+ .limit(500);
98
+ }
99
+
100
+ async saveCategory(input: CategoryInput): Promise<number> {
101
+ const db = this.db;
102
+ const clash = await db.query.categories.findFirst({ where: eq(categories.slug, input.slug) });
103
+ if (clash && clash.id !== input.id) throw Error400('Another category already uses that slug.');
104
+ const { id, ...values } = input;
105
+ if (id === undefined) {
106
+ const [row] = await db.insert(categories).values(values).returning({ id: categories.id });
107
+ return row.id;
108
+ }
109
+ await db.update(categories).set(values).where(eq(categories.id, id));
110
+ return id;
111
+ }
112
+
113
+ /**
114
+ * Creates or updates a product with its categories, images and components. Changing the slug keeps
115
+ * the old one as an alias, so existing links 301 to the new URL. Stock is left alone: new products
116
+ * start at 0 and stock changes go through the stock page.
117
+ */
118
+ async saveProduct(input: ProductInput, now = Date.now()): Promise<number> {
119
+ const db = this.db;
120
+ const [slugClash, skuClash, aliasClash] = await Promise.all([
121
+ db.query.products.findFirst({
122
+ where: and(eq(products.slug, input.slug), input.id ? ne(products.id, input.id) : undefined),
123
+ }),
124
+ db.query.products.findFirst({
125
+ where: and(eq(products.sku, input.sku), input.id ? ne(products.id, input.id) : undefined),
126
+ }),
127
+ db.query.productSlugAliases.findFirst({ where: eq(productSlugAliases.slug, input.slug) }),
128
+ ]);
129
+ if (slugClash) throw Error400('Another product already uses that slug.');
130
+ if (skuClash) throw Error400('Another product already uses that SKU.');
131
+ if (aliasClash && aliasClash.productId !== input.id) {
132
+ throw Error400('That slug is an old link of another product.');
133
+ }
134
+ if (input.categoryIds.length > 0) {
135
+ const known = await db
136
+ .select({ id: categories.id })
137
+ .from(categories)
138
+ .where(inArray(categories.id, input.categoryIds));
139
+ if (known.length !== new Set(input.categoryIds).size) throw Error400('Unknown category.');
140
+ }
141
+ const componentSkus = input.components.map((c) => c.sku);
142
+ const componentRows = componentSkus.length
143
+ ? await db
144
+ .select({ id: products.id, sku: products.sku })
145
+ .from(products)
146
+ .where(inArray(products.sku, componentSkus))
147
+ : [];
148
+ const componentId = new Map(componentRows.map((r) => [r.sku, r.id]));
149
+ const missing = componentSkus.filter((s) => !componentId.has(s));
150
+ if (missing.length > 0) throw Error400(`Unknown component SKU: ${missing.join(', ')}`);
151
+
152
+ const values = {
153
+ active: input.active,
154
+ comparePricePence: input.comparePricePence,
155
+ description: input.description,
156
+ lowStockThreshold: input.lowStockThreshold,
157
+ massGrams: input.massGrams,
158
+ maxPerOrder: input.maxPerOrder,
159
+ name: input.name,
160
+ packSize: input.packSize,
161
+ pricePence: input.pricePence,
162
+ shortDescription: input.shortDescription,
163
+ sku: input.sku,
164
+ slug: input.slug,
165
+ sortOrder: input.sortOrder,
166
+ variationGroupId: await this.variationGroupId(input.variationGroup),
167
+ variationLabel: input.variationGroup ? input.variationLabel || null : null,
168
+ };
169
+
170
+ const components = input.components.map((c) => ({
171
+ componentId: componentId.get(c.sku)!,
172
+ quantity: c.quantity,
173
+ }));
174
+ const stock = new StockService(db);
175
+ await stock.checkComponents(input.id, components);
176
+
177
+ const before = input.id
178
+ ? await db.query.products.findFirst({ where: eq(products.id, input.id) })
179
+ : undefined;
180
+ if (input.id && !before) throw Error400('Product not found.');
181
+ // A new product has no id until the batch inserts it, so later statements find it by SKU.
182
+ const productId =
183
+ input.id ??
184
+ sql<number>`(select ${products.id} from ${products} where ${products.sku} = ${input.sku})`;
185
+
186
+ // One atomic batch: the product, its old-slug redirect, categories, images and components
187
+ // are all saved or none are.
188
+ await db.batch([
189
+ input.id
190
+ ? db.update(products).set(values).where(eq(products.id, input.id))
191
+ : db.insert(products).values({ ...values, createdAt: now, stock: 0 }),
192
+ ...(before && before.slug !== input.slug
193
+ ? [
194
+ db
195
+ .insert(productSlugAliases)
196
+ .values({ productId: before.id, slug: before.slug })
197
+ .onConflictDoNothing(),
198
+ ]
199
+ : []),
200
+ // The new slug is the product's own now, not an alias of it.
201
+ db
202
+ .delete(productSlugAliases)
203
+ .where(
204
+ and(eq(productSlugAliases.slug, input.slug), eq(productSlugAliases.productId, productId))
205
+ ),
206
+ db.delete(productCategories).where(eq(productCategories.productId, productId)),
207
+ db.delete(productImages).where(eq(productImages.productId, productId)),
208
+ ...[...new Set(input.categoryIds)].map((categoryId) =>
209
+ db.insert(productCategories).values({ categoryId, productId })
210
+ ),
211
+ ...input.images.map((image, position) =>
212
+ db.insert(productImages).values({ alt: image.alt, position, productId, src: image.src })
213
+ ),
214
+ ...stock.componentStatements(productId, components),
215
+ ]);
216
+ if (input.id) return input.id;
217
+ const [row] = await db
218
+ .select({ id: products.id })
219
+ .from(products)
220
+ .where(eq(products.sku, input.sku));
221
+ return row.id;
222
+ }
223
+
224
+ /** Names of the existing variation groups, for the editor's suggestions. */
225
+ async variationGroups() {
226
+ return this.db.select().from(variationGroups).orderBy(asc(variationGroups.name));
227
+ }
228
+
229
+ private async variationGroupId(name: null | string): Promise<null | number> {
230
+ if (!name) return null;
231
+ const db = this.db;
232
+ const found = await db.query.variationGroups.findFirst({
233
+ where: eq(variationGroups.name, name),
234
+ });
235
+ if (found) return found.id;
236
+ const [row] = await db.insert(variationGroups).values({ name }).returning();
237
+ return row.id;
238
+ }
239
+ }
@@ -0,0 +1,52 @@
1
+ import { Remote } from '@zeyolabs/kit/server/remote-functions';
2
+ import { Error404 } from '@zeyolabs/kit/utils/errors';
3
+ import { z } from 'zod';
4
+
5
+ import { shopping } from '../config';
6
+ import { ReviewService } from '../reviews/service.server';
7
+ import { ShippingService } from '../shipping/service.server';
8
+ import { ShopSchema } from '../utils/schemas';
9
+ import { Search } from './library';
10
+ import { CatalogueService } from './service.server';
11
+
12
+ const catalogue = () => new CatalogueService(shopping().db());
13
+
14
+ /** The header's Shop menu. Cheap: a handful of rows. */
15
+ export const getMenuCategories = Remote.Query(async () => {
16
+ const service = catalogue();
17
+ return (await service.categories()).map(({ name, slug }) => ({ name, slug }));
18
+ });
19
+
20
+ export const getShop = Remote.Query(async () => {
21
+ const service = catalogue();
22
+ const [categories, products] = await Promise.all([service.categories(), service.products()]);
23
+ return { categories, products };
24
+ });
25
+
26
+ export const getCategoryPage = Remote.Query(ShopSchema.SlugParam, async (slug) => {
27
+ const service = catalogue();
28
+ const category = await service.category(slug);
29
+ if (!category) throw Error404('Category not found');
30
+ return { category, products: await service.categoryProducts(category.id) };
31
+ });
32
+
33
+ export const getProduct = Remote.Query(ShopSchema.SlugParam, async (slug) => {
34
+ const db = shopping().db();
35
+ const service = new CatalogueService(db);
36
+ const found = await service.product(slug);
37
+ if (!found) throw Error404('Product not found');
38
+ const reviews = new ReviewService(db);
39
+ return { ...found, reviews: await reviews.forProduct(found.product.id) };
40
+ });
41
+
42
+ /** The page quotes the live UK rate so it can never disagree with the basket. */
43
+ export const getUkShippingRate = Remote.Query(async () => {
44
+ const service = new ShippingService(shopping().db());
45
+ return { freeFromPence: shopping().shipping.freeUkFromPence, rate: await service.ukRate() };
46
+ });
47
+
48
+ /** Search results for the search page; an empty query returns nothing. */
49
+ export const searchShop = Remote.Query(z.string().max(Search.MAX_LENGTH), async (query) => {
50
+ const service = catalogue();
51
+ return { products: await service.search(query), query };
52
+ });