@zeyolabs/shopping 2026.11.15 → 2026.11.17
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.
- package/fulfilment/admin/OrderPage.svelte +3 -2
- package/fulfilment/admin/OrdersPage.svelte +97 -3
- package/fulfilment/admin.remote.ts +22 -3
- package/fulfilment/filters.ts +7 -1
- package/fulfilment/manager.server.ts +47 -3
- package/fulfilment/schema.ts +10 -1
- package/fulfilment/service.server.ts +55 -12
- package/package.json +1 -1
|
@@ -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, getReadyByService } 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',
|
|
@@ -52,6 +97,11 @@
|
|
|
52
97
|
</a>
|
|
53
98
|
<!-- eslint-enable svelte/no-navigation-without-resolve -->
|
|
54
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>
|
|
55
105
|
<form
|
|
56
106
|
class="ml-auto"
|
|
57
107
|
onsubmit={(event) => {
|
|
@@ -73,15 +123,45 @@
|
|
|
73
123
|
|
|
74
124
|
<Boundary message="Could not load orders.">
|
|
75
125
|
{let rows = $derived(await getOrders({ filter, q }))}
|
|
126
|
+
<!-- Only orders still on screen: a search or tab change must not dispatch hidden ticks. -->
|
|
127
|
+
{let chosen = $derived(rows.map((r) => r.number).filter((n) => selected.has(n)))}
|
|
76
128
|
{#if rows.length === 0}
|
|
77
129
|
<p class="mt-6 text-[var(--ink-muted)]">
|
|
78
130
|
{filter === 'to-ship' && !q ? 'Nothing to ship. All caught up.' : 'No orders match.'}
|
|
79
131
|
</p>
|
|
80
132
|
{:else}
|
|
133
|
+
{#if filter === 'ready'}
|
|
134
|
+
<div class="mt-4 flex flex-wrap items-center gap-4 text-sm">
|
|
135
|
+
<label class="flex items-center gap-2">
|
|
136
|
+
<input
|
|
137
|
+
checked={rows.length > 0 &&
|
|
138
|
+
chosen.length === Math.min(rows.length, BULK_DISPATCH_LIMIT)}
|
|
139
|
+
onchange={(event) => {
|
|
140
|
+
selected.clear();
|
|
141
|
+
if (event.currentTarget.checked)
|
|
142
|
+
for (const r of rows.slice(0, BULK_DISPATCH_LIMIT)) selected.add(r.number);
|
|
143
|
+
}}
|
|
144
|
+
type="checkbox"
|
|
145
|
+
/>
|
|
146
|
+
Select {Math.min(rows.length, BULK_DISPATCH_LIMIT)}
|
|
147
|
+
</label>
|
|
148
|
+
<label class="flex items-center gap-2">
|
|
149
|
+
<input bind:checked={sendEmail} type="checkbox" />
|
|
150
|
+
Email the customers
|
|
151
|
+
</label>
|
|
152
|
+
<Button
|
|
153
|
+
disabled={chosen.length === 0 || dispatching}
|
|
154
|
+
onclick={() => dispatchSelected(chosen)}
|
|
155
|
+
>
|
|
156
|
+
Dispatch {chosen.length} order{chosen.length === 1 ? '' : 's'}
|
|
157
|
+
</Button>
|
|
158
|
+
</div>
|
|
159
|
+
{/if}
|
|
81
160
|
<div class="mt-4 overflow-x-auto rounded-xl border border-[var(--line)] bg-white">
|
|
82
161
|
<table class="w-full text-left text-sm">
|
|
83
162
|
<thead class="border-b border-[var(--line)] text-[var(--ink-muted)]">
|
|
84
163
|
<tr>
|
|
164
|
+
{#if filter === 'ready'}<th class="w-8 px-4 py-2"></th>{/if}
|
|
85
165
|
<th class="px-4 py-2 font-medium">Order</th>
|
|
86
166
|
<th class="px-4 py-2 font-medium">Placed</th>
|
|
87
167
|
<th class="px-4 py-2 font-medium">Customer</th>
|
|
@@ -92,6 +172,20 @@
|
|
|
92
172
|
<tbody class="divide-y divide-[var(--line)]">
|
|
93
173
|
{#each rows as row (row.number)}
|
|
94
174
|
<tr>
|
|
175
|
+
{#if filter === 'ready'}
|
|
176
|
+
<td class="px-4 py-2">
|
|
177
|
+
<input
|
|
178
|
+
aria-label="Select {row.number}"
|
|
179
|
+
checked={selected.has(row.number)}
|
|
180
|
+
disabled={!selected.has(row.number) && chosen.length >= BULK_DISPATCH_LIMIT}
|
|
181
|
+
onchange={(event) => {
|
|
182
|
+
if (event.currentTarget.checked) selected.add(row.number);
|
|
183
|
+
else selected.delete(row.number);
|
|
184
|
+
}}
|
|
185
|
+
type="checkbox"
|
|
186
|
+
/>
|
|
187
|
+
</td>
|
|
188
|
+
{/if}
|
|
95
189
|
<td class="px-4 py-2 font-medium">
|
|
96
190
|
<a href={resolve('/orders/[number]', { number: row.number })}>{row.number}</a>
|
|
97
191
|
</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,
|
|
@@ -16,12 +17,20 @@ export const getOrders = Remote.Query(OrderListSchema, ({ filter, q }) =>
|
|
|
16
17
|
);
|
|
17
18
|
|
|
18
19
|
export const getOrderCounts = Remote.Query(() => FulfilmentManager.counts());
|
|
20
|
+
export const getReadyByService = Remote.Query(() => FulfilmentManager.readyByService());
|
|
19
21
|
|
|
20
22
|
export const getOrder = Remote.Query(OrderNumber, (number) => FulfilmentManager.find(number));
|
|
21
23
|
|
|
22
|
-
export const shipForm = Remote.Form(ShipSchema, async ({ number, trackingNumber }) => {
|
|
23
|
-
const { emailed } = await FulfilmentManager.markShipped(number, trackingNumber || null
|
|
24
|
-
|
|
24
|
+
export const shipForm = Remote.Form(ShipSchema, async ({ number, skipEmail, trackingNumber }) => {
|
|
25
|
+
const { emailed, skipped } = await FulfilmentManager.markShipped(number, trackingNumber || null, {
|
|
26
|
+
email: !skipEmail,
|
|
27
|
+
});
|
|
28
|
+
await Promise.all([
|
|
29
|
+
getOrder(number).refresh(),
|
|
30
|
+
getOrderCounts().refresh(),
|
|
31
|
+
getReadyByService().refresh(),
|
|
32
|
+
]);
|
|
33
|
+
if (skipped) return FormResult.ok('Marked as dispatched. The customer was not emailed.');
|
|
25
34
|
return emailed
|
|
26
35
|
? FormResult.ok('Marked as dispatched and the customer has been emailed.')
|
|
27
36
|
: FormResult.warn(
|
|
@@ -73,3 +82,13 @@ export const refundForm = Remote.Form(RefundSchema, async ({ amount, number }) =
|
|
|
73
82
|
: 'Partly refunded.'
|
|
74
83
|
);
|
|
75
84
|
});
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Dispatches the ticked orders. A command, so it returns each order's result instead of throwing:
|
|
88
|
+
* the list shows which went through and which did not.
|
|
89
|
+
*/
|
|
90
|
+
export const dispatchOrders = Remote.Cmd(BulkDispatchSchema, async ({ numbers, sendEmail }) => {
|
|
91
|
+
const results = await FulfilmentManager.markShippedMany(numbers, { email: sendEmail });
|
|
92
|
+
await Promise.all([getOrderCounts().refresh(), getReadyByService().refresh()]);
|
|
93
|
+
return results;
|
|
94
|
+
});
|
package/fulfilment/filters.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
-
export const ORDER_FILTERS = ['to-ship', '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> = {
|
|
5
5
|
all: 'All',
|
|
6
|
+
'on-hold': 'On hold',
|
|
7
|
+
ready: 'Ready to dispatch',
|
|
6
8
|
shipped: 'Shipped',
|
|
7
9
|
'to-ship': 'To ship',
|
|
10
|
+
unpaid: 'Unpaid',
|
|
8
11
|
};
|
|
12
|
+
|
|
13
|
+
/** Orders one bulk dispatch may carry, to stay inside a Worker's subrequest budget. */
|
|
14
|
+
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
|
|
|
@@ -37,6 +38,11 @@ export const FulfilmentManager = {
|
|
|
37
38
|
return fulfilment.counts();
|
|
38
39
|
},
|
|
39
40
|
|
|
41
|
+
readyByService() {
|
|
42
|
+
const fulfilment = service();
|
|
43
|
+
return fulfilment.readyByService();
|
|
44
|
+
},
|
|
45
|
+
|
|
40
46
|
/**
|
|
41
47
|
* Makes sure Click & Drop holds this order with the parcel as packed, so its label is right.
|
|
42
48
|
* Click & Drop cannot edit an order, so until a label exists the old one is removed and
|
|
@@ -176,7 +182,11 @@ export const FulfilmentManager = {
|
|
|
176
182
|
* database change comes first: a failed email never undoes a parcel that has really left, and
|
|
177
183
|
* the result says whether the email went so the admin can resend it.
|
|
178
184
|
*/
|
|
179
|
-
async markShipped(
|
|
185
|
+
async markShipped(
|
|
186
|
+
number: string,
|
|
187
|
+
trackingNumber: null | string,
|
|
188
|
+
options: { email?: boolean } = {}
|
|
189
|
+
) {
|
|
180
190
|
const order = await findOrThrow(number);
|
|
181
191
|
const { address } = order;
|
|
182
192
|
if (order.status !== 'paid' && order.status !== 'shipped') {
|
|
@@ -208,6 +218,8 @@ export const FulfilmentManager = {
|
|
|
208
218
|
trackingNumber: tracking,
|
|
209
219
|
});
|
|
210
220
|
|
|
221
|
+
if (options.email === false) return { emailed: false, skipped: true };
|
|
222
|
+
|
|
211
223
|
try {
|
|
212
224
|
await shopping().mail.orderDispatched({
|
|
213
225
|
address,
|
|
@@ -217,11 +229,43 @@ export const FulfilmentManager = {
|
|
|
217
229
|
trackingNumber: tracking,
|
|
218
230
|
});
|
|
219
231
|
await fulfilment.update(order.id, { dispatchEmailedAt: now });
|
|
220
|
-
return { emailed: true };
|
|
232
|
+
return { emailed: true, skipped: false };
|
|
221
233
|
} catch (error) {
|
|
222
234
|
logger.error(error, { op: 'dispatchEmail', orderNumber: order.number });
|
|
223
|
-
return { emailed: false };
|
|
235
|
+
return { emailed: false, skipped: false };
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Dispatches several orders one after another (each is its own database change, so one that
|
|
241
|
+
* fails does not hold back the rest). Tracking numbers come from Click & Drop where a label
|
|
242
|
+
* exists. Capped, because each order can cost a Royal Mail call and an email.
|
|
243
|
+
*/
|
|
244
|
+
async markShippedMany(numbers: string[], options: { email: boolean }) {
|
|
245
|
+
if (numbers.length > BULK_DISPATCH_LIMIT) {
|
|
246
|
+
throw Error400(`Dispatch at most ${BULK_DISPATCH_LIMIT} orders at once.`);
|
|
247
|
+
}
|
|
248
|
+
const results: { emailed: boolean; error?: string; number: string; ok: boolean }[] = [];
|
|
249
|
+
for (const number of new Set(numbers)) {
|
|
250
|
+
try {
|
|
251
|
+
// "Ready to dispatch" is only a list filter, so check each order is really ready.
|
|
252
|
+
const order = await findOrThrow(number);
|
|
253
|
+
if (order.status !== 'paid' || order.heldAt || !order.labelCreatedAt) {
|
|
254
|
+
throw Error400('Not ready to dispatch: it needs a label and must not be on hold.');
|
|
255
|
+
}
|
|
256
|
+
const { emailed } = await FulfilmentManager.markShipped(number, null, options);
|
|
257
|
+
results.push({ emailed, number, ok: true });
|
|
258
|
+
} catch (error) {
|
|
259
|
+
logger.error(error, { op: 'bulkDispatch', orderNumber: number });
|
|
260
|
+
results.push({
|
|
261
|
+
emailed: false,
|
|
262
|
+
error: error instanceof Error ? error.message : 'Could not dispatch.',
|
|
263
|
+
number,
|
|
264
|
+
ok: false,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
224
267
|
}
|
|
268
|
+
return results;
|
|
225
269
|
},
|
|
226
270
|
|
|
227
271
|
async saveParcel(number: string, parcel: Parcel) {
|
package/fulfilment/schema.ts
CHANGED
|
@@ -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,51 @@ 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
|
+
case 'unpaid':
|
|
39
|
+
return eq(orders.status, 'pending');
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
21
43
|
/** Fulfilment data access: the order list, one order in full, and the packing state changes. */
|
|
22
44
|
export class FulfilmentService {
|
|
23
45
|
constructor(private readonly db: ShopDb) {}
|
|
24
46
|
|
|
25
47
|
/** Order counts per list filter, for the filter tabs. */
|
|
26
48
|
async counts(): Promise<Record<OrderFilter, number>> {
|
|
27
|
-
const
|
|
28
|
-
.select({
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
49
|
+
const [row] = await this.db
|
|
50
|
+
.select({
|
|
51
|
+
all: count(),
|
|
52
|
+
onHold: sql<number>`coalesce(sum(${orders.status} = 'paid' and ${orders.heldAt} is not null), 0)`,
|
|
53
|
+
ready: sql<number>`coalesce(sum(${orders.status} = 'paid' and ${orders.heldAt} is null and ${orders.labelCreatedAt} is not null), 0)`,
|
|
54
|
+
shipped: sql<number>`coalesce(sum(${orders.status} = 'shipped'), 0)`,
|
|
55
|
+
toShip: sql<number>`coalesce(sum(${orders.status} = 'paid'), 0)`,
|
|
56
|
+
unpaid: sql<number>`coalesce(sum(${orders.status} = 'pending'), 0)`,
|
|
57
|
+
})
|
|
58
|
+
.from(orders);
|
|
32
59
|
return {
|
|
33
|
-
all:
|
|
34
|
-
|
|
35
|
-
|
|
60
|
+
all: row.all,
|
|
61
|
+
'on-hold': Number(row.onHold),
|
|
62
|
+
ready: Number(row.ready),
|
|
63
|
+
shipped: Number(row.shipped),
|
|
64
|
+
'to-ship': Number(row.toShip),
|
|
65
|
+
unpaid: Number(row.unpaid),
|
|
36
66
|
};
|
|
37
67
|
}
|
|
38
68
|
|
|
@@ -71,8 +101,7 @@ export class FulfilmentService {
|
|
|
71
101
|
.innerJoin(addresses, eq(orders.shippingAddressId, addresses.id))
|
|
72
102
|
.where(
|
|
73
103
|
and(
|
|
74
|
-
filter
|
|
75
|
-
filter === 'shipped' ? eq(orders.status, 'shipped') : undefined,
|
|
104
|
+
filterCondition(filter),
|
|
76
105
|
match
|
|
77
106
|
? or(
|
|
78
107
|
sql`${orders.number} like ${match} escape '\\'`,
|
|
@@ -82,7 +111,11 @@ export class FulfilmentService {
|
|
|
82
111
|
: undefined
|
|
83
112
|
)
|
|
84
113
|
)
|
|
85
|
-
.orderBy(
|
|
114
|
+
.orderBy(
|
|
115
|
+
filter === 'to-ship' || filter === 'ready' || filter === 'on-hold'
|
|
116
|
+
? asc(orders.createdAt)
|
|
117
|
+
: desc(orders.createdAt)
|
|
118
|
+
)
|
|
86
119
|
.limit(200);
|
|
87
120
|
}
|
|
88
121
|
|
|
@@ -105,6 +138,16 @@ export class FulfilmentService {
|
|
|
105
138
|
return order;
|
|
106
139
|
}
|
|
107
140
|
|
|
141
|
+
/** Orders ready to dispatch (paid, not held, labelled), counted per postage service. */
|
|
142
|
+
async readyByService(): Promise<Record<string, number>> {
|
|
143
|
+
const rows = await this.db
|
|
144
|
+
.select({ n: count(), service: orders.shippingService })
|
|
145
|
+
.from(orders)
|
|
146
|
+
.where(filterCondition('ready'))
|
|
147
|
+
.groupBy(orders.shippingService);
|
|
148
|
+
return Object.fromEntries(rows.map((r) => [r.service ?? 'No service', r.n]));
|
|
149
|
+
}
|
|
150
|
+
|
|
108
151
|
async saveParcel(number: string, parcel: Parcel) {
|
|
109
152
|
const order = await this.packable(number);
|
|
110
153
|
await this.update(order.id, {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zeyolabs/shopping",
|
|
3
|
-
"version": "2026.11.
|
|
3
|
+
"version": "2026.11.17",
|
|
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",
|