@zeyolabs/shopping 2026.11.13 → 2026.11.15

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 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,11 +6,13 @@
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';
@@ -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'}
@@ -2,7 +2,14 @@ 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 { OrderListSchema, OrderNumber, OrderStepSchema, ParcelSchema, ShipSchema } from './schema';
5
+ import {
6
+ OrderListSchema,
7
+ OrderNumber,
8
+ OrderStepSchema,
9
+ ParcelSchema,
10
+ RefundSchema,
11
+ ShipSchema,
12
+ } from './schema';
6
13
 
7
14
  export const getOrders = Remote.Query(OrderListSchema, ({ filter, q }) =>
8
15
  FulfilmentManager.list(filter, q)
@@ -56,3 +63,13 @@ export const createOrderLabel = Remote.Cmd(OrderNumber, async (number) => {
56
63
  await FulfilmentManager.createLabel(number);
57
64
  await getOrder(number).refresh();
58
65
  });
66
+
67
+ export const refundForm = Remote.Form(RefundSchema, async ({ amount, number }) => {
68
+ const { fullyRefunded } = await FulfilmentManager.refund(number, amount);
69
+ await Promise.all([getOrder(number).refresh(), getOrderCounts().refresh()]);
70
+ return FormResult.ok(
71
+ fullyRefunded
72
+ ? 'Refunded in full. Put the stock back on the stock page if the goods are returned.'
73
+ : 'Partly refunded.'
74
+ );
75
+ });
@@ -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,8 @@ 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 { OrderRefunds } from './refund.server';
12
14
  import { FulfilmentService, type Parcel } from './service.server';
13
15
 
14
16
  const service = () => new FulfilmentService(shopping().db());
@@ -97,6 +99,47 @@ export const FulfilmentManager = {
97
99
  });
98
100
  },
99
101
 
102
+ /**
103
+ * Refunds `pence` of a paid or shipped order through Stripe and records Stripe's new total.
104
+ * Stripe is the source of truth (see `OrderRefunds`), so a refund made in its dashboard, a
105
+ * double click or a failed database write cannot make this order disagree with it. Stock is not
106
+ * put back: the admin does that on the stock page. A full refund marks the order refunded even
107
+ * if it had shipped; a label for a parcel not yet posted is not cancelled.
108
+ */
109
+ async refund(number: string, pence: number) {
110
+ const order = await findOrThrow(number);
111
+ if (order.status !== 'paid' && order.status !== 'shipped') {
112
+ throw Error400(`This order is ${order.status}, so it cannot be refunded.`);
113
+ }
114
+ if (!order.stripePaymentIntentId) throw Error400('This order has no Stripe payment to refund.');
115
+
116
+ const result = await OrderRefunds.run(
117
+ ShopClients.stripe(),
118
+ { number: order.number, stripePaymentIntentId: order.stripePaymentIntentId },
119
+ pence
120
+ );
121
+ try {
122
+ await service().setRefunded(order.id, result.refundedPence);
123
+ } catch (error) {
124
+ // Stripe has the money back already, so retrying would look like a second refund.
125
+ logger.error(error, {
126
+ amountPence: pence,
127
+ op: 'refundRecord',
128
+ orderNumber: order.number,
129
+ refundedPence: result.refundedPence,
130
+ });
131
+ throw Error500(
132
+ `Stripe refunded ${Money.format(result.refundedPence)} but it was not recorded here. Do not retry; reload the page.`
133
+ );
134
+ }
135
+ logger.info('refund', {
136
+ amountPence: pence,
137
+ order: order.number,
138
+ refundedPence: result.refundedPence,
139
+ });
140
+ return { fullyRefunded: result.fullyRefunded };
141
+ },
142
+
100
143
  /** The order in full, with the customer's order page link. */
101
144
  async find(number: string) {
102
145
  const order = await findOrThrow(number);
@@ -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
+ };
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  import { PACKAGE_FORMATS } from '../db/schema';
4
+ import { FormInput } from '../utils/form-input';
4
5
  import { ORDER_FILTERS } from './filters';
5
6
 
6
7
  export const OrderListSchema = z.object({
@@ -48,3 +49,16 @@ export const ParcelSchema = z
48
49
  [heightMm, lengthMm, widthMm].every((v) => v !== undefined),
49
50
  { message: 'give length, width and height, or leave all three blank', path: ['lengthMm'] }
50
51
  );
52
+
53
+ /** Pounds as typed ("12.50"); the amount is refunded in full or in part, up to what is left. */
54
+ export const RefundSchema = z.object({
55
+ amount: z
56
+ .string()
57
+ .trim()
58
+ .refine((v) => {
59
+ const pence = FormInput.parsePounds(v);
60
+ return pence !== null && !Number.isNaN(pence) && pence > 0;
61
+ }, 'enter an amount like 12.50')
62
+ .transform((v) => FormInput.parsePounds(v) as number),
63
+ number: OrderNumber,
64
+ });
@@ -121,6 +121,21 @@ export class FulfilmentService {
121
121
  await this.update(order.id, { heldAt: held ? now : null });
122
122
  }
123
123
 
124
+ /**
125
+ * Sets the order's refunded total to what Stripe reports (never lower than recorded), so
126
+ * recording the same refund twice, or two at once, gives the same result. Reaching the order
127
+ * total makes it `refunded`.
128
+ */
129
+ async setRefunded(orderId: number, refundedPence: number) {
130
+ await this.db
131
+ .update(orders)
132
+ .set({
133
+ refundedPence: sql`max(${orders.refundedPence}, ${refundedPence})`,
134
+ status: sql`case when ${refundedPence} >= ${orders.totalPence} then 'refunded' else ${orders.status} end`,
135
+ })
136
+ .where(eq(orders.id, orderId));
137
+ }
138
+
124
139
  async startPacking(number: string, now = Date.now()) {
125
140
  const order = await this.packable(number);
126
141
  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.13",
3
+ "version": "2026.11.15",
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,7 +67,7 @@
67
67
  "@eslint/compat": "2.1.1",
68
68
  "@eslint/js": "9.39.4",
69
69
  "@sveltejs/kit": "3.1.1",
70
- "@zeyolabs/kit": "2026.11.11",
70
+ "@zeyolabs/kit": "2026.11.15",
71
71
  "@zeyolabs/ui": "2026.1106.0",
72
72
  "drizzle-orm": "0.45.4",
73
73
  "eslint": "9.39.4",