@zeyolabs/shopping 2026.11.42 → 2026.11.44

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.
@@ -50,6 +50,8 @@
50
50
 
51
51
  <Boundary message="Could not load your basket.">
52
52
  {let [summary, countries] = $derived(await Promise.all([getBasket(), getShippableCountries()]))}
53
+ <!-- Some services cost more: the customer picks one on Stripe's page, so totals start "from". -->
54
+ {let dearer = $derived(summary.shippingOptions.some((o) => o.pricePence > summary.shippingPence))}
53
55
 
54
56
  {#if summary.lines.length === 0 && summary.bundles.length === 0}
55
57
  <Text>Your basket is empty.</Text>
@@ -181,7 +183,7 @@
181
183
  <dl class="mt-4 ml-auto grid max-w-xs grid-cols-2 gap-y-1">
182
184
  <dt>Subtotal</dt>
183
185
  <dd class="text-right">{Money.format(summary.subtotalPence)}</dd>
184
- <dt>Delivery</dt>
186
+ <dt>Delivery{dearer ? ' from' : ''}</dt>
185
187
  <dd class="text-right">
186
188
  {summary.shipping === null
187
189
  ? '—'
@@ -189,13 +191,17 @@
189
191
  ? 'Free'
190
192
  : Money.format(summary.shippingPence)}
191
193
  </dd>
192
- <dt><Span bold>Total</Span></dt>
194
+ <dt><Span bold>Total{dearer ? ' from' : ''}</Span></dt>
193
195
  <dd class="text-right"><Span bold>{Money.format(summary.totalPence)}</Span></dd>
194
196
  </dl>
195
197
  {#if summary.shipping === null}
196
198
  <Text class="mt-2 text-right" color="error">
197
199
  We cannot ship this order to the selected country.
198
200
  </Text>
201
+ {:else if summary.shippingOptions.length > 1}
202
+ <Text class="mt-2 text-right">
203
+ Choose {summary.shippingOptions.map((option) => option.name).join(', ')} at checkout.
204
+ </Text>
199
205
  {:else}
200
206
  <Text class="mt-2 text-right">
201
207
  {summary.shipping.name}, {summary.shipping.deliveryTime}.
@@ -59,8 +59,11 @@ export type BasketSummary = {
59
59
  /** UK orders at or above this subtotal ship free. */
60
60
  freeShippingFromPence: number;
61
61
  lines: BasketLine[];
62
- /** Null when nothing can ship to `country` for this basket. */
62
+ /** The cheapest option; null when nothing can ship to `country` for this basket. */
63
63
  shipping: null | ShippingQuote;
64
+ /** Every service that can send it, cheapest first; the customer picks one at checkout. */
65
+ shippingOptions: ShippingQuote[];
66
+ /** The cheapest option's price, so `totalPence` is the lowest the order can cost. */
64
67
  shippingPence: number;
65
68
  subtotalPence: number;
66
69
  totalPence: number;
@@ -91,6 +94,7 @@ export class BasketService {
91
94
  ...offer,
92
95
  lines: [],
93
96
  shipping: null,
97
+ shippingOptions: [],
94
98
  shippingPence: 0,
95
99
  subtotalPence: 0,
96
100
  totalPence: 0,
@@ -138,10 +142,11 @@ export class BasketService {
138
142
  lines.reduce((sum, line) => sum + line.available * line.massGrams, 0) +
139
143
  ready.reduce((sum, b) => sum + b.massGrams, 0);
140
144
  const shippingService = new ShippingService(this.db);
141
- const shipping =
145
+ const shippingOptions =
142
146
  subtotalPence > 0
143
- ? await shippingService.quote(rules, { country, subtotalPence, weightGrams })
144
- : null;
147
+ ? await shippingService.quotes(rules, { country, subtotalPence, weightGrams })
148
+ : [];
149
+ const shipping = shippingOptions[0] ?? null;
145
150
  const shippingPence = shipping?.pricePence ?? 0;
146
151
  return {
147
152
  bundles: bundleLines,
@@ -150,6 +155,7 @@ export class BasketService {
150
155
  ...offer,
151
156
  lines,
152
157
  shipping,
158
+ shippingOptions,
153
159
  shippingPence,
154
160
  subtotalPence,
155
161
  totalPence: subtotalPence + shippingPence,
@@ -101,7 +101,6 @@ function sessionParams(
101
101
 
102
102
  metadata: {
103
103
  country: summary.country,
104
- shippingService: summary.shipping.service,
105
104
  weightGrams: String(summary.weightGrams),
106
105
  },
107
106
  mode: 'payment',
@@ -111,16 +110,16 @@ function sessionParams(
111
110
  summary.country as Stripe.Checkout.SessionCreateParams.ShippingAddressCollection.AllowedCountry,
112
111
  ],
113
112
  },
114
- shipping_options: [
115
- {
116
- shipping_rate_data: {
117
- display_name:
118
- summary.shippingPence === 0 ? `Free ${summary.shipping.name}` : summary.shipping.name,
119
- fixed_amount: { amount: summary.shippingPence, currency: 'gbp' },
120
- type: 'fixed_amount',
121
- },
113
+ // The customer picks one on Stripe's page; the first is preselected. Each carries its service,
114
+ // which `OrderManager.fulfil` reads back from the chosen rate.
115
+ shipping_options: summary.shippingOptions.map((option) => ({
116
+ shipping_rate_data: {
117
+ display_name: option.pricePence === 0 ? `Free ${option.name}` : option.name,
118
+ fixed_amount: { amount: option.pricePence, currency: 'gbp' },
119
+ metadata: { service: option.service },
120
+ type: 'fixed_amount',
122
121
  },
123
- ],
122
+ })),
124
123
  success_url: `${origin}/checkout/complete?session_id={CHECKOUT_SESSION_ID}`,
125
124
  };
126
125
  }
@@ -5,6 +5,11 @@ import { PACKAGE_FORMATS } from '../db/schema';
5
5
  import { FormInput } from '../utils/form-input';
6
6
  import { BULK_DISPATCH_LIMIT, ORDER_FILTERS } from './filters';
7
7
 
8
+ /** The shop's own numbers (`KC-7F3K9Q`), or a number kept from an imported legacy shop. */
9
+ export const OrderNumber = z
10
+ .string()
11
+ .regex(/^(?:[A-Z]{2,5}-[A-Z0-9]{6}|[A-Z0-9]{8,20})$/, 'invalid order number');
12
+
8
13
  export const OrderListSchema = z.object({
9
14
  filter: z.enum(ORDER_FILTERS).default('to-ship'),
10
15
  q: z.string().max(100).default(''),
@@ -12,7 +17,7 @@ export const OrderListSchema = z.object({
12
17
 
13
18
  /** Royal Mail tracking numbers are letters and digits (e.g. AB123456789GB); blank means untracked. */
14
19
  export const ShipSchema = z.object({
15
- number: z.string().regex(/^[A-Z]{2,5}-[A-Z0-9]{6}$/, 'invalid order number'),
20
+ number: OrderNumber,
16
21
  /** Tick to dispatch without emailing the customer (e.g. the email already went another way). */
17
22
  skipEmail: SchemaForm.Boolean,
18
23
  trackingNumber: z
@@ -26,8 +31,6 @@ export const ShipSchema = z.object({
26
31
  ),
27
32
  });
28
33
 
29
- export const OrderNumber = z.string().regex(/^[A-Z]{2,5}-[A-Z0-9]{6}$/, 'invalid order number');
30
-
31
34
  export const ORDER_STEPS = ['start', 'pack', 'hold', 'release'] as const;
32
35
  export type OrderStep = (typeof ORDER_STEPS)[number];
33
36
 
package/orders/library.ts CHANGED
@@ -1,8 +1,25 @@
1
1
  // No 0/O/1/I: the number is read out over the phone.
2
2
  const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
3
3
 
4
+ /** Just what `chosenService` reads of a Checkout Session. */
5
+ type SessionShipping = {
6
+ metadata: null | Record<string, string>;
7
+ shipping_cost: null | { shipping_rate: null | string | { metadata: Record<string, string> } };
8
+ };
9
+
4
10
  /** Order numbers and links. Pure (apart from the random number). */
5
11
  export const Orders = {
12
+ /**
13
+ * The postage service the customer chose at checkout: the chosen rate's `service` (fetched with
14
+ * `shipping_cost.shipping_rate` expanded). Sessions started before customers could choose kept it
15
+ * in the session's metadata.
16
+ */
17
+ chosenService(session: SessionShipping): null | string {
18
+ const rate = session.shipping_cost?.shipping_rate;
19
+ const chosen = rate && typeof rate === 'object' ? rate.metadata.service : undefined;
20
+ return chosen ?? session.metadata?.shippingService ?? null;
21
+ },
22
+
6
23
  /** A new public order number, e.g. `PL-ABC234`. */
7
24
  newNumber(prefix: string): string {
8
25
  const bytes = crypto.getRandomValues(new Uint8Array(6));
@@ -25,7 +25,7 @@ export const OrderManager = {
25
25
  if (order && (await service.hasItems(order.id))) return;
26
26
 
27
27
  const session = await ShopClients.stripe().checkout.sessions.retrieve(sessionId, {
28
- expand: ['line_items.data.price.product'],
28
+ expand: ['line_items.data.price.product', 'shipping_cost.shipping_rate'],
29
29
  });
30
30
  if (session.payment_status !== 'paid') return;
31
31
 
@@ -42,7 +42,7 @@ export const OrderManager = {
42
42
  number: Orders.newNumber(config.orderNumberPrefix),
43
43
  paidAt: Date.now(),
44
44
  shippingPence: session.total_details?.amount_shipping ?? 0,
45
- shippingService: session.metadata?.shippingService ?? null,
45
+ shippingService: Orders.chosenService(session),
46
46
  status: 'paid',
47
47
  stripeInvoiceId: typeof session.invoice === 'string' ? session.invoice : null,
48
48
  stripePaymentIntentId:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeyolabs/shopping",
3
- "version": "2026.11.42",
3
+ "version": "2026.11.44",
4
4
  "description": "Shop and order fulfilment for SvelteKit 3 on Cloudflare: catalogue, basket, Stripe Checkout, orders, Royal Mail Click & Drop, order emails, packing, pages and admin.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -14,6 +14,11 @@ export type ShippingQuote = {
14
14
  service: string;
15
15
  };
16
16
 
17
+ type QuoteInput = { country: string; subtotalPence: number; weightGrams: number };
18
+
19
+ /** Stripe Checkout offers at most this many shipping options. */
20
+ export const MAX_SHIPPING_OPTIONS = 5;
21
+
17
22
  /** Countries and postage rates: data access, with the shop's postage rules passed in. */
18
23
  export class ShippingService {
19
24
  constructor(private readonly db: ShopDb) {}
@@ -27,18 +32,23 @@ export class ShippingService {
27
32
  .orderBy(asc(countries.name));
28
33
  }
29
34
 
35
+ /** The cheapest postage for this parcel, or null when nothing can send it (see `quotes`). */
36
+ async quote(rules: ShippingRules, input: QuoteInput): Promise<null | ShippingQuote> {
37
+ const [cheapest] = await this.quotes(rules, input);
38
+ return cheapest ?? null;
39
+ }
40
+
30
41
  /**
31
- * The cheapest postage for a parcel of `weightGrams` to `country`, or null when that country
32
- * isn't enabled, the parcel is heavier than every band, or the order value rules postage out.
42
+ * Every service that can send a parcel of `weightGrams` to `country`, each at its cheapest band,
43
+ * cheapest first: at most `MAX_SHIPPING_OPTIONS`, the most Stripe Checkout offers. Empty when
44
+ * that country isn't enabled, the parcel is heavier than every band, or the order value rules
45
+ * postage out.
33
46
  */
34
- async quote(
35
- rules: ShippingRules,
36
- input: { country: string; subtotalPence: number; weightGrams: number }
37
- ): Promise<null | ShippingQuote> {
47
+ async quotes(rules: ShippingRules, input: QuoteInput): Promise<ShippingQuote[]> {
38
48
  const country = await this.db.query.countries.findFirst({
39
49
  where: and(eq(countries.code, input.country), eq(countries.enabled, true)),
40
50
  });
41
- if (!country) return null;
51
+ if (!country) return [];
42
52
 
43
53
  const bands = await this.db
44
54
  .select()
@@ -46,24 +56,27 @@ export class ShippingService {
46
56
  .where(
47
57
  and(eq(shippingRates.zone, country.zone), gte(shippingRates.maxGrams, input.weightGrams))
48
58
  )
49
- .orderBy(asc(shippingRates.pricePence));
50
- const rate = bands[0];
51
- if (!rate) return null;
52
-
53
- const pricePence = Postage.charge(rules, {
54
- basePence: rate.pricePence,
55
- subtotalPence: input.subtotalPence,
56
- zone: country.zone,
57
- });
58
- if (pricePence === null) return null;
59
-
60
- return {
61
- deliveryTime: rate.deliveryTime,
62
- name: rate.name,
63
- pricePence,
64
- royalMailServiceCode: rate.royalMailServiceCode,
65
- service: rate.service,
66
- };
59
+ .orderBy(asc(shippingRates.pricePence), asc(shippingRates.maxGrams));
60
+ const seen = new Set<string>();
61
+ const quotes: ShippingQuote[] = [];
62
+ for (const rate of bands) {
63
+ if (seen.has(rate.service)) continue;
64
+ seen.add(rate.service);
65
+ const pricePence = Postage.charge(rules, {
66
+ basePence: rate.pricePence,
67
+ subtotalPence: input.subtotalPence,
68
+ zone: country.zone,
69
+ });
70
+ if (pricePence === null) return [];
71
+ quotes.push({
72
+ deliveryTime: rate.deliveryTime,
73
+ name: rate.name,
74
+ pricePence,
75
+ royalMailServiceCode: rate.royalMailServiceCode,
76
+ service: rate.service,
77
+ });
78
+ }
79
+ return quotes.slice(0, MAX_SHIPPING_OPTIONS);
67
80
  }
68
81
 
69
82
  /** The Click & Drop service code configured for a chosen service, if any. */