@zeyolabs/shopping 2026.11.37 → 2026.11.39

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 (46) hide show
  1. package/basket/client.remote.ts +16 -2
  2. package/basket/cookies.server.ts +13 -1
  3. package/basket/library.ts +58 -0
  4. package/basket/pages/Basket.svelte +80 -30
  5. package/basket/service.server.ts +139 -6
  6. package/bundles/admin/BundleEditPage.svelte +7 -4
  7. package/bundles/admin/BundleForm.svelte +50 -11
  8. package/bundles/admin/BundlesPage.svelte +14 -10
  9. package/bundles/client.remote.ts +18 -6
  10. package/bundles/library.ts +51 -0
  11. package/bundles/pages/Bundle.svelte +233 -68
  12. package/bundles/schema.ts +13 -2
  13. package/bundles/service.server.ts +185 -33
  14. package/catalogue/admin/CategoriesPage.svelte +13 -10
  15. package/catalogue/admin/CategoryForm.svelte +4 -3
  16. package/catalogue/admin/ProductEditPage.svelte +7 -4
  17. package/catalogue/admin/ProductForm.svelte +31 -29
  18. package/catalogue/admin/ProductsPage.svelte +16 -14
  19. package/catalogue/client.remote.ts +23 -9
  20. package/catalogue/components/ProductCard.svelte +22 -14
  21. package/catalogue/library.ts +91 -0
  22. package/catalogue/loads.server.ts +8 -4
  23. package/catalogue/pages/Category.svelte +15 -6
  24. package/catalogue/pages/Product.svelte +164 -45
  25. package/catalogue/pages/Search.svelte +12 -7
  26. package/catalogue/pages/Shop.svelte +12 -12
  27. package/catalogue/service.server.ts +44 -9
  28. package/checkout/manager.server.ts +68 -16
  29. package/checkout/pages/CheckoutSuccess.svelte +10 -8
  30. package/customers/pages/Account.svelte +19 -15
  31. package/db/schema.ts +27 -3
  32. package/fulfilment/admin/OrderPage.svelte +60 -56
  33. package/fulfilment/admin/OrdersPage.svelte +26 -22
  34. package/orders/manager.server.ts +45 -11
  35. package/orders/pages/Order.svelte +35 -29
  36. package/orders/service.server.ts +25 -3
  37. package/package.json +5 -4
  38. package/reviews/admin/ReviewsPage.svelte +23 -19
  39. package/reviews/components/ReviewForm.svelte +3 -2
  40. package/reviews/components/Reviews.svelte +17 -13
  41. package/stock/admin/StockPage.svelte +12 -9
  42. package/stock/admin/StockRow.svelte +3 -2
  43. package/stock/service.server.ts +6 -1
  44. package/ui/PageLinks.svelte +45 -0
  45. package/ui/PageTitle.svelte +20 -4
  46. package/ui/Stars.svelte +3 -1
@@ -7,7 +7,7 @@ import { z } from 'zod';
7
7
  import { shopping } from '../config';
8
8
  import { ShippingService } from '../shipping/service.server';
9
9
  import { BasketCookies } from './cookies.server';
10
- import { BasketCookie } from './library';
10
+ import { BasketBundles, BasketCookie } from './library';
11
11
  import { AddToBasketSchema, BasketQuantitySchema } from './schema';
12
12
  import { BasketService } from './service.server';
13
13
 
@@ -18,10 +18,24 @@ export const getBasket = Remote.Query(async () => {
18
18
  return service.summarise(
19
19
  BasketCookies.read(cookies),
20
20
  BasketCookies.readShipTo(cookies, shipping.defaultCountry),
21
- shipping
21
+ shipping,
22
+ BasketCookies.readBundles(cookies)
22
23
  );
23
24
  });
24
25
 
26
+ /** The basket's remove button on a kit or discounted bundle (they are one line, without − and +). */
27
+ export const removeBundleFromBasket = Remote.Cmd(
28
+ z.object({ index: z.number().int().min(0).max(20) }),
29
+ async ({ index }) => {
30
+ const { cookies } = getRequestEvent();
31
+ BasketCookies.writeBundles(
32
+ cookies,
33
+ BasketBundles.remove(BasketCookies.readBundles(cookies), index)
34
+ );
35
+ await getBasket().refresh();
36
+ }
37
+ );
38
+
25
39
  export const addToBasketForm = Remote.Form(AddToBasketSchema, async ({ productId, quantity }) => {
26
40
  const { cookies } = getRequestEvent();
27
41
  BasketCookies.write(cookies, BasketCookie.add(BasketCookies.read(cookies), productId, quantity));
@@ -1,8 +1,9 @@
1
1
  import type { Cookies } from '@sveltejs/kit';
2
2
 
3
- import { type Basket, BasketCookie } from './library';
3
+ import { type Basket, type BasketBundle, BasketBundles, BasketCookie } from './library';
4
4
 
5
5
  const COOKIE = 'basket';
6
+ const BUNDLES_COOKIE = 'basket_bundles';
6
7
  const SHIP_TO_COOKIE = 'ship_to';
7
8
  const OPTIONS = {
8
9
  httpOnly: true,
@@ -16,12 +17,18 @@ const OPTIONS = {
16
17
  export const BasketCookies = {
17
18
  clear(cookies: Cookies): void {
18
19
  cookies.delete(COOKIE, { path: '/' });
20
+ cookies.delete(BUNDLES_COOKIE, { path: '/' });
19
21
  },
20
22
 
21
23
  read(cookies: Cookies): Basket {
22
24
  return BasketCookie.parse(cookies.get(COOKIE));
23
25
  },
24
26
 
27
+ /** Bundles kept as one line each (kits, discounted bundles). */
28
+ readBundles(cookies: Cookies): BasketBundle[] {
29
+ return BasketBundles.parse(cookies.get(BUNDLES_COOKIE));
30
+ },
31
+
25
32
  /** The chosen country, or `fallback` (the shop's default) when unset or invalid. */
26
33
  readShipTo(cookies: Cookies, fallback: string): string {
27
34
  const value = cookies.get(SHIP_TO_COOKIE);
@@ -32,6 +39,11 @@ export const BasketCookies = {
32
39
  cookies.set(COOKIE, JSON.stringify(basket), OPTIONS);
33
40
  },
34
41
 
42
+ writeBundles(cookies: Cookies, list: BasketBundle[]): void {
43
+ if (list.length === 0) cookies.delete(BUNDLES_COOKIE, { path: '/' });
44
+ else cookies.set(BUNDLES_COOKIE, JSON.stringify(list), OPTIONS);
45
+ },
46
+
35
47
  writeShipTo(cookies: Cookies, country: string): void {
36
48
  cookies.set(SHIP_TO_COOKIE, country, OPTIONS);
37
49
  },
package/basket/library.ts CHANGED
@@ -42,3 +42,61 @@ export const BasketCookie = {
42
42
  return next;
43
43
  },
44
44
  };
45
+
46
+ /**
47
+ * A bundle kept as one basket line (a kit or a discounted bundle): its id and, per step, the chosen
48
+ * product ids (a `fill` step repeats an id per slot). Re-checked and re-priced on every read.
49
+ */
50
+ export type BasketBundle = {
51
+ bundleId: number;
52
+ choices: { productIds: number[]; stepId: number }[];
53
+ };
54
+
55
+ const MAX_BUNDLES = 10;
56
+ const isId = (v: unknown): v is number => Number.isInteger(v) && (v as number) > 0;
57
+
58
+ /** The bundles cookie's contents. Pure. */
59
+ export const BasketBundles = {
60
+ MAX: MAX_BUNDLES,
61
+
62
+ /** Adds a bundle at the end; the oldest drops off past the limit. Returns a new list. */
63
+ add(list: BasketBundle[], entry: BasketBundle): BasketBundle[] {
64
+ return [...list, entry].slice(-MAX_BUNDLES);
65
+ },
66
+
67
+ /** A cookie value to bundles. Junk is dropped, not thrown. */
68
+ parse(raw: string | undefined): BasketBundle[] {
69
+ if (!raw) return [];
70
+ let parsed: unknown;
71
+ try {
72
+ parsed = JSON.parse(raw);
73
+ } catch {
74
+ return [];
75
+ }
76
+ if (!Array.isArray(parsed)) return [];
77
+ const out: BasketBundle[] = [];
78
+ for (const item of parsed.slice(0, MAX_BUNDLES)) {
79
+ if (!item || typeof item !== 'object' || !isId(item.bundleId) || !Array.isArray(item.choices))
80
+ continue;
81
+ const choices = (item.choices as unknown[])
82
+ .slice(0, 20)
83
+ .filter(
84
+ (c): c is { productIds: number[]; stepId: number } =>
85
+ !!c &&
86
+ typeof c === 'object' &&
87
+ isId((c as { stepId: unknown }).stepId) &&
88
+ Array.isArray((c as { productIds: unknown }).productIds) &&
89
+ (c as { productIds: unknown[] }).productIds.length <= 64 &&
90
+ (c as { productIds: unknown[] }).productIds.every(isId)
91
+ )
92
+ .map((c) => ({ productIds: [...c.productIds], stepId: c.stepId }));
93
+ out.push({ bundleId: item.bundleId, choices });
94
+ }
95
+ return out;
96
+ },
97
+
98
+ /** Removes the bundle at `index`. Returns a new list. */
99
+ remove(list: BasketBundle[], index: number): BasketBundle[] {
100
+ return list.filter((_, i) => i !== index);
101
+ },
102
+ };
@@ -1,25 +1,30 @@
1
1
  <script lang="ts">
2
- import { ErrorMessage } from '../../utils/errors';
3
2
  import { resolve } from '$app/paths';
3
+ import Minus from '@lucide/svelte/icons/minus';
4
+ import Plus from '@lucide/svelte/icons/plus';
5
+ import Trash from '@lucide/svelte/icons/trash-2';
6
+ import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
7
+ import { Form } from '@zeyolabs/ui/form';
8
+ import Button from '@zeyolabs/ui/form/Button.svelte';
9
+ import { Select } from '@zeyolabs/ui/form/primitives';
10
+ import SkeletonCard from '@zeyolabs/ui/skeleton/SkeletonCard.svelte';
11
+ import Span from '@zeyolabs/ui/text/Span.svelte';
12
+ import Text from '@zeyolabs/ui/text/Text.svelte';
13
+ import { toast } from 'svelte-sonner';
14
+
15
+ import { shopContext } from '../../context';
4
16
  import PageTitle from '../../ui/PageTitle.svelte';
17
+ import { ErrorMessage } from '../../utils/errors';
18
+ import { Images } from '../../utils/images';
19
+ import { Money } from '../../utils/money';
5
20
  import {
6
21
  basketQuantityForm,
7
22
  getBasket,
8
23
  getShippableCountries,
24
+ removeBundleFromBasket,
9
25
  setShipTo,
10
26
  } from '../client.remote';
11
27
  import { BasketQuantitySchema } from '../schema';
12
- import Minus from '@lucide/svelte/icons/minus';
13
- import Plus from '@lucide/svelte/icons/plus';
14
- import { shopContext } from '../../context';
15
- import { Images } from '../../utils/images';
16
- import { Money } from '../../utils/money';
17
- import { toast } from 'svelte-sonner';
18
- import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
19
- import { Form } from '@zeyolabs/ui/form';
20
- import Button from '@zeyolabs/ui/form/Button.svelte';
21
- import { Select } from '@zeyolabs/ui/form/primitives';
22
- import SkeletonCard from '@zeyolabs/ui/skeleton/SkeletonCard.svelte';
23
28
 
24
29
  /** The app's own checkout remote function, which rate-limits before calling `createCheckout`. */
25
30
  let { startCheckout }: { startCheckout: () => Promise<{ url: string }> } = $props();
@@ -44,11 +49,11 @@
44
49
  <Boundary message="Could not load your basket.">
45
50
  {let [summary, countries] = $derived(await Promise.all([getBasket(), getShippableCountries()]))}
46
51
 
47
- {#if summary.lines.length === 0}
48
- <p>Your basket is empty.</p>
49
- <p class="mt-4"><a class="underline" href={resolve('/')}>Continue shopping</a></p>
52
+ {#if summary.lines.length === 0 && summary.bundles.length === 0}
53
+ <Text>Your basket is empty.</Text>
54
+ <Text class="mt-4"><a class="underline" href={resolve('/')}>Continue shopping</a></Text>
50
55
  {:else}
51
- <ul class="divide-y divide-[var(--line)]">
56
+ <ul class="divide-y divide-[var(--bd)]">
52
57
  {#each summary.lines as line (line.id)}
53
58
  <li class="flex flex-wrap items-center gap-4 py-4">
54
59
  {#if line.cover}
@@ -62,11 +67,11 @@
62
67
  <a class="font-medium" href={resolve('/product/[slug]', { slug: line.slug })}>
63
68
  {line.name}
64
69
  </a>
65
- <p>{Money.format(line.pricePence)}</p>
70
+ <Text>{Money.format(line.pricePence)}</Text>
66
71
  {#if line.available < line.quantity}
67
- <p class="text-sm text-[var(--danger)]">
72
+ <Text class="text-[var(--danger)]">
68
73
  {line.available === 0 ? 'Out of stock' : `Only ${line.available} available`}
69
- </p>
74
+ </Text>
70
75
  {/if}
71
76
  </div>
72
77
  {const form = basketQuantityForm.for(line.id)}
@@ -87,7 +92,7 @@
87
92
  >
88
93
  <Minus size={14} />
89
94
  </Button>
90
- <span class="w-6 text-center">{line.quantity}</span>
95
+ <Span class="w-6" centered>{line.quantity}</Span>
91
96
  <Button
92
97
  {...form.fields.quantity.as('submit', line.quantity + 1)}
93
98
  aria-label="Increase quantity of {line.name}"
@@ -100,7 +105,50 @@
100
105
  <Plus size={14} />
101
106
  </Button>
102
107
  </Form>
103
- <p class="w-20 text-right">{Money.format(line.lineTotalPence)}</p>
108
+ <Text class="w-20 text-right">{Money.format(line.lineTotalPence)}</Text>
109
+ </li>
110
+ {/each}
111
+ {#each summary.bundles as bundle (bundle.index)}
112
+ <li class="flex flex-wrap items-start gap-4 py-4">
113
+ {#if bundle.cover}
114
+ <img
115
+ class="size-20 object-cover"
116
+ alt={bundle.cover.alt || bundle.name}
117
+ src={Images.url(context.imageBaseUrl, bundle.cover.src)}
118
+ />
119
+ {/if}
120
+ <div class="min-w-0 flex-1">
121
+ {#if bundle.slug}
122
+ <a class="font-medium" href={resolve('/bundle/[slug]', { slug: bundle.slug })}>
123
+ {bundle.name}
124
+ </a>
125
+ {:else}
126
+ <Text bold>{bundle.name}</Text>
127
+ {/if}
128
+ {#if bundle.details.length > 0}
129
+ <ul class="mt-1 text-sm text-[var(--txs)]">
130
+ {#each bundle.details as detail, i (i)}<li>{detail}</li>{/each}
131
+ </ul>
132
+ {/if}
133
+ {#if bundle.problem}
134
+ <Text class="mt-1 text-[var(--danger)]">{bundle.problem}</Text>
135
+ {/if}
136
+ </div>
137
+ <Button
138
+ aria-label="Remove {bundle.name}"
139
+ icon
140
+ onclick={() => removeBundleFromBasket({ index: bundle.index })}
141
+ size="sm"
142
+ variant="secondary"
143
+ >
144
+ <Trash size={14} />
145
+ </Button>
146
+ <Text class="w-20 text-right">
147
+ {Money.format(bundle.pricePence)}
148
+ {#if bundle.listPricePence > bundle.pricePence}
149
+ <s class="block text-xs text-[var(--txt)]">{Money.format(bundle.listPricePence)}</s>
150
+ {/if}
151
+ </Text>
104
152
  </li>
105
153
  {/each}
106
154
  </ul>
@@ -134,23 +182,25 @@
134
182
  <dd class="text-right font-medium">{Money.format(summary.totalPence)}</dd>
135
183
  </dl>
136
184
  {#if summary.shipping === null}
137
- <p class="mt-2 text-right text-sm text-[var(--danger)]">
185
+ <Text class="mt-2 text-right text-[var(--danger)]">
138
186
  We cannot ship this order to the selected country.
139
- </p>
187
+ </Text>
140
188
  {:else}
141
- <p class="mt-2 text-right text-sm">
189
+ <Text class="mt-2 text-right">
142
190
  {summary.shipping.name}, {summary.shipping.deliveryTime}.
143
- </p>
191
+ </Text>
144
192
  {/if}
145
193
  {#if summary.domestic && summary.shippingPence > 0}
146
- <p class="mt-2 text-right text-sm">
194
+ <Text class="mt-2 text-right">
147
195
  Free UK delivery on orders of {Money.format(summary.freeShippingFromPence)} or more.
148
- </p>
196
+ </Text>
149
197
  {/if}
150
198
 
151
- <p class="mt-6 text-right">
199
+ <Text class="mt-6 text-right">
152
200
  <Button
153
- disabled={!summary.shipping || summary.lines.some((line) => line.available < 1)}
201
+ disabled={!summary.shipping ||
202
+ summary.lines.some((line) => line.available < 1) ||
203
+ summary.bundles.some((bundle) => !bundle.available)}
154
204
  loading={paying}
155
205
  loadingMessage="Redirecting…"
156
206
  onclick={checkout}
@@ -158,7 +208,7 @@
158
208
  >
159
209
  Checkout
160
210
  </Button>
161
- </p>
211
+ </Text>
162
212
  {/if}
163
213
 
164
214
  {#snippet pending()}
@@ -2,12 +2,14 @@ import { and, asc, eq, inArray } from 'drizzle-orm';
2
2
 
3
3
  import type { ShippingRules } from '../config';
4
4
  import type { ShopDb } from '../db/index';
5
- import type { Basket } from './library';
5
+ import type { Basket, BasketBundle } from './library';
6
6
 
7
+ import { type BundlePart, BundleService } from '../bundles/service.server';
7
8
  import { CoverService } from '../catalogue/covers.server';
8
9
  import { products } from '../db/schema';
9
10
  import { type ShippingQuote, ShippingService } from '../shipping/service.server';
10
11
  import { StockService } from '../stock/service.server';
12
+ import { ErrorMessage } from '../utils/errors';
11
13
 
12
14
  export type BasketLine = {
13
15
  /** What the customer can actually buy right now: min(requested, sellable, max per order). */
@@ -27,7 +29,28 @@ export type BasketLine = {
27
29
  stock: number;
28
30
  };
29
31
 
32
+ /** A kit or discounted bundle: one line at one price, re-checked against the catalogue on every read. */
33
+ export type BasketBundleLine = {
34
+ /** False when it can no longer be bought as chosen; `problem` says why. */
35
+ available: boolean;
36
+ bundleId: number;
37
+ cover: null | { alt: string; src: string };
38
+ /** What was chosen, one line each. */
39
+ details: string[];
40
+ /** Its position in the bundles cookie, for removing it. */
41
+ index: number;
42
+ /** The parts at their own prices; above `pricePence` when there is a discount. */
43
+ listPricePence: number;
44
+ massGrams: number;
45
+ name: string;
46
+ parts: BundlePart[];
47
+ pricePence: number;
48
+ problem: null | string;
49
+ slug: string;
50
+ };
51
+
30
52
  export type BasketSummary = {
53
+ bundles: BasketBundleLine[];
31
54
  /** Total items in the basket, for the header badge. */
32
55
  count: number;
33
56
  country: string;
@@ -49,14 +72,20 @@ export class BasketService {
49
72
  constructor(private readonly db: ShopDb) {}
50
73
 
51
74
  /** Inactive or deleted products drop out; quantities are capped by stock and max per order. */
52
- async summarise(basket: Basket, country: string, rules: ShippingRules): Promise<BasketSummary> {
75
+ async summarise(
76
+ basket: Basket,
77
+ country: string,
78
+ rules: ShippingRules,
79
+ bundleEntries: BasketBundle[] = []
80
+ ): Promise<BasketSummary> {
53
81
  const offer = {
54
82
  domestic: country === rules.defaultCountry,
55
83
  freeShippingFromPence: rules.freeUkFromPence,
56
84
  };
57
85
  const ids = Object.keys(basket).map(Number);
58
- if (ids.length === 0) {
86
+ if (ids.length === 0 && bundleEntries.length === 0) {
59
87
  return {
88
+ bundles: [],
60
89
  count: 0,
61
90
  country,
62
91
  ...offer,
@@ -100,8 +129,14 @@ export class BasketService {
100
129
  };
101
130
  });
102
131
 
103
- const subtotalPence = lines.reduce((sum, line) => sum + line.lineTotalPence, 0);
104
- const weightGrams = lines.reduce((sum, line) => sum + line.available * line.massGrams, 0);
132
+ const bundleLines = await this.bundleLines(bundleEntries, rows, lines);
133
+ const ready = bundleLines.filter((b) => b.available);
134
+ const subtotalPence =
135
+ lines.reduce((sum, line) => sum + line.lineTotalPence, 0) +
136
+ ready.reduce((sum, b) => sum + b.pricePence, 0);
137
+ const weightGrams =
138
+ lines.reduce((sum, line) => sum + line.available * line.massGrams, 0) +
139
+ ready.reduce((sum, b) => sum + b.massGrams, 0);
105
140
  const shippingService = new ShippingService(this.db);
106
141
  const shipping =
107
142
  subtotalPence > 0
@@ -109,7 +144,8 @@ export class BasketService {
109
144
  : null;
110
145
  const shippingPence = shipping?.pricePence ?? 0;
111
146
  return {
112
- count: lines.reduce((sum, line) => sum + line.quantity, 0),
147
+ bundles: bundleLines,
148
+ count: lines.reduce((sum, line) => sum + line.quantity, 0) + bundleLines.length,
113
149
  country,
114
150
  ...offer,
115
151
  lines,
@@ -120,4 +156,101 @@ export class BasketService {
120
156
  weightGrams,
121
157
  };
122
158
  }
159
+
160
+ /**
161
+ * Re-checks and prices each kept bundle. A bundle that no longer resolves, or whose parts the
162
+ * stock cannot cover on top of the ordinary lines and the bundles before it, is unavailable.
163
+ */
164
+ private async bundleLines(
165
+ entries: BasketBundle[],
166
+ rows: (typeof products.$inferSelect)[],
167
+ lines: BasketLine[]
168
+ ): Promise<BasketBundleLine[]> {
169
+ if (entries.length === 0) return [];
170
+ const bundles = new BundleService(this.db);
171
+ const resolved = await Promise.all(
172
+ entries.map((entry) =>
173
+ bundles.resolve(entry.bundleId, entry.choices).then(
174
+ (value) => ({ value }),
175
+ (error: unknown) => ({ error })
176
+ )
177
+ )
178
+ );
179
+ const partIds = [
180
+ ...new Set(
181
+ resolved.flatMap((r) => ('value' in r ? r.value.parts.map((p) => p.productId) : []))
182
+ ),
183
+ ];
184
+ const raw = partIds.length
185
+ ? await this.db
186
+ .select({ id: products.id, packSize: products.packSize, stock: products.stock })
187
+ .from(products)
188
+ .where(inArray(products.id, partIds))
189
+ : [];
190
+ const stockOf = new Map(raw.map((r) => [r.id, r]));
191
+ // Single units already spoken for by the ordinary lines.
192
+ const used = new Map<number, number>();
193
+ for (const line of lines) {
194
+ const row = rows.find((r) => r.id === line.id);
195
+ used.set(line.id, line.available * (row?.packSize ?? 1));
196
+ }
197
+ const covers = new CoverService(this.db);
198
+ const cover = await covers.covers(partIds.slice(0, 50));
199
+
200
+ return resolved.map((result, index) => {
201
+ const entry = entries[index];
202
+ if ('error' in result) {
203
+ const message = ErrorMessage.from(result.error, 'This bundle is no longer available.');
204
+ return {
205
+ available: false,
206
+ bundleId: entry.bundleId,
207
+ cover: null,
208
+ details: [],
209
+ index,
210
+ listPricePence: 0,
211
+ massGrams: 0,
212
+ name: 'Bundle',
213
+ parts: [],
214
+ pricePence: 0,
215
+ problem: message,
216
+ slug: '',
217
+ };
218
+ }
219
+ const bundle = result.value;
220
+ let problem: null | string = null;
221
+ for (const part of bundle.parts) {
222
+ const row = stockOf.get(part.productId);
223
+ const units = part.singleUnits ? part.quantity : part.quantity * (row?.packSize ?? 1);
224
+ const after = (used.get(part.productId) ?? 0) + units;
225
+ if (!row || after > row.stock) {
226
+ problem = `Not enough ${part.name} left for this bundle.`;
227
+ break;
228
+ }
229
+ }
230
+ if (!problem) {
231
+ for (const part of bundle.parts) {
232
+ const row = stockOf.get(part.productId)!;
233
+ const units = part.singleUnits ? part.quantity : part.quantity * row.packSize;
234
+ used.set(part.productId, (used.get(part.productId) ?? 0) + units);
235
+ }
236
+ }
237
+ const first = bundle.parts[0];
238
+ return {
239
+ available: problem === null,
240
+ bundleId: bundle.bundle.id,
241
+ cover: bundle.bundle.image
242
+ ? { alt: bundle.bundle.name, src: bundle.bundle.image }
243
+ : ((first && cover.get(first.productId)) ?? null),
244
+ details: bundle.details,
245
+ index,
246
+ listPricePence: bundle.listPricePence,
247
+ massGrams: bundle.massGrams,
248
+ name: bundle.bundle.name,
249
+ parts: bundle.parts,
250
+ pricePence: bundle.pricePence,
251
+ problem,
252
+ slug: bundle.bundle.slug,
253
+ };
254
+ });
255
+ }
123
256
  }
@@ -1,8 +1,11 @@
1
1
  <script lang="ts">
2
2
  import { resolve } from '$app/paths';
3
+ import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
4
+ import Text from '@zeyolabs/ui/text/Text.svelte';
5
+ import Title from '@zeyolabs/ui/text/Title.svelte';
6
+
3
7
  import { getAdminBundle } from '../admin.remote';
4
8
  import BundleForm from './BundleForm.svelte';
5
- import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
6
9
 
7
10
  /** The bundle to edit; leave out for a new one. */
8
11
  let { id }: { id?: number } = $props();
@@ -10,8 +13,8 @@
10
13
 
11
14
  <svelte:head><title>{id ? 'Edit bundle' : 'New bundle'} · Admin</title></svelte:head>
12
15
 
13
- <p class="text-sm"><a href={resolve('/bundles')}>← Bundles</a></p>
14
- <h1 class="mt-2 mb-6 text-2xl font-semibold">{id ? 'Edit bundle' : 'New bundle'}</h1>
16
+ <Text><a href={resolve('/bundles')}>← Bundles</a></Text>
17
+ <Title class="mt-2 mb-6" level={1} size="md">{id ? 'Edit bundle' : 'New bundle'}</Title>
15
18
 
16
19
  <Boundary message="Could not load the bundle." statusMessages={{ 404: 'Bundle not found.' }}>
17
20
  {let bundle = $derived(id ? await getAdminBundle(id) : null)}
@@ -19,6 +22,6 @@
19
22
  <BundleForm {bundle} />
20
23
  {/key}
21
24
  {#snippet pending()}
22
- <p class="text-[var(--ink-muted)]">Loading…</p>
25
+ <Text color="secondary">Loading…</Text>
23
26
  {/snippet}
24
27
  </Boundary>
@@ -1,12 +1,15 @@
1
1
  <script lang="ts">
2
2
  import { goto } from '$app/navigation';
3
3
  import { resolve } from '$app/paths';
4
+ import { CheckboxField, Form, MessageField, NumberField, TextField } from '@zeyolabs/ui/form';
5
+ import Button from '@zeyolabs/ui/form/Button.svelte';
6
+ import Title from '@zeyolabs/ui/text/Title.svelte';
7
+
4
8
  import type { getAdminBundle } from '../admin.remote';
9
+
10
+ import { shopContext } from '../../context';
5
11
  import { saveBundleForm } from '../admin.remote';
6
12
  import { BundleFormSchema } from '../schema';
7
- import { shopContext } from '../../context';
8
- import { CheckboxField, Form, MessageField, NumberField, TextField } from '@zeyolabs/ui/form';
9
- import Button from '@zeyolabs/ui/form/Button.svelte';
10
13
 
11
14
  type Bundle = Awaited<ReturnType<typeof getAdminBundle>>;
12
15
 
@@ -19,10 +22,24 @@
19
22
  const form = saveBundleForm.for(b?.id ?? 'new');
20
23
  const { steps } = form.fields;
21
24
  const stepRows = $derived(steps.value() ?? []);
22
- const newStep = { description: '', maxChoices: 1, minChoices: 1, skus: '', title: '' };
25
+ const newStep = {
26
+ description: '',
27
+ maxChoices: 1,
28
+ maxPerChoice: '',
29
+ minChoices: 1,
30
+ role: 'pick' as const,
31
+ skus: '',
32
+ title: '',
33
+ };
34
+ const ROLES = [
35
+ { label: 'Pick products', value: 'pick' },
36
+ { label: 'Kit base (sets price and slots)', value: 'base' },
37
+ { label: 'Kit fill (one per slot)', value: 'fill' },
38
+ { label: 'Kit cover (one product for every slot)', value: 'cover' },
39
+ ] as const;
23
40
 
24
- const input = 'mt-1 w-full rounded-md border border-[var(--line)] bg-white px-3 py-1.5';
25
- const section = 'grid gap-4 rounded-xl border border-[var(--line)] bg-white p-5';
41
+ const input = 'mt-1 w-full rounded-md border border-[var(--bd)] bg-white px-3 py-1.5';
42
+ const section = 'grid gap-4 rounded-xl border border-[var(--bd)] bg-white p-5';
26
43
  </script>
27
44
 
28
45
  <Form
@@ -30,11 +47,16 @@
30
47
  defaults={{
31
48
  active: b?.active ?? false,
32
49
  description: b?.description ?? '',
50
+ discountPercent: b?.discountPercent ?? 0,
33
51
  image: b?.image ?? '',
34
52
  name: b?.name ?? '',
35
53
  slug: b?.slug ?? '',
36
54
  sortOrder: b?.sortOrder ?? 0,
37
- steps: b?.steps.map((s) => ({ ...s, skus: s.skus.join('\n') })) ?? [newStep],
55
+ steps: b?.steps.map((s) => ({
56
+ ...s,
57
+ maxPerChoice: s.maxPerChoice ? String(s.maxPerChoice) : '',
58
+ skus: s.skus.join('\n'),
59
+ })) ?? [newStep],
38
60
  }}
39
61
  {form}
40
62
  hidden={{ id: b?.id }}
@@ -51,8 +73,11 @@
51
73
  <TextField name="image" {form} optional>Image file name</TextField>
52
74
  </div>
53
75
  <MessageField name="description" {form} optional>Description</MessageField>
54
- <div class="grid gap-4 sm:grid-cols-2">
76
+ <div class="grid gap-4 sm:grid-cols-3">
55
77
  <NumberField name="sortOrder" {form} inputmode="numeric">Sort order</NumberField>
78
+ <NumberField name="discountPercent" {form} inputmode="numeric">
79
+ Bundle discount % (not for kits)
80
+ </NumberField>
56
81
  <CheckboxField name="active" {form}>On sale in the shop</CheckboxField>
57
82
  </div>
58
83
  </section>
@@ -60,10 +85,10 @@
60
85
  {#each stepRows as _, i (i)}
61
86
  <section class={section}>
62
87
  <div class="flex items-center justify-between">
63
- <h2 class="font-semibold">Step {i + 1}</h2>
88
+ <Title level={2} size="sm">Step {i + 1}</Title>
64
89
  {#if stepRows.length > 1}
65
90
  <Button
66
- onclick={() => steps.set(stepRows.filter((_, j) => j !== i))}
91
+ onclick={() => steps.set(stepRows.filter((_: unknown, j: number) => j !== i))}
67
92
  size="sm"
68
93
  variant="secondary">Remove step</Button
69
94
  >
@@ -77,6 +102,20 @@
77
102
  Help text (optional)
78
103
  <input {...steps[i].description.as('text')} class={input} />
79
104
  </label>
105
+ <div class="grid gap-4 sm:grid-cols-2">
106
+ <label class="text-sm font-medium">
107
+ Kind of step
108
+ <select {...steps[i].role.as('select')} class={input}>
109
+ {#each ROLES as role (role.value)}
110
+ <option value={role.value}>{role.label}</option>
111
+ {/each}
112
+ </select>
113
+ </label>
114
+ <label class="text-sm font-medium">
115
+ Kit fill: most slots per product (blank = no limit)
116
+ <input {...steps[i].maxPerChoice.as('text')} class={input} inputmode="numeric" />
117
+ </label>
118
+ </div>
80
119
  <div class="grid gap-4 sm:grid-cols-2">
81
120
  <label class="text-sm font-medium">
82
121
  Fewest picks (0 = optional)
@@ -88,7 +127,7 @@
88
127
  </label>
89
128
  </div>
90
129
  <label class="text-sm font-medium">
91
- Products offered, one SKU per line
130
+ Products offered, one SKU per line (a kit base as SKU=slots, e.g. BASE44=16)
92
131
  <textarea {...steps[i].skus.as('text')} class="{input} min-h-28 font-mono"></textarea>
93
132
  </label>
94
133
  </section>