@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
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import { resolve } from '$app/paths';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { Stock } from '
|
|
3
|
+
import { shopContext } from '../../context';
|
|
4
|
+
import { Images } from '../../utils/images';
|
|
5
|
+
import { Money } from '../../utils/money';
|
|
6
|
+
import { Stock } from '../../stock/library';
|
|
7
7
|
|
|
8
8
|
type Product = {
|
|
9
9
|
comparePricePence: null | number;
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
let { product }: { product: Product } = $props();
|
|
20
20
|
|
|
21
|
-
const
|
|
21
|
+
const context = shopContext();
|
|
22
22
|
|
|
23
23
|
const badge = $derived(Stock.badge(product.stock, product.lowStockThreshold));
|
|
24
24
|
const onSale = $derived(
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
: ''}"
|
|
44
44
|
alt={product.cover.alt || product.name}
|
|
45
45
|
loading="lazy"
|
|
46
|
-
src={
|
|
46
|
+
src={Images.url(context.imageBaseUrl, product.cover.src)}
|
|
47
47
|
/>
|
|
48
48
|
{/if}
|
|
49
49
|
{#if badge.kind === 'out'}
|
|
@@ -66,9 +66,9 @@
|
|
|
66
66
|
<div class="px-2 pt-3 pb-2">
|
|
67
67
|
<p class="leading-snug font-medium">{product.name}</p>
|
|
68
68
|
<p class="mt-1 text-[var(--txs)]">
|
|
69
|
-
<span class="font-medium text-[var(--tx)]">{
|
|
69
|
+
<span class="font-medium text-[var(--tx)]">{Money.format(product.pricePence)}</span>
|
|
70
70
|
{#if onSale}
|
|
71
|
-
<s class="ml-1 text-sm">{
|
|
71
|
+
<s class="ml-1 text-sm">{Money.format(product.comparePricePence!)}</s>
|
|
72
72
|
{/if}
|
|
73
73
|
</p>
|
|
74
74
|
</div>
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { asc, inArray } from 'drizzle-orm';
|
|
2
|
+
|
|
3
|
+
import type { ShopDb } from '../db/index';
|
|
4
|
+
|
|
5
|
+
import { productImages } from '../db/schema';
|
|
6
|
+
import { Batches } from '../utils/batches';
|
|
7
|
+
|
|
8
|
+
export type Cover = { alt: string; src: string };
|
|
9
|
+
|
|
10
|
+
/** Each product's cover image: its lowest-position photo. */
|
|
11
|
+
export class CoverService {
|
|
12
|
+
constructor(private readonly db: ShopDb) {}
|
|
13
|
+
|
|
14
|
+
/** Cover per product id; products without photos are left out. */
|
|
15
|
+
async covers(productIds: readonly number[]): Promise<Map<number, Cover>> {
|
|
16
|
+
const images = await Batches.rows(productIds, (slice) =>
|
|
17
|
+
this.db
|
|
18
|
+
.select({
|
|
19
|
+
alt: productImages.alt,
|
|
20
|
+
productId: productImages.productId,
|
|
21
|
+
src: productImages.src,
|
|
22
|
+
})
|
|
23
|
+
.from(productImages)
|
|
24
|
+
.where(inArray(productImages.productId, slice))
|
|
25
|
+
.orderBy(asc(productImages.position))
|
|
26
|
+
);
|
|
27
|
+
const covers = new Map<number, Cover>();
|
|
28
|
+
for (const { productId, ...image } of images) {
|
|
29
|
+
if (!covers.has(productId)) covers.set(productId, image);
|
|
30
|
+
}
|
|
31
|
+
return covers;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Shop search terms. Pure. */
|
|
2
|
+
export const Search = {
|
|
3
|
+
/** How many results a search returns. */
|
|
4
|
+
LIMIT: 48,
|
|
5
|
+
/** Longest query the shop accepts. */
|
|
6
|
+
MAX_LENGTH: 100,
|
|
7
|
+
/** D1 rejects a LIKE pattern over 50 bytes; this leaves room for the two `%`. */
|
|
8
|
+
MAX_WORD_BYTES: 48,
|
|
9
|
+
|
|
10
|
+
/** A LIKE pattern matching `word` anywhere; `%` and `_` typed by a customer mean the characters. */
|
|
11
|
+
pattern(word: string): string {
|
|
12
|
+
return `%${word.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
|
|
13
|
+
},
|
|
14
|
+
|
|
15
|
+
/** The words of a query, lower-cased, at most 6 (each must match), each short enough for D1's LIKE limit. */
|
|
16
|
+
words(query: string): string[] {
|
|
17
|
+
return query
|
|
18
|
+
.toLowerCase()
|
|
19
|
+
.slice(0, Search.MAX_LENGTH)
|
|
20
|
+
.split(/\s+/)
|
|
21
|
+
.filter((w) => w.length > 0)
|
|
22
|
+
.slice(0, 6)
|
|
23
|
+
.map(fitPattern);
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** `word` cut so that its escaped LIKE pattern, `%` and `%` included, is at most 50 UTF-8 bytes. */
|
|
28
|
+
function fitPattern(word: string): string {
|
|
29
|
+
const encoder = new TextEncoder();
|
|
30
|
+
let bytes = 0;
|
|
31
|
+
let fitted = '';
|
|
32
|
+
for (const char of word) {
|
|
33
|
+
bytes += encoder.encode(Search.pattern(char).slice(1, -1)).length;
|
|
34
|
+
if (bytes > Search.MAX_WORD_BYTES) break;
|
|
35
|
+
fitted += char;
|
|
36
|
+
}
|
|
37
|
+
return fitted;
|
|
38
|
+
}
|
|
@@ -7,8 +7,9 @@ import {
|
|
|
7
7
|
getProduct,
|
|
8
8
|
getShop,
|
|
9
9
|
getUkShippingRate,
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
searchShop,
|
|
11
|
+
} from './client.remote';
|
|
12
|
+
import { CatalogueService } from './service.server';
|
|
12
13
|
|
|
13
14
|
/**
|
|
14
15
|
* Server `load`s for the public catalogue pages. They call the same remote queries the client uses,
|
|
@@ -39,7 +40,8 @@ export async function productLoad({ params, url }: SlugEvent) {
|
|
|
39
40
|
} catch (err) {
|
|
40
41
|
if (!isHttpError(err, 404)) throw err;
|
|
41
42
|
}
|
|
42
|
-
const
|
|
43
|
+
const service = new CatalogueService(shopping().db());
|
|
44
|
+
const target = await service.redirect({
|
|
43
45
|
legacySlug: slug,
|
|
44
46
|
variantSku: url.searchParams.get('variant'),
|
|
45
47
|
});
|
|
@@ -47,6 +49,12 @@ export async function productLoad({ params, url }: SlugEvent) {
|
|
|
47
49
|
error(404, 'Product not found');
|
|
48
50
|
}
|
|
49
51
|
|
|
52
|
+
/** `/search?q=`: the results are in the server-rendered page. */
|
|
53
|
+
export async function searchLoad({ url }: { url: URL }) {
|
|
54
|
+
const q = (url.searchParams.get('q') ?? '').trim().slice(0, 100);
|
|
55
|
+
return { search: await searchShop(q) };
|
|
56
|
+
}
|
|
57
|
+
|
|
50
58
|
export async function shippingLoad() {
|
|
51
59
|
return { shipping: await getUkShippingRate() };
|
|
52
60
|
}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import { resolve } from '$app/paths';
|
|
3
|
-
import {
|
|
4
|
-
import PageTitle from '
|
|
3
|
+
import { shopContext } from '../../context';
|
|
4
|
+
import PageTitle from '../../ui/PageTitle.svelte';
|
|
5
5
|
import ProductCard from '../components/ProductCard.svelte';
|
|
6
|
-
import type { getCategoryPage } from '../
|
|
6
|
+
import type { getCategoryPage } from '../client.remote';
|
|
7
7
|
|
|
8
8
|
/** From the route's server `load` (`categoryLoad`). */
|
|
9
9
|
let { data }: { data: Awaited<ReturnType<typeof getCategoryPage>> } = $props();
|
|
10
10
|
|
|
11
|
-
const
|
|
11
|
+
const context = shopContext();
|
|
12
12
|
</script>
|
|
13
13
|
|
|
14
14
|
<p class="mb-2 text-sm"><a class="underline" href={resolve('/shop')}>All products</a></p>
|
|
15
15
|
<PageTitle
|
|
16
|
-
description="Buy {data.category.name} from {
|
|
16
|
+
description="Buy {data.category.name} from {context.siteName}."
|
|
17
17
|
title={data.category.name}
|
|
18
18
|
/>
|
|
19
19
|
|
|
@@ -2,15 +2,18 @@
|
|
|
2
2
|
import type { Snippet } from 'svelte';
|
|
3
3
|
|
|
4
4
|
import { resolve } from '$app/paths';
|
|
5
|
-
import PageTitle from '
|
|
6
|
-
import
|
|
7
|
-
import
|
|
5
|
+
import PageTitle from '../../ui/PageTitle.svelte';
|
|
6
|
+
import Reviews from '../../reviews/components/Reviews.svelte';
|
|
7
|
+
import Stars from '../../ui/Stars.svelte';
|
|
8
|
+
import { addToBasketForm } from '../../basket/client.remote';
|
|
9
|
+
import { AddToBasketSchema } from '../../basket/schema';
|
|
10
|
+
import type { getProduct } from '../client.remote';
|
|
8
11
|
import ShoppingBasket from '@lucide/svelte/icons/shopping-basket';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import { Stock } from '
|
|
13
|
-
import {
|
|
12
|
+
import { shopContext } from '../../context';
|
|
13
|
+
import { Images } from '../../utils/images';
|
|
14
|
+
import { Money } from '../../utils/money';
|
|
15
|
+
import { Stock } from '../../stock/library';
|
|
16
|
+
import { Form } from '@zeyolabs/ui/form';
|
|
14
17
|
import Button from '@zeyolabs/ui/form/Button.svelte';
|
|
15
18
|
import ImageGallery from '@zeyolabs/ui/gallery/ImageGallery.svelte';
|
|
16
19
|
|
|
@@ -24,16 +27,7 @@
|
|
|
24
27
|
outOfStock?: Snippet<[productId: number]>;
|
|
25
28
|
} = $props();
|
|
26
29
|
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
async function add(productId: number) {
|
|
30
|
-
try {
|
|
31
|
-
await addToBasket({ productId, quantity: 1 });
|
|
32
|
-
toast.success('Added to your basket');
|
|
33
|
-
} catch {
|
|
34
|
-
toast.error('Could not add to basket. Please try again.');
|
|
35
|
-
}
|
|
36
|
-
}
|
|
30
|
+
const context = shopContext();
|
|
37
31
|
</script>
|
|
38
32
|
|
|
39
33
|
{let product = $derived(data.product)}
|
|
@@ -50,15 +44,22 @@
|
|
|
50
44
|
name={product.name}
|
|
51
45
|
images={product.images.map((image) => ({
|
|
52
46
|
alt: image.alt,
|
|
53
|
-
src:
|
|
47
|
+
src: Images.url(context.imageBaseUrl, image.src),
|
|
54
48
|
}))}
|
|
55
49
|
/>
|
|
56
50
|
{/key}
|
|
57
51
|
<div>
|
|
52
|
+
{#if data.reviews.average !== null}
|
|
53
|
+
<a class="mb-2 flex items-center gap-2 text-sm no-underline" href="#reviews-heading">
|
|
54
|
+
<Stars rating={data.reviews.average} size="text-sm" />
|
|
55
|
+
{data.reviews.count}
|
|
56
|
+
{data.reviews.count === 1 ? 'review' : 'reviews'}
|
|
57
|
+
</a>
|
|
58
|
+
{/if}
|
|
58
59
|
<p class="text-2xl">
|
|
59
|
-
{
|
|
60
|
+
{Money.format(product.pricePence)}
|
|
60
61
|
{#if product.comparePricePence && product.comparePricePence > product.pricePence}
|
|
61
|
-
<s class="text-base opacity-60">{
|
|
62
|
+
<s class="text-base opacity-60">{Money.format(product.comparePricePence)}</s>
|
|
62
63
|
{/if}
|
|
63
64
|
</p>
|
|
64
65
|
{#if data.options.length > 1}
|
|
@@ -82,13 +83,24 @@
|
|
|
82
83
|
left{:else}In stock{/if}
|
|
83
84
|
</p>
|
|
84
85
|
{#if product.stock > 0}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
86
|
+
{const form = addToBasketForm.for(product.id)}
|
|
87
|
+
<Form
|
|
88
|
+
class="mt-4"
|
|
89
|
+
{form}
|
|
90
|
+
hidden={{ productId: product.id, quantity: 1 }}
|
|
91
|
+
reset={false}
|
|
92
|
+
schema={AddToBasketSchema}
|
|
93
|
+
>
|
|
94
|
+
<Button {form} loadingMessage="Adding…" size="lg">
|
|
95
|
+
<ShoppingBasket size={18} />
|
|
96
|
+
Add to basket
|
|
97
|
+
</Button>
|
|
98
|
+
</Form>
|
|
89
99
|
{/if}
|
|
90
100
|
{#if product.stock <= 0}
|
|
91
101
|
{@render outOfStock?.(product.id)}
|
|
92
102
|
{/if}
|
|
93
103
|
</div>
|
|
94
104
|
</div>
|
|
105
|
+
|
|
106
|
+
<Reviews reviews={data.reviews} />
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import PageTitle from '../../ui/PageTitle.svelte';
|
|
3
|
+
import ProductCard from '../components/ProductCard.svelte';
|
|
4
|
+
import type { searchShop } from '../client.remote';
|
|
5
|
+
|
|
6
|
+
let {
|
|
7
|
+
search,
|
|
8
|
+
}: {
|
|
9
|
+
/** From the route's server `load` (`searchLoad`). */
|
|
10
|
+
search: Awaited<ReturnType<typeof searchShop>>;
|
|
11
|
+
} = $props();
|
|
12
|
+
</script>
|
|
13
|
+
|
|
14
|
+
<PageTitle description="Search the shop." title="Search" />
|
|
15
|
+
|
|
16
|
+
<svelte:head>
|
|
17
|
+
<meta name="robots" content="noindex, follow" />
|
|
18
|
+
</svelte:head>
|
|
19
|
+
|
|
20
|
+
<form class="mb-8 flex max-w-xl gap-2" action="/search" method="get" role="search">
|
|
21
|
+
<label class="sr-only" for="shop-search">Search products</label>
|
|
22
|
+
<input
|
|
23
|
+
id="shop-search"
|
|
24
|
+
name="q"
|
|
25
|
+
class="h-[var(--control-h)] min-w-0 flex-1 rounded-md border border-[var(--bd)] bg-white px-3"
|
|
26
|
+
autocomplete="off"
|
|
27
|
+
maxlength="100"
|
|
28
|
+
placeholder="Search products"
|
|
29
|
+
type="search"
|
|
30
|
+
value={search.query}
|
|
31
|
+
/>
|
|
32
|
+
<button
|
|
33
|
+
class="h-[var(--control-h)] rounded-md bg-[var(--primary-strong)] px-4 font-medium text-white"
|
|
34
|
+
type="submit">Search</button
|
|
35
|
+
>
|
|
36
|
+
</form>
|
|
37
|
+
|
|
38
|
+
{#if search.query === ''}
|
|
39
|
+
<p class="text-[var(--txs)]">Type what you are looking for.</p>
|
|
40
|
+
{:else if search.products.length === 0}
|
|
41
|
+
<p>Nothing matches "{search.query}". Try fewer or different words.</p>
|
|
42
|
+
{:else}
|
|
43
|
+
<p class="mb-4 text-[var(--txs)]" aria-live="polite">
|
|
44
|
+
{search.products.length === 48 ? 'Top 48' : search.products.length}
|
|
45
|
+
{search.products.length === 1 ? 'result' : 'results'} for "{search.query}"
|
|
46
|
+
</p>
|
|
47
|
+
<ul class="grid gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
|
48
|
+
{#each search.products as product (product.id)}
|
|
49
|
+
<li><ProductCard {product} /></li>
|
|
50
|
+
{/each}
|
|
51
|
+
</ul>
|
|
52
|
+
{/if}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import { resolve } from '$app/paths';
|
|
3
|
-
import PageTitle from '
|
|
3
|
+
import PageTitle from '../../ui/PageTitle.svelte';
|
|
4
4
|
import ProductCard from '../components/ProductCard.svelte';
|
|
5
|
-
import type { getShop } from '../
|
|
5
|
+
import type { getShop } from '../client.remote';
|
|
6
6
|
|
|
7
7
|
let {
|
|
8
8
|
description,
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { SchemaForm } from '@zeyolabs/kit/utils/form';
|
|
2
|
+
import { Schema } from '@zeyolabs/kit/utils/schema';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
import { FormInput } from '../utils/form-input';
|
|
6
|
+
import { ShopSchema } from '../utils/schemas';
|
|
7
|
+
|
|
8
|
+
/** The admin's product editor. Stock is not here: it changes only through the stock page. */
|
|
9
|
+
export const ProductInputSchema = z.object({
|
|
10
|
+
active: z.boolean(),
|
|
11
|
+
categoryIds: z.array(Schema.Id).max(50),
|
|
12
|
+
comparePricePence: ShopSchema.Pence.nullable(),
|
|
13
|
+
/** Combined products: the parts by SKU. Empty for a normal product. */
|
|
14
|
+
components: z
|
|
15
|
+
.array(z.object({ quantity: z.number().int().min(1).max(1000), sku: z.string().trim().min(1) }))
|
|
16
|
+
.max(10),
|
|
17
|
+
description: z.string().max(20_000),
|
|
18
|
+
id: Schema.Id.optional(),
|
|
19
|
+
/** File names in the image bucket, cover first. */
|
|
20
|
+
images: z
|
|
21
|
+
.array(z.object({ alt: z.string().trim().max(200), src: z.string().trim().min(1).max(200) }))
|
|
22
|
+
.max(20),
|
|
23
|
+
lowStockThreshold: z.number().int().min(0).max(10_000).nullable(),
|
|
24
|
+
massGrams: z.number().int().min(0).max(100_000),
|
|
25
|
+
maxPerOrder: z.number().int().min(1).max(99),
|
|
26
|
+
name: z.string().trim().min(1, 'enter a name').max(200),
|
|
27
|
+
packSize: z.number().int().min(1).max(10_000),
|
|
28
|
+
pricePence: ShopSchema.Pence,
|
|
29
|
+
shortDescription: z.string().trim().max(500),
|
|
30
|
+
sku: z
|
|
31
|
+
.string()
|
|
32
|
+
.trim()
|
|
33
|
+
.min(1, 'enter a SKU')
|
|
34
|
+
.max(60)
|
|
35
|
+
.regex(/^[A-Za-z0-9._-]+$/, 'letters, digits, dots, dashes and underscores'),
|
|
36
|
+
slug: Schema.Slug,
|
|
37
|
+
sortOrder: z.number().int().min(-10_000).max(10_000),
|
|
38
|
+
/** Name of the variation group (created if new), or null. */
|
|
39
|
+
variationGroup: z.string().trim().max(100).nullable(),
|
|
40
|
+
variationLabel: z.string().trim().max(100).nullable(),
|
|
41
|
+
});
|
|
42
|
+
export type ProductInput = z.infer<typeof ProductInputSchema>;
|
|
43
|
+
|
|
44
|
+
export const CategoryInputSchema = z.object({
|
|
45
|
+
description: z.string().trim().max(5000),
|
|
46
|
+
id: Schema.Id.optional(),
|
|
47
|
+
name: z.string().trim().min(1, 'enter a name').max(200),
|
|
48
|
+
slug: Schema.Slug,
|
|
49
|
+
sortOrder: z.number().int().min(-10_000).max(10_000),
|
|
50
|
+
});
|
|
51
|
+
export type CategoryInput = z.infer<typeof CategoryInputSchema>;
|
|
52
|
+
|
|
53
|
+
/** Pounds as typed ("12.50", "£12.5"); blank is allowed only where `optional`. */
|
|
54
|
+
function pounds(optional: boolean) {
|
|
55
|
+
return z
|
|
56
|
+
.string()
|
|
57
|
+
.trim()
|
|
58
|
+
.default('')
|
|
59
|
+
.refine((v) => (v === '' ? optional : !Number.isNaN(FormInput.parsePounds(v))), {
|
|
60
|
+
message: optional
|
|
61
|
+
? 'enter a price like 15.00, or leave it blank'
|
|
62
|
+
: 'enter a price like 12.50',
|
|
63
|
+
})
|
|
64
|
+
.transform((v) => FormInput.parsePounds(v));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The product editor's fields as the form sends them (prices in pounds, category ids as strings,
|
|
69
|
+
* blank rows allowed), turned into a `ProductInput`. A blank slug is made from the name.
|
|
70
|
+
*/
|
|
71
|
+
export const ProductFormSchema = z
|
|
72
|
+
.object({
|
|
73
|
+
active: SchemaForm.Boolean,
|
|
74
|
+
categoryIds: z.array(z.string().regex(/^\d+$/)).default([]),
|
|
75
|
+
comparePrice: pounds(true),
|
|
76
|
+
components: z
|
|
77
|
+
.array(z.object({ quantity: SchemaForm.nullable(SchemaForm.Int), sku: ShopSchema.FormText }))
|
|
78
|
+
.default([]),
|
|
79
|
+
description: ShopSchema.FormText,
|
|
80
|
+
id: Schema.Id.optional(),
|
|
81
|
+
images: z.array(z.object({ alt: ShopSchema.FormText, src: ShopSchema.FormText })).default([]),
|
|
82
|
+
lowStockThreshold: SchemaForm.nullable(SchemaForm.Int),
|
|
83
|
+
massGrams: SchemaForm.Int,
|
|
84
|
+
maxPerOrder: SchemaForm.Int,
|
|
85
|
+
name: ShopSchema.FormText,
|
|
86
|
+
packSize: SchemaForm.Int,
|
|
87
|
+
price: pounds(false),
|
|
88
|
+
shortDescription: ShopSchema.FormText,
|
|
89
|
+
sku: ShopSchema.FormText,
|
|
90
|
+
slug: ShopSchema.FormText,
|
|
91
|
+
sortOrder: SchemaForm.Int,
|
|
92
|
+
variationGroup: ShopSchema.FormText,
|
|
93
|
+
variationLabel: ShopSchema.FormText,
|
|
94
|
+
})
|
|
95
|
+
.transform(({ categoryIds, comparePrice, components, images, price, ...p }) => ({
|
|
96
|
+
...p,
|
|
97
|
+
categoryIds: categoryIds.map(Number),
|
|
98
|
+
comparePricePence: comparePrice,
|
|
99
|
+
components: components
|
|
100
|
+
.filter((c) => c.sku.trim() !== '')
|
|
101
|
+
.map((c) => ({ quantity: c.quantity ?? 1, sku: c.sku })),
|
|
102
|
+
images: images.filter((i) => i.src.trim() !== ''),
|
|
103
|
+
pricePence: price ?? 0,
|
|
104
|
+
slug: p.slug.trim() || FormInput.slugify(p.name),
|
|
105
|
+
variationGroup: p.variationGroup.trim() || null,
|
|
106
|
+
variationLabel: p.variationLabel.trim() || null,
|
|
107
|
+
}))
|
|
108
|
+
.pipe(ProductInputSchema);
|
|
109
|
+
|
|
110
|
+
/** The category editor's fields; a blank slug is made from the name. */
|
|
111
|
+
export const CategoryFormSchema = z
|
|
112
|
+
.object({
|
|
113
|
+
description: ShopSchema.FormText,
|
|
114
|
+
id: Schema.Id.optional(),
|
|
115
|
+
name: ShopSchema.FormText,
|
|
116
|
+
slug: ShopSchema.FormText,
|
|
117
|
+
sortOrder: SchemaForm.Int,
|
|
118
|
+
})
|
|
119
|
+
.transform((c) => ({ ...c, slug: c.slug.trim() || FormInput.slugify(c.name) }))
|
|
120
|
+
.pipe(CategoryInputSchema);
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { and, asc, desc, eq, sql } from 'drizzle-orm';
|
|
2
|
+
|
|
3
|
+
import type { ShopDb } from '../db/index';
|
|
4
|
+
|
|
5
|
+
import { BundleService } from '../bundles/service.server';
|
|
6
|
+
import {
|
|
7
|
+
categories,
|
|
8
|
+
productCategories,
|
|
9
|
+
productImages,
|
|
10
|
+
products,
|
|
11
|
+
productSlugAliases,
|
|
12
|
+
} from '../db/schema';
|
|
13
|
+
import { StockService } from '../stock/service.server';
|
|
14
|
+
import { CoverService } from './covers.server';
|
|
15
|
+
import { Search } from './library';
|
|
16
|
+
|
|
17
|
+
type Product = typeof products.$inferSelect;
|
|
18
|
+
|
|
19
|
+
/** The public catalogue: categories, products, search, old-URL redirects and the sitemap. */
|
|
20
|
+
export class CatalogueService {
|
|
21
|
+
constructor(private readonly db: ShopDb) {}
|
|
22
|
+
|
|
23
|
+
async categories() {
|
|
24
|
+
return this.db
|
|
25
|
+
.select()
|
|
26
|
+
.from(categories)
|
|
27
|
+
.orderBy(asc(categories.sortOrder), asc(categories.name));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async category(slug: string) {
|
|
31
|
+
return this.db.query.categories.findFirst({ where: eq(categories.slug, slug) });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Active products in a category, each with its cover image, if any. */
|
|
35
|
+
async categoryProducts(categoryId: number) {
|
|
36
|
+
const list = await this.db
|
|
37
|
+
.select({ product: products })
|
|
38
|
+
.from(productCategories)
|
|
39
|
+
.innerJoin(products, eq(products.id, productCategories.productId))
|
|
40
|
+
.where(and(eq(productCategories.categoryId, categoryId), eq(products.active, true)))
|
|
41
|
+
.orderBy(asc(products.sortOrder), asc(products.name))
|
|
42
|
+
.then((rows) => rows.map((r) => r.product));
|
|
43
|
+
return this.withCovers(list);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** An active product with its images and the other options in its variation group. */
|
|
47
|
+
async product(slug: string) {
|
|
48
|
+
const product = await this.db.query.products.findFirst({
|
|
49
|
+
where: and(eq(products.slug, slug), eq(products.active, true)),
|
|
50
|
+
with: { images: { orderBy: asc(productImages.position) }, variationGroup: true },
|
|
51
|
+
});
|
|
52
|
+
if (!product) return undefined;
|
|
53
|
+
const stock = new StockService(this.db);
|
|
54
|
+
product.stock = await stock.available(product.id);
|
|
55
|
+
|
|
56
|
+
const options = product.variationGroupId
|
|
57
|
+
? await this.db
|
|
58
|
+
.select({ label: products.variationLabel, slug: products.slug })
|
|
59
|
+
.from(products)
|
|
60
|
+
.where(
|
|
61
|
+
and(eq(products.variationGroupId, product.variationGroupId), eq(products.active, true))
|
|
62
|
+
)
|
|
63
|
+
.orderBy(asc(products.sortOrder), asc(products.name))
|
|
64
|
+
: [];
|
|
65
|
+
|
|
66
|
+
return { options, product, variationName: product.variationGroup?.name };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Every active product, each with its cover image. */
|
|
70
|
+
async products() {
|
|
71
|
+
const list = await this.db
|
|
72
|
+
.select()
|
|
73
|
+
.from(products)
|
|
74
|
+
.where(eq(products.active, true))
|
|
75
|
+
.orderBy(asc(products.sortOrder), asc(products.name));
|
|
76
|
+
return this.withCovers(list);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The current slug for a retired legacy slug, or for a legacy `?variant=` product code (the SKU). */
|
|
80
|
+
async redirect(input: { legacySlug: string; variantSku: null | string }) {
|
|
81
|
+
if (input.variantSku) {
|
|
82
|
+
const variant = await this.db.query.products.findFirst({
|
|
83
|
+
where: and(eq(products.sku, input.variantSku), eq(products.active, true)),
|
|
84
|
+
});
|
|
85
|
+
if (variant) return variant.slug;
|
|
86
|
+
}
|
|
87
|
+
const alias = await this.db.query.productSlugAliases.findFirst({
|
|
88
|
+
where: eq(productSlugAliases.slug, input.legacySlug),
|
|
89
|
+
with: { product: true },
|
|
90
|
+
});
|
|
91
|
+
return alias?.product.active ? alias.product.slug : undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Active products whose name, variation, SKU or descriptions contain every word of the query,
|
|
96
|
+
* name matches first. A LIKE scan: fine for a shop's few hundred products, no index to keep.
|
|
97
|
+
*/
|
|
98
|
+
async search(query: string) {
|
|
99
|
+
const words = Search.words(query);
|
|
100
|
+
if (words.length === 0) return [];
|
|
101
|
+
const field = sql`lower(${products.name} || ' ' || coalesce(${products.variationLabel}, '') || ' ' || ${products.sku} || ' ' || ${products.shortDescription} || ' ' || ${products.description})`;
|
|
102
|
+
const conditions = words.map((w) => sql`${field} like ${Search.pattern(w)} escape '\\'`);
|
|
103
|
+
const nameHit = sql<number>`lower(${products.name}) like ${Search.pattern(words[0])} escape '\\'`;
|
|
104
|
+
const list = await this.db
|
|
105
|
+
.select()
|
|
106
|
+
.from(products)
|
|
107
|
+
.where(and(eq(products.active, true), ...conditions))
|
|
108
|
+
.orderBy(desc(nameHit), asc(products.sortOrder), asc(products.name))
|
|
109
|
+
.limit(Search.LIMIT);
|
|
110
|
+
return this.withCovers(list);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Slugs for the sitemap: categories, active products and active bundles. */
|
|
114
|
+
async sitemapEntries() {
|
|
115
|
+
const bundles = new BundleService(this.db);
|
|
116
|
+
const [cats, prods, bundleSlugs] = await Promise.all([
|
|
117
|
+
this.db.select({ slug: categories.slug }).from(categories),
|
|
118
|
+
this.db.select({ slug: products.slug }).from(products).where(eq(products.active, true)),
|
|
119
|
+
bundles.activeSlugs(),
|
|
120
|
+
]);
|
|
121
|
+
return {
|
|
122
|
+
bundles: bundleSlugs,
|
|
123
|
+
categories: cats.map((c) => c.slug),
|
|
124
|
+
products: prods.map((p) => p.slug),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Adds each product's cover image (lowest position). `stock` becomes what can be sold now. */
|
|
129
|
+
private async withCovers(list: Product[]) {
|
|
130
|
+
if (list.length === 0) return [];
|
|
131
|
+
const ids = list.map((p) => p.id);
|
|
132
|
+
const covers = new CoverService(this.db);
|
|
133
|
+
const stock = new StockService(this.db);
|
|
134
|
+
const [cover, sellable] = await Promise.all([covers.covers(ids), stock.availableMany(ids)]);
|
|
135
|
+
return list.map((product) => ({
|
|
136
|
+
...product,
|
|
137
|
+
cover: cover.get(product.id),
|
|
138
|
+
stock: sellable.get(product.id) ?? 0,
|
|
139
|
+
}));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -3,9 +3,10 @@ import type { RequestHandler } from '@sveltejs/kit';
|
|
|
3
3
|
import { redirect } from '@sveltejs/kit';
|
|
4
4
|
import { logger } from '@zeyolabs/kit/server/logger';
|
|
5
5
|
|
|
6
|
+
import { BasketCookies } from '../basket/cookies.server';
|
|
6
7
|
import { shopping } from '../config';
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
8
|
+
import { OrderManager } from '../orders/manager.server';
|
|
9
|
+
import { OrderService } from '../orders/service.server';
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* Stripe sends the customer here after paying. Fulfils the order in case the webhook has not
|
|
@@ -16,14 +17,14 @@ export const GET: RequestHandler = async ({ cookies, url }) => {
|
|
|
16
17
|
const sessionId = url.searchParams.get('session_id') ?? '';
|
|
17
18
|
if (!/^cs_\w{1,250}$/.test(sessionId)) redirect(303, '/basket');
|
|
18
19
|
|
|
19
|
-
const db = shopping().db();
|
|
20
20
|
try {
|
|
21
|
-
await
|
|
21
|
+
await OrderManager.fulfil(sessionId);
|
|
22
22
|
} catch (err) {
|
|
23
23
|
// The webhook retries fulfilment, so the customer still gets the thank-you page.
|
|
24
24
|
logger.error(err, { op: 'checkoutComplete' });
|
|
25
25
|
}
|
|
26
|
-
|
|
26
|
+
const service = new OrderService(shopping().db());
|
|
27
|
+
if (await service.bySession(sessionId)) BasketCookies.clear(cookies);
|
|
27
28
|
|
|
28
29
|
redirect(303, `/checkout/success?session_id=${sessionId}`);
|
|
29
30
|
};
|