@zeyolabs/shopping 2026.11.16 → 2026.11.18

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.
@@ -4,13 +4,21 @@
4
4
  import { page } from '$app/state';
5
5
  import {
6
6
  createOrderLabel,
7
+ detailsForm,
7
8
  getOrder,
9
+ getShippingServices,
8
10
  parcelForm,
9
11
  refundForm,
10
12
  shipForm,
11
13
  updateOrderForm,
12
14
  } from '../admin.remote';
13
- import { OrderStepSchema, ParcelSchema, RefundSchema, ShipSchema } from '../schema';
15
+ import {
16
+ OrderDetailsSchema,
17
+ OrderStepSchema,
18
+ ParcelSchema,
19
+ RefundSchema,
20
+ ShipSchema,
21
+ } from '../schema';
14
22
  import { Money } from '../../utils/money';
15
23
  import { FormInput } from '../../utils/form-input';
16
24
  import { Orders } from '../../orders/library';
@@ -238,6 +246,70 @@
238
246
  </section>
239
247
  {/if}
240
248
 
249
+ {#if order.status === 'paid' || order.status === 'shipped'}
250
+ {let services = $derived(await getShippingServices())}
251
+ <section class="mt-6 max-w-xl rounded-xl border border-[var(--line)] bg-white p-5">
252
+ <details>
253
+ <summary class="cursor-pointer font-semibold">Edit contact, address and postage</summary>
254
+ <p class="mt-2 text-sm text-[var(--ink-muted)]">
255
+ For fixing a typo or a customer's request. If you change the country, check the postage
256
+ service still fits. {#if order.status === 'paid' && order.labelCreatedAt}The label is
257
+ already made, so after a change you need to print it again.{/if}
258
+ </p>
259
+ <Form
260
+ class="mt-4 grid gap-4"
261
+ defaults={{
262
+ city: order.address.city,
263
+ country: order.address.country,
264
+ email: order.email,
265
+ line1: order.address.line1,
266
+ line2: order.address.line2 ?? '',
267
+ name: order.address.name,
268
+ phone: order.address.phone ?? '',
269
+ postcode: order.address.postcode,
270
+ shippingService: order.shippingService ?? '',
271
+ trackingNumber: order.trackingNumber ?? '',
272
+ }}
273
+ form={detailsForm}
274
+ hidden={{ number: order.number }}
275
+ reset={false}
276
+ schema={OrderDetailsSchema}
277
+ >
278
+ <TextField name="name" form={detailsForm}>Name</TextField>
279
+ <TextField name="email" form={detailsForm} inputmode="email">Email</TextField>
280
+ <TextField name="phone" form={detailsForm} inputmode="tel" optional>Phone</TextField>
281
+ <TextField name="line1" form={detailsForm}>Address line 1</TextField>
282
+ <TextField name="line2" form={detailsForm} optional>Address line 2</TextField>
283
+ <TextField name="city" form={detailsForm}>Town or city</TextField>
284
+ <TextField name="postcode" autocapitalize="characters" form={detailsForm}
285
+ >Postcode</TextField
286
+ >
287
+ <TextField name="country" autocapitalize="characters" form={detailsForm}
288
+ >Country code (e.g. GB)</TextField
289
+ >
290
+ <SelectField
291
+ name="shippingService"
292
+ form={detailsForm}
293
+ getLabel={(s) => services.find((x) => x.service === s)?.name ?? s}
294
+ items={services.map((s) => s.service)}
295
+ placeholder="Postage service"
296
+ />
297
+ {#if order.status === 'shipped'}
298
+ <TextField
299
+ name="trackingNumber"
300
+ autocapitalize="characters"
301
+ form={detailsForm}
302
+ optional
303
+ >
304
+ Tracking number (no email is sent)
305
+ </TextField>
306
+ {/if}
307
+ <div><Button form={detailsForm}>Save details</Button></div>
308
+ </Form>
309
+ </details>
310
+ </section>
311
+ {/if}
312
+
241
313
  {#if (order.status === 'paid' || order.status === 'shipped') && order.stripePaymentIntentId && order.refundedPence < order.totalPence}
242
314
  {let left = $derived(order.totalPence - order.refundedPence)}
243
315
  <section class="mt-6 max-w-xl rounded-xl border border-[var(--line)] bg-white p-5">
@@ -3,7 +3,7 @@
3
3
  import { resolve } from '$app/paths';
4
4
  import { page } from '$app/state';
5
5
  import { BULK_DISPATCH_LIMIT, FILTER_LABELS, ORDER_FILTERS, type OrderFilter } from '../filters';
6
- import { dispatchOrders, getOrderCounts, getOrders } from '../admin.remote';
6
+ import { dispatchOrders, getOrderCounts, getOrders, getReadyByService } from '../admin.remote';
7
7
  import { ErrorMessage } from '../../utils/errors';
8
8
  import { toast } from 'svelte-sonner';
9
9
  import Button from '@zeyolabs/ui/form/Button.svelte';
@@ -97,6 +97,11 @@
97
97
  </a>
98
98
  <!-- eslint-enable svelte/no-navigation-without-resolve -->
99
99
  {/each}
100
+ <Boundary message="Could not load ready counts.">
101
+ {#each Object.entries(await getReadyByService()) as [service, n] (service)}
102
+ <span class="text-sm text-[var(--muted)]">{service}: {n} ready</span>
103
+ {/each}
104
+ </Boundary>
100
105
  <form
101
106
  class="ml-auto"
102
107
  onsubmit={(event) => {
@@ -4,6 +4,7 @@ import { FormResult } from '@zeyolabs/kit/utils/form';
4
4
  import { FulfilmentManager } from './manager.server';
5
5
  import {
6
6
  BulkDispatchSchema,
7
+ OrderDetailsSchema,
7
8
  OrderListSchema,
8
9
  OrderNumber,
9
10
  OrderStepSchema,
@@ -17,6 +18,7 @@ export const getOrders = Remote.Query(OrderListSchema, ({ filter, q }) =>
17
18
  );
18
19
 
19
20
  export const getOrderCounts = Remote.Query(() => FulfilmentManager.counts());
21
+ export const getReadyByService = Remote.Query(() => FulfilmentManager.readyByService());
20
22
 
21
23
  export const getOrder = Remote.Query(OrderNumber, (number) => FulfilmentManager.find(number));
22
24
 
@@ -24,7 +26,11 @@ export const shipForm = Remote.Form(ShipSchema, async ({ number, skipEmail, trac
24
26
  const { emailed, skipped } = await FulfilmentManager.markShipped(number, trackingNumber || null, {
25
27
  email: !skipEmail,
26
28
  });
27
- await Promise.all([getOrder(number).refresh(), getOrderCounts().refresh()]);
29
+ await Promise.all([
30
+ getOrder(number).refresh(),
31
+ getOrderCounts().refresh(),
32
+ getReadyByService().refresh(),
33
+ ]);
28
34
  if (skipped) return FormResult.ok('Marked as dispatched. The customer was not emailed.');
29
35
  return emailed
30
36
  ? FormResult.ok('Marked as dispatched and the customer has been emailed.')
@@ -62,6 +68,18 @@ export const parcelForm = Remote.Form(
62
68
  }
63
69
  );
64
70
 
71
+ export const getShippingServices = Remote.Query(() => FulfilmentManager.shippingServices());
72
+
73
+ export const detailsForm = Remote.Form(OrderDetailsSchema, async ({ number, ...details }) => {
74
+ const { labelStale } = await FulfilmentManager.saveDetails(number, { number, ...details });
75
+ await getOrder(number).refresh();
76
+ return FormResult.ok(
77
+ labelStale
78
+ ? 'Details saved. The label no longer matches: print it again to replace it.'
79
+ : 'Details saved.'
80
+ );
81
+ });
82
+
65
83
  /** Creates the label in Click & Drop. The page then opens it from `/orders/<number>/label`. */
66
84
  export const createOrderLabel = Remote.Cmd(OrderNumber, async (number) => {
67
85
  await FulfilmentManager.createLabel(number);
@@ -84,6 +102,6 @@ export const refundForm = Remote.Form(RefundSchema, async ({ amount, number }) =
84
102
  */
85
103
  export const dispatchOrders = Remote.Cmd(BulkDispatchSchema, async ({ numbers, sendEmail }) => {
86
104
  const results = await FulfilmentManager.markShippedMany(numbers, { email: sendEmail });
87
- await getOrderCounts().refresh();
105
+ await Promise.all([getOrderCounts().refresh(), getReadyByService().refresh()]);
88
106
  return results;
89
107
  });
@@ -1,4 +1,4 @@
1
- export const ORDER_FILTERS = ['to-ship', 'ready', 'on-hold', 'shipped', 'all'] as const;
1
+ export const ORDER_FILTERS = ['to-ship', 'ready', 'on-hold', 'unpaid', 'shipped', 'all'] as const;
2
2
  export type OrderFilter = (typeof ORDER_FILTERS)[number];
3
3
 
4
4
  export const FILTER_LABELS: Record<OrderFilter, string> = {
@@ -7,6 +7,7 @@ export const FILTER_LABELS: Record<OrderFilter, string> = {
7
7
  ready: 'Ready to dispatch',
8
8
  shipped: 'Shipped',
9
9
  'to-ship': 'To ship',
10
+ unpaid: 'Unpaid',
10
11
  };
11
12
 
12
13
  /** Orders one bulk dispatch may carry, to stay inside a Worker's subrequest budget. */
@@ -2,7 +2,7 @@ import { logger } from '@zeyolabs/kit/server/logger';
2
2
  import { Crypto } from '@zeyolabs/kit/utils/crypto';
3
3
  import { Error400, Error404, Error500 } from '@zeyolabs/kit/utils/errors';
4
4
 
5
- import type { OrderStep } from './schema';
5
+ import type { OrderDetails, OrderStep } from './schema';
6
6
 
7
7
  import { ShopClients } from '../clients/shop.server';
8
8
  import { shopping } from '../config';
@@ -38,6 +38,11 @@ export const FulfilmentManager = {
38
38
  return fulfilment.counts();
39
39
  },
40
40
 
41
+ readyByService() {
42
+ const fulfilment = service();
43
+ return fulfilment.readyByService();
44
+ },
45
+
41
46
  /**
42
47
  * Makes sure Click & Drop holds this order with the parcel as packed, so its label is right.
43
48
  * Click & Drop cannot edit an order, so until a label exists the old one is removed and
@@ -100,6 +105,38 @@ export const FulfilmentManager = {
100
105
  });
101
106
  },
102
107
 
108
+ /**
109
+ * Saves corrected contact, address, postage service and tracking. Click & Drop cannot edit an
110
+ * order, so when something it holds changed on an order that has a label, the label is marked
111
+ * stale: printing it again deletes the old Click & Drop order and creates a fresh one.
112
+ */
113
+ async saveDetails(number: string, details: OrderDetails) {
114
+ const db = shopping().db();
115
+ if (details.shippingService) {
116
+ const known = await new ShippingService(db).services();
117
+ if (!known.some((s) => s.service === details.shippingService))
118
+ throw Error400('Choose one of the shop’s postage services.');
119
+ }
120
+ const fulfilment = new FulfilmentService(db);
121
+ const order = await findOrThrow(number);
122
+ // Tracking is only edited once the order has shipped; before that Click & Drop assigns it.
123
+ const result = await fulfilment.saveDetails(number, {
124
+ ...details,
125
+ trackingNumber: order.status === 'shipped' ? details.trackingNumber : undefined,
126
+ });
127
+ // An email edit moves the order to another account, so it leaves a trace.
128
+ logger.info('order details edited', {
129
+ emailChanged: details.email.toLowerCase() !== order.email.toLowerCase(),
130
+ order: order.number,
131
+ });
132
+ return result;
133
+ },
134
+
135
+ /** Postage services the admin can pick when correcting an order. */
136
+ shippingServices() {
137
+ return new ShippingService(shopping().db()).services();
138
+ },
139
+
103
140
  /**
104
141
  * Refunds `pence` of a paid or shipped order through Stripe and records Stripe's new total.
105
142
  * Stripe is the source of truth (see `OrderRefunds`), so a refund made in its dashboard, a
@@ -53,6 +53,36 @@ export const ParcelSchema = z
53
53
  { message: 'give length, width and height, or leave all three blank', path: ['lengthMm'] }
54
54
  );
55
55
 
56
+ const Tracking = z
57
+ .string()
58
+ .transform((value) => value.replace(/\s+/g, '').toUpperCase())
59
+ .pipe(
60
+ z.union([
61
+ z.literal(''),
62
+ z.string().regex(/^[A-Z0-9]{8,20}$/, 'enter the tracking number, letters and digits only'),
63
+ ])
64
+ );
65
+
66
+ /** Contact, address, postage service and tracking, as the admin corrects them on a paid or shipped order. */
67
+ export const OrderDetailsSchema = z.object({
68
+ city: z.string().trim().min(1, 'enter the town or city').max(100),
69
+ country: z
70
+ .string()
71
+ .trim()
72
+ .toUpperCase()
73
+ .regex(/^[A-Z]{2}$/, 'enter the two-letter country code, e.g. GB'),
74
+ email: z.string().trim().toLowerCase().max(254).pipe(z.email('enter a valid email')),
75
+ line1: z.string().trim().min(1, 'enter the first address line').max(200),
76
+ line2: z.string().trim().max(200).default(''),
77
+ name: z.string().trim().min(1, 'enter the name').max(200),
78
+ number: OrderNumber,
79
+ phone: z.string().trim().max(40).default(''),
80
+ postcode: z.string().trim().min(1, 'enter the postcode').max(20),
81
+ shippingService: z.string().trim().max(50).default(''),
82
+ trackingNumber: Tracking.default(''),
83
+ });
84
+ export type OrderDetails = z.infer<typeof OrderDetailsSchema>;
85
+
56
86
  /** Orders ticked on the list. Capped at `BULK_DISPATCH_LIMIT`. */
57
87
  export const BulkDispatchSchema = z.object({
58
88
  numbers: z.array(OrderNumber).min(1).max(BULK_DISPATCH_LIMIT),
@@ -3,6 +3,7 @@ import { and, asc, count, desc, eq, inArray, isNotNull, isNull, or, sql } from '
3
3
 
4
4
  import type { ShopDb } from '../db/index';
5
5
  import type { OrderFilter } from './filters';
6
+ import type { OrderDetails } from './schema';
6
7
 
7
8
  import { Search } from '../catalogue/library';
8
9
  import { addresses, orderItems, orders, type PackageFormat, products } from '../db/schema';
@@ -35,6 +36,8 @@ function filterCondition(filter: OrderFilter) {
35
36
  return eq(orders.status, 'shipped');
36
37
  case 'to-ship':
37
38
  return eq(orders.status, 'paid');
39
+ case 'unpaid':
40
+ return eq(orders.status, 'pending');
38
41
  }
39
42
  }
40
43
 
@@ -51,6 +54,7 @@ export class FulfilmentService {
51
54
  ready: sql<number>`coalesce(sum(${orders.status} = 'paid' and ${orders.heldAt} is null and ${orders.labelCreatedAt} is not null), 0)`,
52
55
  shipped: sql<number>`coalesce(sum(${orders.status} = 'shipped'), 0)`,
53
56
  toShip: sql<number>`coalesce(sum(${orders.status} = 'paid'), 0)`,
57
+ unpaid: sql<number>`coalesce(sum(${orders.status} = 'pending'), 0)`,
54
58
  })
55
59
  .from(orders);
56
60
  return {
@@ -59,6 +63,7 @@ export class FulfilmentService {
59
63
  ready: Number(row.ready),
60
64
  shipped: Number(row.shipped),
61
65
  'to-ship': Number(row.toShip),
66
+ unpaid: Number(row.unpaid),
62
67
  };
63
68
  }
64
69
 
@@ -134,6 +139,70 @@ export class FulfilmentService {
134
139
  return order;
135
140
  }
136
141
 
142
+ /** Orders ready to dispatch (paid, not held, labelled), counted per postage service. */
143
+ async readyByService(): Promise<Record<string, number>> {
144
+ const rows = await this.db
145
+ .select({ n: count(), service: orders.shippingService })
146
+ .from(orders)
147
+ .where(filterCondition('ready'))
148
+ .groupBy(orders.shippingService);
149
+ return Object.fromEntries(rows.map((r) => [r.service ?? 'No service', r.n]));
150
+ }
151
+
152
+ /**
153
+ * Corrects the customer's contact, the address and the postage service of a paid or shipped
154
+ * order. Returns whether anything Click & Drop holds (address, email, phone, service) changed.
155
+ */
156
+ async saveDetails(
157
+ number: string,
158
+ details: Omit<OrderDetails, 'number' | 'trackingNumber'> & { trackingNumber?: null | string }
159
+ ) {
160
+ const order = await this.db.query.orders.findFirst({ where: eq(orders.number, number) });
161
+ if (!order) throw Error404('Order not found.');
162
+ if (order.status !== 'paid' && order.status !== 'shipped')
163
+ throw Error400(`This order is ${order.status}, so its details cannot be edited.`);
164
+ const address = await this.db.query.addresses.findFirst({
165
+ where: eq(addresses.id, order.shippingAddressId),
166
+ });
167
+ if (!address) throw Error404('Order not found.');
168
+
169
+ const next = {
170
+ city: details.city,
171
+ country: details.country,
172
+ line1: details.line1,
173
+ line2: details.line2 || null,
174
+ name: details.name,
175
+ phone: details.phone || null,
176
+ postcode: details.postcode,
177
+ };
178
+ // A blank service keeps the order's current one: a paid order should not lose its postage.
179
+ const service = details.shippingService || order.shippingService;
180
+ const email = details.email.toLowerCase();
181
+ const labelAffected =
182
+ email !== order.email.toLowerCase() ||
183
+ service !== order.shippingService ||
184
+ (Object.keys(next) as (keyof typeof next)[]).some((key) => next[key] !== address[key]);
185
+ // Click & Drop cannot edit an order: a label made before the change is stale, so printing
186
+ // again replaces it. Cleared in the same batch as the address, so they cannot disagree.
187
+ const labelStale = labelAffected && order.status === 'paid' && order.labelCreatedAt !== null;
188
+
189
+ await this.db.batch([
190
+ this.db.update(addresses).set(next).where(eq(addresses.id, address.id)),
191
+ this.db
192
+ .update(orders)
193
+ .set({
194
+ email: details.email,
195
+ shippingService: service,
196
+ ...(labelStale ? { labelCreatedAt: null } : {}),
197
+ ...(details.trackingNumber === undefined
198
+ ? {}
199
+ : { trackingNumber: details.trackingNumber || null }),
200
+ })
201
+ .where(eq(orders.id, order.id)),
202
+ ]);
203
+ return { labelStale };
204
+ }
205
+
137
206
  async saveParcel(number: string, parcel: Parcel) {
138
207
  const order = await this.packable(number);
139
208
  await this.update(order.id, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeyolabs/shopping",
3
- "version": "2026.11.16",
3
+ "version": "2026.11.18",
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",
@@ -75,6 +75,15 @@ export class ShippingService {
75
75
  return rate?.royalMailServiceCode ?? null;
76
76
  }
77
77
 
78
+ /** The distinct postage services that have a rate, for the admin's service picker. */
79
+ async services() {
80
+ const rows = await this.db
81
+ .selectDistinct({ name: shippingRates.name, service: shippingRates.service })
82
+ .from(shippingRates)
83
+ .orderBy(asc(shippingRates.service));
84
+ return rows;
85
+ }
86
+
78
87
  /** The cheapest UK rate, for pages that quote delivery so they never disagree with the basket. */
79
88
  async ukRate() {
80
89
  const [rate] = await this.db