@zeyolabs/shopping 2026.11.14 → 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.
- package/db/schema.ts +2 -0
- package/fulfilment/admin/OrderPage.svelte +35 -3
- package/fulfilment/admin/OrdersPage.svelte +92 -3
- package/fulfilment/admin.remote.ts +34 -3
- package/fulfilment/filters.ts +6 -1
- package/fulfilment/manager.server.ts +86 -4
- package/fulfilment/refund.server.ts +65 -0
- package/fulfilment/schema.ts +24 -1
- package/fulfilment/service.server.ts +56 -12
- package/package.json +1 -1
package/db/schema.ts
CHANGED
|
@@ -221,6 +221,8 @@ export const orders = sqliteTable(
|
|
|
221
221
|
/** When someone started packing it, so two people don't pack the same order. */
|
|
222
222
|
packingStartedAt: integer('packing_started_at'),
|
|
223
223
|
paidAt: integer('paid_at'),
|
|
224
|
+
/** Total refunded through Stripe so far, in pence. Equal to `totalPence` means fully refunded. */
|
|
225
|
+
refundedPence: integer('refunded_pence').notNull().default(0),
|
|
224
226
|
/** Click & Drop order identifier, once the order has been pushed to Royal Mail. */
|
|
225
227
|
royalMailOrderId: text('royal_mail_order_id'),
|
|
226
228
|
shippedAt: integer('shipped_at'),
|
|
@@ -6,18 +6,20 @@
|
|
|
6
6
|
createOrderLabel,
|
|
7
7
|
getOrder,
|
|
8
8
|
parcelForm,
|
|
9
|
+
refundForm,
|
|
9
10
|
shipForm,
|
|
10
11
|
updateOrderForm,
|
|
11
12
|
} from '../admin.remote';
|
|
12
|
-
import { OrderStepSchema, ParcelSchema, ShipSchema } from '../schema';
|
|
13
|
+
import { OrderStepSchema, ParcelSchema, RefundSchema, ShipSchema } from '../schema';
|
|
13
14
|
import { Money } from '../../utils/money';
|
|
15
|
+
import { FormInput } from '../../utils/form-input';
|
|
14
16
|
import { Orders } from '../../orders/library';
|
|
15
17
|
import { toast } from 'svelte-sonner';
|
|
16
18
|
import { PACKAGE_FORMATS } from '../../db/schema';
|
|
17
19
|
import { Packing } from '../library';
|
|
18
20
|
import Badge from '@zeyolabs/ui/badge/Badge.svelte';
|
|
19
21
|
import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
|
|
20
|
-
import { Form, NumberField, SelectField, TextField } from '@zeyolabs/ui/form';
|
|
22
|
+
import { CheckboxField, Form, NumberField, SelectField, TextField } from '@zeyolabs/ui/form';
|
|
21
23
|
import Button from '@zeyolabs/ui/form/Button.svelte';
|
|
22
24
|
|
|
23
25
|
const number = $derived(page.params.number ?? '');
|
|
@@ -119,6 +121,12 @@
|
|
|
119
121
|
<dt>Total</dt>
|
|
120
122
|
<dd>{Money.format(order.totalPence)}</dd>
|
|
121
123
|
</div>
|
|
124
|
+
{#if order.refundedPence > 0}
|
|
125
|
+
<div class="flex justify-between">
|
|
126
|
+
<dt>Refunded</dt>
|
|
127
|
+
<dd>-{Money.format(order.refundedPence)}</dd>
|
|
128
|
+
</div>
|
|
129
|
+
{/if}
|
|
122
130
|
</dl>
|
|
123
131
|
</section>
|
|
124
132
|
</div>
|
|
@@ -230,6 +238,29 @@
|
|
|
230
238
|
</section>
|
|
231
239
|
{/if}
|
|
232
240
|
|
|
241
|
+
{#if (order.status === 'paid' || order.status === 'shipped') && order.stripePaymentIntentId && order.refundedPence < order.totalPence}
|
|
242
|
+
{let left = $derived(order.totalPence - order.refundedPence)}
|
|
243
|
+
<section class="mt-6 max-w-xl rounded-xl border border-[var(--line)] bg-white p-5">
|
|
244
|
+
<h2 class="font-semibold">Refund</h2>
|
|
245
|
+
<p class="mt-1 text-sm text-[var(--ink-muted)]">
|
|
246
|
+
Up to {Money.format(left)} can be refunded to the customer's card through Stripe. A full refund
|
|
247
|
+
marks the order refunded, even if it had shipped, and does not cancel a Royal Mail label. Stock
|
|
248
|
+
is not put back; do that on the stock page if the goods come back.
|
|
249
|
+
</p>
|
|
250
|
+
<Form
|
|
251
|
+
class="mt-4 grid gap-4"
|
|
252
|
+
defaults={{ amount: FormInput.penceToPounds(left) }}
|
|
253
|
+
form={refundForm}
|
|
254
|
+
hidden={{ number: order.number }}
|
|
255
|
+
reset={false}
|
|
256
|
+
schema={RefundSchema}
|
|
257
|
+
>
|
|
258
|
+
<TextField name="amount" form={refundForm} inputmode="decimal">Amount (£)</TextField>
|
|
259
|
+
<div><Button form={refundForm} variant="secondary">Refund</Button></div>
|
|
260
|
+
</Form>
|
|
261
|
+
</section>
|
|
262
|
+
{/if}
|
|
263
|
+
|
|
233
264
|
<section class="mt-6 max-w-xl rounded-xl border border-[var(--line)] bg-white p-5">
|
|
234
265
|
<h2 class="font-semibold">Dispatch</h2>
|
|
235
266
|
{#if order.status === 'paid' || order.status === 'shipped'}
|
|
@@ -250,7 +281,7 @@
|
|
|
250
281
|
{/if}
|
|
251
282
|
<Form
|
|
252
283
|
class="mt-4 grid gap-4"
|
|
253
|
-
defaults={{ trackingNumber: order.trackingNumber ?? '' }}
|
|
284
|
+
defaults={{ skipEmail: false, trackingNumber: order.trackingNumber ?? '' }}
|
|
254
285
|
form={shipForm}
|
|
255
286
|
hidden={{ number: order.number }}
|
|
256
287
|
reset={false}
|
|
@@ -259,6 +290,7 @@
|
|
|
259
290
|
<TextField name="trackingNumber" autocapitalize="characters" form={shipForm} optional>
|
|
260
291
|
Tracking number
|
|
261
292
|
</TextField>
|
|
293
|
+
<CheckboxField name="skipEmail" form={shipForm}>Do not email the customer</CheckboxField>
|
|
262
294
|
<div>
|
|
263
295
|
<Button form={shipForm} loadingMessage="Sending…">
|
|
264
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>
|
|
@@ -2,7 +2,15 @@ import { Remote } from '@zeyolabs/kit/server/remote-functions';
|
|
|
2
2
|
import { FormResult } from '@zeyolabs/kit/utils/form';
|
|
3
3
|
|
|
4
4
|
import { FulfilmentManager } from './manager.server';
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
BulkDispatchSchema,
|
|
7
|
+
OrderListSchema,
|
|
8
|
+
OrderNumber,
|
|
9
|
+
OrderStepSchema,
|
|
10
|
+
ParcelSchema,
|
|
11
|
+
RefundSchema,
|
|
12
|
+
ShipSchema,
|
|
13
|
+
} from './schema';
|
|
6
14
|
|
|
7
15
|
export const getOrders = Remote.Query(OrderListSchema, ({ filter, q }) =>
|
|
8
16
|
FulfilmentManager.list(filter, q)
|
|
@@ -12,9 +20,12 @@ export const getOrderCounts = Remote.Query(() => FulfilmentManager.counts());
|
|
|
12
20
|
|
|
13
21
|
export const getOrder = Remote.Query(OrderNumber, (number) => FulfilmentManager.find(number));
|
|
14
22
|
|
|
15
|
-
export const shipForm = Remote.Form(ShipSchema, async ({ number, trackingNumber }) => {
|
|
16
|
-
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
|
+
});
|
|
17
27
|
await Promise.all([getOrder(number).refresh(), getOrderCounts().refresh()]);
|
|
28
|
+
if (skipped) return FormResult.ok('Marked as dispatched. The customer was not emailed.');
|
|
18
29
|
return emailed
|
|
19
30
|
? FormResult.ok('Marked as dispatched and the customer has been emailed.')
|
|
20
31
|
: FormResult.warn(
|
|
@@ -56,3 +67,23 @@ export const createOrderLabel = Remote.Cmd(OrderNumber, async (number) => {
|
|
|
56
67
|
await FulfilmentManager.createLabel(number);
|
|
57
68
|
await getOrder(number).refresh();
|
|
58
69
|
});
|
|
70
|
+
|
|
71
|
+
export const refundForm = Remote.Form(RefundSchema, async ({ amount, number }) => {
|
|
72
|
+
const { fullyRefunded } = await FulfilmentManager.refund(number, amount);
|
|
73
|
+
await Promise.all([getOrder(number).refresh(), getOrderCounts().refresh()]);
|
|
74
|
+
return FormResult.ok(
|
|
75
|
+
fullyRefunded
|
|
76
|
+
? 'Refunded in full. Put the stock back on the stock page if the goods are returned.'
|
|
77
|
+
: 'Partly refunded.'
|
|
78
|
+
);
|
|
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
|
+
});
|
package/fulfilment/filters.ts
CHANGED
|
@@ -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;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { logger } from '@zeyolabs/kit/server/logger';
|
|
2
2
|
import { Crypto } from '@zeyolabs/kit/utils/crypto';
|
|
3
|
-
import { Error400, Error404 } from '@zeyolabs/kit/utils/errors';
|
|
3
|
+
import { Error400, Error404, Error500 } from '@zeyolabs/kit/utils/errors';
|
|
4
4
|
|
|
5
5
|
import type { OrderStep } from './schema';
|
|
6
6
|
|
|
@@ -9,6 +9,9 @@ import { shopping } from '../config';
|
|
|
9
9
|
import { Orders } from '../orders/library';
|
|
10
10
|
import { OrderManager } from '../orders/manager.server';
|
|
11
11
|
import { ShippingService } from '../shipping/service.server';
|
|
12
|
+
import { Money } from '../utils/money';
|
|
13
|
+
import { BULK_DISPATCH_LIMIT } from './filters';
|
|
14
|
+
import { OrderRefunds } from './refund.server';
|
|
12
15
|
import { FulfilmentService, type Parcel } from './service.server';
|
|
13
16
|
|
|
14
17
|
const service = () => new FulfilmentService(shopping().db());
|
|
@@ -97,6 +100,47 @@ export const FulfilmentManager = {
|
|
|
97
100
|
});
|
|
98
101
|
},
|
|
99
102
|
|
|
103
|
+
/**
|
|
104
|
+
* Refunds `pence` of a paid or shipped order through Stripe and records Stripe's new total.
|
|
105
|
+
* Stripe is the source of truth (see `OrderRefunds`), so a refund made in its dashboard, a
|
|
106
|
+
* double click or a failed database write cannot make this order disagree with it. Stock is not
|
|
107
|
+
* put back: the admin does that on the stock page. A full refund marks the order refunded even
|
|
108
|
+
* if it had shipped; a label for a parcel not yet posted is not cancelled.
|
|
109
|
+
*/
|
|
110
|
+
async refund(number: string, pence: number) {
|
|
111
|
+
const order = await findOrThrow(number);
|
|
112
|
+
if (order.status !== 'paid' && order.status !== 'shipped') {
|
|
113
|
+
throw Error400(`This order is ${order.status}, so it cannot be refunded.`);
|
|
114
|
+
}
|
|
115
|
+
if (!order.stripePaymentIntentId) throw Error400('This order has no Stripe payment to refund.');
|
|
116
|
+
|
|
117
|
+
const result = await OrderRefunds.run(
|
|
118
|
+
ShopClients.stripe(),
|
|
119
|
+
{ number: order.number, stripePaymentIntentId: order.stripePaymentIntentId },
|
|
120
|
+
pence
|
|
121
|
+
);
|
|
122
|
+
try {
|
|
123
|
+
await service().setRefunded(order.id, result.refundedPence);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
// Stripe has the money back already, so retrying would look like a second refund.
|
|
126
|
+
logger.error(error, {
|
|
127
|
+
amountPence: pence,
|
|
128
|
+
op: 'refundRecord',
|
|
129
|
+
orderNumber: order.number,
|
|
130
|
+
refundedPence: result.refundedPence,
|
|
131
|
+
});
|
|
132
|
+
throw Error500(
|
|
133
|
+
`Stripe refunded ${Money.format(result.refundedPence)} but it was not recorded here. Do not retry; reload the page.`
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
logger.info('refund', {
|
|
137
|
+
amountPence: pence,
|
|
138
|
+
order: order.number,
|
|
139
|
+
refundedPence: result.refundedPence,
|
|
140
|
+
});
|
|
141
|
+
return { fullyRefunded: result.fullyRefunded };
|
|
142
|
+
},
|
|
143
|
+
|
|
100
144
|
/** The order in full, with the customer's order page link. */
|
|
101
145
|
async find(number: string) {
|
|
102
146
|
const order = await findOrThrow(number);
|
|
@@ -133,7 +177,11 @@ export const FulfilmentManager = {
|
|
|
133
177
|
* database change comes first: a failed email never undoes a parcel that has really left, and
|
|
134
178
|
* the result says whether the email went so the admin can resend it.
|
|
135
179
|
*/
|
|
136
|
-
async markShipped(
|
|
180
|
+
async markShipped(
|
|
181
|
+
number: string,
|
|
182
|
+
trackingNumber: null | string,
|
|
183
|
+
options: { email?: boolean } = {}
|
|
184
|
+
) {
|
|
137
185
|
const order = await findOrThrow(number);
|
|
138
186
|
const { address } = order;
|
|
139
187
|
if (order.status !== 'paid' && order.status !== 'shipped') {
|
|
@@ -165,6 +213,8 @@ export const FulfilmentManager = {
|
|
|
165
213
|
trackingNumber: tracking,
|
|
166
214
|
});
|
|
167
215
|
|
|
216
|
+
if (options.email === false) return { emailed: false, skipped: true };
|
|
217
|
+
|
|
168
218
|
try {
|
|
169
219
|
await shopping().mail.orderDispatched({
|
|
170
220
|
address,
|
|
@@ -174,11 +224,43 @@ export const FulfilmentManager = {
|
|
|
174
224
|
trackingNumber: tracking,
|
|
175
225
|
});
|
|
176
226
|
await fulfilment.update(order.id, { dispatchEmailedAt: now });
|
|
177
|
-
return { emailed: true };
|
|
227
|
+
return { emailed: true, skipped: false };
|
|
178
228
|
} catch (error) {
|
|
179
229
|
logger.error(error, { op: 'dispatchEmail', orderNumber: order.number });
|
|
180
|
-
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
|
+
}
|
|
181
262
|
}
|
|
263
|
+
return results;
|
|
182
264
|
},
|
|
183
265
|
|
|
184
266
|
async saveParcel(number: string, parcel: Parcel) {
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { Error400 } from '@zeyolabs/kit/utils/errors';
|
|
2
|
+
|
|
3
|
+
import { Money } from '../utils/money';
|
|
4
|
+
|
|
5
|
+
/** The slice of the Stripe SDK refunds use, so a test can pass a fake. */
|
|
6
|
+
export type RefundStripe = {
|
|
7
|
+
charges: { retrieve(id: string): Promise<{ amount: number; amount_refunded: number }> };
|
|
8
|
+
paymentIntents: {
|
|
9
|
+
retrieve(id: string): Promise<{ latest_charge: null | string | { id: string } }>;
|
|
10
|
+
};
|
|
11
|
+
refunds: {
|
|
12
|
+
create(
|
|
13
|
+
params: { amount: number; metadata: Record<string, string>; payment_intent: string },
|
|
14
|
+
options: { idempotencyKey: string }
|
|
15
|
+
): Promise<unknown>;
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Refunds with Stripe as the source of truth. What was already refunded is read from the charge,
|
|
21
|
+
* not from our database, so a refund Stripe accepted but we failed to record (or one made in the
|
|
22
|
+
* Stripe dashboard) is never refunded twice. After refunding, the new total is read back so the
|
|
23
|
+
* caller records an absolute amount: recording twice, or two admins at once, ends in the same value.
|
|
24
|
+
*/
|
|
25
|
+
export const OrderRefunds = {
|
|
26
|
+
async run(
|
|
27
|
+
stripe: RefundStripe,
|
|
28
|
+
order: { number: string; stripePaymentIntentId: string },
|
|
29
|
+
pence: number
|
|
30
|
+
): Promise<{ amount: number; fullyRefunded: boolean; refundedPence: number }> {
|
|
31
|
+
const charge = await OrderRefunds.charge(stripe, order.stripePaymentIntentId);
|
|
32
|
+
const left = charge.amount - charge.amount_refunded;
|
|
33
|
+
if (pence > left) {
|
|
34
|
+
throw Error400(
|
|
35
|
+
left > 0
|
|
36
|
+
? `Only ${Money.format(left)} is left to refund on this order.`
|
|
37
|
+
: 'This order is already fully refunded.'
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
// Keyed on what Stripe has refunded so far: a same-amount retry or double click gets the same
|
|
41
|
+
// refund back, a different amount gets its own.
|
|
42
|
+
await stripe.refunds.create(
|
|
43
|
+
{
|
|
44
|
+
amount: pence,
|
|
45
|
+
metadata: { order: order.number },
|
|
46
|
+
payment_intent: order.stripePaymentIntentId,
|
|
47
|
+
},
|
|
48
|
+
{ idempotencyKey: `refund-${order.number}-${charge.amount_refunded}-${pence}` }
|
|
49
|
+
);
|
|
50
|
+
const after = await OrderRefunds.charge(stripe, order.stripePaymentIntentId);
|
|
51
|
+
return {
|
|
52
|
+
amount: after.amount,
|
|
53
|
+
fullyRefunded: after.amount_refunded >= after.amount,
|
|
54
|
+
refundedPence: after.amount_refunded,
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
async charge(stripe: RefundStripe, paymentIntentId: string) {
|
|
59
|
+
const intent = await stripe.paymentIntents.retrieve(paymentIntentId);
|
|
60
|
+
const id =
|
|
61
|
+
typeof intent.latest_charge === 'string' ? intent.latest_charge : intent.latest_charge?.id;
|
|
62
|
+
if (!id) throw Error400('This payment has no charge to refund.');
|
|
63
|
+
return stripe.charges.retrieve(id);
|
|
64
|
+
},
|
|
65
|
+
};
|
package/fulfilment/schema.ts
CHANGED
|
@@ -1,7 +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
|
-
import {
|
|
5
|
+
import { FormInput } from '../utils/form-input';
|
|
6
|
+
import { BULK_DISPATCH_LIMIT, ORDER_FILTERS } from './filters';
|
|
5
7
|
|
|
6
8
|
export const OrderListSchema = z.object({
|
|
7
9
|
filter: z.enum(ORDER_FILTERS).default('to-ship'),
|
|
@@ -11,6 +13,8 @@ export const OrderListSchema = z.object({
|
|
|
11
13
|
/** Royal Mail tracking numbers are letters and digits (e.g. AB123456789GB); blank means untracked. */
|
|
12
14
|
export const ShipSchema = z.object({
|
|
13
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,
|
|
14
18
|
trackingNumber: z
|
|
15
19
|
.string()
|
|
16
20
|
.transform((value) => value.replace(/\s+/g, '').toUpperCase())
|
|
@@ -48,3 +52,22 @@ export const ParcelSchema = z
|
|
|
48
52
|
[heightMm, lengthMm, widthMm].every((v) => v !== undefined),
|
|
49
53
|
{ message: 'give length, width and height, or leave all three blank', path: ['lengthMm'] }
|
|
50
54
|
);
|
|
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
|
+
|
|
62
|
+
/** Pounds as typed ("12.50"); the amount is refunded in full or in part, up to what is left. */
|
|
63
|
+
export const RefundSchema = z.object({
|
|
64
|
+
amount: z
|
|
65
|
+
.string()
|
|
66
|
+
.trim()
|
|
67
|
+
.refine((v) => {
|
|
68
|
+
const pence = FormInput.parsePounds(v);
|
|
69
|
+
return pence !== null && !Number.isNaN(pence) && pence > 0;
|
|
70
|
+
}, 'enter an amount like 12.50')
|
|
71
|
+
.transform((v) => FormInput.parsePounds(v) as number),
|
|
72
|
+
number: OrderNumber,
|
|
73
|
+
});
|
|
@@ -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
|
|
28
|
-
.select({
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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:
|
|
34
|
-
|
|
35
|
-
|
|
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
|
|
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(
|
|
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
|
|
|
@@ -121,6 +150,21 @@ export class FulfilmentService {
|
|
|
121
150
|
await this.update(order.id, { heldAt: held ? now : null });
|
|
122
151
|
}
|
|
123
152
|
|
|
153
|
+
/**
|
|
154
|
+
* Sets the order's refunded total to what Stripe reports (never lower than recorded), so
|
|
155
|
+
* recording the same refund twice, or two at once, gives the same result. Reaching the order
|
|
156
|
+
* total makes it `refunded`.
|
|
157
|
+
*/
|
|
158
|
+
async setRefunded(orderId: number, refundedPence: number) {
|
|
159
|
+
await this.db
|
|
160
|
+
.update(orders)
|
|
161
|
+
.set({
|
|
162
|
+
refundedPence: sql`max(${orders.refundedPence}, ${refundedPence})`,
|
|
163
|
+
status: sql`case when ${refundedPence} >= ${orders.totalPence} then 'refunded' else ${orders.status} end`,
|
|
164
|
+
})
|
|
165
|
+
.where(eq(orders.id, orderId));
|
|
166
|
+
}
|
|
167
|
+
|
|
124
168
|
async startPacking(number: string, now = Date.now()) {
|
|
125
169
|
const order = await this.packable(number);
|
|
126
170
|
if (order.packingStartedAt && !order.heldAt) return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zeyolabs/shopping",
|
|
3
|
-
"version": "2026.11.
|
|
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",
|