@zeyolabs/shopping 2026.11.15 → 2026.11.16

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.
@@ -19,7 +19,7 @@
19
19
  import { Packing } from '../library';
20
20
  import Badge from '@zeyolabs/ui/badge/Badge.svelte';
21
21
  import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
22
- import { Form, NumberField, SelectField, TextField } from '@zeyolabs/ui/form';
22
+ import { CheckboxField, Form, NumberField, SelectField, TextField } from '@zeyolabs/ui/form';
23
23
  import Button from '@zeyolabs/ui/form/Button.svelte';
24
24
 
25
25
  const number = $derived(page.params.number ?? '');
@@ -281,7 +281,7 @@
281
281
  {/if}
282
282
  <Form
283
283
  class="mt-4 grid gap-4"
284
- defaults={{ trackingNumber: order.trackingNumber ?? '' }}
284
+ defaults={{ skipEmail: false, trackingNumber: order.trackingNumber ?? '' }}
285
285
  form={shipForm}
286
286
  hidden={{ number: order.number }}
287
287
  reset={false}
@@ -290,6 +290,7 @@
290
290
  <TextField name="trackingNumber" autocapitalize="characters" form={shipForm} optional>
291
291
  Tracking number
292
292
  </TextField>
293
+ <CheckboxField name="skipEmail" form={shipForm}>Do not email the customer</CheckboxField>
293
294
  <div>
294
295
  <Button form={shipForm} loadingMessage="Sending…">
295
296
  {order.shippedAt ? 'Save and resend email' : 'Mark as dispatched and email customer'}
@@ -2,10 +2,13 @@
2
2
  import { goto } from '$app/navigation';
3
3
  import { resolve } from '$app/paths';
4
4
  import { page } from '$app/state';
5
- import { FILTER_LABELS, ORDER_FILTERS, type OrderFilter } from '../filters';
6
- import { getOrderCounts, getOrders } from '../admin.remote';
5
+ import { BULK_DISPATCH_LIMIT, FILTER_LABELS, ORDER_FILTERS, type OrderFilter } from '../filters';
6
+ import { dispatchOrders, getOrderCounts, getOrders } from '../admin.remote';
7
+ import { ErrorMessage } from '../../utils/errors';
8
+ import { toast } from 'svelte-sonner';
9
+ import Button from '@zeyolabs/ui/form/Button.svelte';
7
10
  import { Money } from '../../utils/money';
8
- import { SvelteURLSearchParams } from 'svelte/reactivity';
11
+ import { SvelteSet, SvelteURLSearchParams } from 'svelte/reactivity';
9
12
  import { Packing } from '../library';
10
13
  import Badge from '@zeyolabs/ui/badge/Badge.svelte';
11
14
  import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
@@ -16,6 +19,48 @@
16
19
  });
17
20
  const q = $derived(page.url.searchParams.get('q') ?? '');
18
21
 
22
+ /** Orders ticked for bulk dispatch (only on the "Ready to dispatch" tab). */
23
+ const selected = new SvelteSet<string>();
24
+ let sendEmail = $state(true);
25
+ let dispatching = $state(false);
26
+
27
+ async function dispatchSelected(numbers: string[]) {
28
+ if (
29
+ sendEmail &&
30
+ !confirm(
31
+ `Dispatch ${numbers.length} order${numbers.length === 1 ? '' : 's'} and email the customer${numbers.length === 1 ? '' : 's'}?`
32
+ )
33
+ )
34
+ return;
35
+ dispatching = true;
36
+ try {
37
+ const results = await dispatchOrders({ numbers, sendEmail });
38
+ const failed = results.filter((r) => !r.ok);
39
+ const noEmail = results.filter((r) => r.ok && sendEmail && !r.emailed);
40
+ selected.clear();
41
+ if (failed.length === 0 && noEmail.length === 0) {
42
+ toast.success(`Dispatched ${results.length} order${results.length === 1 ? '' : 's'}.`);
43
+ } else {
44
+ toast.warning(
45
+ [
46
+ `Dispatched ${results.length - failed.length} of ${results.length}.`,
47
+ ...failed.map((r) => `${r.number}: ${r.error}`),
48
+ ...(noEmail.length > 0
49
+ ? [
50
+ `Email failed for ${noEmail.map((r) => r.number).join(', ')}: resend from the order page.`,
51
+ ]
52
+ : []),
53
+ ].join(' ')
54
+ );
55
+ }
56
+ await getOrders({ filter, q }).refresh();
57
+ } catch (error) {
58
+ toast.error(ErrorMessage.from(error, 'Could not dispatch the orders.'));
59
+ } finally {
60
+ dispatching = false;
61
+ }
62
+ }
63
+
19
64
  const date = new Intl.DateTimeFormat('en-GB', {
20
65
  dateStyle: 'medium',
21
66
  timeStyle: 'short',
@@ -73,15 +118,45 @@
73
118
 
74
119
  <Boundary message="Could not load orders.">
75
120
  {let rows = $derived(await getOrders({ filter, q }))}
121
+ <!-- Only orders still on screen: a search or tab change must not dispatch hidden ticks. -->
122
+ {let chosen = $derived(rows.map((r) => r.number).filter((n) => selected.has(n)))}
76
123
  {#if rows.length === 0}
77
124
  <p class="mt-6 text-[var(--ink-muted)]">
78
125
  {filter === 'to-ship' && !q ? 'Nothing to ship. All caught up.' : 'No orders match.'}
79
126
  </p>
80
127
  {:else}
128
+ {#if filter === 'ready'}
129
+ <div class="mt-4 flex flex-wrap items-center gap-4 text-sm">
130
+ <label class="flex items-center gap-2">
131
+ <input
132
+ checked={rows.length > 0 &&
133
+ chosen.length === Math.min(rows.length, BULK_DISPATCH_LIMIT)}
134
+ onchange={(event) => {
135
+ selected.clear();
136
+ if (event.currentTarget.checked)
137
+ for (const r of rows.slice(0, BULK_DISPATCH_LIMIT)) selected.add(r.number);
138
+ }}
139
+ type="checkbox"
140
+ />
141
+ Select {Math.min(rows.length, BULK_DISPATCH_LIMIT)}
142
+ </label>
143
+ <label class="flex items-center gap-2">
144
+ <input bind:checked={sendEmail} type="checkbox" />
145
+ Email the customers
146
+ </label>
147
+ <Button
148
+ disabled={chosen.length === 0 || dispatching}
149
+ onclick={() => dispatchSelected(chosen)}
150
+ >
151
+ Dispatch {chosen.length} order{chosen.length === 1 ? '' : 's'}
152
+ </Button>
153
+ </div>
154
+ {/if}
81
155
  <div class="mt-4 overflow-x-auto rounded-xl border border-[var(--line)] bg-white">
82
156
  <table class="w-full text-left text-sm">
83
157
  <thead class="border-b border-[var(--line)] text-[var(--ink-muted)]">
84
158
  <tr>
159
+ {#if filter === 'ready'}<th class="w-8 px-4 py-2"></th>{/if}
85
160
  <th class="px-4 py-2 font-medium">Order</th>
86
161
  <th class="px-4 py-2 font-medium">Placed</th>
87
162
  <th class="px-4 py-2 font-medium">Customer</th>
@@ -92,6 +167,20 @@
92
167
  <tbody class="divide-y divide-[var(--line)]">
93
168
  {#each rows as row (row.number)}
94
169
  <tr>
170
+ {#if filter === 'ready'}
171
+ <td class="px-4 py-2">
172
+ <input
173
+ aria-label="Select {row.number}"
174
+ checked={selected.has(row.number)}
175
+ disabled={!selected.has(row.number) && chosen.length >= BULK_DISPATCH_LIMIT}
176
+ onchange={(event) => {
177
+ if (event.currentTarget.checked) selected.add(row.number);
178
+ else selected.delete(row.number);
179
+ }}
180
+ type="checkbox"
181
+ />
182
+ </td>
183
+ {/if}
95
184
  <td class="px-4 py-2 font-medium">
96
185
  <a href={resolve('/orders/[number]', { number: row.number })}>{row.number}</a>
97
186
  </td>
@@ -3,6 +3,7 @@ import { FormResult } from '@zeyolabs/kit/utils/form';
3
3
 
4
4
  import { FulfilmentManager } from './manager.server';
5
5
  import {
6
+ BulkDispatchSchema,
6
7
  OrderListSchema,
7
8
  OrderNumber,
8
9
  OrderStepSchema,
@@ -19,9 +20,12 @@ export const getOrderCounts = Remote.Query(() => FulfilmentManager.counts());
19
20
 
20
21
  export const getOrder = Remote.Query(OrderNumber, (number) => FulfilmentManager.find(number));
21
22
 
22
- export const shipForm = Remote.Form(ShipSchema, async ({ number, trackingNumber }) => {
23
- const { emailed } = await FulfilmentManager.markShipped(number, trackingNumber || null);
23
+ export const shipForm = Remote.Form(ShipSchema, async ({ number, skipEmail, trackingNumber }) => {
24
+ const { emailed, skipped } = await FulfilmentManager.markShipped(number, trackingNumber || null, {
25
+ email: !skipEmail,
26
+ });
24
27
  await Promise.all([getOrder(number).refresh(), getOrderCounts().refresh()]);
28
+ if (skipped) return FormResult.ok('Marked as dispatched. The customer was not emailed.');
25
29
  return emailed
26
30
  ? FormResult.ok('Marked as dispatched and the customer has been emailed.')
27
31
  : FormResult.warn(
@@ -73,3 +77,13 @@ export const refundForm = Remote.Form(RefundSchema, async ({ amount, number }) =
73
77
  : 'Partly refunded.'
74
78
  );
75
79
  });
80
+
81
+ /**
82
+ * Dispatches the ticked orders. A command, so it returns each order's result instead of throwing:
83
+ * the list shows which went through and which did not.
84
+ */
85
+ export const dispatchOrders = Remote.Cmd(BulkDispatchSchema, async ({ numbers, sendEmail }) => {
86
+ const results = await FulfilmentManager.markShippedMany(numbers, { email: sendEmail });
87
+ await getOrderCounts().refresh();
88
+ return results;
89
+ });
@@ -1,8 +1,13 @@
1
- export const ORDER_FILTERS = ['to-ship', 'shipped', 'all'] as const;
1
+ export const ORDER_FILTERS = ['to-ship', 'ready', 'on-hold', 'shipped', 'all'] as const;
2
2
  export type OrderFilter = (typeof ORDER_FILTERS)[number];
3
3
 
4
4
  export const FILTER_LABELS: Record<OrderFilter, string> = {
5
5
  all: 'All',
6
+ 'on-hold': 'On hold',
7
+ ready: 'Ready to dispatch',
6
8
  shipped: 'Shipped',
7
9
  'to-ship': 'To ship',
8
10
  };
11
+
12
+ /** Orders one bulk dispatch may carry, to stay inside a Worker's subrequest budget. */
13
+ export const BULK_DISPATCH_LIMIT = 20;
@@ -10,6 +10,7 @@ import { Orders } from '../orders/library';
10
10
  import { OrderManager } from '../orders/manager.server';
11
11
  import { ShippingService } from '../shipping/service.server';
12
12
  import { Money } from '../utils/money';
13
+ import { BULK_DISPATCH_LIMIT } from './filters';
13
14
  import { OrderRefunds } from './refund.server';
14
15
  import { FulfilmentService, type Parcel } from './service.server';
15
16
 
@@ -176,7 +177,11 @@ export const FulfilmentManager = {
176
177
  * database change comes first: a failed email never undoes a parcel that has really left, and
177
178
  * the result says whether the email went so the admin can resend it.
178
179
  */
179
- async markShipped(number: string, trackingNumber: null | string) {
180
+ async markShipped(
181
+ number: string,
182
+ trackingNumber: null | string,
183
+ options: { email?: boolean } = {}
184
+ ) {
180
185
  const order = await findOrThrow(number);
181
186
  const { address } = order;
182
187
  if (order.status !== 'paid' && order.status !== 'shipped') {
@@ -208,6 +213,8 @@ export const FulfilmentManager = {
208
213
  trackingNumber: tracking,
209
214
  });
210
215
 
216
+ if (options.email === false) return { emailed: false, skipped: true };
217
+
211
218
  try {
212
219
  await shopping().mail.orderDispatched({
213
220
  address,
@@ -217,11 +224,43 @@ export const FulfilmentManager = {
217
224
  trackingNumber: tracking,
218
225
  });
219
226
  await fulfilment.update(order.id, { dispatchEmailedAt: now });
220
- return { emailed: true };
227
+ return { emailed: true, skipped: false };
221
228
  } catch (error) {
222
229
  logger.error(error, { op: 'dispatchEmail', orderNumber: order.number });
223
- return { emailed: false };
230
+ return { emailed: false, skipped: false };
231
+ }
232
+ },
233
+
234
+ /**
235
+ * Dispatches several orders one after another (each is its own database change, so one that
236
+ * fails does not hold back the rest). Tracking numbers come from Click & Drop where a label
237
+ * exists. Capped, because each order can cost a Royal Mail call and an email.
238
+ */
239
+ async markShippedMany(numbers: string[], options: { email: boolean }) {
240
+ if (numbers.length > BULK_DISPATCH_LIMIT) {
241
+ throw Error400(`Dispatch at most ${BULK_DISPATCH_LIMIT} orders at once.`);
242
+ }
243
+ const results: { emailed: boolean; error?: string; number: string; ok: boolean }[] = [];
244
+ for (const number of new Set(numbers)) {
245
+ try {
246
+ // "Ready to dispatch" is only a list filter, so check each order is really ready.
247
+ const order = await findOrThrow(number);
248
+ if (order.status !== 'paid' || order.heldAt || !order.labelCreatedAt) {
249
+ throw Error400('Not ready to dispatch: it needs a label and must not be on hold.');
250
+ }
251
+ const { emailed } = await FulfilmentManager.markShipped(number, null, options);
252
+ results.push({ emailed, number, ok: true });
253
+ } catch (error) {
254
+ logger.error(error, { op: 'bulkDispatch', orderNumber: number });
255
+ results.push({
256
+ emailed: false,
257
+ error: error instanceof Error ? error.message : 'Could not dispatch.',
258
+ number,
259
+ ok: false,
260
+ });
261
+ }
224
262
  }
263
+ return results;
225
264
  },
226
265
 
227
266
  async saveParcel(number: string, parcel: Parcel) {
@@ -1,8 +1,9 @@
1
+ import { SchemaForm } from '@zeyolabs/kit/utils/form';
1
2
  import { z } from 'zod';
2
3
 
3
4
  import { PACKAGE_FORMATS } from '../db/schema';
4
5
  import { FormInput } from '../utils/form-input';
5
- import { ORDER_FILTERS } from './filters';
6
+ import { BULK_DISPATCH_LIMIT, ORDER_FILTERS } from './filters';
6
7
 
7
8
  export const OrderListSchema = z.object({
8
9
  filter: z.enum(ORDER_FILTERS).default('to-ship'),
@@ -12,6 +13,8 @@ export const OrderListSchema = z.object({
12
13
  /** Royal Mail tracking numbers are letters and digits (e.g. AB123456789GB); blank means untracked. */
13
14
  export const ShipSchema = z.object({
14
15
  number: z.string().regex(/^[A-Z]{2,5}-[A-Z0-9]{6}$/, 'invalid order number'),
16
+ /** Tick to dispatch without emailing the customer (e.g. the email already went another way). */
17
+ skipEmail: SchemaForm.Boolean,
15
18
  trackingNumber: z
16
19
  .string()
17
20
  .transform((value) => value.replace(/\s+/g, '').toUpperCase())
@@ -50,6 +53,12 @@ export const ParcelSchema = z
50
53
  { message: 'give length, width and height, or leave all three blank', path: ['lengthMm'] }
51
54
  );
52
55
 
56
+ /** Orders ticked on the list. Capped at `BULK_DISPATCH_LIMIT`. */
57
+ export const BulkDispatchSchema = z.object({
58
+ numbers: z.array(OrderNumber).min(1).max(BULK_DISPATCH_LIMIT),
59
+ sendEmail: z.boolean(),
60
+ });
61
+
53
62
  /** Pounds as typed ("12.50"); the amount is refunded in full or in part, up to what is left. */
54
63
  export const RefundSchema = z.object({
55
64
  amount: z
@@ -1,5 +1,5 @@
1
1
  import { Error400, Error404 } from '@zeyolabs/kit/utils/errors';
2
- import { and, asc, count, desc, eq, inArray, or, sql } from 'drizzle-orm';
2
+ import { and, asc, count, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
3
3
 
4
4
  import type { ShopDb } from '../db/index';
5
5
  import type { OrderFilter } from './filters';
@@ -18,21 +18,47 @@ export type Parcel = {
18
18
 
19
19
  type OrderRow = typeof orders.$inferSelect;
20
20
 
21
+ /** The SQL condition behind each list filter: paid orders are split by hold and label. */
22
+ function filterCondition(filter: OrderFilter) {
23
+ switch (filter) {
24
+ case 'all':
25
+ return undefined;
26
+ case 'on-hold':
27
+ return and(eq(orders.status, 'paid'), isNotNull(orders.heldAt));
28
+ case 'ready':
29
+ return and(
30
+ eq(orders.status, 'paid'),
31
+ isNull(orders.heldAt),
32
+ isNotNull(orders.labelCreatedAt)
33
+ );
34
+ case 'shipped':
35
+ return eq(orders.status, 'shipped');
36
+ case 'to-ship':
37
+ return eq(orders.status, 'paid');
38
+ }
39
+ }
40
+
21
41
  /** Fulfilment data access: the order list, one order in full, and the packing state changes. */
22
42
  export class FulfilmentService {
23
43
  constructor(private readonly db: ShopDb) {}
24
44
 
25
45
  /** Order counts per list filter, for the filter tabs. */
26
46
  async counts(): Promise<Record<OrderFilter, number>> {
27
- const rows = await this.db
28
- .select({ n: count(), status: orders.status })
29
- .from(orders)
30
- .groupBy(orders.status);
31
- const byStatus = Object.fromEntries(rows.map((r) => [r.status, r.n]));
47
+ const [row] = await this.db
48
+ .select({
49
+ all: count(),
50
+ onHold: sql<number>`coalesce(sum(${orders.status} = 'paid' and ${orders.heldAt} is not null), 0)`,
51
+ ready: sql<number>`coalesce(sum(${orders.status} = 'paid' and ${orders.heldAt} is null and ${orders.labelCreatedAt} is not null), 0)`,
52
+ shipped: sql<number>`coalesce(sum(${orders.status} = 'shipped'), 0)`,
53
+ toShip: sql<number>`coalesce(sum(${orders.status} = 'paid'), 0)`,
54
+ })
55
+ .from(orders);
32
56
  return {
33
- all: rows.reduce((sum, r) => sum + r.n, 0),
34
- shipped: byStatus.shipped ?? 0,
35
- 'to-ship': byStatus.paid ?? 0,
57
+ all: row.all,
58
+ 'on-hold': Number(row.onHold),
59
+ ready: Number(row.ready),
60
+ shipped: Number(row.shipped),
61
+ 'to-ship': Number(row.toShip),
36
62
  };
37
63
  }
38
64
 
@@ -71,8 +97,7 @@ export class FulfilmentService {
71
97
  .innerJoin(addresses, eq(orders.shippingAddressId, addresses.id))
72
98
  .where(
73
99
  and(
74
- filter === 'to-ship' ? eq(orders.status, 'paid') : undefined,
75
- filter === 'shipped' ? eq(orders.status, 'shipped') : undefined,
100
+ filterCondition(filter),
76
101
  match
77
102
  ? or(
78
103
  sql`${orders.number} like ${match} escape '\\'`,
@@ -82,7 +107,11 @@ export class FulfilmentService {
82
107
  : undefined
83
108
  )
84
109
  )
85
- .orderBy(filter === 'to-ship' ? asc(orders.createdAt) : desc(orders.createdAt))
110
+ .orderBy(
111
+ filter === 'to-ship' || filter === 'ready' || filter === 'on-hold'
112
+ ? asc(orders.createdAt)
113
+ : desc(orders.createdAt)
114
+ )
86
115
  .limit(200);
87
116
  }
88
117
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeyolabs/shopping",
3
- "version": "2026.11.15",
3
+ "version": "2026.11.16",
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",