@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
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type Stripe from 'stripe';
|
|
2
|
+
|
|
3
|
+
import { getRequestEvent } from '$app/server';
|
|
4
|
+
import { AuthHandle } from '@zeyolabs/kit/auth/sessions/handle';
|
|
5
|
+
import { Error400 } from '@zeyolabs/kit/utils/errors';
|
|
6
|
+
|
|
7
|
+
import { BasketCookies } from '../basket/cookies.server';
|
|
8
|
+
import { BasketService, type BasketSummary } from '../basket/service.server';
|
|
9
|
+
import { ShopClients } from '../clients/shop.server';
|
|
10
|
+
import { shopping } from '../config';
|
|
11
|
+
import { CustomerService } from '../customers/service.server';
|
|
12
|
+
import { Images } from '../utils/images';
|
|
13
|
+
|
|
14
|
+
type ShippableSummary = BasketSummary & { shipping: NonNullable<BasketSummary['shipping']> };
|
|
15
|
+
|
|
16
|
+
/** Starting a Stripe Checkout. The app wraps `start` in its own remote function and rate-limits it. */
|
|
17
|
+
export const CheckoutManager = {
|
|
18
|
+
/**
|
|
19
|
+
* Prices the basket from the database and returns the Stripe Checkout URL to redirect to. The
|
|
20
|
+
* order itself is only created from the webhook once paid. A signed-in customer (the app's kit
|
|
21
|
+
* `AuthHandle` in front) is passed to Stripe as a Customer, so their saved details are filled
|
|
22
|
+
* in; the email is read from their session here, never taken from the caller.
|
|
23
|
+
*/
|
|
24
|
+
async start(): Promise<{ url: string }> {
|
|
25
|
+
const event = getRequestEvent();
|
|
26
|
+
const { cookies, url } = event;
|
|
27
|
+
const config = shopping();
|
|
28
|
+
const db = config.db();
|
|
29
|
+
const basket = new BasketService(db);
|
|
30
|
+
const summary = await basket.summarise(
|
|
31
|
+
BasketCookies.read(cookies),
|
|
32
|
+
BasketCookies.readShipTo(cookies, config.shipping.defaultCountry),
|
|
33
|
+
config.shipping
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
if (summary.lines.length === 0) throw Error400('Your basket is empty.');
|
|
37
|
+
const unavailable = summary.lines.find((line) => line.available < 1);
|
|
38
|
+
if (unavailable)
|
|
39
|
+
throw Error400(`${unavailable.name} is out of stock. Please remove it to continue.`);
|
|
40
|
+
const short = summary.lines.find((line) => line.available < line.quantity);
|
|
41
|
+
if (short) {
|
|
42
|
+
throw Error400(
|
|
43
|
+
`Only ${short.available} of ${short.name} available. Please update your basket.`
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
if (!summary.shipping) {
|
|
47
|
+
throw Error400(
|
|
48
|
+
'We cannot ship this order to the selected country. Please choose another or contact us.'
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const client = ShopClients.stripe();
|
|
53
|
+
const customers = new CustomerService(db);
|
|
54
|
+
const email = AuthHandle.locals(event).user?.email;
|
|
55
|
+
const customerId = email ? await customers.stripeCustomerId(client, email) : undefined;
|
|
56
|
+
const session = await client.checkout.sessions.create(
|
|
57
|
+
sessionParams({ ...summary, shipping: summary.shipping }, url.origin, customerId)
|
|
58
|
+
);
|
|
59
|
+
if (!session.url) throw new Error('Stripe returned a Checkout Session without a url');
|
|
60
|
+
return { url: session.url };
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The hosted Checkout for a priced basket. The shipping fee is a Stripe shipping rate so the
|
|
66
|
+
* customer sees it before paying. Promotion codes and invoices follow the shop's `checkout` config.
|
|
67
|
+
*/
|
|
68
|
+
function sessionParams(
|
|
69
|
+
summary: ShippableSummary,
|
|
70
|
+
origin: string,
|
|
71
|
+
customerId: string | undefined
|
|
72
|
+
): Stripe.Checkout.SessionCreateParams {
|
|
73
|
+
const { checkout = {}, imageBaseUrl } = shopping();
|
|
74
|
+
return {
|
|
75
|
+
allow_promotion_codes: checkout.promotionCodes || undefined,
|
|
76
|
+
cancel_url: `${origin}/basket`,
|
|
77
|
+
customer: customerId,
|
|
78
|
+
customer_update: customerId ? { address: 'auto', name: 'auto', shipping: 'auto' } : undefined,
|
|
79
|
+
invoice_creation: checkout.invoices
|
|
80
|
+
? {
|
|
81
|
+
enabled: true,
|
|
82
|
+
invoice_data: {
|
|
83
|
+
custom_fields: checkout.invoices.customFields?.slice(0, 4),
|
|
84
|
+
footer: checkout.invoices.footer,
|
|
85
|
+
metadata: { source: 'checkout' },
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
: undefined,
|
|
89
|
+
line_items: summary.lines.map((line) => ({
|
|
90
|
+
price_data: {
|
|
91
|
+
currency: 'gbp',
|
|
92
|
+
product_data: {
|
|
93
|
+
images: line.cover
|
|
94
|
+
? [new URL(Images.url(imageBaseUrl, line.cover.src), origin).href]
|
|
95
|
+
: undefined,
|
|
96
|
+
metadata: { productId: String(line.id), sku: line.sku },
|
|
97
|
+
name: line.name,
|
|
98
|
+
},
|
|
99
|
+
unit_amount: line.pricePence,
|
|
100
|
+
},
|
|
101
|
+
quantity: line.available,
|
|
102
|
+
})),
|
|
103
|
+
metadata: {
|
|
104
|
+
country: summary.country,
|
|
105
|
+
shippingService: summary.shipping.service,
|
|
106
|
+
weightGrams: String(summary.weightGrams),
|
|
107
|
+
},
|
|
108
|
+
mode: 'payment',
|
|
109
|
+
phone_number_collection: { enabled: true },
|
|
110
|
+
shipping_address_collection: {
|
|
111
|
+
allowed_countries: [
|
|
112
|
+
summary.country as Stripe.Checkout.SessionCreateParams.ShippingAddressCollection.AllowedCountry,
|
|
113
|
+
],
|
|
114
|
+
},
|
|
115
|
+
shipping_options: [
|
|
116
|
+
{
|
|
117
|
+
shipping_rate_data: {
|
|
118
|
+
display_name:
|
|
119
|
+
summary.shippingPence === 0 ? `Free ${summary.shipping.name}` : summary.shipping.name,
|
|
120
|
+
fixed_amount: { amount: summary.shippingPence, currency: 'gbp' },
|
|
121
|
+
type: 'fixed_amount',
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
],
|
|
125
|
+
success_url: `${origin}/checkout/complete?session_id={CHECKOUT_SESSION_ID}`,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import { resolve } from '$app/paths';
|
|
3
3
|
import { page } from '$app/state';
|
|
4
|
-
import PageTitle from '
|
|
5
|
-
import { getCheckoutOrder } from '
|
|
4
|
+
import PageTitle from '../../ui/PageTitle.svelte';
|
|
5
|
+
import { getCheckoutOrder } from '../../orders/client.remote';
|
|
6
6
|
import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
|
|
7
7
|
import SkeletonText from '@zeyolabs/ui/skeleton/SkeletonText.svelte';
|
|
8
8
|
|
|
@@ -3,24 +3,24 @@ import type { RequestHandler } from '@sveltejs/kit';
|
|
|
3
3
|
import { error } from '@sveltejs/kit';
|
|
4
4
|
import { logger } from '@zeyolabs/kit/server/logger';
|
|
5
5
|
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
6
|
+
import { ShopClients } from '../clients/shop.server';
|
|
7
|
+
import { StripeClient } from '../clients/stripe';
|
|
8
|
+
import { secret } from '../config';
|
|
9
|
+
import { OrderManager } from '../orders/manager.server';
|
|
9
10
|
|
|
10
11
|
/** Stripe calls this after payment. Unsigned or mis-signed requests are rejected before any work. */
|
|
11
12
|
export const POST: RequestHandler = async ({ request }) => {
|
|
12
13
|
const signature = request.headers.get('stripe-signature');
|
|
13
14
|
if (!signature) error(400, 'Missing signature');
|
|
14
15
|
|
|
15
|
-
const stripe = await getStripe();
|
|
16
16
|
let event;
|
|
17
17
|
try {
|
|
18
|
-
event = await stripe.webhooks.constructEventAsync(
|
|
18
|
+
event = await ShopClients.stripe().webhooks.constructEventAsync(
|
|
19
19
|
await request.text(),
|
|
20
20
|
signature,
|
|
21
21
|
secret('stripeWebhookSecret'),
|
|
22
22
|
undefined,
|
|
23
|
-
webhookCrypto
|
|
23
|
+
StripeClient.webhookCrypto
|
|
24
24
|
);
|
|
25
25
|
} catch {
|
|
26
26
|
error(400, 'Invalid signature');
|
|
@@ -31,7 +31,7 @@ export const POST: RequestHandler = async ({ request }) => {
|
|
|
31
31
|
event.type === 'checkout.session.async_payment_succeeded'
|
|
32
32
|
) {
|
|
33
33
|
try {
|
|
34
|
-
await
|
|
34
|
+
await OrderManager.fulfil(event.data.object.id);
|
|
35
35
|
} catch (err) {
|
|
36
36
|
logger.error(err, { eventId: event.id, op: 'stripeWebhook' });
|
|
37
37
|
// 500 makes Stripe retry; fulfilment is idempotent.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PackageFormat } from '
|
|
1
|
+
import type { PackageFormat } from '../db/schema';
|
|
2
2
|
|
|
3
3
|
/** Royal Mail Click & Drop API: paid orders are pushed in so staff can print the label. */
|
|
4
4
|
const ORDERS_URL = 'https://api.parcel.royalmail.com/api/v1/orders';
|
|
@@ -45,10 +45,7 @@ function headers(apiKey: string, extra: Record<string, string> = {}) {
|
|
|
45
45
|
* Creates the order in Click & Drop and returns its identifier. Throws on any failure so the caller
|
|
46
46
|
* can log it: the customer's order is already safely recorded either way.
|
|
47
47
|
*/
|
|
48
|
-
|
|
49
|
-
apiKey: string,
|
|
50
|
-
order: ClickAndDropOrder
|
|
51
|
-
): Promise<string> {
|
|
48
|
+
async function createOrder(apiKey: string, order: ClickAndDropOrder): Promise<string> {
|
|
52
49
|
// Shoppers only give a delivery address, so it doubles as the billing address (the API requires both).
|
|
53
50
|
const address = {
|
|
54
51
|
addressLine1: order.address.line1 ?? '',
|
|
@@ -112,7 +109,7 @@ export async function createClickAndDropOrder(
|
|
|
112
109
|
}
|
|
113
110
|
|
|
114
111
|
/** Removes an order from Click & Drop. Only works until its label has been printed. A 404 is fine. */
|
|
115
|
-
|
|
112
|
+
async function deleteOrder(apiKey: string, orderId: string): Promise<void> {
|
|
116
113
|
const response = await fetch(`${ORDERS_URL}/${encodeURIComponent(orderId)}`, {
|
|
117
114
|
headers: headers(apiKey),
|
|
118
115
|
method: 'DELETE',
|
|
@@ -123,10 +120,7 @@ export async function deleteClickAndDropOrder(apiKey: string, orderId: string):
|
|
|
123
120
|
}
|
|
124
121
|
|
|
125
122
|
/** The Royal Mail tracking number once Click & Drop has one; undefined for untracked services. */
|
|
126
|
-
|
|
127
|
-
apiKey: string,
|
|
128
|
-
orderId: string
|
|
129
|
-
): Promise<string | undefined> {
|
|
123
|
+
async function trackingNumber(apiKey: string, orderId: string): Promise<string | undefined> {
|
|
130
124
|
const response = await fetch(`${ORDERS_URL}/${encodeURIComponent(orderId)}`, {
|
|
131
125
|
headers: headers(apiKey),
|
|
132
126
|
});
|
|
@@ -137,7 +131,7 @@ export async function getClickAndDropTracking(
|
|
|
137
131
|
}
|
|
138
132
|
|
|
139
133
|
/** The postage label (with the customs form when the destination needs one) as a PDF. */
|
|
140
|
-
|
|
134
|
+
async function label(apiKey: string, orderId: string): Promise<ArrayBuffer> {
|
|
141
135
|
const response = await fetch(
|
|
142
136
|
`${ORDERS_URL}/${encodeURIComponent(orderId)}/label?documentType=postageLabel&includeReturnsLabel=false&includeCN=true`,
|
|
143
137
|
{ headers: headers(apiKey, { Accept: 'application/pdf' }) }
|
|
@@ -146,3 +140,28 @@ export async function getClickAndDropLabel(apiKey: string, orderId: string): Pro
|
|
|
146
140
|
throw new Error(`Click & Drop label for order ${orderId} failed (${response.status})`);
|
|
147
141
|
return response.arrayBuffer();
|
|
148
142
|
}
|
|
143
|
+
|
|
144
|
+
/** Royal Mail Click & Drop, for one account. The API key comes in; nothing is read ambiently. */
|
|
145
|
+
export class RoyalMailClient {
|
|
146
|
+
constructor(private readonly apiKey: string) {}
|
|
147
|
+
|
|
148
|
+
/** Creates the order and returns its Click & Drop identifier. Throws on any failure. */
|
|
149
|
+
createOrder(order: ClickAndDropOrder): Promise<string> {
|
|
150
|
+
return createOrder(this.apiKey, order);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Removes an order; only works until its label is printed. A 404 is fine. */
|
|
154
|
+
deleteOrder(orderId: string): Promise<void> {
|
|
155
|
+
return deleteOrder(this.apiKey, orderId);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The postage label (and customs form when needed) as a PDF. */
|
|
159
|
+
label(orderId: string): Promise<ArrayBuffer> {
|
|
160
|
+
return label(this.apiKey, orderId);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The tracking number once Click & Drop has one; undefined for untracked services. */
|
|
164
|
+
trackingNumber(orderId: string): Promise<string | undefined> {
|
|
165
|
+
return trackingNumber(this.apiKey, orderId);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type Stripe from 'stripe';
|
|
2
|
+
|
|
3
|
+
import { secret } from '../config';
|
|
4
|
+
import { RoyalMailClient } from './royalmail';
|
|
5
|
+
import { StripeClient } from './stripe';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The shop's clients, built with its own secrets. For managers and handlers (the edge), never
|
|
9
|
+
* services. Kept out of `config.ts` so code that only needs the config (the back-in-stock worker)
|
|
10
|
+
* does not bundle the Stripe SDK.
|
|
11
|
+
*/
|
|
12
|
+
export const ShopClients = {
|
|
13
|
+
royalMail(): RoyalMailClient {
|
|
14
|
+
return new RoyalMailClient(secret('royalMailApiKey'));
|
|
15
|
+
},
|
|
16
|
+
|
|
17
|
+
stripe(): Stripe {
|
|
18
|
+
return StripeClient.create(secret('stripeSecretKey'));
|
|
19
|
+
},
|
|
20
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import Stripe from 'stripe';
|
|
2
|
+
|
|
3
|
+
/** Stripe on Workers. The secret key comes in; nothing is read ambiently. */
|
|
4
|
+
export const StripeClient = {
|
|
5
|
+
create(secretKey: string): Stripe {
|
|
6
|
+
return new Stripe(secretKey, { httpClient: Stripe.createFetchHttpClient() });
|
|
7
|
+
},
|
|
8
|
+
|
|
9
|
+
/** Subtle-crypto verifier, required for webhooks on Workers (no Node crypto). */
|
|
10
|
+
webhookCrypto: Stripe.createSubtleCryptoProvider(),
|
|
11
|
+
};
|
package/config.ts
CHANGED
|
@@ -2,10 +2,10 @@ import type { EmailBrand } from '@zeyolabs/kit/utils/email';
|
|
|
2
2
|
|
|
3
3
|
import { envStore } from '@zeyolabs/kit/utils/env';
|
|
4
4
|
|
|
5
|
-
import type { ShopDb } from './db';
|
|
6
|
-
import type {
|
|
7
|
-
import type {
|
|
8
|
-
import type {
|
|
5
|
+
import type { ShopDb } from './db/index';
|
|
6
|
+
import type { DispatchEmailData } from './fulfilment/dispatch-email';
|
|
7
|
+
import type { OrderEmailData } from './orders/email';
|
|
8
|
+
import type { BackInStockEmailData } from './stock-alerts/email';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Names of the secrets the shop reads, as they are called in the app's wrangler config. The app must
|
|
@@ -46,9 +46,28 @@ export type ShopMail = {
|
|
|
46
46
|
orderDispatched: (order: DispatchEmailData) => Promise<void>;
|
|
47
47
|
};
|
|
48
48
|
|
|
49
|
+
/** Stripe Checkout options. Both are off unless the site turns them on. */
|
|
50
|
+
export type CheckoutOptions = {
|
|
51
|
+
/**
|
|
52
|
+
* Have Stripe issue a numbered, paid invoice (PDF) for every order and email it with the
|
|
53
|
+
* receipt. Stripe charges per invoice. `customFields` appear on the invoice, e.g. the VAT number
|
|
54
|
+
* (up to 4); `footer` is printed at the bottom, e.g. the registered company details.
|
|
55
|
+
*/
|
|
56
|
+
invoices?: {
|
|
57
|
+
customFields?: { name: string; value: string }[];
|
|
58
|
+
footer?: string;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Let customers enter a Stripe promotion code at Checkout. Codes, coupons and their limits are
|
|
62
|
+
* created and managed in the Stripe dashboard; the shop stores only the discount on each order.
|
|
63
|
+
*/
|
|
64
|
+
promotionCodes?: boolean;
|
|
65
|
+
};
|
|
66
|
+
|
|
49
67
|
/** Everything that differs between sites. The package holds no brand, address or account of its own. */
|
|
50
68
|
export type ShoppingConfig = {
|
|
51
69
|
brand: EmailBrand;
|
|
70
|
+
checkout?: CheckoutOptions;
|
|
52
71
|
db: () => ShopDb;
|
|
53
72
|
/** Where product image files are served from; the database stores only file names. */
|
|
54
73
|
imageBaseUrl: string;
|
package/context.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { getContext, setContext } from 'svelte';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What pages need in the browser. The server config in `config.ts` never reaches the client, so
|
|
5
|
+
* the app hands these over once from its root layout with `setShopContext`.
|
|
6
|
+
*/
|
|
7
|
+
export type ShopContext = {
|
|
8
|
+
imageBaseUrl: string;
|
|
9
|
+
siteName: string;
|
|
10
|
+
siteUrl: string;
|
|
11
|
+
supportEmail: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const KEY = Symbol('@zeyolabs/shopping-context');
|
|
15
|
+
|
|
16
|
+
export function setShopContext(client: ShopContext): void {
|
|
17
|
+
setContext(KEY, client);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function shopContext(): ShopContext {
|
|
21
|
+
const client = getContext<ShopContext | undefined>(KEY);
|
|
22
|
+
if (!client) throw new Error('@zeyolabs/shopping: call setShopContext() in the root layout');
|
|
23
|
+
return client;
|
|
24
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { getRequestEvent } from '$app/server';
|
|
2
|
+
import { AuthHandle } from '@zeyolabs/kit/auth/sessions/handle';
|
|
3
|
+
import { Remote } from '@zeyolabs/kit/server/remote-functions';
|
|
4
|
+
|
|
5
|
+
import { shopping } from '../config';
|
|
6
|
+
import { CustomerService } from './service.server';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The signed-in customer's orders (by the email they signed in with). Needs the app's auth handle
|
|
10
|
+
* (kit `AuthHandle`) in front; signed out it is a 401.
|
|
11
|
+
*/
|
|
12
|
+
export const getMyOrders = Remote.Query(async () => {
|
|
13
|
+
const user = AuthHandle.requireUser(getRequestEvent());
|
|
14
|
+
const service = new CustomerService(shopping().db());
|
|
15
|
+
return {
|
|
16
|
+
email: user.email,
|
|
17
|
+
orders: await service.orders(user.email),
|
|
18
|
+
};
|
|
19
|
+
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import type { Snippet } from 'svelte';
|
|
3
|
+
|
|
4
|
+
import PageTitle from '../../ui/PageTitle.svelte';
|
|
5
|
+
import { getMyOrders } from '../client.remote';
|
|
6
|
+
import { Money } from '../../utils/money';
|
|
7
|
+
import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
|
|
8
|
+
import SkeletonCard from '@zeyolabs/ui/skeleton/SkeletonCard.svelte';
|
|
9
|
+
|
|
10
|
+
let {
|
|
11
|
+
children,
|
|
12
|
+
}: {
|
|
13
|
+
/** Anything the app adds below the orders, e.g. passkeys and signing out. */
|
|
14
|
+
children?: Snippet;
|
|
15
|
+
} = $props();
|
|
16
|
+
|
|
17
|
+
const date = new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium', timeZone: 'Europe/London' });
|
|
18
|
+
const STATUS: Record<string, string> = {
|
|
19
|
+
cancelled: 'Cancelled',
|
|
20
|
+
paid: 'Being prepared',
|
|
21
|
+
pending: 'Awaiting payment',
|
|
22
|
+
refunded: 'Refunded',
|
|
23
|
+
shipped: 'Dispatched',
|
|
24
|
+
};
|
|
25
|
+
</script>
|
|
26
|
+
|
|
27
|
+
<PageTitle description="Your orders." title="Your account" />
|
|
28
|
+
|
|
29
|
+
<svelte:head>
|
|
30
|
+
<meta name="robots" content="noindex, nofollow" />
|
|
31
|
+
</svelte:head>
|
|
32
|
+
|
|
33
|
+
<Boundary message="Could not load your orders.">
|
|
34
|
+
{let data = $derived(await getMyOrders())}
|
|
35
|
+
<p class="text-[var(--txs)]">
|
|
36
|
+
Signed in as <strong class="text-[var(--tx)]">{data.email}</strong>
|
|
37
|
+
</p>
|
|
38
|
+
|
|
39
|
+
<h2 class="mt-8 text-lg font-semibold">Orders</h2>
|
|
40
|
+
{#if data.orders.length === 0}
|
|
41
|
+
<p class="mt-2 text-[var(--txs)]">
|
|
42
|
+
No orders yet. Orders placed with this email address, signed in or not, show here.
|
|
43
|
+
</p>
|
|
44
|
+
{:else}
|
|
45
|
+
<ul class="mt-2 divide-y divide-[var(--bd)] border-y border-[var(--bd)]">
|
|
46
|
+
{#each data.orders as order (order.number)}
|
|
47
|
+
<li class="flex flex-wrap items-center justify-between gap-2 py-3">
|
|
48
|
+
<span>
|
|
49
|
+
{#if order.path}
|
|
50
|
+
<!-- eslint-disable-next-line svelte/no-navigation-without-resolve -- the order's private path -->
|
|
51
|
+
<a class="font-medium underline" href={order.path}>{order.number}</a>
|
|
52
|
+
{:else}
|
|
53
|
+
<span class="font-medium">{order.number}</span>
|
|
54
|
+
{/if}
|
|
55
|
+
<span class="text-[var(--txs)]"> · {date.format(order.createdAt)}</span>
|
|
56
|
+
</span>
|
|
57
|
+
<span>
|
|
58
|
+
<span class="text-[var(--txs)]">{STATUS[order.status] ?? order.status}</span>
|
|
59
|
+
· {Money.format(order.totalPence)}
|
|
60
|
+
</span>
|
|
61
|
+
</li>
|
|
62
|
+
{/each}
|
|
63
|
+
</ul>
|
|
64
|
+
{/if}
|
|
65
|
+
{#snippet pending()}
|
|
66
|
+
<SkeletonCard lines={3} />
|
|
67
|
+
{/snippet}
|
|
68
|
+
</Boundary>
|
|
69
|
+
|
|
70
|
+
{@render children?.()}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type Stripe from 'stripe';
|
|
2
|
+
|
|
3
|
+
import { and, desc, eq, isNotNull, sql } from 'drizzle-orm';
|
|
4
|
+
|
|
5
|
+
import type { ShopDb } from '../db/index';
|
|
6
|
+
|
|
7
|
+
import { customers, orders } from '../db/schema';
|
|
8
|
+
import { Orders } from '../orders/library';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Signed-in customers. Sign-in itself is the app's (kit's passwordless auth); the shop only needs
|
|
12
|
+
* the email: orders belong to an email address, so an account sees every order placed with it,
|
|
13
|
+
* including guest orders from before the account existed.
|
|
14
|
+
*/
|
|
15
|
+
export class CustomerService {
|
|
16
|
+
constructor(private readonly db: ShopDb) {}
|
|
17
|
+
|
|
18
|
+
/** Paid orders placed with this email, newest first, with the private link to each. */
|
|
19
|
+
async orders(email: string, limit = 50) {
|
|
20
|
+
const rows = await this.db
|
|
21
|
+
.select({
|
|
22
|
+
accessToken: orders.accessToken,
|
|
23
|
+
createdAt: orders.createdAt,
|
|
24
|
+
number: orders.number,
|
|
25
|
+
shippedAt: orders.shippedAt,
|
|
26
|
+
status: orders.status,
|
|
27
|
+
totalPence: orders.totalPence,
|
|
28
|
+
})
|
|
29
|
+
.from(orders)
|
|
30
|
+
.where(
|
|
31
|
+
and(eq(sql`lower(${orders.email})`, email.trim().toLowerCase()), isNotNull(orders.paidAt))
|
|
32
|
+
)
|
|
33
|
+
.orderBy(desc(orders.createdAt))
|
|
34
|
+
.limit(limit);
|
|
35
|
+
return rows.map(({ accessToken, ...order }) => ({
|
|
36
|
+
...order,
|
|
37
|
+
path: accessToken ? Orders.path(order.number, accessToken) : null,
|
|
38
|
+
}));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The customer's Stripe Customer id, creating the Customer on first checkout. */
|
|
42
|
+
async stripeCustomerId(stripe: Stripe, email: string, now = Date.now()): Promise<string> {
|
|
43
|
+
const key = email.trim().toLowerCase();
|
|
44
|
+
const found = await this.db.query.customers.findFirst({ where: eq(customers.email, key) });
|
|
45
|
+
if (found) return found.stripeCustomerId;
|
|
46
|
+
const customer = await stripe.customers.create(
|
|
47
|
+
{ email: key },
|
|
48
|
+
{ idempotencyKey: `cus:${key}` }
|
|
49
|
+
);
|
|
50
|
+
await this.db
|
|
51
|
+
.insert(customers)
|
|
52
|
+
.values({ createdAt: now, email: key, stripeCustomerId: customer.id })
|
|
53
|
+
.onConflictDoNothing();
|
|
54
|
+
const row = await this.db.query.customers.findFirst({ where: eq(customers.email, key) });
|
|
55
|
+
return row?.stripeCustomerId ?? customer.id;
|
|
56
|
+
}
|
|
57
|
+
}
|
package/db/schema.ts
CHANGED
|
@@ -231,6 +231,8 @@ export const orders = sqliteTable(
|
|
|
231
231
|
/** The `shipping_rates.service` the customer chose. */
|
|
232
232
|
shippingService: text('shipping_service'),
|
|
233
233
|
status: text('status', { enum: ORDER_STATUSES }).notNull().default('pending'),
|
|
234
|
+
/** The Stripe invoice made for this payment (when the shop issues invoices), for its PDF link. */
|
|
235
|
+
stripeInvoiceId: text('stripe_invoice_id'),
|
|
234
236
|
stripePaymentIntentId: text('stripe_payment_intent_id').unique(),
|
|
235
237
|
stripeSessionId: text('stripe_session_id').unique(),
|
|
236
238
|
subtotalPence: integer('subtotal_pence').notNull(),
|
|
@@ -265,6 +267,100 @@ export const orderItems = sqliteTable(
|
|
|
265
267
|
]
|
|
266
268
|
);
|
|
267
269
|
|
|
270
|
+
/**
|
|
271
|
+
* A signed-in customer's Stripe Customer, so Checkout fills in their saved name and address. Keyed
|
|
272
|
+
* by the lower-cased email the customer signs in with (orders are matched to accounts by email).
|
|
273
|
+
*/
|
|
274
|
+
export const customers = sqliteTable('customers', {
|
|
275
|
+
createdAt: integer('created_at').notNull(),
|
|
276
|
+
email: text('email').primaryKey(),
|
|
277
|
+
stripeCustomerId: text('stripe_customer_id').notNull().unique(),
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
export const REVIEW_STATUSES = ['pending', 'approved', 'rejected'] as const;
|
|
281
|
+
export type ReviewStatus = (typeof REVIEW_STATUSES)[number];
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Product reviews from verified buyers: one per product per order, written from the order page.
|
|
285
|
+
* Only `approved` reviews are shown; staff approve or reject them in the admin.
|
|
286
|
+
*/
|
|
287
|
+
export const reviews = sqliteTable(
|
|
288
|
+
'reviews',
|
|
289
|
+
{
|
|
290
|
+
body: text('body').notNull(),
|
|
291
|
+
createdAt: integer('created_at').notNull(),
|
|
292
|
+
id: integer('id').primaryKey({ autoIncrement: true }),
|
|
293
|
+
/** When staff approved or rejected it. */
|
|
294
|
+
moderatedAt: integer('moderated_at'),
|
|
295
|
+
/** The name shown with the review, as the customer typed it. */
|
|
296
|
+
name: text('name').notNull(),
|
|
297
|
+
orderId: integer('order_id')
|
|
298
|
+
.notNull()
|
|
299
|
+
.references(() => orders.id, { onDelete: 'cascade' }),
|
|
300
|
+
productId: integer('product_id')
|
|
301
|
+
.notNull()
|
|
302
|
+
.references(() => products.id, { onDelete: 'cascade' }),
|
|
303
|
+
/** 1 to 5 stars. */
|
|
304
|
+
rating: integer('rating').notNull(),
|
|
305
|
+
status: text('status', { enum: REVIEW_STATUSES }).notNull().default('pending'),
|
|
306
|
+
title: text('title').notNull().default(''),
|
|
307
|
+
},
|
|
308
|
+
(t) => [
|
|
309
|
+
uniqueIndex('reviews_order_product_unique').on(t.orderId, t.productId),
|
|
310
|
+
index('reviews_product_status_idx').on(t.productId, t.status),
|
|
311
|
+
]
|
|
312
|
+
);
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* A bundle is built in steps: at each step the customer picks from that step's products. Adding a
|
|
316
|
+
* bundle to the basket adds the chosen products as ordinary lines at their own prices, so stock,
|
|
317
|
+
* shipping and orders work unchanged.
|
|
318
|
+
*/
|
|
319
|
+
export const bundles = sqliteTable('bundles', {
|
|
320
|
+
active: integer('active', { mode: 'boolean' }).notNull().default(true),
|
|
321
|
+
createdAt: integer('created_at').notNull(),
|
|
322
|
+
description: text('description').notNull().default(''),
|
|
323
|
+
id: integer('id').primaryKey({ autoIncrement: true }),
|
|
324
|
+
/** File name in the product image bucket, shown on the bundle page. */
|
|
325
|
+
image: text('image'),
|
|
326
|
+
name: text('name').notNull(),
|
|
327
|
+
slug: text('slug').notNull().unique(),
|
|
328
|
+
sortOrder: integer('sort_order').notNull().default(0),
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
/** One step of a bundle: pick between `minChoices` and `maxChoices` of its products. */
|
|
332
|
+
export const bundleSteps = sqliteTable(
|
|
333
|
+
'bundle_steps',
|
|
334
|
+
{
|
|
335
|
+
bundleId: integer('bundle_id')
|
|
336
|
+
.notNull()
|
|
337
|
+
.references(() => bundles.id, { onDelete: 'cascade' }),
|
|
338
|
+
description: text('description').notNull().default(''),
|
|
339
|
+
id: integer('id').primaryKey({ autoIncrement: true }),
|
|
340
|
+
maxChoices: integer('max_choices').notNull().default(1),
|
|
341
|
+
/** 0 makes the step optional. */
|
|
342
|
+
minChoices: integer('min_choices').notNull().default(1),
|
|
343
|
+
position: integer('position').notNull().default(0),
|
|
344
|
+
title: text('title').notNull(),
|
|
345
|
+
},
|
|
346
|
+
(t) => [index('bundle_steps_bundle_idx').on(t.bundleId, t.position)]
|
|
347
|
+
);
|
|
348
|
+
|
|
349
|
+
/** The products a step offers, in display order. */
|
|
350
|
+
export const bundleStepProducts = sqliteTable(
|
|
351
|
+
'bundle_step_products',
|
|
352
|
+
{
|
|
353
|
+
position: integer('position').notNull().default(0),
|
|
354
|
+
productId: integer('product_id')
|
|
355
|
+
.notNull()
|
|
356
|
+
.references(() => products.id, { onDelete: 'cascade' }),
|
|
357
|
+
stepId: integer('step_id')
|
|
358
|
+
.notNull()
|
|
359
|
+
.references(() => bundleSteps.id, { onDelete: 'cascade' }),
|
|
360
|
+
},
|
|
361
|
+
(t) => [primaryKey({ columns: [t.stepId, t.productId] })]
|
|
362
|
+
);
|
|
363
|
+
|
|
268
364
|
export const productsRelations = relations(products, ({ many, one }) => ({
|
|
269
365
|
images: many(productImages),
|
|
270
366
|
variationGroup: one(variationGroups, {
|