@zeyolabs/shopping 2026.11.44 → 2026.11.46

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.
@@ -14,8 +14,6 @@ export type ClickAndDropOrder = {
14
14
  state?: null | string;
15
15
  };
16
16
  createdAt: number;
17
- /** Parcel size in mm; sent only when all three are known. */
18
- dimensions?: null | { heightMm: number; lengthMm: number; widthMm: number };
19
17
  email: string;
20
18
  number: string;
21
19
  /** Click & Drop package format; a plain parcel unless packing says otherwise. */
@@ -68,15 +66,6 @@ async function createOrder(apiKey: string, order: ClickAndDropOrder): Promise<st
68
66
  orderReference: order.number,
69
67
  packages: [
70
68
  {
71
- ...(order.dimensions
72
- ? {
73
- dimensions: {
74
- depthInMms: order.dimensions.lengthMm,
75
- heightInMms: order.dimensions.heightMm,
76
- widthInMms: order.dimensions.widthMm,
77
- },
78
- }
79
- : {}),
80
69
  packageFormatIdentifier: order.packageFormat ?? 'parcel',
81
70
  weightInGrams: order.weightGrams,
82
71
  },
@@ -130,12 +119,17 @@ async function trackingNumber(apiKey: string, orderId: string): Promise<string |
130
119
  return order?.trackingNumber || undefined;
131
120
  }
132
121
 
133
- /** The postage label (with the customs form when the destination needs one) as a PDF. */
134
- async function label(apiKey: string, orderId: string): Promise<ArrayBuffer> {
122
+ /**
123
+ * The postage label (with the customs form when the destination needs one) as a PDF, or null when
124
+ * the account may not download labels: the API serves them to Online Business Account customers
125
+ * only (403), so everyone else prints from Click & Drop itself.
126
+ */
127
+ async function label(apiKey: string, orderId: string): Promise<ArrayBuffer | null> {
135
128
  const response = await fetch(
136
129
  `${ORDERS_URL}/${encodeURIComponent(orderId)}/label?documentType=postageLabel&includeReturnsLabel=false&includeCN=true`,
137
130
  { headers: headers(apiKey, { Accept: 'application/pdf' }) }
138
131
  );
132
+ if (response.status === 403) return null;
139
133
  if (!response.ok)
140
134
  throw new Error(`Click & Drop label for order ${orderId} failed (${response.status})`);
141
135
  return response.arrayBuffer();
@@ -155,8 +149,8 @@ export class RoyalMailClient {
155
149
  return deleteOrder(this.apiKey, orderId);
156
150
  }
157
151
 
158
- /** The postage label (and customs form when needed) as a PDF. */
159
- label(orderId: string): Promise<ArrayBuffer> {
152
+ /** The postage label (and customs form when needed) as a PDF; null if the account may not. */
153
+ label(orderId: string): Promise<ArrayBuffer | null> {
160
154
  return label(this.apiKey, orderId);
161
155
  }
162
156
 
package/db/schema.ts CHANGED
@@ -180,13 +180,7 @@ export const ORDER_STATUSES = ['pending', 'paid', 'shipped', 'cancelled', 'refun
180
180
  export type OrderStatus = (typeof ORDER_STATUSES)[number];
181
181
 
182
182
  /** Click & Drop package formats a parcel can be sent as. */
183
- export const PACKAGE_FORMATS = [
184
- 'smallParcel',
185
- 'mediumParcel',
186
- 'parcel',
187
- 'largeLetter',
188
- 'letter',
189
- ] as const;
183
+ export const PACKAGE_FORMATS = ['letter', 'largeLetter', 'smallParcel', 'parcel'] as const;
190
184
  export type PackageFormat = (typeof PACKAGE_FORMATS)[number];
191
185
 
192
186
  /** Guest checkout: an order belongs to an email address, not an account. */
@@ -213,9 +207,6 @@ export const orders = sqliteTable(
213
207
  number: text('number').notNull().unique(),
214
208
  /** Parcel size in mm, as measured when packing. All three or none. */
215
209
  packageFormat: text('package_format', { enum: PACKAGE_FORMATS }).notNull().default('parcel'),
216
- packageHeightMm: integer('package_height_mm'),
217
- packageLengthMm: integer('package_length_mm'),
218
- packageWidthMm: integer('package_width_mm'),
219
210
  /** When the parcel was packed. Dispatching fills it in if the step was skipped. */
220
211
  packedAt: integer('packed_at'),
221
212
  /** When someone started packing it, so two people don't pack the same order. */
@@ -11,10 +11,12 @@
11
11
  import Title from '@zeyolabs/ui/text/Title.svelte';
12
12
  import { toast } from 'svelte-sonner';
13
13
 
14
+ import { shopContext } from '../../context';
14
15
  import { PACKAGE_FORMATS } from '../../db/schema';
15
16
  import { Orders } from '../../orders/library';
16
17
  import { ErrorMessage } from '../../utils/errors';
17
18
  import { FormInput } from '../../utils/form-input';
19
+ import { Images } from '../../utils/images';
18
20
  import { Money } from '../../utils/money';
19
21
  import {
20
22
  createOrderLabel,
@@ -35,16 +37,18 @@
35
37
  ShipSchema,
36
38
  } from '../schema';
37
39
 
40
+ const context = shopContext();
38
41
  const number = $derived(page.params.number ?? '');
39
42
 
40
43
  let printing = $state(false);
41
44
 
42
- /** Creates the label in Click & Drop, then opens the PDF to print. */
45
+ /** Creates the label in Click & Drop, then opens the PDF to print when Royal Mail serves it. */
43
46
  async function printLabel(orderNumber: string) {
44
47
  printing = true;
45
48
  try {
46
- await createOrderLabel(orderNumber);
47
- window.open(resolve('/orders/[number]/label', { number: orderNumber }), '_blank');
49
+ const { pdf, royalMailOrderId } = await createOrderLabel(orderNumber);
50
+ if (pdf) window.open(resolve('/orders/[number]/label', { number: orderNumber }), '_blank');
51
+ else toast.success(`In Click & Drop as order ${royalMailOrderId}. Print the label there.`);
48
52
  } catch (error) {
49
53
  toast.error(ErrorMessage.from(error, 'Could not create the label.'));
50
54
  } finally {
@@ -110,9 +114,20 @@
110
114
  <ul class="mt-2 divide-y divide-[var(--bd)]">
111
115
  {#each order.items as item (item.id)}
112
116
  <li class="py-2">
113
- <Cluster gap="sm" justify="between" nowrap>
114
- <Span>{item.name} <Span color="secondary">× {item.quantity}</Span></Span>
115
- <Span>{Money.format(item.quantity * item.unitPricePence)}</Span>
117
+ <Cluster gap="sm" nowrap>
118
+ {#if item.cover}
119
+ <img
120
+ class="size-14 shrink-0 rounded-md object-cover"
121
+ alt={item.cover.alt || item.name}
122
+ src={Images.url(context.imageBaseUrl, item.cover.src)}
123
+ />
124
+ {:else}
125
+ <div class="size-14 shrink-0 rounded-md bg-[var(--bd)]"></div>
126
+ {/if}
127
+ <Cluster class="grow" gap="sm" justify="between" nowrap>
128
+ <Span>{item.name} <Span color="secondary">× {item.quantity}</Span></Span>
129
+ <Span>{Money.format(item.quantity * item.unitPricePence)}</Span>
130
+ </Cluster>
116
131
  </Cluster>
117
132
  </li>
118
133
  {/each}
@@ -217,16 +232,13 @@
217
232
  <Text class="mt-1" color="secondary">
218
233
  {order.weightGrams === null
219
234
  ? `Estimated ${order.estimatedWeightGrams} g from the items. Weigh the parcel and correct it.`
220
- : 'Weight and size go on the Royal Mail label.'}
235
+ : 'Weight and format go on the Royal Mail label.'}
221
236
  </Text>
222
237
  <Form
223
238
  class="mt-3 grid gap-4"
224
239
  defaults={{
225
240
  format: order.packageFormat,
226
- heightMm: order.packageHeightMm ?? undefined,
227
- lengthMm: order.packageLengthMm ?? undefined,
228
241
  weightGrams: order.weightGrams ?? (order.estimatedWeightGrams || undefined),
229
- widthMm: order.packageWidthMm ?? undefined,
230
242
  }}
231
243
  form={parcelForm}
232
244
  hidden={{ number: order.number }}
@@ -243,17 +255,6 @@
243
255
  items={PACKAGE_FORMATS}
244
256
  placeholder="Package format"
245
257
  />
246
- <div class="grid grid-cols-3 gap-3">
247
- <NumberField name="lengthMm" form={parcelForm} inputmode="numeric" optional>
248
- Length (mm)
249
- </NumberField>
250
- <NumberField name="widthMm" form={parcelForm} inputmode="numeric" optional>
251
- Width (mm)
252
- </NumberField>
253
- <NumberField name="heightMm" form={parcelForm} inputmode="numeric" optional>
254
- Height (mm)
255
- </NumberField>
256
- </div>
257
258
  <div><Button form={parcelForm}>Save parcel</Button></div>
258
259
  </Form>
259
260
  </section>
@@ -53,20 +53,11 @@ export const updateOrderForm = Remote.Form(OrderStepSchema, async ({ number, ste
53
53
  return FormResult.ok(STEP_MESSAGES[step]);
54
54
  });
55
55
 
56
- export const parcelForm = Remote.Form(
57
- ParcelSchema,
58
- async ({ format, number, weightGrams, ...size }) => {
59
- await FulfilmentManager.saveParcel(number, {
60
- format,
61
- heightMm: size.heightMm ?? null,
62
- lengthMm: size.lengthMm ?? null,
63
- weightGrams,
64
- widthMm: size.widthMm ?? null,
65
- });
66
- await getOrder(number).refresh();
67
- return FormResult.ok('Parcel details saved.');
68
- }
69
- );
56
+ export const parcelForm = Remote.Form(ParcelSchema, async ({ format, number, weightGrams }) => {
57
+ await FulfilmentManager.saveParcel(number, { format, weightGrams });
58
+ await getOrder(number).refresh();
59
+ return FormResult.ok('Parcel details saved.');
60
+ });
70
61
 
71
62
  export const getShippingServices = Remote.Query(() => FulfilmentManager.shippingServices());
72
63
 
@@ -80,10 +71,14 @@ export const detailsForm = Remote.Form(OrderDetailsSchema, async ({ number, ...d
80
71
  );
81
72
  });
82
73
 
83
- /** Creates the label in Click & Drop. The page then opens it from `/orders/<number>/label`. */
74
+ /**
75
+ * Creates the label in Click & Drop. With `pdf` the page opens it from `/orders/<number>/label`;
76
+ * without, the account prints from Click & Drop itself.
77
+ */
84
78
  export const createOrderLabel = Remote.Cmd(OrderNumber, async (number) => {
85
- await FulfilmentManager.createLabel(number);
79
+ const label = await FulfilmentManager.createLabel(number);
86
80
  await getOrder(number).refresh();
81
+ return label;
87
82
  });
88
83
 
89
84
  export const refundForm = Remote.Form(RefundSchema, async ({ amount, number }) => {
@@ -17,7 +17,6 @@ export const Packing = {
17
17
  FORMAT_LABELS: {
18
18
  largeLetter: 'Large letter',
19
19
  letter: 'Letter',
20
- mediumParcel: 'Medium parcel',
21
20
  parcel: 'Parcel',
22
21
  smallParcel: 'Small parcel',
23
22
  } satisfies Record<PackageFormat, string>,
@@ -54,20 +54,18 @@ export const FulfilmentManager = {
54
54
  if (order.status !== 'paid') {
55
55
  throw Error400(`This order is ${order.status}, so it cannot have a label.`);
56
56
  }
57
- if (order.labelCreatedAt && order.royalMailOrderId) return;
57
+ const client = ShopClients.royalMail();
58
+ if (order.labelCreatedAt && order.royalMailOrderId) {
59
+ const pdf = await client.label(order.royalMailOrderId);
60
+ return { pdf: pdf !== null, royalMailOrderId: order.royalMailOrderId };
61
+ }
58
62
 
59
63
  const weightGrams = order.weightGrams ?? estimatedWeightGrams;
60
64
  if (weightGrams < 1) throw Error400('Set the parcel weight before printing the label.');
61
- const { packageHeightMm, packageLengthMm, packageWidthMm } = order;
62
- const dimensions =
63
- packageHeightMm && packageLengthMm && packageWidthMm
64
- ? { heightMm: packageHeightMm, lengthMm: packageLengthMm, widthMm: packageWidthMm }
65
- : null;
66
65
 
67
66
  const db = shopping().db();
68
67
  const fulfilment = new FulfilmentService(db);
69
68
  const shipping = new ShippingService(db);
70
- const client = ShopClients.royalMail();
71
69
  if (order.royalMailOrderId) await client.deleteOrder(order.royalMailOrderId);
72
70
  const royalMailOrderId = await client.createOrder({
73
71
  address: {
@@ -80,7 +78,6 @@ export const FulfilmentManager = {
80
78
  state: null,
81
79
  },
82
80
  createdAt: order.createdAt,
83
- dimensions,
84
81
  email: order.email,
85
82
  number: order.number,
86
83
  packageFormat: order.packageFormat,
@@ -93,7 +90,7 @@ export const FulfilmentManager = {
93
90
  });
94
91
  // Keep the new id before fetching the label, so a failed fetch can be retried without a duplicate.
95
92
  await fulfilment.update(order.id, { royalMailOrderId });
96
- await client.label(royalMailOrderId);
93
+ const pdf = await client.label(royalMailOrderId);
97
94
 
98
95
  const now = Date.now();
99
96
  await fulfilment.update(order.id, {
@@ -103,6 +100,7 @@ export const FulfilmentManager = {
103
100
  packingStartedAt: order.packingStartedAt ?? now,
104
101
  weightGrams,
105
102
  });
103
+ return { pdf: pdf !== null, royalMailOrderId };
106
104
  },
107
105
 
108
106
  /**
@@ -201,7 +199,9 @@ export const FulfilmentManager = {
201
199
  const order = await findOrThrow(number);
202
200
  if (!order.royalMailOrderId || !order.labelCreatedAt)
203
201
  throw Error404('No label for this order yet.');
204
- return ShopClients.royalMail().label(order.royalMailOrderId);
202
+ const pdf = await ShopClients.royalMail().label(order.royalMailOrderId);
203
+ if (!pdf) throw Error404('Royal Mail only offers this label in Click & Drop. Print it there.');
204
+ return pdf;
205
205
  },
206
206
 
207
207
  list(filter: Parameters<FulfilmentService['list']>[0], query: string) {
@@ -37,24 +37,12 @@ export type OrderStep = (typeof ORDER_STEPS)[number];
37
37
  /** One form moves an order through packing: the order, and which button was pressed. */
38
38
  export const OrderStepSchema = z.object({ number: OrderNumber, step: z.enum(ORDER_STEPS) });
39
39
 
40
- const Millimetres = z.number().int().min(1).max(1000);
41
-
42
- /** Click & Drop takes parcels up to 30 kg. The three measurements go together or not at all. */
43
- export const ParcelSchema = z
44
- .object({
45
- format: z.enum(PACKAGE_FORMATS),
46
- heightMm: Millimetres.optional(),
47
- lengthMm: Millimetres.optional(),
48
- number: OrderNumber,
49
- weightGrams: z.number().int().min(1, 'enter the weight in grams').max(30_000),
50
- widthMm: Millimetres.optional(),
51
- })
52
- .refine(
53
- ({ heightMm, lengthMm, widthMm }) =>
54
- [heightMm, lengthMm, widthMm].every((v) => v === undefined) ||
55
- [heightMm, lengthMm, widthMm].every((v) => v !== undefined),
56
- { message: 'give length, width and height, or leave all three blank', path: ['lengthMm'] }
57
- );
40
+ /** Click & Drop takes parcels up to 30 kg. */
41
+ export const ParcelSchema = z.object({
42
+ format: z.enum(PACKAGE_FORMATS),
43
+ number: OrderNumber,
44
+ weightGrams: z.number().int().min(1, 'enter the weight in grams').max(30_000),
45
+ });
58
46
 
59
47
  const Tracking = z
60
48
  .string()
@@ -5,17 +5,12 @@ import type { ShopDb } from '../db/index';
5
5
  import type { OrderFilter } from './filters';
6
6
  import type { OrderDetails } from './schema';
7
7
 
8
+ import { CoverService } from '../catalogue/covers.server';
8
9
  import { Search } from '../catalogue/library';
9
10
  import { addresses, orderItems, orders, type PackageFormat, products } from '../db/schema';
10
11
  import { Batches } from '../utils/batches';
11
12
 
12
- export type Parcel = {
13
- format: PackageFormat;
14
- heightMm: null | number;
15
- lengthMm: null | number;
16
- weightGrams: number;
17
- widthMm: null | number;
18
- };
13
+ export type Parcel = { format: PackageFormat; weightGrams: number };
19
14
 
20
15
  type OrderRow = typeof orders.$inferSelect;
21
16
 
@@ -76,7 +71,20 @@ export class FulfilmentService {
76
71
  this.db.query.addresses.findFirst({ where: eq(addresses.id, order.shippingAddressId) }),
77
72
  ]);
78
73
  if (!address) return undefined;
79
- return { ...order, address, estimatedWeightGrams: await this.estimateWeight(items), items };
74
+ const productIds = items.flatMap((item) => (item.productId === null ? [] : [item.productId]));
75
+ const [covers, estimatedWeightGrams] = await Promise.all([
76
+ new CoverService(this.db).covers(productIds),
77
+ this.estimateWeight(items),
78
+ ]);
79
+ return {
80
+ ...order,
81
+ address,
82
+ estimatedWeightGrams,
83
+ items: items.map((item) => ({
84
+ ...item,
85
+ cover: item.productId === null ? null : (covers.get(item.productId) ?? null),
86
+ })),
87
+ };
80
88
  }
81
89
 
82
90
  /** Orders for the admin list: oldest first when packing, newest first when browsing. */
@@ -207,9 +215,6 @@ export class FulfilmentService {
207
215
  const order = await this.packable(number);
208
216
  await this.update(order.id, {
209
217
  packageFormat: parcel.format,
210
- packageHeightMm: parcel.heightMm,
211
- packageLengthMm: parcel.lengthMm,
212
- packageWidthMm: parcel.widthMm,
213
218
  weightGrams: parcel.weightGrams,
214
219
  });
215
220
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeyolabs/shopping",
3
- "version": "2026.11.44",
3
+ "version": "2026.11.46",
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",
@@ -67,8 +67,8 @@
67
67
  "@eslint/compat": "2.1.1",
68
68
  "@eslint/js": "10.0.1",
69
69
  "@sveltejs/kit": "3.2.0",
70
- "@zeyolabs/kit": "2026.11.38",
71
- "@zeyolabs/ui": "2026.11.37",
70
+ "@zeyolabs/kit": "2026.11.42",
71
+ "@zeyolabs/ui": "2026.11.40",
72
72
  "drizzle-orm": "0.45.4",
73
73
  "eslint": "10.15.0",
74
74
  "eslint-config-prettier": "10.1.8",