@zeyolabs/shopping 2026.11.11 → 2026.11.12

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 +19 -31
  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
package/README.md CHANGED
@@ -12,17 +12,39 @@ Published as source (no build step): the consuming app compiles it.
12
12
  pnpm add -E @zeyolabs/shopping @zeyolabs/ui @zeyolabs/kit
13
13
  ```
14
14
 
15
+ ## Layout
16
+
17
+ One folder per feature (library, client, service, manager, remote functions, pages, admin). See
18
+ `CLAUDE.md` for the map.
19
+
15
20
  ## Using it in an app
16
21
 
17
22
  1. Register the site's config once on the server: `configureShopping({...})` (brand, shipping,
18
23
  order prefix, `db`, secret names, `mail`), imported by `hooks.server.ts`, and pass its secret
19
24
  names to `runWithContext`.
20
- 2. In the root layout, `setShoppingClient({ imageBaseUrl, siteName, siteUrl, supportEmail })`.
25
+ 2. In the root layout, `setShopContext({ imageBaseUrl, siteName, siteUrl, supportEmail })`.
21
26
  3. Thin routes: render the pages (`<Basket startCheckout={...} />`, `<Shop description intro shop={data.shop} />`)
22
- and re-export handlers and loads from `@zeyolabs/shopping/routes/*`.
27
+ and re-export handlers and loads from `@zeyolabs/shopping/<feature>/*.server`.
23
28
  4. Tailwind must scan the components: `@source "../node_modules/@zeyolabs/shopping";`.
24
29
  5. Generate D1 migrations in the app from `@zeyolabs/shopping/db/schema` (drizzle-kit).
25
30
 
31
+ ## Optional features
32
+
33
+ - **Discount codes**: `checkout.promotionCodes: true` shows Stripe's promotion-code box at
34
+ Checkout. Codes are made and limited in the Stripe dashboard; orders record the discount.
35
+ - **Invoices**: `checkout.invoices: { footer, customFields }` has Stripe issue a paid invoice PDF
36
+ per order (Stripe charges per invoice). Customers get it from their order page
37
+ (`orders/invoice.server`), staff from the admin order (`fulfilment/invoice.server`).
38
+ - **Search**: `catalogue/pages/Search.svelte` + `searchLoad`.
39
+ - **Customer accounts**: `customers/pages/Account.svelte` lists the orders for the signed-in email; sign-in
40
+ is kit's passwordless auth in the app. `CheckoutManager.start()` passes a signed-in customer to Stripe (their
41
+ email comes from the session, never from the caller) so their saved details are filled in.
42
+ - **Reviews**: verified buyers review items from their order page; staff moderate in
43
+ `reviews/admin/ReviewsPage.svelte`; approved reviews show on the product page.
44
+ - **Bundles**: `bundles/pages/Bundle.svelte` + `bundleLoad`; the customer picks per step and the picks go
45
+ into the basket as ordinary products. Edited in `bundles/admin/BundlesPage.svelte`.
46
+ - **Product admin**: `catalogue/admin/` (`ProductsPage`, `ProductEditPage`, `CategoriesPage`).
47
+
26
48
  ## Versions
27
49
 
28
50
  Every merge to `main` publishes a new version (`.github/workflows/publish.yaml`); there is no
@@ -0,0 +1,62 @@
1
+ import { getRequestEvent } from '$app/server';
2
+ import { Remote } from '@zeyolabs/kit/server/remote-functions';
3
+ import { Error400 } from '@zeyolabs/kit/utils/errors';
4
+ import { FormResult } from '@zeyolabs/kit/utils/form';
5
+ import { z } from 'zod';
6
+
7
+ import { shopping } from '../config';
8
+ import { ShippingService } from '../shipping/service.server';
9
+ import { BasketCookies } from './cookies.server';
10
+ import { BasketCookie } from './library';
11
+ import { AddToBasketSchema, BasketQuantitySchema } from './schema';
12
+ import { BasketService } from './service.server';
13
+
14
+ export const getBasket = Remote.Query(async () => {
15
+ const { cookies } = getRequestEvent();
16
+ const { db, shipping } = shopping();
17
+ const service = new BasketService(db());
18
+ return service.summarise(
19
+ BasketCookies.read(cookies),
20
+ BasketCookies.readShipTo(cookies, shipping.defaultCountry),
21
+ shipping
22
+ );
23
+ });
24
+
25
+ export const addToBasketForm = Remote.Form(AddToBasketSchema, async ({ productId, quantity }) => {
26
+ const { cookies } = getRequestEvent();
27
+ BasketCookies.write(cookies, BasketCookie.add(BasketCookies.read(cookies), productId, quantity));
28
+ await getBasket().refresh();
29
+ return FormResult.ok('Added to your basket');
30
+ });
31
+
32
+ /** The basket's − and + buttons. Quantity 0 removes the line. */
33
+ export const basketQuantityForm = Remote.Form(
34
+ BasketQuantitySchema,
35
+ async ({ productId, quantity }) => {
36
+ const { cookies } = getRequestEvent();
37
+ BasketCookies.write(
38
+ cookies,
39
+ BasketCookie.set(BasketCookies.read(cookies), productId, quantity)
40
+ );
41
+ await getBasket().refresh();
42
+ return FormResult.ok();
43
+ }
44
+ );
45
+
46
+ export const getShippableCountries = Remote.Query(async () => {
47
+ const service = new ShippingService(shopping().db());
48
+ return service.countries();
49
+ });
50
+
51
+ /** The country picker changes it as soon as a country is chosen, so this stays a command. */
52
+ export const setShipTo = Remote.Cmd(
53
+ z.object({ country: z.string().regex(/^[A-Z]{2}$/) }),
54
+ async ({ country }) => {
55
+ const { cookies } = getRequestEvent();
56
+ const service = new ShippingService(shopping().db());
57
+ const allowed = await service.countries();
58
+ if (!allowed.some((c) => c.code === country)) throw Error400('We do not ship to that country.');
59
+ BasketCookies.writeShipTo(cookies, country);
60
+ await getBasket().refresh();
61
+ }
62
+ );
@@ -0,0 +1,38 @@
1
+ import type { Cookies } from '@sveltejs/kit';
2
+
3
+ import { type Basket, BasketCookie } from './library';
4
+
5
+ const COOKIE = 'basket';
6
+ const SHIP_TO_COOKIE = 'ship_to';
7
+ const OPTIONS = {
8
+ httpOnly: true,
9
+ maxAge: 60 * 60 * 24 * 30,
10
+ path: '/',
11
+ sameSite: 'lax',
12
+ secure: true,
13
+ } as const;
14
+
15
+ /** The basket and ship-to country, kept in cookies for 30 days. For the edge (remote functions, handlers). */
16
+ export const BasketCookies = {
17
+ clear(cookies: Cookies): void {
18
+ cookies.delete(COOKIE, { path: '/' });
19
+ },
20
+
21
+ read(cookies: Cookies): Basket {
22
+ return BasketCookie.parse(cookies.get(COOKIE));
23
+ },
24
+
25
+ /** The chosen country, or `fallback` (the shop's default) when unset or invalid. */
26
+ readShipTo(cookies: Cookies, fallback: string): string {
27
+ const value = cookies.get(SHIP_TO_COOKIE);
28
+ return value && /^[A-Z]{2}$/.test(value) ? value : fallback;
29
+ },
30
+
31
+ write(cookies: Cookies, basket: Basket): void {
32
+ cookies.set(COOKIE, JSON.stringify(basket), OPTIONS);
33
+ },
34
+
35
+ writeShipTo(cookies: Cookies, country: string): void {
36
+ cookies.set(SHIP_TO_COOKIE, country, OPTIONS);
37
+ },
38
+ };
@@ -0,0 +1,44 @@
1
+ /** `{ [productId]: quantity }`, as stored in the basket cookie. Prices always come from D1. */
2
+ export type Basket = Record<number, number>;
3
+
4
+ const MAX_LINES = 30;
5
+ const MAX_QUANTITY = 99;
6
+
7
+ /** The basket cookie's contents. Pure. */
8
+ export const BasketCookie = {
9
+ MAX_QUANTITY,
10
+
11
+ /** Adds `quantity` of a product, capped. Returns a new basket. */
12
+ add(basket: Basket, productId: number, quantity: number): Basket {
13
+ return { ...basket, [productId]: Math.min((basket[productId] ?? 0) + quantity, MAX_QUANTITY) };
14
+ },
15
+
16
+ /** A cookie value to a basket. Junk, bad ids and bad quantities are dropped, not thrown. */
17
+ parse(raw: string | undefined): Basket {
18
+ if (!raw) return {};
19
+ let parsed: unknown;
20
+ try {
21
+ parsed = JSON.parse(raw);
22
+ } catch {
23
+ return {};
24
+ }
25
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return {};
26
+
27
+ const basket: Basket = {};
28
+ for (const [key, value] of Object.entries(parsed).slice(0, MAX_LINES)) {
29
+ const id = Number(key);
30
+ if (Number.isInteger(id) && id > 0 && Number.isInteger(value) && value > 0) {
31
+ basket[id] = Math.min(value as number, MAX_QUANTITY);
32
+ }
33
+ }
34
+ return basket;
35
+ },
36
+
37
+ /** Sets a line's quantity; 0 removes it. Returns a new basket. */
38
+ set(basket: Basket, productId: number, quantity: number): Basket {
39
+ const next = { ...basket };
40
+ if (quantity === 0) delete next[productId];
41
+ else next[productId] = Math.min(quantity, MAX_QUANTITY);
42
+ return next;
43
+ },
44
+ };
@@ -1,19 +1,22 @@
1
1
  <script lang="ts">
2
+ import { ErrorMessage } from '../../utils/errors';
2
3
  import { resolve } from '$app/paths';
3
- import PageTitle from '../components/PageTitle.svelte';
4
+ import PageTitle from '../../ui/PageTitle.svelte';
4
5
  import {
6
+ basketQuantityForm,
5
7
  getBasket,
6
8
  getShippableCountries,
7
- setBasketQuantity,
8
9
  setShipTo,
9
- } from '../remote/basket.remote';
10
+ } from '../client.remote';
11
+ import { BasketQuantitySchema } from '../schema';
10
12
  import Minus from '@lucide/svelte/icons/minus';
11
13
  import Plus from '@lucide/svelte/icons/plus';
12
- import { shoppingClient } from '../client';
13
- import { productImageUrl } from '../images';
14
- import { formatMoney } from '../money';
14
+ import { shopContext } from '../../context';
15
+ import { Images } from '../../utils/images';
16
+ import { Money } from '../../utils/money';
15
17
  import { toast } from 'svelte-sonner';
16
18
  import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
19
+ import { Form } from '@zeyolabs/ui/form';
17
20
  import Button from '@zeyolabs/ui/form/Button.svelte';
18
21
  import { Select } from '@zeyolabs/ui/form/primitives';
19
22
  import SkeletonCard from '@zeyolabs/ui/skeleton/SkeletonCard.svelte';
@@ -21,7 +24,7 @@
21
24
  /** The app's own checkout remote function, which rate-limits before calling `createCheckout`. */
22
25
  let { startCheckout }: { startCheckout: () => Promise<{ url: string }> } = $props();
23
26
 
24
- const client = shoppingClient();
27
+ const context = shopContext();
25
28
  let paying = $state(false);
26
29
 
27
30
  async function checkout() {
@@ -30,7 +33,7 @@
30
33
  const { url } = await startCheckout();
31
34
  window.location.href = url;
32
35
  } catch (error) {
33
- toast.error(error instanceof Error ? error.message : 'Could not start checkout.');
36
+ toast.error(ErrorMessage.from(error, 'Could not start checkout.'));
34
37
  paying = false;
35
38
  }
36
39
  }
@@ -52,25 +55,33 @@
52
55
  <img
53
56
  class="size-20 object-cover"
54
57
  alt={line.cover.alt || line.name}
55
- src={productImageUrl(client.imageBaseUrl, line.cover.src)}
58
+ src={Images.url(context.imageBaseUrl, line.cover.src)}
56
59
  />
57
60
  {/if}
58
61
  <div class="min-w-0 flex-1">
59
62
  <a class="font-medium" href={resolve('/product/[slug]', { slug: line.slug })}>
60
63
  {line.name}
61
64
  </a>
62
- <p>{formatMoney(line.pricePence)}</p>
65
+ <p>{Money.format(line.pricePence)}</p>
63
66
  {#if line.available < line.quantity}
64
67
  <p class="text-sm text-[var(--danger)]">
65
68
  {line.available === 0 ? 'Out of stock' : `Only ${line.available} available`}
66
69
  </p>
67
70
  {/if}
68
71
  </div>
69
- <div class="flex items-center gap-2">
72
+ {const form = basketQuantityForm.for(line.id)}
73
+ <Form
74
+ class="flex items-center gap-2"
75
+ {form}
76
+ hidden={{ productId: line.id }}
77
+ reset={false}
78
+ schema={BasketQuantitySchema}
79
+ >
70
80
  <Button
81
+ {...form.fields.quantity.as('submit', line.quantity - 1)}
71
82
  aria-label="Decrease quantity of {line.name}"
83
+ {form}
72
84
  icon
73
- onclick={() => setBasketQuantity({ productId: line.id, quantity: line.quantity - 1 })}
74
85
  size="sm"
75
86
  variant="secondary"
76
87
  >
@@ -78,17 +89,18 @@
78
89
  </Button>
79
90
  <span class="w-6 text-center">{line.quantity}</span>
80
91
  <Button
92
+ {...form.fields.quantity.as('submit', line.quantity + 1)}
81
93
  aria-label="Increase quantity of {line.name}"
82
94
  disabled={line.quantity >= line.limit}
95
+ {form}
83
96
  icon
84
- onclick={() => setBasketQuantity({ productId: line.id, quantity: line.quantity + 1 })}
85
97
  size="sm"
86
98
  variant="secondary"
87
99
  >
88
100
  <Plus size={14} />
89
101
  </Button>
90
- </div>
91
- <p class="w-20 text-right">{formatMoney(line.lineTotalPence)}</p>
102
+ </Form>
103
+ <p class="w-20 text-right">{Money.format(line.lineTotalPence)}</p>
92
104
  </li>
93
105
  {/each}
94
106
  </ul>
@@ -109,17 +121,17 @@
109
121
 
110
122
  <dl class="mt-4 ml-auto grid max-w-xs grid-cols-2 gap-y-1">
111
123
  <dt>Subtotal</dt>
112
- <dd class="text-right">{formatMoney(summary.subtotalPence)}</dd>
124
+ <dd class="text-right">{Money.format(summary.subtotalPence)}</dd>
113
125
  <dt>Delivery</dt>
114
126
  <dd class="text-right">
115
127
  {summary.shipping === null
116
128
  ? '—'
117
129
  : summary.shippingPence === 0
118
130
  ? 'Free'
119
- : formatMoney(summary.shippingPence)}
131
+ : Money.format(summary.shippingPence)}
120
132
  </dd>
121
133
  <dt class="font-medium">Total</dt>
122
- <dd class="text-right font-medium">{formatMoney(summary.totalPence)}</dd>
134
+ <dd class="text-right font-medium">{Money.format(summary.totalPence)}</dd>
123
135
  </dl>
124
136
  {#if summary.shipping === null}
125
137
  <p class="mt-2 text-right text-sm text-[var(--danger)]">
@@ -132,7 +144,7 @@
132
144
  {/if}
133
145
  {#if summary.domestic && summary.shippingPence > 0}
134
146
  <p class="mt-2 text-right text-sm">
135
- Free UK delivery on orders of {formatMoney(summary.freeShippingFromPence)} or more.
147
+ Free UK delivery on orders of {Money.format(summary.freeShippingFromPence)} or more.
136
148
  </p>
137
149
  {/if}
138
150
 
@@ -0,0 +1,14 @@
1
+ import { Schema } from '@zeyolabs/kit/utils/schema';
2
+ import { z } from 'zod';
3
+
4
+ /** "Add to basket" on a product page. */
5
+ export const AddToBasketSchema = z.object({
6
+ productId: Schema.Id,
7
+ quantity: z.number().int().min(1).max(99).default(1),
8
+ });
9
+
10
+ /** The basket's − and + buttons: each submits the line's new quantity; 0 removes the line. */
11
+ export const BasketQuantitySchema = z.object({
12
+ productId: Schema.Id,
13
+ quantity: z.number().int().min(0).max(99),
14
+ });
@@ -0,0 +1,123 @@
1
+ import { and, asc, eq, inArray } from 'drizzle-orm';
2
+
3
+ import type { ShippingRules } from '../config';
4
+ import type { ShopDb } from '../db/index';
5
+ import type { Basket } from './library';
6
+
7
+ import { CoverService } from '../catalogue/covers.server';
8
+ import { products } from '../db/schema';
9
+ import { type ShippingQuote, ShippingService } from '../shipping/service.server';
10
+ import { StockService } from '../stock/service.server';
11
+
12
+ export type BasketLine = {
13
+ /** What the customer can actually buy right now: min(requested, sellable, max per order). */
14
+ available: number;
15
+ cover: null | { alt: string; src: string };
16
+ id: number;
17
+ /** The most of this product one order can hold: min(sellable, max per order). */
18
+ limit: number;
19
+ lineTotalPence: number;
20
+ massGrams: number;
21
+ name: string;
22
+ pricePence: number;
23
+ quantity: number;
24
+ sku: string;
25
+ slug: string;
26
+ /** Units that can be sold now (whole packs, or complete sets), not the raw stock count. */
27
+ stock: number;
28
+ };
29
+
30
+ export type BasketSummary = {
31
+ /** Total items in the basket, for the header badge. */
32
+ count: number;
33
+ country: string;
34
+ /** True when `country` is the shop's home country, where the free-delivery offer applies. */
35
+ domestic: boolean;
36
+ /** UK orders at or above this subtotal ship free. */
37
+ freeShippingFromPence: number;
38
+ lines: BasketLine[];
39
+ /** Null when nothing can ship to `country` for this basket. */
40
+ shipping: null | ShippingQuote;
41
+ shippingPence: number;
42
+ subtotalPence: number;
43
+ totalPence: number;
44
+ weightGrams: number;
45
+ };
46
+
47
+ /** Prices a basket from current catalogue data, with the shop's postage rules passed in. */
48
+ export class BasketService {
49
+ constructor(private readonly db: ShopDb) {}
50
+
51
+ /** 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> {
53
+ const offer = {
54
+ domestic: country === rules.defaultCountry,
55
+ freeShippingFromPence: rules.freeUkFromPence,
56
+ };
57
+ const ids = Object.keys(basket).map(Number);
58
+ if (ids.length === 0) {
59
+ return {
60
+ count: 0,
61
+ country,
62
+ ...offer,
63
+ lines: [],
64
+ shipping: null,
65
+ shippingPence: 0,
66
+ subtotalPence: 0,
67
+ totalPence: 0,
68
+ weightGrams: 0,
69
+ };
70
+ }
71
+
72
+ const rows = await this.db
73
+ .select()
74
+ .from(products)
75
+ .where(and(inArray(products.id, ids), eq(products.active, true)))
76
+ .orderBy(asc(products.name));
77
+ const stock = new StockService(this.db);
78
+ const sellable = await stock.availableMany(rows.map((p) => p.id));
79
+ const covers = new CoverService(this.db);
80
+ const cover = await covers.covers(rows.map((p) => p.id));
81
+
82
+ const lines = rows.map((product): BasketLine => {
83
+ const quantity = basket[product.id];
84
+ const inStock = sellable.get(product.id) ?? 0;
85
+ const available = Math.max(0, Math.min(quantity, inStock, product.maxPerOrder));
86
+ const image = cover.get(product.id);
87
+ return {
88
+ available,
89
+ cover: image ?? null,
90
+ id: product.id,
91
+ limit: Math.max(0, Math.min(inStock, product.maxPerOrder)),
92
+ lineTotalPence: available * product.pricePence,
93
+ massGrams: product.massGrams,
94
+ name: product.name,
95
+ pricePence: product.pricePence,
96
+ quantity,
97
+ sku: product.sku,
98
+ slug: product.slug,
99
+ stock: inStock,
100
+ };
101
+ });
102
+
103
+ const subtotalPence = lines.reduce((sum, line) => sum + line.lineTotalPence, 0);
104
+ const weightGrams = lines.reduce((sum, line) => sum + line.available * line.massGrams, 0);
105
+ const shippingService = new ShippingService(this.db);
106
+ const shipping =
107
+ subtotalPence > 0
108
+ ? await shippingService.quote(rules, { country, subtotalPence, weightGrams })
109
+ : null;
110
+ const shippingPence = shipping?.pricePence ?? 0;
111
+ return {
112
+ count: lines.reduce((sum, line) => sum + line.quantity, 0),
113
+ country,
114
+ ...offer,
115
+ lines,
116
+ shipping,
117
+ shippingPence,
118
+ subtotalPence,
119
+ totalPence: subtotalPence + shippingPence,
120
+ weightGrams,
121
+ };
122
+ }
123
+ }
@@ -0,0 +1,24 @@
1
+ <script lang="ts">
2
+ import { resolve } from '$app/paths';
3
+ import { getAdminBundle } from '../admin.remote';
4
+ import BundleForm from './BundleForm.svelte';
5
+ import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
6
+
7
+ /** The bundle to edit; leave out for a new one. */
8
+ let { id }: { id?: number } = $props();
9
+ </script>
10
+
11
+ <svelte:head><title>{id ? 'Edit bundle' : 'New bundle'} · Admin</title></svelte:head>
12
+
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>
15
+
16
+ <Boundary message="Could not load the bundle." statusMessages={{ 404: 'Bundle not found.' }}>
17
+ {let bundle = $derived(id ? await getAdminBundle(id) : null)}
18
+ {#key bundle?.id}
19
+ <BundleForm {bundle} />
20
+ {/key}
21
+ {#snippet pending()}
22
+ <p class="text-[var(--ink-muted)]">Loading…</p>
23
+ {/snippet}
24
+ </Boundary>
@@ -0,0 +1,107 @@
1
+ <script lang="ts">
2
+ import { goto } from '$app/navigation';
3
+ import { resolve } from '$app/paths';
4
+ import type { getAdminBundle } from '../admin.remote';
5
+ import { saveBundleForm } from '../admin.remote';
6
+ 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
+
11
+ type Bundle = Awaited<ReturnType<typeof getAdminBundle>>;
12
+
13
+ let { bundle }: { bundle: Bundle | null } = $props();
14
+
15
+ const context = shopContext();
16
+ // The page re-creates this component per bundle ({#key}), so reading the prop once is right.
17
+ // svelte-ignore state_referenced_locally
18
+ const b = bundle;
19
+ const form = saveBundleForm.for(b?.id ?? 'new');
20
+ const { steps } = form.fields;
21
+ const stepRows = $derived(steps.value() ?? []);
22
+ const newStep = { description: '', maxChoices: 1, minChoices: 1, skus: '', title: '' };
23
+
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';
26
+ </script>
27
+
28
+ <Form
29
+ class="grid max-w-3xl gap-6"
30
+ defaults={{
31
+ active: b?.active ?? false,
32
+ description: b?.description ?? '',
33
+ image: b?.image ?? '',
34
+ name: b?.name ?? '',
35
+ slug: b?.slug ?? '',
36
+ sortOrder: b?.sortOrder ?? 0,
37
+ steps: b?.steps.map((s) => ({ ...s, skus: s.skus.join('\n') })) ?? [newStep],
38
+ }}
39
+ {form}
40
+ hidden={{ id: b?.id }}
41
+ onSuccess={(data) => {
42
+ if (!b) goto(resolve('/bundles/[id]', { id: String(data.id) }));
43
+ }}
44
+ reset={false}
45
+ schema={BundleFormSchema}
46
+ >
47
+ <section class={section}>
48
+ <TextField name="name" {form}>Name</TextField>
49
+ <div class="grid gap-4 sm:grid-cols-2">
50
+ <TextField name="slug" {form} optional placeholder="made from the name">Slug (URL)</TextField>
51
+ <TextField name="image" {form} optional>Image file name</TextField>
52
+ </div>
53
+ <MessageField name="description" {form} optional>Description</MessageField>
54
+ <div class="grid gap-4 sm:grid-cols-2">
55
+ <NumberField name="sortOrder" {form} inputmode="numeric">Sort order</NumberField>
56
+ <CheckboxField name="active" {form}>On sale in the shop</CheckboxField>
57
+ </div>
58
+ </section>
59
+
60
+ {#each stepRows as _, i (i)}
61
+ <section class={section}>
62
+ <div class="flex items-center justify-between">
63
+ <h2 class="font-semibold">Step {i + 1}</h2>
64
+ {#if stepRows.length > 1}
65
+ <Button
66
+ onclick={() => steps.set(stepRows.filter((_, j) => j !== i))}
67
+ size="sm"
68
+ variant="secondary">Remove step</Button
69
+ >
70
+ {/if}
71
+ </div>
72
+ <label class="text-sm font-medium">
73
+ Title, e.g. "Choose your switches"
74
+ <input {...steps[i].title.as('text')} class={input} />
75
+ </label>
76
+ <label class="text-sm font-medium">
77
+ Help text (optional)
78
+ <input {...steps[i].description.as('text')} class={input} />
79
+ </label>
80
+ <div class="grid gap-4 sm:grid-cols-2">
81
+ <label class="text-sm font-medium">
82
+ Fewest picks (0 = optional)
83
+ <input {...steps[i].minChoices.as('number')} class={input} min="0" />
84
+ </label>
85
+ <label class="text-sm font-medium">
86
+ Most picks
87
+ <input {...steps[i].maxChoices.as('number')} class={input} min="1" />
88
+ </label>
89
+ </div>
90
+ <label class="text-sm font-medium">
91
+ Products offered, one SKU per line
92
+ <textarea {...steps[i].skus.as('text')} class="{input} min-h-28 font-mono"></textarea>
93
+ </label>
94
+ </section>
95
+ {/each}
96
+ <div>
97
+ <Button onclick={() => steps.set([...stepRows, newStep])} variant="secondary">Add step</Button>
98
+ </div>
99
+
100
+ <div class="flex items-center gap-4">
101
+ <Button {form} loadingMessage="Saving…">Save bundle</Button>
102
+ {#if b?.active}
103
+ <!-- eslint-disable-next-line svelte/no-navigation-without-resolve -- the shop's own domain -->
104
+ <a href="{context.siteUrl}/bundle/{b.slug}" rel="noopener" target="_blank">View in shop</a>
105
+ {/if}
106
+ </div>
107
+ </Form>
@@ -0,0 +1,40 @@
1
+ <script lang="ts">
2
+ import { resolve } from '$app/paths';
3
+ import { getAdminBundles } from '../admin.remote';
4
+ import Badge from '@zeyolabs/ui/badge/Badge.svelte';
5
+ import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
6
+ </script>
7
+
8
+ <svelte:head><title>Bundles · Admin</title></svelte:head>
9
+
10
+ <p class="text-sm"><a href={resolve('/products')}>← Products</a></p>
11
+ <div class="mt-2 flex items-center justify-between">
12
+ <h1 class="text-2xl font-semibold">Bundles</h1>
13
+ <a
14
+ class="rounded-md bg-[var(--leaf-dark)] px-3 py-1.5 text-sm text-white no-underline"
15
+ href={resolve('/bundles/new')}>New bundle</a
16
+ >
17
+ </div>
18
+ <p class="mt-1 text-sm text-[var(--ink-muted)]">
19
+ A bundle is built in steps; the customer's picks go into the basket as ordinary products at their
20
+ own prices. Use a Stripe promotion code for a bundle discount.
21
+ </p>
22
+
23
+ <Boundary message="Could not load bundles.">
24
+ {let rows = $derived(await getAdminBundles())}
25
+ <ul class="mt-4 divide-y divide-[var(--line)] rounded-xl border border-[var(--line)] bg-white">
26
+ {#each rows as row (row.id)}
27
+ <li class="px-4 py-2 text-sm">
28
+ <a class="font-medium" href={resolve('/bundles/[id]', { id: String(row.id) })}>{row.name}</a
29
+ >
30
+ <span class="text-[var(--ink-muted)]">/bundle/{row.slug}</span>
31
+ {#if !row.active}<Badge color="neutral">inactive</Badge>{/if}
32
+ </li>
33
+ {:else}
34
+ <li class="px-4 py-6 text-[var(--ink-muted)]">No bundles yet.</li>
35
+ {/each}
36
+ </ul>
37
+ {#snippet pending()}
38
+ <p class="mt-6 text-[var(--ink-muted)]">Loading…</p>
39
+ {/snippet}
40
+ </Boundary>
@@ -0,0 +1,30 @@
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
+
6
+ import { shopping } from '../config';
7
+ import { BundleFormSchema } from './schema';
8
+ import { BundleService } from './service.server';
9
+
10
+ const bundles = () => new BundleService(shopping().db());
11
+
12
+ export const getAdminBundles = Remote.Query(() => {
13
+ const service = bundles();
14
+ return service.list();
15
+ });
16
+
17
+ export const getAdminBundle = Remote.Query(Schema.Id, async (id) => {
18
+ const service = bundles();
19
+ const bundle = await service.forEdit(id);
20
+ if (!bundle) throw Error404('Bundle not found.');
21
+ return bundle;
22
+ });
23
+
24
+ /** Saves a bundle and all its steps; `data.id` is its id (new bundles get one here). */
25
+ export const saveBundleForm = Remote.Form(BundleFormSchema, async (input) => {
26
+ const service = bundles();
27
+ const id = await service.save(input);
28
+ await Promise.all([getAdminBundles().refresh(), getAdminBundle(id).refresh()]);
29
+ return FormResult.okData({ data: { id }, message: 'Bundle saved.' });
30
+ });