create-marcapony-app 0.1.0 → 0.2.0
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 +29 -27
- package/dist/index.d.ts +37 -3
- package/dist/index.js +138 -23
- package/package.json +5 -4
- package/template/base/.dev.vars.example +7 -0
- package/template/{_package.json → base/_package.json} +14 -10
- package/template/{marcapony.json → base/marcapony.json} +1 -1
- package/template/{scripts → base/scripts}/dev.ts +19 -2
- package/template/base/src/server/marcapony.ts +85 -0
- package/template/base/src/ui/api.ts +34 -0
- package/template/base/src/ui/styles.css +115 -0
- package/template/blank/README.md +48 -0
- package/template/{src → blank/src}/server/index.ts +9 -7
- package/template/booking/README.md +58 -0
- package/template/booking/marcapony.json +26 -0
- package/template/booking/src/server/index.ts +113 -0
- package/template/booking/src/ui/App.tsx +188 -0
- package/template/shop/README.md +66 -0
- package/template/shop/marcapony.json +12 -0
- package/template/shop/src/server/index.ts +211 -0
- package/template/shop/src/ui/App.tsx +214 -0
- package/template/team-tool/README.md +59 -0
- package/template/team-tool/marcapony.json +25 -0
- package/template/team-tool/src/server/index.ts +116 -0
- package/template/team-tool/src/ui/App.tsx +179 -0
- package/template/.dev.vars.example +0 -5
- package/template/README.md +0 -59
- package/template/src/server/marcapony.ts +0 -28
- package/template/src/ui/styles.css +0 -45
- /package/template/{_gitignore → base/_gitignore} +0 -0
- /package/template/{index.html → base/index.html} +0 -0
- /package/template/{src → base/src}/ui/main.tsx +0 -0
- /package/template/{tsconfig.json → base/tsconfig.json} +0 -0
- /package/template/{vite.config.ts → base/vite.config.ts} +0 -0
- /package/template/{src → blank/src}/ui/App.tsx +0 -0
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { Hono, type Context } from 'hono'
|
|
2
|
+
import type { PaymentLink, PaymentLinkLineItem, Product } from 'marcapony-sdk'
|
|
3
|
+
import { errorResponse, isSimulated, marcaponyFromEnv, type MarcaponyBindings } from './marcapony'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A small public shop: the catalog, a cart kept in the browser, and a checkout
|
|
7
|
+
* that turns the cart into a hosted payment link. Only `/api/*` reaches this
|
|
8
|
+
* worker; everything else is served from `dist/client`.
|
|
9
|
+
*
|
|
10
|
+
* The browser only ever sends product ids and quantities. Prices, currency and
|
|
11
|
+
* the total are read from the catalog here, on every checkout.
|
|
12
|
+
*/
|
|
13
|
+
const app = new Hono<{ Bindings: MarcaponyBindings }>()
|
|
14
|
+
|
|
15
|
+
const MAX_LINES = 20
|
|
16
|
+
const MAX_QUANTITY = 99
|
|
17
|
+
const ATTEMPT_ID = /^[A-Za-z0-9-]{8,64}$/
|
|
18
|
+
/** `Product.status`: 1 draft, 2 published, 3 archived. Only published products are for sale. */
|
|
19
|
+
const PUBLISHED = 2
|
|
20
|
+
|
|
21
|
+
/** What the browser sees of a product: enough to show it, nothing to trust. */
|
|
22
|
+
interface ShopProduct {
|
|
23
|
+
id: string
|
|
24
|
+
name: string
|
|
25
|
+
description: string
|
|
26
|
+
categoryName: string | null
|
|
27
|
+
price: number
|
|
28
|
+
currency: string
|
|
29
|
+
inStock: boolean
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The price a buyer pays: the sale price when there is one. Null when the product has no price. */
|
|
33
|
+
function unitPrice(product: Product): number | null {
|
|
34
|
+
return product.salePrice ?? product.price
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function toShopProduct(product: Product, fallbackCurrency: string): ShopProduct | null {
|
|
38
|
+
if (product.status !== PUBLISHED) return null
|
|
39
|
+
const price = unitPrice(product)
|
|
40
|
+
if (price === null) return null
|
|
41
|
+
return {
|
|
42
|
+
id: product.id,
|
|
43
|
+
name: product.name,
|
|
44
|
+
description: product.description,
|
|
45
|
+
categoryName: product.categoryName,
|
|
46
|
+
price,
|
|
47
|
+
currency: product.currency ?? fallbackCurrency,
|
|
48
|
+
inStock: !product.trackStock || product.stock === null || product.stock > 0,
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function cartFingerprint(quantities: Map<string, number>): Promise<string> {
|
|
53
|
+
const canonical = [...quantities.entries()]
|
|
54
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
55
|
+
.map(([id, quantity]) => `${id}:${quantity}`)
|
|
56
|
+
.join(',')
|
|
57
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonical))
|
|
58
|
+
return [...new Uint8Array(digest).slice(0, 8)].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
app.get('/api/health', (c) => c.json({ ok: true }))
|
|
62
|
+
|
|
63
|
+
app.get('/api/catalog', async (c) => {
|
|
64
|
+
const mp = marcaponyFromEnv(c.env)
|
|
65
|
+
const category = c.req.query('category') || undefined
|
|
66
|
+
const [site, categories, page] = await Promise.all([
|
|
67
|
+
mp.site.get(),
|
|
68
|
+
mp.categories.list(),
|
|
69
|
+
// `category` is a category slug.
|
|
70
|
+
mp.products.list({ perPage: 50, category }),
|
|
71
|
+
])
|
|
72
|
+
const products = page.data
|
|
73
|
+
.map((product) => toShopProduct(product, site.defaultCurrency))
|
|
74
|
+
.filter((product): product is ShopProduct => product !== null)
|
|
75
|
+
return c.json({
|
|
76
|
+
shopName: site.name,
|
|
77
|
+
categories: categories.map(({ id, name, slug }) => ({ id, name, slug })),
|
|
78
|
+
products,
|
|
79
|
+
})
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
interface CheckoutBody {
|
|
83
|
+
attemptId?: unknown
|
|
84
|
+
items?: unknown
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
type ShopContext = Context<{ Bindings: MarcaponyBindings }>
|
|
88
|
+
|
|
89
|
+
/** A checkout that passed the guard: its attempt id and the merged cart. */
|
|
90
|
+
interface CheckoutRequest {
|
|
91
|
+
attemptId: string
|
|
92
|
+
quantities: Map<string, number>
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Checkout is open to anonymous visitors, and every accepted request can create
|
|
97
|
+
* a payment link, so it must be refused as early and as cheaply as possible.
|
|
98
|
+
* Today this only rejects obviously bad input: a missing attempt id, an empty
|
|
99
|
+
* or oversized cart, and quantities out of bounds.
|
|
100
|
+
*
|
|
101
|
+
* Before going live, add a bot check here (for example a Turnstile token sent
|
|
102
|
+
* by the checkout form and verified with Turnstile's siteverify endpoint), or
|
|
103
|
+
* put a rate limit in front of `/api/checkout`. An in-memory counter is not a
|
|
104
|
+
* rate limit: every Worker isolate has its own memory.
|
|
105
|
+
*/
|
|
106
|
+
async function guardCheckout(c: ShopContext): Promise<CheckoutRequest | Response> {
|
|
107
|
+
const body = (await c.req.json().catch(() => ({}))) as CheckoutBody
|
|
108
|
+
if (typeof body.attemptId !== 'string' || !ATTEMPT_ID.test(body.attemptId)) {
|
|
109
|
+
return c.json({ error: 'attemptId is missing or malformed.' }, 400)
|
|
110
|
+
}
|
|
111
|
+
if (!Array.isArray(body.items) || body.items.length === 0) {
|
|
112
|
+
return c.json({ error: 'The cart is empty.' }, 400)
|
|
113
|
+
}
|
|
114
|
+
if (body.items.length > MAX_LINES) {
|
|
115
|
+
return c.json({ error: `A cart holds at most ${MAX_LINES} lines.` }, 400)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Merge repeated lines and refuse anything that is not an id and a whole quantity.
|
|
119
|
+
const quantities = new Map<string, number>()
|
|
120
|
+
for (const item of body.items as Array<{ productId?: unknown; quantity?: unknown }>) {
|
|
121
|
+
const { productId, quantity } = item ?? {}
|
|
122
|
+
if (typeof productId !== 'string' || productId.length === 0 || productId.length > 64) {
|
|
123
|
+
return c.json({ error: 'Every cart line needs a productId.' }, 400)
|
|
124
|
+
}
|
|
125
|
+
if (typeof quantity !== 'number' || !Number.isInteger(quantity) || quantity < 1) {
|
|
126
|
+
return c.json({ error: 'Quantities must be whole numbers of at least 1.' }, 400)
|
|
127
|
+
}
|
|
128
|
+
const merged = (quantities.get(productId) ?? 0) + quantity
|
|
129
|
+
if (merged > MAX_QUANTITY) {
|
|
130
|
+
return c.json({ error: `At most ${MAX_QUANTITY} of one product per order.` }, 400)
|
|
131
|
+
}
|
|
132
|
+
quantities.set(productId, merged)
|
|
133
|
+
}
|
|
134
|
+
return { attemptId: body.attemptId, quantities }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
app.post('/api/checkout', async (c) => {
|
|
138
|
+
const guarded = await guardCheckout(c)
|
|
139
|
+
if (guarded instanceof Response) return guarded
|
|
140
|
+
const { attemptId, quantities } = guarded
|
|
141
|
+
|
|
142
|
+
const mp = marcaponyFromEnv(c.env)
|
|
143
|
+
const site = await mp.site.get()
|
|
144
|
+
// Re-read every product: prices in the browser are for display only.
|
|
145
|
+
const products = await Promise.all([...quantities.keys()].map((id) => mp.products.get(id)))
|
|
146
|
+
|
|
147
|
+
const lineItems: PaymentLinkLineItem[] = []
|
|
148
|
+
let currency: string | null = null
|
|
149
|
+
let totalCents = 0
|
|
150
|
+
for (const product of products) {
|
|
151
|
+
const quantity = quantities.get(product.id) ?? 0
|
|
152
|
+
if (product.status !== PUBLISHED) {
|
|
153
|
+
return c.json({ error: `${product.name} is not for sale.` }, 422)
|
|
154
|
+
}
|
|
155
|
+
const price = unitPrice(product)
|
|
156
|
+
if (price === null) return c.json({ error: `${product.name} cannot be bought online.` }, 422)
|
|
157
|
+
if (product.trackStock && product.stock !== null && product.stock < quantity) {
|
|
158
|
+
return c.json({ error: `Only ${product.stock} of ${product.name} left.` }, 422)
|
|
159
|
+
}
|
|
160
|
+
const lineCurrency = product.currency ?? site.defaultCurrency
|
|
161
|
+
if (currency !== null && currency !== lineCurrency) {
|
|
162
|
+
return c.json({ error: 'Products in different currencies cannot share one checkout.' }, 422)
|
|
163
|
+
}
|
|
164
|
+
currency = lineCurrency
|
|
165
|
+
// Whole cents, so the total does not pick up floating point noise.
|
|
166
|
+
totalCents += Math.round(price * 100) * quantity
|
|
167
|
+
lineItems.push({
|
|
168
|
+
name: product.name,
|
|
169
|
+
price,
|
|
170
|
+
quantity,
|
|
171
|
+
productId: product.id,
|
|
172
|
+
...(product.categoryId ? { categoryId: product.categoryId } : {}),
|
|
173
|
+
})
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const amount = totalCents / 100
|
|
177
|
+
// One attempt id per checkout attempt, reused by the browser when it retries
|
|
178
|
+
// the same cart, so a retry cannot create a second link. The cart's contents
|
|
179
|
+
// are part of the key too: a reused attempt id with a different cart must
|
|
180
|
+
// not be answered with the earlier cart's link.
|
|
181
|
+
const idempotencyKey = `checkout-${attemptId}-${await cartFingerprint(quantities)}`
|
|
182
|
+
const link = (await mp.paymentLinks.create(
|
|
183
|
+
{
|
|
184
|
+
title: `${site.name} order`,
|
|
185
|
+
amount,
|
|
186
|
+
currency: currency ?? site.defaultCurrency,
|
|
187
|
+
lineItems,
|
|
188
|
+
},
|
|
189
|
+
{ idempotencyKey },
|
|
190
|
+
)) as PaymentLink
|
|
191
|
+
|
|
192
|
+
// The SDK returns the link's short id; the buyer pays it at /pay/{linkId} on
|
|
193
|
+
// the business's site.
|
|
194
|
+
const payUrl = site.domain ? `https://${site.domain}/pay/${encodeURIComponent(link.linkId)}` : null
|
|
195
|
+
// In test mode the link is only simulated: there is nothing to pay yet.
|
|
196
|
+
const simulated = isSimulated(link)
|
|
197
|
+
return c.json(
|
|
198
|
+
{
|
|
199
|
+
amount,
|
|
200
|
+
currency: link.currency ?? currency,
|
|
201
|
+
payUrl: simulated ? null : payUrl,
|
|
202
|
+
linkId: link.linkId,
|
|
203
|
+
simulated,
|
|
204
|
+
},
|
|
205
|
+
201,
|
|
206
|
+
)
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
app.onError((err) => errorResponse(err))
|
|
210
|
+
|
|
211
|
+
export default app
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { useEffect, useMemo, useState } from 'react'
|
|
2
|
+
import { api, errorMessage, newRequestId } from './api'
|
|
3
|
+
|
|
4
|
+
interface ShopProduct {
|
|
5
|
+
id: string
|
|
6
|
+
name: string
|
|
7
|
+
description: string
|
|
8
|
+
categoryName: string | null
|
|
9
|
+
price: number
|
|
10
|
+
currency: string
|
|
11
|
+
inStock: boolean
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface Category {
|
|
15
|
+
id: string
|
|
16
|
+
name: string
|
|
17
|
+
slug: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface Catalog {
|
|
21
|
+
shopName: string
|
|
22
|
+
categories: Category[]
|
|
23
|
+
products: ShopProduct[]
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface CheckoutResult {
|
|
27
|
+
amount: number
|
|
28
|
+
currency: string
|
|
29
|
+
payUrl: string | null
|
|
30
|
+
linkId: string
|
|
31
|
+
simulated: boolean
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** productId → quantity. Only ids and quantities: the server prices the cart. */
|
|
35
|
+
type Cart = Record<string, number>
|
|
36
|
+
|
|
37
|
+
const CART_KEY = 'cart'
|
|
38
|
+
|
|
39
|
+
function loadCart(): Cart {
|
|
40
|
+
try {
|
|
41
|
+
const parsed = JSON.parse(localStorage.getItem(CART_KEY) ?? '{}') as unknown
|
|
42
|
+
return parsed && typeof parsed === 'object' ? (parsed as Cart) : {}
|
|
43
|
+
} catch {
|
|
44
|
+
return {}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function money(amount: number, currency: string): string {
|
|
49
|
+
try {
|
|
50
|
+
return new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(amount)
|
|
51
|
+
} catch {
|
|
52
|
+
return `${amount} ${currency}`
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function App() {
|
|
57
|
+
const [catalog, setCatalog] = useState<Catalog | null>(null)
|
|
58
|
+
const [category, setCategory] = useState('')
|
|
59
|
+
const [cart, setCart] = useState<Cart>(loadCart)
|
|
60
|
+
// Products seen so far, so cart lines stay readable when a category filter hides them.
|
|
61
|
+
const [known, setKnown] = useState<Record<string, ShopProduct>>({})
|
|
62
|
+
// One id per checkout attempt. A retry of the same cart reuses it; any change
|
|
63
|
+
// to the cart starts a new attempt.
|
|
64
|
+
const [attemptId, setAttemptId] = useState(newRequestId)
|
|
65
|
+
const [result, setResult] = useState<CheckoutResult | null>(null)
|
|
66
|
+
const [busy, setBusy] = useState(false)
|
|
67
|
+
const [error, setError] = useState<string | null>(null)
|
|
68
|
+
|
|
69
|
+
useEffect(() => {
|
|
70
|
+
const query = category ? `?category=${encodeURIComponent(category)}` : ''
|
|
71
|
+
api<Catalog>(`/api/catalog${query}`)
|
|
72
|
+
.then((body) => {
|
|
73
|
+
setCatalog(body)
|
|
74
|
+
setKnown((previous) => ({
|
|
75
|
+
...previous,
|
|
76
|
+
...Object.fromEntries(body.products.map((product) => [product.id, product])),
|
|
77
|
+
}))
|
|
78
|
+
})
|
|
79
|
+
.catch((err: unknown) => setError(errorMessage(err)))
|
|
80
|
+
}, [category])
|
|
81
|
+
|
|
82
|
+
useEffect(() => {
|
|
83
|
+
localStorage.setItem(CART_KEY, JSON.stringify(cart))
|
|
84
|
+
}, [cart])
|
|
85
|
+
|
|
86
|
+
function changeQuantity(productId: string, delta: number) {
|
|
87
|
+
setCart((previous) => {
|
|
88
|
+
const next = { ...previous }
|
|
89
|
+
const quantity = (next[productId] ?? 0) + delta
|
|
90
|
+
if (quantity > 0) next[productId] = quantity
|
|
91
|
+
else delete next[productId]
|
|
92
|
+
return next
|
|
93
|
+
})
|
|
94
|
+
setAttemptId(newRequestId())
|
|
95
|
+
setResult(null)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const lines = useMemo(
|
|
99
|
+
() =>
|
|
100
|
+
Object.entries(cart).map(([productId, quantity]) => ({
|
|
101
|
+
productId,
|
|
102
|
+
quantity,
|
|
103
|
+
product: known[productId],
|
|
104
|
+
})),
|
|
105
|
+
[cart, known],
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
async function checkout() {
|
|
109
|
+
setBusy(true)
|
|
110
|
+
setError(null)
|
|
111
|
+
try {
|
|
112
|
+
const body = await api<CheckoutResult>('/api/checkout', {
|
|
113
|
+
body: {
|
|
114
|
+
attemptId,
|
|
115
|
+
items: lines.map(({ productId, quantity }) => ({ productId, quantity })),
|
|
116
|
+
},
|
|
117
|
+
})
|
|
118
|
+
setResult(body)
|
|
119
|
+
} catch (err) {
|
|
120
|
+
setError(errorMessage(err))
|
|
121
|
+
} finally {
|
|
122
|
+
setBusy(false)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return (
|
|
127
|
+
<main>
|
|
128
|
+
<h1>{catalog?.shopName ?? 'Shop'}</h1>
|
|
129
|
+
{error ? <p className="error">{error}</p> : null}
|
|
130
|
+
|
|
131
|
+
{catalog && catalog.categories.length > 0 ? (
|
|
132
|
+
<label>
|
|
133
|
+
Category
|
|
134
|
+
<select value={category} onChange={(e) => setCategory(e.target.value)}>
|
|
135
|
+
<option value="">All products</option>
|
|
136
|
+
{catalog.categories.map((c) => (
|
|
137
|
+
<option key={c.id} value={c.slug}>
|
|
138
|
+
{c.name}
|
|
139
|
+
</option>
|
|
140
|
+
))}
|
|
141
|
+
</select>
|
|
142
|
+
</label>
|
|
143
|
+
) : null}
|
|
144
|
+
|
|
145
|
+
<h2>Products</h2>
|
|
146
|
+
{catalog === null && !error ? <p>Loading…</p> : null}
|
|
147
|
+
{catalog?.products.length === 0 ? <p>No products to show yet.</p> : null}
|
|
148
|
+
<ul className="rows">
|
|
149
|
+
{catalog?.products.map((product) => (
|
|
150
|
+
<li key={product.id}>
|
|
151
|
+
<span>
|
|
152
|
+
{product.name} <span className="muted">{money(product.price, product.currency)}</span>
|
|
153
|
+
</span>
|
|
154
|
+
<button
|
|
155
|
+
type="button"
|
|
156
|
+
disabled={!product.inStock}
|
|
157
|
+
onClick={() => changeQuantity(product.id, 1)}
|
|
158
|
+
>
|
|
159
|
+
{product.inStock ? 'Add to cart' : 'Out of stock'}
|
|
160
|
+
</button>
|
|
161
|
+
</li>
|
|
162
|
+
))}
|
|
163
|
+
</ul>
|
|
164
|
+
|
|
165
|
+
<h2>Cart</h2>
|
|
166
|
+
{lines.length === 0 ? <p>Your cart is empty.</p> : null}
|
|
167
|
+
<ul className="rows">
|
|
168
|
+
{lines.map(({ productId, quantity, product }) => (
|
|
169
|
+
<li key={productId}>
|
|
170
|
+
<span>
|
|
171
|
+
{product?.name ?? 'Product'} × {quantity}
|
|
172
|
+
{product ? (
|
|
173
|
+
<span className="muted"> {money(product.price * quantity, product.currency)}</span>
|
|
174
|
+
) : null}
|
|
175
|
+
</span>
|
|
176
|
+
<span className="actions">
|
|
177
|
+
<button type="button" onClick={() => changeQuantity(productId, -1)}>
|
|
178
|
+
−
|
|
179
|
+
</button>
|
|
180
|
+
<button type="button" onClick={() => changeQuantity(productId, 1)}>
|
|
181
|
+
+
|
|
182
|
+
</button>
|
|
183
|
+
</span>
|
|
184
|
+
</li>
|
|
185
|
+
))}
|
|
186
|
+
</ul>
|
|
187
|
+
{lines.length > 0 && !result ? (
|
|
188
|
+
<p>
|
|
189
|
+
<button type="button" disabled={busy} onClick={() => void checkout()}>
|
|
190
|
+
{busy ? 'Preparing payment…' : 'Checkout'}
|
|
191
|
+
</button>
|
|
192
|
+
</p>
|
|
193
|
+
) : null}
|
|
194
|
+
|
|
195
|
+
{result ? (
|
|
196
|
+
<section>
|
|
197
|
+
<h2>Ready to pay</h2>
|
|
198
|
+
<p>Total: {money(result.amount, result.currency)}</p>
|
|
199
|
+
{result.simulated ? (
|
|
200
|
+
<p className="notice">
|
|
201
|
+
Test mode: the payment link was simulated, so there is nothing to pay yet.
|
|
202
|
+
</p>
|
|
203
|
+
) : result.payUrl ? (
|
|
204
|
+
<p>
|
|
205
|
+
<a href={result.payUrl}>Pay now</a>
|
|
206
|
+
</p>
|
|
207
|
+
) : (
|
|
208
|
+
<p className="muted">Payment link {result.linkId} was created.</p>
|
|
209
|
+
)}
|
|
210
|
+
</section>
|
|
211
|
+
) : null}
|
|
212
|
+
</main>
|
|
213
|
+
)
|
|
214
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Marcapony app: team tool
|
|
2
|
+
|
|
3
|
+
A tool for the business's team: the day's reservations, with buttons to
|
|
4
|
+
approve, reject, complete or cancel them. Team members open it from the
|
|
5
|
+
Marcapony dashboard.
|
|
6
|
+
|
|
7
|
+
## Set up in the dashboard
|
|
8
|
+
|
|
9
|
+
Create the app under **My Apps** with:
|
|
10
|
+
|
|
11
|
+
- **Placement:** portal (`"placement": "portal"`)
|
|
12
|
+
- **Data access:** team (`"dataAccess": "team"`)
|
|
13
|
+
- **Scopes:** `reservations:read`, `reservations:write`
|
|
14
|
+
- **Plugin:** the account needs reservations enabled
|
|
15
|
+
- **Permissions** (declared in `marcapony.json`; choose which members get them):
|
|
16
|
+
- `view`, "See reservations": `reservations.read`
|
|
17
|
+
- `manage`, "Approve, reject and complete reservations": `reservations.write`
|
|
18
|
+
|
|
19
|
+
A member who should change reservations needs both. A member's own role still
|
|
20
|
+
applies: someone who may only view reservations in the dashboard cannot change
|
|
21
|
+
them through this tool either.
|
|
22
|
+
|
|
23
|
+
## Routes
|
|
24
|
+
|
|
25
|
+
| Route | What it does |
|
|
26
|
+
| ------------------------------------ | -------------------------------------------------------------- |
|
|
27
|
+
| `GET /api/me` | The signed-in member; 401 if nobody, 403 for anyone but a team member |
|
|
28
|
+
| `GET /api/reservations?date=YYYY-MM-DD` | Reservations on that day, earliest first |
|
|
29
|
+
| `POST /api/reservations/:id/status` | `{ status, rejectionReason? }`, status one of approved, rejected, cancelled, completed |
|
|
30
|
+
|
|
31
|
+
The status buttons only show for members with the `manage` permission. When
|
|
32
|
+
the owner previews the tool, a banner says that changes are simulated.
|
|
33
|
+
|
|
34
|
+
## What to change first
|
|
35
|
+
|
|
36
|
+
1. Which actions each status offers (`ACTIONS` in `src/ui/App.tsx`).
|
|
37
|
+
2. The columns of the list: customer phone, notes, service.
|
|
38
|
+
3. Test it on the deployed app: locally nobody is signed in, so `/api/me`
|
|
39
|
+
answers 401.
|
|
40
|
+
|
|
41
|
+
## Develop and publish
|
|
42
|
+
|
|
43
|
+
Requires [Bun](https://bun.sh).
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
bun install
|
|
47
|
+
bun run link # paste the connection code from the app's page; writes .dev.vars and AGENTS.md
|
|
48
|
+
bun run dev # interface and /api routes on your machine
|
|
49
|
+
bun run deploy # build and publish; prints the address
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`.dev.vars` holds the app key. Never commit it, and never send it to the
|
|
53
|
+
browser: the interface calls this app's own `/api` routes, and only those talk
|
|
54
|
+
to Marcapony. `MARCAPONY_APP_ID` is set by Marcapony when the app is deployed;
|
|
55
|
+
locally there is none, so nobody is signed in during `bun run dev`.
|
|
56
|
+
|
|
57
|
+
New apps start in test mode: writes are simulated until you switch test mode off
|
|
58
|
+
on the app's page. Pass an `idempotencyKey` to every create call so a retry
|
|
59
|
+
cannot create the same thing twice.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"build": "bun run build",
|
|
3
|
+
"worker": "dist/worker/index.js",
|
|
4
|
+
"assets": "dist/client",
|
|
5
|
+
"assetsConfig": {
|
|
6
|
+
"not_found_handling": "single-page-application",
|
|
7
|
+
"run_worker_first": ["/api/*"]
|
|
8
|
+
},
|
|
9
|
+
"compatibilityDate": "2026-10-01",
|
|
10
|
+
"compatibilityFlags": ["nodejs_compat"],
|
|
11
|
+
"placement": "portal",
|
|
12
|
+
"dataAccess": "team",
|
|
13
|
+
"permissions": [
|
|
14
|
+
{
|
|
15
|
+
"id": "view",
|
|
16
|
+
"label": "See reservations",
|
|
17
|
+
"grants": ["reservations.read"]
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"id": "manage",
|
|
21
|
+
"label": "Approve, reject and complete reservations",
|
|
22
|
+
"grants": ["reservations.write"]
|
|
23
|
+
}
|
|
24
|
+
]
|
|
25
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { Hono } from 'hono'
|
|
2
|
+
import type { Identity, Reservation, UpdateReservationStatusInput } from 'marcapony-sdk'
|
|
3
|
+
import {
|
|
4
|
+
errorResponse,
|
|
5
|
+
identityOf,
|
|
6
|
+
isSimulated,
|
|
7
|
+
marcaponyFromEnv,
|
|
8
|
+
type Marcapony,
|
|
9
|
+
type MarcaponyBindings,
|
|
10
|
+
} from './marcapony'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A tool for the business's team: today's reservations with buttons to
|
|
14
|
+
* approve, reject, complete or cancel them. Team members open it from the
|
|
15
|
+
* Marcapony dashboard. Only `/api/*` reaches this worker; everything else is
|
|
16
|
+
* served from `dist/client`.
|
|
17
|
+
*
|
|
18
|
+
* Every call goes through `mp.forRequest(c.req.raw)`, so the platform limits it
|
|
19
|
+
* to the key's scopes, the permissions the owner granted this member and the
|
|
20
|
+
* member's own role. Never keep a scoped client or its answers in module scope.
|
|
21
|
+
*/
|
|
22
|
+
const app = new Hono<{ Bindings: MarcaponyBindings }>()
|
|
23
|
+
|
|
24
|
+
const DATE = /^\d{4}-\d{2}-\d{2}$/
|
|
25
|
+
const STATUSES = new Set<UpdateReservationStatusInput['status']>([
|
|
26
|
+
'approved',
|
|
27
|
+
'rejected',
|
|
28
|
+
'cancelled',
|
|
29
|
+
'completed',
|
|
30
|
+
])
|
|
31
|
+
/** The list call has no date filter, so read at most this many pages looking for the day. */
|
|
32
|
+
const MAX_PAGES = 5
|
|
33
|
+
const PER_PAGE = 100
|
|
34
|
+
|
|
35
|
+
/** The signed-in team member, or a 401/403 answer to send instead. */
|
|
36
|
+
async function memberOf(
|
|
37
|
+
mp: Marcapony,
|
|
38
|
+
env: MarcaponyBindings,
|
|
39
|
+
request: Request,
|
|
40
|
+
): Promise<Identity | Response> {
|
|
41
|
+
const who = await identityOf(mp, env, request)
|
|
42
|
+
if (!who) {
|
|
43
|
+
return Response.json(
|
|
44
|
+
{ error: 'Open this tool from the Marcapony dashboard while signed in.' },
|
|
45
|
+
{ status: 401 },
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
if (who.kind !== 'member') {
|
|
49
|
+
return Response.json({ error: 'This tool is for team members only.' }, { status: 403 })
|
|
50
|
+
}
|
|
51
|
+
return who
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
app.get('/api/health', (c) => c.json({ ok: true }))
|
|
55
|
+
|
|
56
|
+
app.get('/api/me', async (c) => {
|
|
57
|
+
const mp = marcaponyFromEnv(c.env)
|
|
58
|
+
const who = await memberOf(mp, c.env, c.req.raw)
|
|
59
|
+
if (who instanceof Response) return who
|
|
60
|
+
return c.json({ email: who.email, preview: who.preview, canManage: who.can('manage') })
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
/** `?date=YYYY-MM-DD`, sent by the browser so "today" is the member's local day. */
|
|
64
|
+
app.get('/api/reservations', async (c) => {
|
|
65
|
+
const mp = marcaponyFromEnv(c.env)
|
|
66
|
+
const who = await memberOf(mp, c.env, c.req.raw)
|
|
67
|
+
if (who instanceof Response) return who
|
|
68
|
+
|
|
69
|
+
const date = c.req.query('date') ?? ''
|
|
70
|
+
if (!DATE.test(date)) return c.json({ error: 'date must be YYYY-MM-DD.' }, 400)
|
|
71
|
+
|
|
72
|
+
const team = mp.forRequest(c.req.raw)
|
|
73
|
+
const found: Reservation[] = []
|
|
74
|
+
let truncated = false
|
|
75
|
+
for (let page = 1; page <= MAX_PAGES; page++) {
|
|
76
|
+
const result = await team.reservations.list({ page, perPage: PER_PAGE })
|
|
77
|
+
found.push(...result.data.filter((r) => r.requestedDate.startsWith(date)))
|
|
78
|
+
if (page * PER_PAGE >= result.meta.total) break
|
|
79
|
+
if (page === MAX_PAGES) truncated = true
|
|
80
|
+
}
|
|
81
|
+
found.sort((a, b) => a.requestedTime.localeCompare(b.requestedTime))
|
|
82
|
+
return c.json({ reservations: found, truncated })
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
interface StatusBody {
|
|
86
|
+
status?: unknown
|
|
87
|
+
rejectionReason?: unknown
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
app.post('/api/reservations/:id/status', async (c) => {
|
|
91
|
+
const mp = marcaponyFromEnv(c.env)
|
|
92
|
+
const who = await memberOf(mp, c.env, c.req.raw)
|
|
93
|
+
if (who instanceof Response) return who
|
|
94
|
+
// The platform would refuse the write anyway; answering here gives a clear message.
|
|
95
|
+
if (!who.can('manage')) {
|
|
96
|
+
return c.json({ error: 'You are not allowed to change reservations.' }, 403)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const body = (await c.req.json().catch(() => ({}))) as StatusBody
|
|
100
|
+
const status = body.status as UpdateReservationStatusInput['status']
|
|
101
|
+
if (!STATUSES.has(status)) {
|
|
102
|
+
return c.json({ error: 'status must be approved, rejected, cancelled or completed.' }, 400)
|
|
103
|
+
}
|
|
104
|
+
const input: UpdateReservationStatusInput = { status }
|
|
105
|
+
if (status === 'rejected' && typeof body.rejectionReason === 'string' && body.rejectionReason.trim()) {
|
|
106
|
+
input.rejectionReason = body.rejectionReason.trim().slice(0, 500)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const result = await mp.forRequest(c.req.raw).reservations.updateStatus(c.req.param('id'), input)
|
|
110
|
+
// Simulated in a preview, and in test mode for every member.
|
|
111
|
+
return c.json({ ok: true, simulated: who.preview || isSimulated(result) })
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
app.onError((err) => errorResponse(err))
|
|
115
|
+
|
|
116
|
+
export default app
|