@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,29 @@
|
|
|
1
|
+
import { getRequestEvent } from '$app/server';
|
|
2
|
+
import { Remote } from '@zeyolabs/kit/server/remote-functions';
|
|
3
|
+
import { Error404 } from '@zeyolabs/kit/utils/errors';
|
|
4
|
+
|
|
5
|
+
import { getBasket } from '../basket/client.remote';
|
|
6
|
+
import { BasketCookies } from '../basket/cookies.server';
|
|
7
|
+
import { BasketCookie } from '../basket/library';
|
|
8
|
+
import { shopping } from '../config';
|
|
9
|
+
import { ShopSchema } from '../utils/schemas';
|
|
10
|
+
import { BundleChoiceSchema } from './schema';
|
|
11
|
+
import { BundleService } from './service.server';
|
|
12
|
+
|
|
13
|
+
export const getBundle = Remote.Query(ShopSchema.SlugParam, async (slug) => {
|
|
14
|
+
const service = new BundleService(shopping().db());
|
|
15
|
+
const bundle = await service.page(slug);
|
|
16
|
+
if (!bundle) throw Error404('Bundle not found');
|
|
17
|
+
return bundle;
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
/** Adds the chosen products to the basket as ordinary lines, after checking the choice. */
|
|
21
|
+
export const addBundleToBasket = Remote.Cmd(BundleChoiceSchema, async ({ bundleId, choices }) => {
|
|
22
|
+
const service = new BundleService(shopping().db());
|
|
23
|
+
const lines = await service.expand(bundleId, choices);
|
|
24
|
+
const { cookies } = getRequestEvent();
|
|
25
|
+
let basket = BasketCookies.read(cookies);
|
|
26
|
+
for (const [productId, quantity] of lines) basket = BasketCookie.add(basket, productId, quantity);
|
|
27
|
+
BasketCookies.write(cookies, basket);
|
|
28
|
+
await getBasket().refresh();
|
|
29
|
+
});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { getBundle } from './client.remote';
|
|
2
|
+
|
|
3
|
+
/** `/bundle/<slug>`: unknown or inactive bundles 404 (a real 404 response, from the server load). */
|
|
4
|
+
export async function bundleLoad({ params }: { params: { slug?: string } }) {
|
|
5
|
+
return { bundle: await getBundle(params.slug ?? '') };
|
|
6
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import { ErrorMessage } from '../../utils/errors';
|
|
3
|
+
import { goto } from '$app/navigation';
|
|
4
|
+
import { resolve } from '$app/paths';
|
|
5
|
+
import PageTitle from '../../ui/PageTitle.svelte';
|
|
6
|
+
import { addBundleToBasket, type getBundle } from '../client.remote';
|
|
7
|
+
import { shopContext } from '../../context';
|
|
8
|
+
import { Images } from '../../utils/images';
|
|
9
|
+
import { Money } from '../../utils/money';
|
|
10
|
+
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
|
|
11
|
+
import { toast } from 'svelte-sonner';
|
|
12
|
+
import Button from '@zeyolabs/ui/form/Button.svelte';
|
|
13
|
+
|
|
14
|
+
let {
|
|
15
|
+
bundle,
|
|
16
|
+
}: {
|
|
17
|
+
/** From the route's server `load` (`bundleLoad`). */
|
|
18
|
+
bundle: Awaited<ReturnType<typeof getBundle>>;
|
|
19
|
+
} = $props();
|
|
20
|
+
|
|
21
|
+
const context = shopContext();
|
|
22
|
+
/** Step id to the chosen product ids. */
|
|
23
|
+
const picked = new SvelteMap<number, SvelteSet<number>>();
|
|
24
|
+
let busy = $state(false);
|
|
25
|
+
|
|
26
|
+
const chosen = (stepId: number) => picked.get(stepId) ?? new SvelteSet<number>();
|
|
27
|
+
|
|
28
|
+
function toggle(step: { id: number; maxChoices: number }, productId: number) {
|
|
29
|
+
const set = picked.get(step.id) ?? new SvelteSet<number>();
|
|
30
|
+
if (step.maxChoices === 1) {
|
|
31
|
+
const was = set.has(productId);
|
|
32
|
+
set.clear();
|
|
33
|
+
if (!was) set.add(productId);
|
|
34
|
+
} else if (set.has(productId)) {
|
|
35
|
+
set.delete(productId);
|
|
36
|
+
} else if (set.size < step.maxChoices) {
|
|
37
|
+
set.add(productId);
|
|
38
|
+
}
|
|
39
|
+
picked.set(step.id, set);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const totalPence = $derived(
|
|
43
|
+
bundle.steps.reduce(
|
|
44
|
+
(sum, step) =>
|
|
45
|
+
sum +
|
|
46
|
+
step.products
|
|
47
|
+
.filter((p) => chosen(step.id).has(p.id))
|
|
48
|
+
.reduce((s, p) => s + p.pricePence, 0),
|
|
49
|
+
0
|
|
50
|
+
)
|
|
51
|
+
);
|
|
52
|
+
const missing = $derived(bundle.steps.find((s) => chosen(s.id).size < s.minChoices));
|
|
53
|
+
|
|
54
|
+
async function add() {
|
|
55
|
+
busy = true;
|
|
56
|
+
try {
|
|
57
|
+
await addBundleToBasket({
|
|
58
|
+
bundleId: bundle.id,
|
|
59
|
+
choices: bundle.steps.map((s) => ({ productIds: [...chosen(s.id)], stepId: s.id })),
|
|
60
|
+
});
|
|
61
|
+
toast.success('Bundle added to your basket');
|
|
62
|
+
await goto(resolve('/basket'));
|
|
63
|
+
} catch (err) {
|
|
64
|
+
toast.error(ErrorMessage.from(err, 'Could not add the bundle. Please try again.'));
|
|
65
|
+
} finally {
|
|
66
|
+
busy = false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const rule = (s: { maxChoices: number; minChoices: number }) =>
|
|
71
|
+
s.minChoices === 0
|
|
72
|
+
? `Optional, up to ${s.maxChoices}`
|
|
73
|
+
: s.minChoices === s.maxChoices
|
|
74
|
+
? `Choose ${s.minChoices}`
|
|
75
|
+
: `Choose ${s.minChoices} to ${s.maxChoices}`;
|
|
76
|
+
</script>
|
|
77
|
+
|
|
78
|
+
<PageTitle description={bundle.description.slice(0, 160)} title={bundle.name} />
|
|
79
|
+
|
|
80
|
+
{#if bundle.description}
|
|
81
|
+
<p class="-mt-4 mb-8 max-w-prose whitespace-pre-line">{bundle.description}</p>
|
|
82
|
+
{/if}
|
|
83
|
+
|
|
84
|
+
<ol class="space-y-10">
|
|
85
|
+
{#each bundle.steps as step, i (step.id)}
|
|
86
|
+
<li>
|
|
87
|
+
<h2 class="text-lg font-semibold">{i + 1}. {step.title}</h2>
|
|
88
|
+
<p class="text-sm text-[var(--txs)]">
|
|
89
|
+
{rule(step)}{step.description ? ` · ${step.description}` : ''}
|
|
90
|
+
</p>
|
|
91
|
+
<ul class="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
|
92
|
+
{#each step.products as product (product.id)}
|
|
93
|
+
{const on = chosen(step.id).has(product.id)}
|
|
94
|
+
{const out = product.stock < 1}
|
|
95
|
+
<li>
|
|
96
|
+
<button
|
|
97
|
+
class="flex w-full items-center gap-3 rounded-xl border p-2 text-left transition {on
|
|
98
|
+
? 'border-[var(--primary-strong)] bg-[var(--primary-soft)]'
|
|
99
|
+
: 'border-[var(--bd)] bg-white'} disabled:opacity-50"
|
|
100
|
+
aria-pressed={on}
|
|
101
|
+
disabled={out}
|
|
102
|
+
onclick={() => toggle(step, product.id)}
|
|
103
|
+
type="button"
|
|
104
|
+
>
|
|
105
|
+
{#if product.cover}
|
|
106
|
+
<img
|
|
107
|
+
class="size-16 shrink-0 rounded-md object-cover"
|
|
108
|
+
alt={product.cover.alt || product.name}
|
|
109
|
+
loading="lazy"
|
|
110
|
+
src={Images.url(context.imageBaseUrl, product.cover.src)}
|
|
111
|
+
/>
|
|
112
|
+
{/if}
|
|
113
|
+
<span class="min-w-0">
|
|
114
|
+
<span class="block font-medium"
|
|
115
|
+
>{product.name}{product.variationLabel
|
|
116
|
+
? ` · ${product.variationLabel}`
|
|
117
|
+
: ''}</span
|
|
118
|
+
>
|
|
119
|
+
<span class="block text-sm text-[var(--txs)]">
|
|
120
|
+
{out ? 'Out of stock' : Money.format(product.pricePence)}
|
|
121
|
+
</span>
|
|
122
|
+
</span>
|
|
123
|
+
</button>
|
|
124
|
+
</li>
|
|
125
|
+
{/each}
|
|
126
|
+
</ul>
|
|
127
|
+
</li>
|
|
128
|
+
{/each}
|
|
129
|
+
</ol>
|
|
130
|
+
|
|
131
|
+
<div
|
|
132
|
+
class="sticky bottom-0 mt-10 flex flex-wrap items-center justify-between gap-3 border-t border-[var(--bd)] bg-white py-4"
|
|
133
|
+
>
|
|
134
|
+
<p>
|
|
135
|
+
<span class="text-[var(--txs)]">Total</span>
|
|
136
|
+
<strong class="ml-2 text-xl">{Money.format(totalPence)}</strong>
|
|
137
|
+
</p>
|
|
138
|
+
<div class="flex items-center gap-3">
|
|
139
|
+
{#if missing}<span class="text-sm text-[var(--txs)]">{missing.title}: {rule(missing)}</span
|
|
140
|
+
>{/if}
|
|
141
|
+
<Button disabled={busy || missing !== undefined || totalPence === 0} onclick={add} size="lg">
|
|
142
|
+
Add bundle to basket
|
|
143
|
+
</Button>
|
|
144
|
+
</div>
|
|
145
|
+
</div>
|
|
@@ -0,0 +1,82 @@
|
|
|
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
|
+
/** What the customer picked: per step, the chosen product ids. */
|
|
9
|
+
export const BundleChoiceSchema = z.object({
|
|
10
|
+
bundleId: Schema.Id,
|
|
11
|
+
choices: z
|
|
12
|
+
.array(
|
|
13
|
+
z.object({
|
|
14
|
+
productIds: z.array(Schema.Id).max(30),
|
|
15
|
+
stepId: Schema.Id,
|
|
16
|
+
})
|
|
17
|
+
)
|
|
18
|
+
.max(20),
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
export const BundleStepInputSchema = z
|
|
22
|
+
.object({
|
|
23
|
+
description: z.string().trim().max(500),
|
|
24
|
+
maxChoices: z.number().int().min(1).max(30),
|
|
25
|
+
minChoices: z.number().int().min(0).max(30),
|
|
26
|
+
/** The products offered, by SKU, in display order. */
|
|
27
|
+
skus: z.array(z.string().trim().min(1).max(60)).min(1, 'add at least one product').max(60),
|
|
28
|
+
title: z.string().trim().min(1, 'name the step').max(120),
|
|
29
|
+
})
|
|
30
|
+
.refine((s) => s.minChoices <= s.maxChoices, 'minimum is above maximum');
|
|
31
|
+
|
|
32
|
+
/** The admin's bundle editor: the bundle and all its steps, saved together. */
|
|
33
|
+
export const BundleInputSchema = z.object({
|
|
34
|
+
active: z.boolean(),
|
|
35
|
+
description: z.string().trim().max(5000),
|
|
36
|
+
id: Schema.Id.optional(),
|
|
37
|
+
image: z.string().trim().max(200).nullable(),
|
|
38
|
+
name: z.string().trim().min(1, 'enter a name').max(200),
|
|
39
|
+
slug: Schema.Slug,
|
|
40
|
+
sortOrder: z.number().int().min(-10_000).max(10_000),
|
|
41
|
+
steps: z.array(BundleStepInputSchema).min(1, 'add at least one step').max(20),
|
|
42
|
+
});
|
|
43
|
+
export type BundleInput = z.infer<typeof BundleInputSchema>;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The bundle editor's fields as the form sends them (SKUs as typed, one per line), turned into a
|
|
47
|
+
* `BundleInput`. A blank slug is made from the name.
|
|
48
|
+
*/
|
|
49
|
+
export const BundleFormSchema = z
|
|
50
|
+
.object({
|
|
51
|
+
active: SchemaForm.Boolean,
|
|
52
|
+
description: ShopSchema.FormText,
|
|
53
|
+
id: Schema.Id.optional(),
|
|
54
|
+
image: ShopSchema.FormText,
|
|
55
|
+
name: ShopSchema.FormText,
|
|
56
|
+
slug: ShopSchema.FormText,
|
|
57
|
+
sortOrder: SchemaForm.Int,
|
|
58
|
+
steps: z
|
|
59
|
+
.array(
|
|
60
|
+
z.object({
|
|
61
|
+
description: ShopSchema.FormText,
|
|
62
|
+
maxChoices: SchemaForm.Int,
|
|
63
|
+
minChoices: SchemaForm.Int,
|
|
64
|
+
skus: ShopSchema.FormText,
|
|
65
|
+
title: ShopSchema.FormText,
|
|
66
|
+
})
|
|
67
|
+
)
|
|
68
|
+
.default([]),
|
|
69
|
+
})
|
|
70
|
+
.transform((b) => ({
|
|
71
|
+
...b,
|
|
72
|
+
image: b.image.trim() || null,
|
|
73
|
+
slug: b.slug.trim() || FormInput.slugify(b.name),
|
|
74
|
+
steps: b.steps.map((step) => ({
|
|
75
|
+
...step,
|
|
76
|
+
skus: step.skus
|
|
77
|
+
.split(/[\s,]+/)
|
|
78
|
+
.map((sku) => sku.trim())
|
|
79
|
+
.filter(Boolean),
|
|
80
|
+
})),
|
|
81
|
+
}))
|
|
82
|
+
.pipe(BundleInputSchema);
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { Error400 } from '@zeyolabs/kit/utils/errors';
|
|
2
|
+
import { and, asc, eq, inArray, sql } from 'drizzle-orm';
|
|
3
|
+
|
|
4
|
+
import type { ShopDb } from '../db/index';
|
|
5
|
+
import type { BundleInput } from './schema';
|
|
6
|
+
|
|
7
|
+
import { CoverService } from '../catalogue/covers.server';
|
|
8
|
+
import { bundles, bundleStepProducts, bundleSteps, products } from '../db/schema';
|
|
9
|
+
import { StockService } from '../stock/service.server';
|
|
10
|
+
import { Batches } from '../utils/batches';
|
|
11
|
+
|
|
12
|
+
type Choice = { productIds: number[]; stepId: number };
|
|
13
|
+
|
|
14
|
+
/** Bundles built in steps. Data access and the rules for a valid choice; the basket does the rest. */
|
|
15
|
+
export class BundleService {
|
|
16
|
+
constructor(private readonly db: ShopDb) {}
|
|
17
|
+
|
|
18
|
+
/** Slugs of active bundles, for the sitemap. */
|
|
19
|
+
async activeSlugs(): Promise<string[]> {
|
|
20
|
+
const rows = await this.db
|
|
21
|
+
.select({ slug: bundles.slug })
|
|
22
|
+
.from(bundles)
|
|
23
|
+
.where(eq(bundles.active, true));
|
|
24
|
+
return rows.map((r) => r.slug);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Checks a customer's choice against the bundle's steps and returns how many of each product to
|
|
29
|
+
* add to the basket. Throws a 400 with a message the customer can act on.
|
|
30
|
+
*/
|
|
31
|
+
async expand(bundleId: number, choices: Choice[]): Promise<Map<number, number>> {
|
|
32
|
+
const bundle = await this.db.query.bundles.findFirst({
|
|
33
|
+
where: and(eq(bundles.id, bundleId), eq(bundles.active, true)),
|
|
34
|
+
});
|
|
35
|
+
if (!bundle) throw Error400('This bundle is no longer available.');
|
|
36
|
+
const steps = await this.steps(bundle.id, { activeOnly: true });
|
|
37
|
+
const chosen = new Map(choices.map((c) => [c.stepId, [...new Set(c.productIds)]]));
|
|
38
|
+
const lines = new Map<number, number>();
|
|
39
|
+
for (const step of steps) {
|
|
40
|
+
const picks = chosen.get(step.id) ?? [];
|
|
41
|
+
if (picks.length < step.minChoices || picks.length > step.maxChoices) {
|
|
42
|
+
throw Error400(
|
|
43
|
+
step.minChoices === step.maxChoices
|
|
44
|
+
? `${step.title}: choose ${step.minChoices}.`
|
|
45
|
+
: `${step.title}: choose ${step.minChoices} to ${step.maxChoices}.`
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
for (const id of picks) {
|
|
49
|
+
const product = step.products.find((p) => p.id === id);
|
|
50
|
+
if (!product) throw Error400(`${step.title}: that choice is not available.`);
|
|
51
|
+
if (product.stock < 1) throw Error400(`${product.name} is out of stock.`);
|
|
52
|
+
lines.set(id, (lines.get(id) ?? 0) + 1);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const known = new Set(steps.map((s) => s.id));
|
|
56
|
+
if (choices.some((c) => !known.has(c.stepId))) throw Error400('This bundle has changed.');
|
|
57
|
+
if (lines.size === 0) throw Error400('Choose at least one product.');
|
|
58
|
+
return lines;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** One bundle for the admin editor, steps listing their products by SKU. */
|
|
62
|
+
async forEdit(id: number) {
|
|
63
|
+
const bundle = await this.db.query.bundles.findFirst({ where: eq(bundles.id, id) });
|
|
64
|
+
if (!bundle) return undefined;
|
|
65
|
+
const steps = await this.steps(id, { activeOnly: false });
|
|
66
|
+
return {
|
|
67
|
+
...bundle,
|
|
68
|
+
steps: steps.map((s) => ({
|
|
69
|
+
description: s.description,
|
|
70
|
+
maxChoices: s.maxChoices,
|
|
71
|
+
minChoices: s.minChoices,
|
|
72
|
+
skus: s.products.map((p) => p.sku),
|
|
73
|
+
title: s.title,
|
|
74
|
+
})),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Every bundle for the admin list. */
|
|
79
|
+
async list() {
|
|
80
|
+
return this.db.select().from(bundles).orderBy(asc(bundles.sortOrder), asc(bundles.name));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** An active bundle with its steps and each step's active products (cover, price, sellable). */
|
|
84
|
+
async page(slug: string) {
|
|
85
|
+
const bundle = await this.db.query.bundles.findFirst({
|
|
86
|
+
where: and(eq(bundles.slug, slug), eq(bundles.active, true)),
|
|
87
|
+
});
|
|
88
|
+
if (!bundle) return undefined;
|
|
89
|
+
return { ...bundle, steps: await this.steps(bundle.id, { activeOnly: true }) };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Creates or replaces a bundle and all its steps. Unknown SKUs are a 400 naming them. */
|
|
93
|
+
async save(input: BundleInput, now = Date.now()): Promise<number> {
|
|
94
|
+
const skus = [...new Set(input.steps.flatMap((s) => s.skus))];
|
|
95
|
+
const skuRows = await Batches.rows(skus, (slice) =>
|
|
96
|
+
this.db
|
|
97
|
+
.select({ id: products.id, sku: products.sku })
|
|
98
|
+
.from(products)
|
|
99
|
+
.where(inArray(products.sku, slice))
|
|
100
|
+
);
|
|
101
|
+
const found = new Map(skuRows.map((r) => [r.sku, r.id]));
|
|
102
|
+
const missing = skus.filter((s) => !found.has(s));
|
|
103
|
+
if (missing.length > 0) throw Error400(`Unknown SKU: ${missing.join(', ')}`);
|
|
104
|
+
const clash = await this.db.query.bundles.findFirst({ where: eq(bundles.slug, input.slug) });
|
|
105
|
+
if (clash && clash.id !== input.id) throw Error400('Another bundle already uses that slug.');
|
|
106
|
+
|
|
107
|
+
const values = {
|
|
108
|
+
active: input.active,
|
|
109
|
+
description: input.description,
|
|
110
|
+
image: input.image || null,
|
|
111
|
+
name: input.name,
|
|
112
|
+
slug: input.slug,
|
|
113
|
+
sortOrder: input.sortOrder,
|
|
114
|
+
};
|
|
115
|
+
// A new bundle has no id until the batch inserts it, so later statements find it by slug,
|
|
116
|
+
// and each step by its bundle and position.
|
|
117
|
+
const bundleId =
|
|
118
|
+
input.id ??
|
|
119
|
+
sql<number>`(select ${bundles.id} from ${bundles} where ${bundles.slug} = ${input.slug})`;
|
|
120
|
+
const stepId = (position: number) =>
|
|
121
|
+
sql<number>`(select ${bundleSteps.id} from ${bundleSteps} where ${bundleSteps.bundleId} = ${bundleId} and ${bundleSteps.position} = ${position})`;
|
|
122
|
+
const offered = input.steps.flatMap((step, position) =>
|
|
123
|
+
[...new Set(step.skus)].map((sku, i) => ({
|
|
124
|
+
position: i,
|
|
125
|
+
productId: found.get(sku)!,
|
|
126
|
+
stepId: stepId(position),
|
|
127
|
+
}))
|
|
128
|
+
);
|
|
129
|
+
|
|
130
|
+
// One atomic batch: the bundle and all its steps are saved, or nothing is. Steps are replaced
|
|
131
|
+
// whole: simpler than diffing, and nothing else points at a step.
|
|
132
|
+
await this.db.batch([
|
|
133
|
+
input.id
|
|
134
|
+
? this.db.update(bundles).set(values).where(eq(bundles.id, input.id))
|
|
135
|
+
: this.db.insert(bundles).values({ ...values, createdAt: now }),
|
|
136
|
+
this.db.delete(bundleSteps).where(eq(bundleSteps.bundleId, bundleId)),
|
|
137
|
+
...input.steps.map((step, position) =>
|
|
138
|
+
this.db.insert(bundleSteps).values({
|
|
139
|
+
bundleId,
|
|
140
|
+
description: step.description,
|
|
141
|
+
maxChoices: step.maxChoices,
|
|
142
|
+
minChoices: step.minChoices,
|
|
143
|
+
position,
|
|
144
|
+
title: step.title,
|
|
145
|
+
})
|
|
146
|
+
),
|
|
147
|
+
// Each row carries a subquery's parameters; 15 rows keep a statement under D1's 100.
|
|
148
|
+
...Batches.chunks(offered, 15).map((rows) => this.db.insert(bundleStepProducts).values(rows)),
|
|
149
|
+
]);
|
|
150
|
+
if (input.id) return input.id;
|
|
151
|
+
const [row] = await this.db
|
|
152
|
+
.select({ id: bundles.id })
|
|
153
|
+
.from(bundles)
|
|
154
|
+
.where(eq(bundles.slug, input.slug));
|
|
155
|
+
return row.id;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
private async steps(bundleId: number, { activeOnly }: { activeOnly: boolean }) {
|
|
159
|
+
const steps = await this.db
|
|
160
|
+
.select()
|
|
161
|
+
.from(bundleSteps)
|
|
162
|
+
.where(eq(bundleSteps.bundleId, bundleId))
|
|
163
|
+
.orderBy(asc(bundleSteps.position), asc(bundleSteps.id));
|
|
164
|
+
if (steps.length === 0) return [];
|
|
165
|
+
const offered = await this.db
|
|
166
|
+
.select({
|
|
167
|
+
active: products.active,
|
|
168
|
+
id: products.id,
|
|
169
|
+
name: products.name,
|
|
170
|
+
pricePence: products.pricePence,
|
|
171
|
+
sku: products.sku,
|
|
172
|
+
slug: products.slug,
|
|
173
|
+
stepId: bundleStepProducts.stepId,
|
|
174
|
+
variationLabel: products.variationLabel,
|
|
175
|
+
})
|
|
176
|
+
.from(bundleStepProducts)
|
|
177
|
+
.innerJoin(products, eq(products.id, bundleStepProducts.productId))
|
|
178
|
+
.where(
|
|
179
|
+
and(
|
|
180
|
+
inArray(
|
|
181
|
+
bundleStepProducts.stepId,
|
|
182
|
+
steps.map((s) => s.id)
|
|
183
|
+
),
|
|
184
|
+
activeOnly ? eq(products.active, true) : undefined
|
|
185
|
+
)
|
|
186
|
+
)
|
|
187
|
+
.orderBy(asc(bundleStepProducts.position), asc(products.name));
|
|
188
|
+
const ids = [...new Set(offered.map((p) => p.id))];
|
|
189
|
+
const stock = new StockService(this.db);
|
|
190
|
+
const sellable = await stock.availableMany(ids);
|
|
191
|
+
const coverService = new CoverService(this.db);
|
|
192
|
+
const covers = await coverService.covers(ids);
|
|
193
|
+
return steps.map((step) => ({
|
|
194
|
+
...step,
|
|
195
|
+
products: offered
|
|
196
|
+
.filter((p) => p.stepId === step.id)
|
|
197
|
+
.map(({ stepId: _stepId, ...p }) => ({
|
|
198
|
+
...p,
|
|
199
|
+
cover: covers.get(p.id) ?? null,
|
|
200
|
+
stock: sellable.get(p.id) ?? 0,
|
|
201
|
+
})),
|
|
202
|
+
}));
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import { resolve } from '$app/paths';
|
|
3
|
+
import { getAdminCategories } from '../admin.remote';
|
|
4
|
+
import CategoryForm from './CategoryForm.svelte';
|
|
5
|
+
import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
|
|
6
|
+
import Button from '@zeyolabs/ui/form/Button.svelte';
|
|
7
|
+
|
|
8
|
+
type Category = {
|
|
9
|
+
description: string;
|
|
10
|
+
id: number;
|
|
11
|
+
name: string;
|
|
12
|
+
slug: string;
|
|
13
|
+
sortOrder: number;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** The category open in the editor: a row, `null` for a new one, `undefined` when closed. */
|
|
17
|
+
let editing = $state<Category | null | undefined>(undefined);
|
|
18
|
+
</script>
|
|
19
|
+
|
|
20
|
+
<svelte:head><title>Categories · Admin</title></svelte:head>
|
|
21
|
+
|
|
22
|
+
<p class="text-sm"><a href={resolve('/products')}>← Products</a></p>
|
|
23
|
+
<div class="mt-2 flex items-center justify-between">
|
|
24
|
+
<h1 class="text-2xl font-semibold">Categories</h1>
|
|
25
|
+
<Button onclick={() => (editing = null)}>New category</Button>
|
|
26
|
+
</div>
|
|
27
|
+
|
|
28
|
+
{#if editing !== undefined}
|
|
29
|
+
{#key editing?.id ?? 'new'}
|
|
30
|
+
<div class="mt-4"><CategoryForm category={editing} onDone={() => (editing = undefined)} /></div>
|
|
31
|
+
{/key}
|
|
32
|
+
{/if}
|
|
33
|
+
|
|
34
|
+
<Boundary message="Could not load categories.">
|
|
35
|
+
{let rows = $derived(await getAdminCategories())}
|
|
36
|
+
<ul class="mt-4 divide-y divide-[var(--line)] rounded-xl border border-[var(--line)] bg-white">
|
|
37
|
+
{#each rows as row (row.id)}
|
|
38
|
+
<li class="flex items-center justify-between gap-3 px-4 py-2 text-sm">
|
|
39
|
+
<span
|
|
40
|
+
><strong>{row.name}</strong>
|
|
41
|
+
<span class="text-[var(--ink-muted)]">/category/{row.slug} · {row.products} products</span
|
|
42
|
+
></span
|
|
43
|
+
>
|
|
44
|
+
<button class="underline" onclick={() => (editing = row)} type="button">Edit</button>
|
|
45
|
+
</li>
|
|
46
|
+
{:else}
|
|
47
|
+
<li class="px-4 py-6 text-[var(--ink-muted)]">No categories yet.</li>
|
|
48
|
+
{/each}
|
|
49
|
+
</ul>
|
|
50
|
+
{#snippet pending()}
|
|
51
|
+
<p class="mt-6 text-[var(--ink-muted)]">Loading…</p>
|
|
52
|
+
{/snippet}
|
|
53
|
+
</Boundary>
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import { saveCategoryForm } from '../admin.remote';
|
|
3
|
+
import { CategoryFormSchema } from '../schema';
|
|
4
|
+
import { Form, MessageField, NumberField, TextField } from '@zeyolabs/ui/form';
|
|
5
|
+
import Button from '@zeyolabs/ui/form/Button.svelte';
|
|
6
|
+
|
|
7
|
+
type Category = {
|
|
8
|
+
description: string;
|
|
9
|
+
id: number;
|
|
10
|
+
name: string;
|
|
11
|
+
slug: string;
|
|
12
|
+
sortOrder: number;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
let {
|
|
16
|
+
category,
|
|
17
|
+
onDone,
|
|
18
|
+
}: {
|
|
19
|
+
/** The category to edit; null for a new one. */
|
|
20
|
+
category: Category | null;
|
|
21
|
+
onDone: () => void;
|
|
22
|
+
} = $props();
|
|
23
|
+
|
|
24
|
+
// svelte-ignore state_referenced_locally
|
|
25
|
+
const form = saveCategoryForm.for(category?.id ?? 'new');
|
|
26
|
+
</script>
|
|
27
|
+
|
|
28
|
+
<Form
|
|
29
|
+
class="grid max-w-xl gap-3 rounded-xl border border-[var(--line)] bg-white p-5"
|
|
30
|
+
defaults={{
|
|
31
|
+
description: category?.description ?? '',
|
|
32
|
+
name: category?.name ?? '',
|
|
33
|
+
slug: category?.slug ?? '',
|
|
34
|
+
sortOrder: category?.sortOrder ?? 0,
|
|
35
|
+
}}
|
|
36
|
+
{form}
|
|
37
|
+
hidden={{ id: category?.id }}
|
|
38
|
+
onSuccess={onDone}
|
|
39
|
+
reset={false}
|
|
40
|
+
schema={CategoryFormSchema}
|
|
41
|
+
>
|
|
42
|
+
<TextField name="name" {form}>Name</TextField>
|
|
43
|
+
<TextField name="slug" {form} optional placeholder="made from the name">Slug (URL)</TextField>
|
|
44
|
+
<MessageField name="description" {form} optional>Description</MessageField>
|
|
45
|
+
<NumberField name="sortOrder" {form} inputmode="numeric">Sort order</NumberField>
|
|
46
|
+
<div class="flex gap-3">
|
|
47
|
+
<Button {form}>Save</Button>
|
|
48
|
+
<Button onclick={onDone} variant="secondary">Cancel</Button>
|
|
49
|
+
</div>
|
|
50
|
+
</Form>
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import { resolve } from '$app/paths';
|
|
3
|
+
import { getAdminProduct, getProductOptions } from '../admin.remote';
|
|
4
|
+
import ProductForm from './ProductForm.svelte';
|
|
5
|
+
import Boundary from '@zeyolabs/ui/boundary/Boundary.svelte';
|
|
6
|
+
|
|
7
|
+
/** The product to edit; leave out for a new one. */
|
|
8
|
+
let { id }: { id?: number } = $props();
|
|
9
|
+
</script>
|
|
10
|
+
|
|
11
|
+
<svelte:head><title>{id ? 'Edit product' : 'New product'} · Admin</title></svelte:head>
|
|
12
|
+
|
|
13
|
+
<p class="text-sm"><a href={resolve('/products')}>← Products</a></p>
|
|
14
|
+
<h1 class="mt-2 mb-6 text-2xl font-semibold">{id ? 'Edit product' : 'New product'}</h1>
|
|
15
|
+
|
|
16
|
+
<Boundary message="Could not load the product." statusMessages={{ 404: 'Product not found.' }}>
|
|
17
|
+
{let options = $derived(await getProductOptions())}
|
|
18
|
+
{let product = $derived(id ? await getAdminProduct(id) : null)}
|
|
19
|
+
{#key product?.id}
|
|
20
|
+
<ProductForm {options} {product} />
|
|
21
|
+
{/key}
|
|
22
|
+
{#snippet pending()}
|
|
23
|
+
<p class="text-[var(--ink-muted)]">Loading…</p>
|
|
24
|
+
{/snippet}
|
|
25
|
+
</Boundary>
|