@zeyolabs/shopping 2026.11.11 → 2026.11.13
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/README.md +24 -2
- package/basket/client.remote.ts +62 -0
- package/basket/cookies.server.ts +38 -0
- package/basket/library.ts +44 -0
- package/{pages → basket/pages}/Basket.svelte +31 -19
- package/basket/schema.ts +14 -0
- package/basket/service.server.ts +123 -0
- package/bundles/admin/BundleEditPage.svelte +24 -0
- package/bundles/admin/BundleForm.svelte +107 -0
- package/bundles/admin/BundlesPage.svelte +40 -0
- package/bundles/admin.remote.ts +30 -0
- package/bundles/client.remote.ts +29 -0
- package/bundles/loads.server.ts +6 -0
- package/bundles/pages/Bundle.svelte +145 -0
- package/bundles/schema.ts +82 -0
- package/bundles/service.server.ts +204 -0
- package/catalogue/admin/CategoriesPage.svelte +53 -0
- package/catalogue/admin/CategoryForm.svelte +50 -0
- package/catalogue/admin/ProductEditPage.svelte +25 -0
- package/catalogue/admin/ProductForm.svelte +249 -0
- package/catalogue/admin/ProductsPage.svelte +88 -0
- package/catalogue/admin.remote.ts +50 -0
- package/catalogue/admin.service.server.ts +239 -0
- package/catalogue/client.remote.ts +52 -0
- package/{components → catalogue/components}/ProductCard.svelte +8 -8
- package/catalogue/covers.server.ts +33 -0
- package/catalogue/library.ts +38 -0
- package/{routes/catalogue-loads.ts → catalogue/loads.server.ts} +11 -3
- package/{pages → catalogue/pages}/Category.svelte +5 -5
- package/{pages → catalogue/pages}/Product.svelte +37 -25
- package/catalogue/pages/Search.svelte +52 -0
- package/{pages → catalogue/pages}/Shop.svelte +2 -2
- package/catalogue/schema.ts +120 -0
- package/catalogue/service.server.ts +141 -0
- package/{routes/checkout-complete.ts → checkout/complete.server.ts} +6 -5
- package/checkout/manager.server.ts +127 -0
- package/{pages → checkout/pages}/CheckoutSuccess.svelte +2 -2
- package/{routes/stripe-webhook.ts → checkout/webhook.server.ts} +7 -7
- package/{royalmail.ts → clients/royalmail.ts} +30 -11
- package/clients/shop.server.ts +20 -0
- package/clients/stripe.ts +11 -0
- package/config.ts +23 -4
- package/context.ts +24 -0
- package/customers/client.remote.ts +19 -0
- package/customers/pages/Account.svelte +70 -0
- package/customers/service.server.ts +57 -0
- package/db/schema.ts +96 -0
- package/{admin → fulfilment/admin}/OrderPage.svelte +23 -16
- package/{admin → fulfilment/admin}/OrdersPage.svelte +7 -7
- package/{remote/admin-orders.remote.ts → fulfilment/admin.remote.ts} +11 -28
- package/fulfilment/dispatch-email.ts +66 -0
- package/fulfilment/invoice.server.ts +14 -0
- package/{routes/order-label.ts → fulfilment/label.server.ts} +3 -3
- package/fulfilment/library.ts +52 -0
- package/fulfilment/manager.server.ts +188 -0
- package/fulfilment/service.server.ts +155 -0
- package/{server/mail.ts → mail/default.ts} +9 -9
- package/{remote/order.remote.ts → orders/client.remote.ts} +10 -5
- package/orders/email.ts +111 -0
- package/orders/invoice.server.ts +19 -0
- package/orders/library.ts +26 -0
- package/orders/manager.server.ts +132 -0
- package/{pages → orders/pages}/Order.svelte +58 -16
- package/orders/service.server.ts +99 -0
- package/package.json +20 -32
- package/reviews/admin/ReviewsPage.svelte +95 -0
- package/reviews/admin.remote.ts +22 -0
- package/reviews/client.remote.ts +43 -0
- package/reviews/components/ReviewForm.svelte +32 -0
- package/reviews/components/Reviews.svelte +48 -0
- package/reviews/schema.ts +21 -0
- package/reviews/service.server.ts +122 -0
- package/shipping/library.ts +18 -0
- package/shipping/service.server.ts +88 -0
- package/{admin → stock/admin}/StockPage.svelte +1 -1
- package/{admin → stock/admin}/StockRow.svelte +2 -2
- package/stock/admin.remote.ts +19 -0
- package/{admin/stock.schema.ts → stock/schema.ts} +2 -1
- package/{server/stock-service.ts → stock/service.server.ts} +105 -58
- package/stock-alerts/email.ts +42 -0
- package/stock-alerts/job.server.ts +75 -0
- package/stock-alerts/service.server.ts +74 -0
- package/{components → ui}/PageTitle.svelte +5 -5
- package/ui/Stars.svelte +18 -0
- package/utils/batches.ts +21 -0
- package/utils/errors.ts +15 -0
- package/utils/form-input.ts +28 -0
- package/utils/images.ts +7 -0
- package/utils/money.ts +9 -0
- package/utils/schemas.ts +22 -0
- package/client.ts +0 -24
- package/emails/back-in-stock.ts +0 -36
- package/emails/dispatch.ts +0 -60
- package/emails/order.ts +0 -103
- package/images.ts +0 -2
- package/money.ts +0 -4
- package/order-links.ts +0 -11
- package/packing.ts +0 -49
- package/remote/admin-stock.remote.ts +0 -13
- package/remote/basket.remote.ts +0 -63
- package/remote/catalogue.remote.ts +0 -45
- package/server/admin-orders.ts +0 -304
- package/server/admin-stock.ts +0 -28
- package/server/basket.ts +0 -187
- package/server/catalogue.ts +0 -114
- package/server/checkout.ts +0 -41
- package/server/orders.ts +0 -182
- package/server/shipping.ts +0 -82
- package/server/stock-alert-service.ts +0 -30
- package/server/stock-alerts.ts +0 -105
- package/server/stripe.ts +0 -70
- package/shipping-rules.ts +0 -15
- /package/{admin → fulfilment}/filters.ts +0 -0
- /package/{admin/orders.schema.ts → fulfilment/schema.ts} +0 -0
- /package/{stock.ts → stock/library.ts} +0 -0
package/emails/dispatch.ts
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import type { EmailParams } from '@zeyolabs/kit/utils/email';
|
|
2
|
-
|
|
3
|
-
import { shopping } from '../config';
|
|
4
|
-
import { orderUrl, trackingUrl } from '../order-links';
|
|
5
|
-
|
|
6
|
-
export type DispatchEmailData = {
|
|
7
|
-
address: {
|
|
8
|
-
city: string;
|
|
9
|
-
country: string;
|
|
10
|
-
line1: string;
|
|
11
|
-
line2?: null | string;
|
|
12
|
-
name: string;
|
|
13
|
-
postcode: string;
|
|
14
|
-
};
|
|
15
|
-
email: string;
|
|
16
|
-
number: string;
|
|
17
|
-
/** Access token of the order page. */
|
|
18
|
-
token: string;
|
|
19
|
-
trackingNumber?: null | string;
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
/** Sent when the order leaves the shop: where it is, and how to follow it. */
|
|
23
|
-
export function dispatchEmail(order: DispatchEmailData): EmailParams {
|
|
24
|
-
const firstName = order.address.name.split(' ')[0] || 'there';
|
|
25
|
-
const tracked = Boolean(order.trackingNumber);
|
|
26
|
-
return {
|
|
27
|
-
badge: 'Dispatched',
|
|
28
|
-
brand: shopping().brand,
|
|
29
|
-
cta: tracked
|
|
30
|
-
? { href: trackingUrl(order.trackingNumber!), label: 'Track your parcel' }
|
|
31
|
-
: { href: orderUrl(order.number, order.token), label: 'View your order' },
|
|
32
|
-
eyebrow: `Order ${order.number}`,
|
|
33
|
-
footnote: tracked
|
|
34
|
-
? `Your tracking number is ${order.trackingNumber}. It can take a few hours for Royal Mail's tracking to show movement.`
|
|
35
|
-
: 'This parcel is sent untracked.',
|
|
36
|
-
heading: `Your order is on its way, ${firstName}`,
|
|
37
|
-
intro: [
|
|
38
|
-
`Your order ${order.number} has been dispatched by Royal Mail. UK orders usually arrive 2 to 10 working days after dispatch.`,
|
|
39
|
-
...(tracked
|
|
40
|
-
? [
|
|
41
|
-
`You can also see it any time on your order page: ${orderUrl(order.number, order.token)}`,
|
|
42
|
-
]
|
|
43
|
-
: []),
|
|
44
|
-
],
|
|
45
|
-
preheader: `Order ${order.number} has been dispatched. Thank you for shopping with ${shopping().brand.name}.`,
|
|
46
|
-
sections: [
|
|
47
|
-
{
|
|
48
|
-
lines: [
|
|
49
|
-
order.address.name,
|
|
50
|
-
order.address.line1,
|
|
51
|
-
order.address.line2,
|
|
52
|
-
order.address.city,
|
|
53
|
-
order.address.postcode,
|
|
54
|
-
order.address.country,
|
|
55
|
-
].filter((line): line is string => Boolean(line)),
|
|
56
|
-
title: 'Delivering to',
|
|
57
|
-
},
|
|
58
|
-
],
|
|
59
|
-
};
|
|
60
|
-
}
|
package/emails/order.ts
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
import type { EmailParams, EmailRow } from '@zeyolabs/kit/utils/email';
|
|
2
|
-
|
|
3
|
-
import { shopping } from '../config';
|
|
4
|
-
import { formatMoney } from '../money';
|
|
5
|
-
|
|
6
|
-
export type OrderEmailData = {
|
|
7
|
-
address: {
|
|
8
|
-
city?: null | string;
|
|
9
|
-
country?: null | string;
|
|
10
|
-
line1?: null | string;
|
|
11
|
-
line2?: null | string;
|
|
12
|
-
name: string;
|
|
13
|
-
postal_code?: null | string;
|
|
14
|
-
};
|
|
15
|
-
email: string;
|
|
16
|
-
items: { name: string; quantity: number; unitPricePence: number }[];
|
|
17
|
-
number: string;
|
|
18
|
-
/** Link to the customer's order page, which shows dispatch and tracking as they happen. */
|
|
19
|
-
orderUrl?: string;
|
|
20
|
-
phone?: null | string;
|
|
21
|
-
shippingPence: number;
|
|
22
|
-
subtotalPence: number;
|
|
23
|
-
totalPence: number;
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
const COUNTRIES: Record<string, string> = { GB: 'United Kingdom' };
|
|
27
|
-
|
|
28
|
-
function addressLines(address: OrderEmailData['address']): string[] {
|
|
29
|
-
return [
|
|
30
|
-
address.name,
|
|
31
|
-
address.line1,
|
|
32
|
-
address.line2,
|
|
33
|
-
address.city,
|
|
34
|
-
address.postal_code,
|
|
35
|
-
address.country ? (COUNTRIES[address.country] ?? address.country) : undefined,
|
|
36
|
-
].filter((line): line is string => Boolean(line));
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function itemRows(order: OrderEmailData): EmailRow[] {
|
|
40
|
-
return order.items.map((item) => ({
|
|
41
|
-
label: item.name,
|
|
42
|
-
sub: `${item.quantity} × ${formatMoney(item.unitPricePence)}`,
|
|
43
|
-
value: formatMoney(item.quantity * item.unitPricePence),
|
|
44
|
-
}));
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function totalRows(order: OrderEmailData): EmailRow[] {
|
|
48
|
-
return [
|
|
49
|
-
{ label: 'Subtotal', value: formatMoney(order.subtotalPence) },
|
|
50
|
-
{
|
|
51
|
-
label: 'Delivery',
|
|
52
|
-
value: order.shippingPence === 0 ? 'Free' : formatMoney(order.shippingPence),
|
|
53
|
-
},
|
|
54
|
-
{ label: 'Total', strong: true, value: formatMoney(order.totalPence) },
|
|
55
|
-
];
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/** What the customer receives once payment has gone through. */
|
|
59
|
-
export function customerOrderEmail(order: OrderEmailData): EmailParams {
|
|
60
|
-
const firstName = order.address.name.split(' ')[0] || 'there';
|
|
61
|
-
return {
|
|
62
|
-
badge: 'Paid',
|
|
63
|
-
brand: shopping().brand,
|
|
64
|
-
cta: order.orderUrl
|
|
65
|
-
? { href: order.orderUrl, label: 'View your order' }
|
|
66
|
-
: { href: `${shopping().siteUrl}/shipping`, label: 'Delivery and returns' },
|
|
67
|
-
eyebrow: `Order ${order.number}`,
|
|
68
|
-
footnote: `Keep this email as your receipt. Quote ${order.number} if you contact us.${order.orderUrl ? ' Your order link is private to you, so please do not share it.' : ''}`,
|
|
69
|
-
heading: `Thank you, ${firstName}`,
|
|
70
|
-
intro: [
|
|
71
|
-
`We have your order and your payment of ${formatMoney(order.totalPence)}. We will pack it carefully and send it by Royal Mail.`,
|
|
72
|
-
'UK orders usually arrive 2 to 10 working days after dispatch.',
|
|
73
|
-
...(order.orderUrl
|
|
74
|
-
? ['Use the link below to see when it is dispatched and to track it.']
|
|
75
|
-
: []),
|
|
76
|
-
],
|
|
77
|
-
preheader: `Order ${order.number} is confirmed. Thank you for shopping with ${shopping().brand.name}.`,
|
|
78
|
-
sections: [
|
|
79
|
-
{ rows: itemRows(order), title: 'Your order' },
|
|
80
|
-
{ rows: totalRows(order) },
|
|
81
|
-
{ lines: addressLines(order.address), title: 'Delivering to' },
|
|
82
|
-
],
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** The internal heads-up to the shop: who ordered what, and where it goes. */
|
|
87
|
-
export function shopOrderEmail(order: OrderEmailData): EmailParams {
|
|
88
|
-
return {
|
|
89
|
-
badge: 'Paid',
|
|
90
|
-
brand: shopping().brand,
|
|
91
|
-
eyebrow: 'New order',
|
|
92
|
-
heading: `${order.number}: ${formatMoney(order.totalPence)}`,
|
|
93
|
-
intro: [
|
|
94
|
-
`${order.address.name} (${order.email}${order.phone ? `, ${order.phone}` : ''}) has paid.`,
|
|
95
|
-
],
|
|
96
|
-
preheader: `New order ${order.number} for ${formatMoney(order.totalPence)}`,
|
|
97
|
-
sections: [
|
|
98
|
-
{ rows: itemRows(order), title: 'Items' },
|
|
99
|
-
{ rows: totalRows(order) },
|
|
100
|
-
{ lines: addressLines(order.address), title: 'Ship to' },
|
|
101
|
-
],
|
|
102
|
-
};
|
|
103
|
-
}
|
package/images.ts
DELETED
package/money.ts
DELETED
package/order-links.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { shopping } from './config';
|
|
2
|
-
|
|
3
|
-
/** The customer's private order page. The token is the only access control, so never log or index it. */
|
|
4
|
-
export function orderUrl(number: string, token: string): string {
|
|
5
|
-
return `${shopping().siteUrl}/order/${number}/${token}`;
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
/** Royal Mail's public tracker takes the number in the URL, so no API call is needed. */
|
|
9
|
-
export function trackingUrl(trackingNumber: string): string {
|
|
10
|
-
return `https://www.royalmail.com/track-your-item#/tracking-results/${encodeURIComponent(trackingNumber)}`;
|
|
11
|
-
}
|
package/packing.ts
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import type { BadgeColor } from '@zeyolabs/ui/badge/color';
|
|
2
|
-
|
|
3
|
-
import type { PackageFormat } from './db/schema';
|
|
4
|
-
|
|
5
|
-
export const FORMAT_LABELS: Record<PackageFormat, string> = {
|
|
6
|
-
largeLetter: 'Large letter',
|
|
7
|
-
letter: 'Letter',
|
|
8
|
-
mediumParcel: 'Medium parcel',
|
|
9
|
-
parcel: 'Parcel',
|
|
10
|
-
smallParcel: 'Small parcel',
|
|
11
|
-
};
|
|
12
|
-
|
|
13
|
-
export type PackingStage = 'held' | 'label' | 'new' | 'packed' | 'packing' | 'shipped';
|
|
14
|
-
|
|
15
|
-
type PackingFields = {
|
|
16
|
-
heldAt: null | number;
|
|
17
|
-
labelCreatedAt: null | number;
|
|
18
|
-
packedAt: null | number;
|
|
19
|
-
packingStartedAt: null | number;
|
|
20
|
-
shippedAt: null | number;
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
/** Where an order is in the packing flow. Later steps win, and a hold overrides until released. */
|
|
24
|
-
export function packingStage(order: PackingFields): PackingStage {
|
|
25
|
-
if (order.shippedAt) return 'shipped';
|
|
26
|
-
if (order.heldAt) return 'held';
|
|
27
|
-
if (order.labelCreatedAt) return 'label';
|
|
28
|
-
if (order.packedAt) return 'packed';
|
|
29
|
-
if (order.packingStartedAt) return 'packing';
|
|
30
|
-
return 'new';
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export const STAGE_LABELS: Record<PackingStage, string> = {
|
|
34
|
-
held: 'On hold',
|
|
35
|
-
label: 'Label printed',
|
|
36
|
-
new: 'To pack',
|
|
37
|
-
packed: 'Packed',
|
|
38
|
-
packing: 'Packing',
|
|
39
|
-
shipped: 'Shipped',
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
export const STAGE_COLORS: Record<PackingStage, BadgeColor> = {
|
|
43
|
-
held: 'neutral',
|
|
44
|
-
label: 'success',
|
|
45
|
-
new: 'warning',
|
|
46
|
-
packed: 'purple',
|
|
47
|
-
packing: 'info',
|
|
48
|
-
shipped: 'success',
|
|
49
|
-
};
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { Remote } from '@zeyolabs/kit/server/remote-functions';
|
|
2
|
-
import { FormResult } from '@zeyolabs/kit/utils/form';
|
|
3
|
-
|
|
4
|
-
import { StockSchema } from '../admin/stock.schema';
|
|
5
|
-
import { listStock, setStock } from '../server/admin-stock';
|
|
6
|
-
|
|
7
|
-
export const getStock = Remote.Query(() => listStock());
|
|
8
|
-
|
|
9
|
-
export const setStockForm = Remote.Form(StockSchema, async ({ productId, stock }) => {
|
|
10
|
-
await setStock(productId, stock);
|
|
11
|
-
await getStock().refresh();
|
|
12
|
-
return FormResult.ok('Stock saved.');
|
|
13
|
-
});
|
package/remote/basket.remote.ts
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import { getRequestEvent } from '$app/server';
|
|
2
|
-
import { Remote } from '@zeyolabs/kit/server/remote-functions';
|
|
3
|
-
import { Error400 } from '@zeyolabs/kit/utils/errors';
|
|
4
|
-
import { z } from 'zod';
|
|
5
|
-
|
|
6
|
-
import { shopping } from '../config';
|
|
7
|
-
import {
|
|
8
|
-
readBasket,
|
|
9
|
-
readShipTo,
|
|
10
|
-
summariseBasket,
|
|
11
|
-
writeBasket,
|
|
12
|
-
writeShipTo,
|
|
13
|
-
} from '../server/basket';
|
|
14
|
-
import { listShippableCountries } from '../server/shipping';
|
|
15
|
-
|
|
16
|
-
const ProductId = z.number().int().positive();
|
|
17
|
-
|
|
18
|
-
function context() {
|
|
19
|
-
const { cookies } = getRequestEvent();
|
|
20
|
-
return { cookies, db: shopping().db() };
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export const getBasket = Remote.Query(async () => {
|
|
24
|
-
const { cookies, db } = context();
|
|
25
|
-
return summariseBasket(db, readBasket(cookies), readShipTo(cookies));
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
export const addToBasket = Remote.Cmd(
|
|
29
|
-
z.object({ productId: ProductId, quantity: z.number().int().min(1).max(99).default(1) }),
|
|
30
|
-
async ({ productId, quantity }) => {
|
|
31
|
-
const { cookies } = context();
|
|
32
|
-
const basket = readBasket(cookies);
|
|
33
|
-
basket[productId] = Math.min((basket[productId] ?? 0) + quantity, 99);
|
|
34
|
-
writeBasket(cookies, basket);
|
|
35
|
-
await getBasket().refresh();
|
|
36
|
-
}
|
|
37
|
-
);
|
|
38
|
-
|
|
39
|
-
/** Quantity 0 removes the line. */
|
|
40
|
-
export const setBasketQuantity = Remote.Cmd(
|
|
41
|
-
z.object({ productId: ProductId, quantity: z.number().int().min(0).max(99) }),
|
|
42
|
-
async ({ productId, quantity }) => {
|
|
43
|
-
const { cookies } = context();
|
|
44
|
-
const basket = readBasket(cookies);
|
|
45
|
-
if (quantity === 0) delete basket[productId];
|
|
46
|
-
else basket[productId] = quantity;
|
|
47
|
-
writeBasket(cookies, basket);
|
|
48
|
-
await getBasket().refresh();
|
|
49
|
-
}
|
|
50
|
-
);
|
|
51
|
-
|
|
52
|
-
export const getShippableCountries = Remote.Query(async () => listShippableCountries(context().db));
|
|
53
|
-
|
|
54
|
-
export const setShipTo = Remote.Cmd(
|
|
55
|
-
z.object({ country: z.string().regex(/^[A-Z]{2}$/) }),
|
|
56
|
-
async ({ country }) => {
|
|
57
|
-
const { cookies, db } = context();
|
|
58
|
-
const allowed = await listShippableCountries(db);
|
|
59
|
-
if (!allowed.some((c) => c.code === country)) throw Error400('We do not ship to that country.');
|
|
60
|
-
writeShipTo(cookies, country);
|
|
61
|
-
await getBasket().refresh();
|
|
62
|
-
}
|
|
63
|
-
);
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { Remote } from '@zeyolabs/kit/server/remote-functions';
|
|
2
|
-
import { Error404 } from '@zeyolabs/kit/utils/errors';
|
|
3
|
-
import { z } from 'zod';
|
|
4
|
-
|
|
5
|
-
import { shopping } from '../config';
|
|
6
|
-
import {
|
|
7
|
-
getProduct as findProduct,
|
|
8
|
-
getCategory,
|
|
9
|
-
listCategories,
|
|
10
|
-
listCategoryProducts,
|
|
11
|
-
listShopProducts,
|
|
12
|
-
} from '../server/catalogue';
|
|
13
|
-
import { getUkRate } from '../server/shipping';
|
|
14
|
-
|
|
15
|
-
const Slug = z.string().min(1).max(200);
|
|
16
|
-
|
|
17
|
-
/** The header's Shop menu. Cheap: a handful of rows. */
|
|
18
|
-
export const getMenuCategories = Remote.Query(async () =>
|
|
19
|
-
(await listCategories(shopping().db())).map(({ name, slug }) => ({ name, slug }))
|
|
20
|
-
);
|
|
21
|
-
|
|
22
|
-
export const getShop = Remote.Query(async () => {
|
|
23
|
-
const db = shopping().db();
|
|
24
|
-
const [categories, products] = await Promise.all([listCategories(db), listShopProducts(db)]);
|
|
25
|
-
return { categories, products };
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
export const getCategoryPage = Remote.Query(Slug, async (slug) => {
|
|
29
|
-
const db = shopping().db();
|
|
30
|
-
const category = await getCategory(db, slug);
|
|
31
|
-
if (!category) throw Error404('Category not found');
|
|
32
|
-
return { category, products: await listCategoryProducts(db, category.id) };
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
export const getProduct = Remote.Query(Slug, async (slug) => {
|
|
36
|
-
const found = await findProduct(shopping().db(), slug);
|
|
37
|
-
if (!found) throw Error404('Product not found');
|
|
38
|
-
return found;
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
/** The page quotes the live UK rate so it can never disagree with the basket. */
|
|
42
|
-
export const getUkShippingRate = Remote.Query(async () => ({
|
|
43
|
-
freeFromPence: shopping().shipping.freeUkFromPence,
|
|
44
|
-
rate: await getUkRate(shopping().db()),
|
|
45
|
-
}));
|
package/server/admin-orders.ts
DELETED
|
@@ -1,304 +0,0 @@
|
|
|
1
|
-
import { logger } from '@zeyolabs/kit/server/logger';
|
|
2
|
-
import { Crypto } from '@zeyolabs/kit/utils/crypto';
|
|
3
|
-
import { Error400, Error404 } from '@zeyolabs/kit/utils/errors';
|
|
4
|
-
import { and, asc, count, desc, eq, inArray, like, or } from 'drizzle-orm';
|
|
5
|
-
|
|
6
|
-
import type { OrderFilter } from '../admin/filters';
|
|
7
|
-
import type { OrderStep } from '../admin/orders.schema';
|
|
8
|
-
|
|
9
|
-
import { secret, shopping } from '../config';
|
|
10
|
-
import { addresses, orderItems, orders, type PackageFormat, products } from '../db/schema';
|
|
11
|
-
import { orderUrl } from '../order-links';
|
|
12
|
-
import {
|
|
13
|
-
createClickAndDropOrder,
|
|
14
|
-
deleteClickAndDropOrder,
|
|
15
|
-
getClickAndDropLabel,
|
|
16
|
-
getClickAndDropTracking,
|
|
17
|
-
} from '../royalmail';
|
|
18
|
-
import { quoteServiceCode } from './shipping';
|
|
19
|
-
|
|
20
|
-
const getDb = () => shopping().db();
|
|
21
|
-
|
|
22
|
-
/** Escapes LIKE wildcards so a search for "100%" matches literally. */
|
|
23
|
-
const likePattern = (text: string) => `%${text.replace(/[\\%_]/g, '\\$&')}%`;
|
|
24
|
-
|
|
25
|
-
export async function listOrders(filter: OrderFilter, query: string) {
|
|
26
|
-
const search = query.trim();
|
|
27
|
-
const match = search ? likePattern(search) : undefined;
|
|
28
|
-
return (
|
|
29
|
-
getDb()
|
|
30
|
-
.select({
|
|
31
|
-
country: addresses.country,
|
|
32
|
-
createdAt: orders.createdAt,
|
|
33
|
-
email: orders.email,
|
|
34
|
-
heldAt: orders.heldAt,
|
|
35
|
-
labelCreatedAt: orders.labelCreatedAt,
|
|
36
|
-
name: addresses.name,
|
|
37
|
-
number: orders.number,
|
|
38
|
-
packedAt: orders.packedAt,
|
|
39
|
-
packingStartedAt: orders.packingStartedAt,
|
|
40
|
-
shippedAt: orders.shippedAt,
|
|
41
|
-
status: orders.status,
|
|
42
|
-
totalPence: orders.totalPence,
|
|
43
|
-
})
|
|
44
|
-
.from(orders)
|
|
45
|
-
.innerJoin(addresses, eq(orders.shippingAddressId, addresses.id))
|
|
46
|
-
.where(
|
|
47
|
-
and(
|
|
48
|
-
filter === 'to-ship' ? eq(orders.status, 'paid') : undefined,
|
|
49
|
-
filter === 'shipped' ? eq(orders.status, 'shipped') : undefined,
|
|
50
|
-
match
|
|
51
|
-
? or(like(orders.number, match), like(orders.email, match), like(addresses.name, match))
|
|
52
|
-
: undefined
|
|
53
|
-
)
|
|
54
|
-
)
|
|
55
|
-
// Oldest first when packing, newest first when browsing.
|
|
56
|
-
.orderBy(filter === 'to-ship' ? asc(orders.createdAt) : desc(orders.createdAt))
|
|
57
|
-
.limit(200)
|
|
58
|
-
);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export async function countOrders(): Promise<Record<OrderFilter, number>> {
|
|
62
|
-
const rows = await getDb()
|
|
63
|
-
.select({ n: count(), status: orders.status })
|
|
64
|
-
.from(orders)
|
|
65
|
-
.groupBy(orders.status);
|
|
66
|
-
const byStatus = Object.fromEntries(rows.map((r) => [r.status, r.n]));
|
|
67
|
-
return {
|
|
68
|
-
all: rows.reduce((sum, r) => sum + r.n, 0),
|
|
69
|
-
shipped: byStatus.shipped ?? 0,
|
|
70
|
-
'to-ship': byStatus.paid ?? 0,
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/** The order with its address, items and the weight the items add up to. */
|
|
75
|
-
export async function findOrder(number: string) {
|
|
76
|
-
const db = getDb();
|
|
77
|
-
const order = await db.query.orders.findFirst({ where: eq(orders.number, number) });
|
|
78
|
-
if (!order) return undefined;
|
|
79
|
-
const [items, address] = await Promise.all([
|
|
80
|
-
db.query.orderItems.findMany({ where: eq(orderItems.orderId, order.id) }),
|
|
81
|
-
db.query.addresses.findFirst({ where: eq(addresses.id, order.shippingAddressId) }),
|
|
82
|
-
]);
|
|
83
|
-
if (!address) return undefined;
|
|
84
|
-
return {
|
|
85
|
-
...order,
|
|
86
|
-
address,
|
|
87
|
-
customerUrl: order.accessToken ? orderUrl(order.number, order.accessToken) : null,
|
|
88
|
-
estimatedWeightGrams: await estimateWeight(items),
|
|
89
|
-
items,
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** What the basket weighs by the products' current weights; the starting point for packing. */
|
|
94
|
-
async function estimateWeight(items: { productId: null | number; quantity: number }[]) {
|
|
95
|
-
const ids = items.flatMap((item) => (item.productId === null ? [] : [item.productId]));
|
|
96
|
-
if (ids.length === 0) return 0;
|
|
97
|
-
const rows = await getDb()
|
|
98
|
-
.select({ id: products.id, massGrams: products.massGrams })
|
|
99
|
-
.from(products)
|
|
100
|
-
.where(inArray(products.id, ids));
|
|
101
|
-
const mass = new Map(rows.map((row) => [row.id, row.massGrams]));
|
|
102
|
-
return items.reduce(
|
|
103
|
-
(sum, item) =>
|
|
104
|
-
sum + (item.productId === null ? 0 : (mass.get(item.productId) ?? 0) * item.quantity),
|
|
105
|
-
0
|
|
106
|
-
);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Marks a paid order as dispatched, records the tracking number and emails the customer. The
|
|
111
|
-
* database change comes first: a failed email never undoes a parcel that has really left, and the
|
|
112
|
-
* result says whether the email went so the admin can resend it.
|
|
113
|
-
*/
|
|
114
|
-
export async function markShipped(number: string, trackingNumber: null | string) {
|
|
115
|
-
const order = await findOrder(number);
|
|
116
|
-
if (!order) throw Error404('Order not found.');
|
|
117
|
-
const { address } = order;
|
|
118
|
-
if (order.status !== 'paid' && order.status !== 'shipped') {
|
|
119
|
-
throw Error400(`This order is ${order.status}, so it cannot be dispatched.`);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
// No tracking number typed in: take the one Click & Drop assigned (tracked services only).
|
|
123
|
-
let tracking = trackingNumber;
|
|
124
|
-
if (!tracking && order.royalMailOrderId) {
|
|
125
|
-
try {
|
|
126
|
-
tracking =
|
|
127
|
-
(await getClickAndDropTracking(secret('royalMailApiKey'), order.royalMailOrderId)) ?? null;
|
|
128
|
-
} catch (error) {
|
|
129
|
-
logger.error(error, { op: 'royalMailTracking', orderNumber: order.number });
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// Orders from before the order page existed have no link token: mint one so the email can link.
|
|
134
|
-
const accessToken = order.accessToken ?? Crypto.getRandomSecret(16);
|
|
135
|
-
const now = Date.now();
|
|
136
|
-
await getDb()
|
|
137
|
-
.update(orders)
|
|
138
|
-
.set({
|
|
139
|
-
accessToken,
|
|
140
|
-
// Dispatching implies the earlier steps happened, so fill in any that were skipped.
|
|
141
|
-
heldAt: null,
|
|
142
|
-
packedAt: order.packedAt ?? now,
|
|
143
|
-
packingStartedAt: order.packingStartedAt ?? now,
|
|
144
|
-
shippedAt: order.shippedAt ?? now,
|
|
145
|
-
status: 'shipped',
|
|
146
|
-
trackingNumber: tracking,
|
|
147
|
-
})
|
|
148
|
-
.where(eq(orders.id, order.id));
|
|
149
|
-
|
|
150
|
-
try {
|
|
151
|
-
await shopping().mail.orderDispatched({
|
|
152
|
-
address,
|
|
153
|
-
email: order.email,
|
|
154
|
-
number: order.number,
|
|
155
|
-
token: accessToken,
|
|
156
|
-
trackingNumber: tracking,
|
|
157
|
-
});
|
|
158
|
-
await getDb().update(orders).set({ dispatchEmailedAt: now }).where(eq(orders.id, order.id));
|
|
159
|
-
return { emailed: true };
|
|
160
|
-
} catch (error) {
|
|
161
|
-
logger.error(error, { op: 'dispatchEmail', orderNumber: order.number });
|
|
162
|
-
return { emailed: false };
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/** Orders only move through packing while they are paid and not yet shipped. */
|
|
167
|
-
async function packableOrder(number: string) {
|
|
168
|
-
const order = await getDb().query.orders.findFirst({ where: eq(orders.number, number) });
|
|
169
|
-
if (!order) throw Error404('Order not found.');
|
|
170
|
-
if (order.status !== 'paid')
|
|
171
|
-
throw Error400(`This order is ${order.status}, so it cannot be packed.`);
|
|
172
|
-
return order;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
export async function startPacking(number: string) {
|
|
176
|
-
const order = await packableOrder(number);
|
|
177
|
-
if (order.packingStartedAt && !order.heldAt) return;
|
|
178
|
-
await getDb()
|
|
179
|
-
.update(orders)
|
|
180
|
-
.set({ heldAt: null, packingStartedAt: order.packingStartedAt ?? Date.now() })
|
|
181
|
-
.where(eq(orders.id, order.id));
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
/** Packed implies packing started, and a held order that gets packed is no longer held. */
|
|
185
|
-
export async function markPacked(number: string) {
|
|
186
|
-
const order = await packableOrder(number);
|
|
187
|
-
const now = Date.now();
|
|
188
|
-
await getDb()
|
|
189
|
-
.update(orders)
|
|
190
|
-
.set({ heldAt: null, packedAt: now, packingStartedAt: order.packingStartedAt ?? now })
|
|
191
|
-
.where(eq(orders.id, order.id));
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
export async function setHold(number: string, held: boolean) {
|
|
195
|
-
const order = await packableOrder(number);
|
|
196
|
-
await getDb()
|
|
197
|
-
.update(orders)
|
|
198
|
-
.set({ heldAt: held ? Date.now() : null })
|
|
199
|
-
.where(eq(orders.id, order.id));
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
const STEP_ACTIONS: Record<OrderStep, (number: string) => Promise<void>> = {
|
|
203
|
-
hold: (number) => setHold(number, true),
|
|
204
|
-
pack: markPacked,
|
|
205
|
-
release: (number) => setHold(number, false),
|
|
206
|
-
start: startPacking,
|
|
207
|
-
};
|
|
208
|
-
|
|
209
|
-
/** Moves a paid order to its next packing state. */
|
|
210
|
-
export const applyStep = (number: string, step: OrderStep) => STEP_ACTIONS[step](number);
|
|
211
|
-
|
|
212
|
-
export type Parcel = {
|
|
213
|
-
format: PackageFormat;
|
|
214
|
-
heightMm: null | number;
|
|
215
|
-
lengthMm: null | number;
|
|
216
|
-
weightGrams: number;
|
|
217
|
-
widthMm: null | number;
|
|
218
|
-
};
|
|
219
|
-
|
|
220
|
-
export async function saveParcel(number: string, parcel: Parcel) {
|
|
221
|
-
const order = await packableOrder(number);
|
|
222
|
-
await getDb()
|
|
223
|
-
.update(orders)
|
|
224
|
-
.set({
|
|
225
|
-
packageFormat: parcel.format,
|
|
226
|
-
packageHeightMm: parcel.heightMm,
|
|
227
|
-
packageLengthMm: parcel.lengthMm,
|
|
228
|
-
packageWidthMm: parcel.widthMm,
|
|
229
|
-
weightGrams: parcel.weightGrams,
|
|
230
|
-
})
|
|
231
|
-
.where(eq(orders.id, order.id));
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/**
|
|
235
|
-
* Makes sure Click & Drop holds this order with the parcel as packed, so its label is right.
|
|
236
|
-
* Click & Drop cannot edit an order, so until a label exists the old one is removed and re-created.
|
|
237
|
-
* Creating the label counts as packing, so it also fills in any earlier packing step.
|
|
238
|
-
*/
|
|
239
|
-
export async function createLabel(number: string) {
|
|
240
|
-
const order = await findOrder(number);
|
|
241
|
-
if (!order) throw Error404('Order not found.');
|
|
242
|
-
const { address, estimatedWeightGrams } = order;
|
|
243
|
-
if (order.status !== 'paid') {
|
|
244
|
-
throw Error400(`This order is ${order.status}, so it cannot have a label.`);
|
|
245
|
-
}
|
|
246
|
-
if (order.labelCreatedAt && order.royalMailOrderId) return;
|
|
247
|
-
|
|
248
|
-
const weightGrams = order.weightGrams ?? estimatedWeightGrams;
|
|
249
|
-
if (weightGrams < 1) throw Error400('Set the parcel weight before printing the label.');
|
|
250
|
-
const { packageHeightMm, packageLengthMm, packageWidthMm } = order;
|
|
251
|
-
const dimensions =
|
|
252
|
-
packageHeightMm && packageLengthMm && packageWidthMm
|
|
253
|
-
? { heightMm: packageHeightMm, lengthMm: packageLengthMm, widthMm: packageWidthMm }
|
|
254
|
-
: null;
|
|
255
|
-
|
|
256
|
-
const db = getDb();
|
|
257
|
-
if (order.royalMailOrderId)
|
|
258
|
-
await deleteClickAndDropOrder(secret('royalMailApiKey'), order.royalMailOrderId);
|
|
259
|
-
const royalMailOrderId = await createClickAndDropOrder(secret('royalMailApiKey'), {
|
|
260
|
-
address: {
|
|
261
|
-
city: address.city,
|
|
262
|
-
country: address.country,
|
|
263
|
-
line1: address.line1,
|
|
264
|
-
line2: address.line2,
|
|
265
|
-
name: address.name,
|
|
266
|
-
postal_code: address.postcode,
|
|
267
|
-
state: null,
|
|
268
|
-
},
|
|
269
|
-
createdAt: order.createdAt,
|
|
270
|
-
dimensions,
|
|
271
|
-
email: order.email,
|
|
272
|
-
number: order.number,
|
|
273
|
-
packageFormat: order.packageFormat,
|
|
274
|
-
phone: address.phone,
|
|
275
|
-
serviceCode: await quoteServiceCode(db, order.shippingService),
|
|
276
|
-
shippingPence: order.shippingPence,
|
|
277
|
-
subtotalPence: order.subtotalPence,
|
|
278
|
-
totalPence: order.totalPence,
|
|
279
|
-
weightGrams,
|
|
280
|
-
});
|
|
281
|
-
// Keep the new id before fetching the label, so a failed fetch can be retried without a duplicate.
|
|
282
|
-
await db.update(orders).set({ royalMailOrderId }).where(eq(orders.id, order.id));
|
|
283
|
-
await getClickAndDropLabel(secret('royalMailApiKey'), royalMailOrderId);
|
|
284
|
-
|
|
285
|
-
const now = Date.now();
|
|
286
|
-
await db
|
|
287
|
-
.update(orders)
|
|
288
|
-
.set({
|
|
289
|
-
heldAt: null,
|
|
290
|
-
labelCreatedAt: now,
|
|
291
|
-
packedAt: order.packedAt ?? now,
|
|
292
|
-
packingStartedAt: order.packingStartedAt ?? now,
|
|
293
|
-
weightGrams,
|
|
294
|
-
})
|
|
295
|
-
.where(eq(orders.id, order.id));
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
/** The label PDF for an order that already has one. */
|
|
299
|
-
export async function fetchLabel(number: string) {
|
|
300
|
-
const order = await getDb().query.orders.findFirst({ where: eq(orders.number, number) });
|
|
301
|
-
if (!order?.royalMailOrderId || !order.labelCreatedAt)
|
|
302
|
-
throw Error404('No label for this order yet.');
|
|
303
|
-
return getClickAndDropLabel(secret('royalMailApiKey'), order.royalMailOrderId);
|
|
304
|
-
}
|
package/server/admin-stock.ts
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { asc, count, sql } from 'drizzle-orm';
|
|
2
|
-
|
|
3
|
-
import { shopping } from '../config';
|
|
4
|
-
import { products, stockAlerts } from '../db/schema';
|
|
5
|
-
import { StockService } from './stock-service';
|
|
6
|
-
|
|
7
|
-
const getDb = () => shopping().db();
|
|
8
|
-
|
|
9
|
-
/** Every product with its stock and how many customers are waiting for it, sold-out first. */
|
|
10
|
-
export async function listStock() {
|
|
11
|
-
return getDb()
|
|
12
|
-
.select({
|
|
13
|
-
active: products.active,
|
|
14
|
-
id: products.id,
|
|
15
|
-
name: products.name,
|
|
16
|
-
sku: products.sku,
|
|
17
|
-
stock: products.stock,
|
|
18
|
-
variationLabel: products.variationLabel,
|
|
19
|
-
waiting: sql<number>`(select ${count()} from ${stockAlerts} where ${stockAlerts.productId} = ${products.id})`,
|
|
20
|
-
})
|
|
21
|
-
.from(products)
|
|
22
|
-
.orderBy(asc(sql`${products.stock} > 0`), asc(products.name), asc(products.id));
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/** Sets a product's stock in single units. Customers waiting on it are emailed by the stock-alerts cron, not here. */
|
|
26
|
-
export async function setStock(productId: number, stock: number) {
|
|
27
|
-
await new StockService(getDb()).setStock(productId, stock);
|
|
28
|
-
}
|