create-nymbal-app 0.6.0 → 0.7.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.
Files changed (29) hide show
  1. package/dist/index.js +5 -2
  2. package/dist/index.js.map +1 -1
  3. package/package.json +1 -1
  4. package/scaffold/templates/astro/astro.config.mjs +3 -0
  5. package/scaffold/templates/astro/package.json +25 -25
  6. package/scaffold/templates/astro/src/layouts/AccountLayout.astro +1 -0
  7. package/scaffold/templates/astro/src/layouts/BaseLayout.astro +3 -1
  8. package/scaffold/templates/astro/src/lib/api.ts +15 -5
  9. package/scaffold/templates/astro/src/lib/client.ts +5 -2
  10. package/scaffold/templates/astro/src/pages/account/index.astro +1 -0
  11. package/scaffold/templates/astro/src/pages/account/orders/[orderNumber].astro +1 -1
  12. package/scaffold/templates/astro/src/pages/cart.astro +3 -0
  13. package/scaffold/templates/astro/src/pages/checkout.astro +9 -2
  14. package/scaffold/templates/astro/src/pages/order/[orderNumber].astro +152 -59
  15. package/scaffold/templates/astro/src/scripts/account-guard.ts +1 -0
  16. package/scaffold/templates/astro/src/scripts/order-access.ts +154 -0
  17. package/scaffold/templates/astro/src/scripts/pdp.ts +1 -0
  18. package/scaffold/templates/astro/src/scripts/plp.ts +1 -0
  19. package/scaffold/templates/astro/src/scripts/search.ts +1 -0
  20. package/scaffold/templates/nextjs/app/(shopper)/checkout/CheckoutView.tsx +6 -2
  21. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderDetails.tsx +23 -0
  22. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderEmailPrompt.tsx +90 -0
  23. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderLinkForm.tsx +73 -0
  24. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderNotFound.tsx +25 -0
  25. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderView.tsx +140 -0
  26. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/not-found.tsx +6 -0
  27. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/page.tsx +6 -134
  28. package/scaffold/templates/nextjs/lib/api.ts +13 -5
  29. package/scaffold/templates/nextjs/package.json +26 -26
@@ -1,22 +1,28 @@
1
1
  ---
2
2
  import '../../styles/pages/confirmation.css'
3
+ import '../../styles/pages/error.css'
3
4
  import BaseLayout from '../../layouts/BaseLayout.astro'
4
5
  import NymbalElement from '@nymbalhq/web-components/astro'
5
6
  import { fetchOrder } from '../../lib/api'
6
7
  import { isPaid, orderHeading } from '../../lib/order-status'
7
8
 
8
- // The URL carries the order's key (`?key=`), so nothing this page links to or loads may be told the URL: a header
9
- // and the meta tag below. The rewrite to /404 drops the header, so the not-found page sets its own.
9
+ // The URL carries the order's key (`?key=`), so nothing this page links to or loads may be told the URL: a header,
10
+ // the meta tag below and a canonical URL without the query. No shared cache may keep what a key opened.
10
11
  Astro.response.headers.set('Referrer-Policy', 'no-referrer')
12
+ Astro.response.headers.set('Cache-Control', 'no-store')
11
13
 
12
14
  const { orderNumber } = Astro.params
13
15
  const key = Astro.url.searchParams.get('key') ?? undefined
14
- // Rejects when the API fails, so a failed read is a 500 and never a 404 for an order the shopper has.
15
- const order = await fetchOrder(orderNumber!, key)
16
+ // Rejects when the API fails, so a failed read is a 500 and never a not-found page for an order the shopper has. A POST
17
+ // here (a form sent before its script ran) is answered as the plain page: its body is never read.
18
+ const read = await fetchOrder(orderNumber!, key)
19
+ const order = read === 'expired' ? null : read
20
+ const canonical = new URL(Astro.url.pathname, Astro.url).href
16
21
 
17
- if (!order) return Astro.rewrite('/404')
22
+ // The order page's own not-found state, which offers a fresh link; the site-wide 404 would drop the headers above.
23
+ if (read === null) Astro.response.status = 404
18
24
 
19
- const summary = {
25
+ const summary = order && {
20
26
  items: JSON.stringify(
21
27
  (order.lineItems ?? []).map((item) => ({
22
28
  name: `${item.productName}${item.variantName ? ` - ${item.variantName}` : ''}`,
@@ -33,81 +39,168 @@ const summary = {
33
39
  currency: order.currency,
34
40
  }
35
41
 
36
- const shippingAddress = order.shippingAddress
37
- const heading = orderHeading(order.status)
38
- const paid = isPaid(order.status)
42
+ const shippingAddress = order?.shippingAddress
43
+ const heading = order ? orderHeading(order.status) : read === 'expired' ? 'Open your order' : 'Order not found'
44
+ const paid = order ? isPaid(order.status) : false
39
45
  ---
40
46
 
41
- <BaseLayout title={`${heading} | Nymbal`} description="Your order with Nymbal.">
47
+ <BaseLayout title={`${heading} | Nymbal`} description="Your order with Nymbal." canonical={canonical}>
42
48
  <meta slot="head" name="referrer" content="no-referrer" />
43
- <div class="container section">
44
- <div class="confirmation-page" data-order-number={order.orderNumber} data-order-status={order.status}>
45
- {paid && (
46
- <div class="confirmation-icon">
49
+ {read === 'expired' && (
50
+ <div class="container section" id="order-email-prompt">
51
+ <form method="post" class="error-page" id="order-email-form" data-order-number={orderNumber}>
52
+ <h1 class="error-title">Open your order</h1>
53
+ <p class="error-message">This order link has expired. Enter the email you gave at checkout to open the order.</p>
54
+ <div class="form-group">
55
+ <label for="order-email">Email</label>
56
+ <input id="order-email" type="email" name="email" autocomplete="email" required data-testid="order-email-input" />
57
+ </div>
58
+ <p class="error-message" data-testid="order-email-limited" hidden>
59
+ Too many tries for now. Please try again in a while.
60
+ </p>
61
+ <p class="error-message" id="order-email-failed" hidden>We could not open the order just now. Please try again.</p>
62
+ <div class="error-actions">
63
+ <button type="submit" class="btn btn-primary" data-testid="order-email-submit">Open order</button>
64
+ </div>
65
+ </form>
66
+ </div>
67
+ )}
68
+ {read === 'expired' && (
69
+ <div class="container section" id="order-opened" hidden>
70
+ <div class="confirmation-page">
71
+ <div class="confirmation-icon" data-order-field="paid">
47
72
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
48
73
  <polyline points="20 6 9 17 4 12"></polyline>
49
74
  </svg>
50
75
  </div>
51
- )}
52
-
53
- <h1 class="confirmation-title" data-testid="order-heading">{heading}</h1>
54
- {paid ? (
55
- <p class="confirmation-subtitle">
56
- Thank you. Your order <strong data-testid="order-number">{order.orderNumber}</strong> is paid.
57
- We'll send a confirmation to <strong>{order.email}</strong>.
58
- </p>
59
- ) : order.status === 'pending' ? (
60
- <p class="confirmation-subtitle">
61
- Your order <strong data-testid="order-number">{order.orderNumber}</strong> is waiting for its payment.
62
- We'll email <strong>{order.email}</strong> once it arrives.
63
- </p>
64
- ) : (
65
- <p class="confirmation-subtitle">
66
- Your order <strong data-testid="order-number">{order.orderNumber}</strong> is {order.status.replace(/_/g, ' ')}.
76
+ <h1 class="confirmation-title" data-order-field="heading"></h1>
77
+ <p class="confirmation-subtitle" data-order-field="subtitle"></p>
78
+ <div class="confirmation-card">
79
+ <h2 class="confirmation-card-title">Order Details</h2>
80
+ <dl>
81
+ <div class="confirmation-detail-row">
82
+ <dt>Order Number</dt>
83
+ <dd data-order-field="number"></dd>
84
+ </div>
85
+ <div class="confirmation-detail-row">
86
+ <dt>Status</dt>
87
+ <dd style="text-transform: capitalize;" data-order-field="status"></dd>
88
+ </div>
89
+ </dl>
90
+ </div>
91
+ <nymbal-order-timeline class="confirmation-summary"></nymbal-order-timeline>
92
+ <nymbal-order-summary class="confirmation-summary"></nymbal-order-summary>
93
+ <div class="confirmation-card" data-order-field="shipping" hidden>
94
+ <h2 class="confirmation-card-title">Shipping Address</h2>
95
+ <p style="font-size: var(--nymbal-font-size-sm, 0.875rem); color: var(--nymbal-color-text-muted, #71717a); line-height: 1.6;" data-order-field="address"></p>
96
+ </div>
97
+ <div class="confirmation-actions">
98
+ <a href="/account/register" class="btn btn-primary">Create an Account</a>
99
+ <a href="/products" class="btn btn-secondary">Continue Shopping</a>
100
+ </div>
101
+ </div>
102
+ </div>
103
+ )}
104
+ {(read === 'expired' || read === null) && (
105
+ <div class="container section" id="order-not-found" hidden={read === 'expired'}>
106
+ <div class="error-page">
107
+ <span class="error-code">404</span>
108
+ <h1 class="error-title">Order not found</h1>
109
+ <p class="error-message">
110
+ This link does not open an order. Give its order number and the email you gave at checkout, and we'll email
111
+ you a fresh link if they match.
67
112
  </p>
68
- )}
69
-
70
- <div class="confirmation-card">
71
- <h2 class="confirmation-card-title">Order Details</h2>
72
-
73
- <dl>
74
- <div class="confirmation-detail-row">
75
- <dt>Order Number</dt>
76
- <dd>{order.orderNumber}</dd>
113
+ <form method="post" id="order-link-form">
114
+ <div class="form-group">
115
+ <label for="order-link-number">Order number</label>
116
+ <input id="order-link-number" name="orderNumber" required data-testid="order-link-number" />
77
117
  </div>
78
- <div class="confirmation-detail-row">
79
- <dt>Status</dt>
80
- <dd style="text-transform: capitalize;" data-testid="order-status">{order.status}</dd>
118
+ <div class="form-group">
119
+ <label for="order-link-email">Email</label>
120
+ <input id="order-link-email" type="email" name="email" autocomplete="email" required data-testid="order-link-email" />
81
121
  </div>
82
- </dl>
122
+ <div class="error-actions">
123
+ <button type="submit" class="btn btn-primary" data-testid="order-link-submit">Send me my order link</button>
124
+ </div>
125
+ </form>
126
+ <p class="error-message" data-testid="order-link-sent" hidden>
127
+ If that number and email match an order, its link is on its way to that email.
128
+ </p>
129
+ <p class="error-message" id="order-link-failed" hidden>We could not send the link just now. Please try again.</p>
83
130
  </div>
131
+ </div>
132
+ )}
133
+ {order && (
134
+ <div class="container section">
135
+ <div class="confirmation-page" data-order-number={order.orderNumber} data-order-status={order.status}>
136
+ {paid && (
137
+ <div class="confirmation-icon">
138
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
139
+ <polyline points="20 6 9 17 4 12"></polyline>
140
+ </svg>
141
+ </div>
142
+ )}
84
143
 
85
- <NymbalElement tag="nymbal-order-timeline" attributes={{ class: 'confirmation-summary', entries: JSON.stringify(order.timeline ?? []) }} />
86
-
87
- <NymbalElement tag="nymbal-order-summary" attributes={{ class: 'confirmation-summary', ...summary }} />
144
+ <h1 class="confirmation-title" data-testid="order-heading">{heading}</h1>
145
+ {paid ? (
146
+ <p class="confirmation-subtitle">
147
+ Thank you. Your order <strong data-testid="order-number">{order.orderNumber}</strong> is paid.
148
+ We'll send a confirmation to the email you gave at checkout.
149
+ </p>
150
+ ) : order.status === 'pending' ? (
151
+ <p class="confirmation-subtitle">
152
+ Your order <strong data-testid="order-number">{order.orderNumber}</strong> is waiting for its payment.
153
+ We'll email the address you gave at checkout once it arrives.
154
+ </p>
155
+ ) : (
156
+ <p class="confirmation-subtitle">
157
+ Your order <strong data-testid="order-number">{order.orderNumber}</strong> is {order.status.replace(/_/g, ' ')}.
158
+ </p>
159
+ )}
88
160
 
89
- {shippingAddress && (
90
161
  <div class="confirmation-card">
91
- <h2 class="confirmation-card-title">Shipping Address</h2>
92
- <p style="font-size: var(--nymbal-font-size-sm, 0.875rem); color: var(--nymbal-color-text-muted, #71717a); line-height: 1.6;">
93
- {shippingAddress.addressLine1}<br />
94
- {shippingAddress.addressLine2 && <>{shippingAddress.addressLine2}<br /></>}
95
- {shippingAddress.city}, {shippingAddress.region} {shippingAddress.postalCode}<br />
96
- {shippingAddress.country}
97
- </p>
162
+ <h2 class="confirmation-card-title">Order Details</h2>
163
+
164
+ <dl>
165
+ <div class="confirmation-detail-row">
166
+ <dt>Order Number</dt>
167
+ <dd>{order.orderNumber}</dd>
168
+ </div>
169
+ <div class="confirmation-detail-row">
170
+ <dt>Status</dt>
171
+ <dd style="text-transform: capitalize;" data-testid="order-status">{order.status}</dd>
172
+ </div>
173
+ </dl>
98
174
  </div>
99
- )}
100
175
 
101
- <div class="confirmation-actions">
102
- <a href="/account/register" class="btn btn-primary">Create an Account</a>
103
- <a href="/products" class="btn btn-secondary">Continue Shopping</a>
176
+ <NymbalElement tag="nymbal-order-timeline" attributes={{ class: 'confirmation-summary', entries: JSON.stringify(order.timeline ?? []) }} />
177
+
178
+ <NymbalElement tag="nymbal-order-summary" attributes={{ class: 'confirmation-summary', ...summary }} />
179
+
180
+ {shippingAddress && (
181
+ <div class="confirmation-card">
182
+ <h2 class="confirmation-card-title">Shipping Address</h2>
183
+ <p style="font-size: var(--nymbal-font-size-sm, 0.875rem); color: var(--nymbal-color-text-muted, #71717a); line-height: 1.6;">
184
+ {shippingAddress.addressLine1}<br />
185
+ {shippingAddress.addressLine2 && <>{shippingAddress.addressLine2}<br /></>}
186
+ {shippingAddress.city}, {shippingAddress.region} {shippingAddress.postalCode}<br />
187
+ {shippingAddress.country}
188
+ </p>
189
+ </div>
190
+ )}
191
+
192
+ <div class="confirmation-actions">
193
+ <a href="/account/register" class="btn btn-primary">Create an Account</a>
194
+ <a href="/products" class="btn btn-secondary">Continue Shopping</a>
195
+ </div>
104
196
  </div>
105
197
  </div>
106
- </div>
198
+ )}
107
199
  </BaseLayout>
108
200
 
109
201
  <script>
110
202
  import '../../scripts/order-status.js'
203
+ import '../../scripts/order-access.js'
111
204
  import { NymbalOrderSummary } from '@nymbalhq/web-components/elements/nymbal-order-summary'
112
205
  import { NymbalOrderTimeline } from '@nymbalhq/web-components/elements/nymbal-order-timeline'
113
206
 
@@ -1,3 +1,4 @@
1
+ import '@nymbalhq/sdk/ns/auth'
1
2
  import { client } from '../lib/client.js'
2
3
 
3
4
  export async function guardAuth(): Promise<boolean> {
@@ -0,0 +1,154 @@
1
+ import { NymbalApiError } from '@nymbalhq/sdk/core'
2
+ import type { ShopperAddress, ShopperOrder } from '@nymbalhq/types'
3
+ import { client } from '../lib/client.js'
4
+ import { isPaid, orderHeading } from '../lib/order-status.js'
5
+ import { submitOnce } from '../lib/submit-once.js'
6
+
7
+ // The order page's two forms, each sent once per click from the browser. The expired key's email prompt reads the
8
+ // order with the email in a header and shows it on this page: read by the storefront's server instead, every shopper's
9
+ // tries would count against the API's per-address limit as one. "Send me my order link" asks the API, which answers
10
+ // the same whatever matched.
11
+
12
+ const byId = (id: string): HTMLElement | null => document.getElementById(id)
13
+
14
+ const field = (root: HTMLElement, name: string): HTMLElement | null =>
15
+ root.querySelector<HTMLElement>(`[data-order-field="${name}"]`)
16
+
17
+ /** The subtitle the server-rendered page gives the same status, its number under the same test id. */
18
+ function subtitle(order: ShopperOrder): Node[] {
19
+ const number = document.createElement('strong')
20
+ number.dataset.testid = 'order-number'
21
+ number.textContent = order.orderNumber
22
+ const text = (value: string) => document.createTextNode(value)
23
+ if (isPaid(order.status)) {
24
+ return [
25
+ text('Thank you. Your order '),
26
+ number,
27
+ text(" is paid. We'll send a confirmation to the email you gave at checkout."),
28
+ ]
29
+ }
30
+ if (order.status === 'pending') {
31
+ return [
32
+ text('Your order '),
33
+ number,
34
+ text(
35
+ " is waiting for its payment. We'll email the address you gave at checkout once it arrives.",
36
+ ),
37
+ ]
38
+ }
39
+ return [text('Your order '), number, text(` is ${order.status.replace(/_/g, ' ')}.`)]
40
+ }
41
+
42
+ function addressLines(address: ShopperAddress): Node[] {
43
+ const lines = [
44
+ address.addressLine1,
45
+ address.addressLine2,
46
+ `${address.city}, ${address.region} ${address.postalCode}`,
47
+ address.country,
48
+ ].filter((line): line is string => typeof line === 'string' && line !== '')
49
+ return lines.flatMap((line, i) => {
50
+ const node = document.createTextNode(line)
51
+ return i === 0 ? [node] : [document.createElement('br'), node]
52
+ })
53
+ }
54
+
55
+ /** Fills the page's empty confirmation with the order, as the server renders a key's order. */
56
+ function fillOrder(view: HTMLElement, order: ShopperOrder): void {
57
+ // The check mark is a flex box, which `hidden` does not hide: an unpaid order's is removed.
58
+ if (!isPaid(order.status)) field(view, 'paid')?.remove()
59
+ const heading = field(view, 'heading')
60
+ if (heading) {
61
+ heading.textContent = orderHeading(order.status)
62
+ heading.dataset.testid = 'order-heading'
63
+ }
64
+ field(view, 'subtitle')?.replaceChildren(...subtitle(order))
65
+ const number = field(view, 'number')
66
+ if (number) number.textContent = order.orderNumber
67
+ const status = field(view, 'status')
68
+ if (status) {
69
+ status.textContent = order.status
70
+ status.dataset.testid = 'order-status'
71
+ }
72
+ view
73
+ .querySelector('nymbal-order-timeline')
74
+ ?.setAttribute('entries', JSON.stringify(order.timeline ?? []))
75
+ const summary = view.querySelector('nymbal-order-summary')
76
+ if (summary) {
77
+ const items = (order.lineItems ?? []).map((item) => ({
78
+ name: `${item.productName}${item.variantName ? ` - ${item.variantName}` : ''}`,
79
+ qty: item.qty,
80
+ unitPriceMinor: item.unitPriceMinor,
81
+ lineTotalMinor: item.lineTotalMinor,
82
+ }))
83
+ summary.setAttribute('items', JSON.stringify(items))
84
+ summary.setAttribute('subtotal-minor', String(order.subtotalMinor))
85
+ summary.setAttribute('discount-minor', String(order.discountTotalMinor ?? 0))
86
+ summary.setAttribute('shipping-minor', String(order.shippingTotalMinor ?? 0))
87
+ summary.setAttribute('tax-minor', String(order.taxTotalMinor ?? 0))
88
+ summary.setAttribute('total-minor', String(order.totalMinor))
89
+ summary.setAttribute('currency', order.currency)
90
+ }
91
+ const shipping = field(view, 'shipping')
92
+ if (shipping) {
93
+ field(shipping, 'address')?.replaceChildren(...addressLines(order.shippingAddress))
94
+ shipping.hidden = false
95
+ }
96
+ }
97
+
98
+ /** Shows one of the expired page's three views: the prompt, the order, or the not-found state. */
99
+ function show(id: 'order-email-prompt' | 'order-opened' | 'order-not-found'): void {
100
+ for (const view of ['order-email-prompt', 'order-opened', 'order-not-found']) {
101
+ const el = byId(view)
102
+ if (el) el.hidden = view !== id
103
+ }
104
+ }
105
+
106
+ const prompt = document.getElementById('order-email-form') as HTMLFormElement | null
107
+ submitOnce(prompt, async () => {
108
+ if (prompt === null) return
109
+ const limited = prompt.querySelector<HTMLElement>('[data-testid="order-email-limited"]')
110
+ const failed = byId('order-email-failed')
111
+ if (limited) limited.hidden = true
112
+ if (failed) failed.hidden = true
113
+ const orderNumber = prompt.dataset.orderNumber ?? ''
114
+ const key = new URLSearchParams(window.location.search).get('key') ?? ''
115
+ const email = String(new FormData(prompt).get('email') ?? '').trim()
116
+
117
+ let order: ShopperOrder
118
+ try {
119
+ order = await client.orders.get(orderNumber, { key, email })
120
+ } catch (err) {
121
+ // The answer an unknown number gets: the email did not open the order.
122
+ if (err instanceof NymbalApiError && err.status === 404) return show('order-not-found')
123
+ if (err instanceof NymbalApiError && err.status === 429) {
124
+ if (limited) limited.hidden = false
125
+ return
126
+ }
127
+ if (failed) failed.hidden = false
128
+ throw err
129
+ }
130
+ const view = byId('order-opened')
131
+ if (view === null) return
132
+ fillOrder(view, order)
133
+ show('order-opened')
134
+ })
135
+
136
+ const linkForm = document.getElementById('order-link-form') as HTMLFormElement | null
137
+ submitOnce(linkForm, async () => {
138
+ if (linkForm === null) return
139
+ const data = new FormData(linkForm)
140
+ const failed = document.getElementById('order-link-failed')
141
+ if (failed) failed.hidden = true
142
+ try {
143
+ await client.orders.requestLink({
144
+ orderNumber: String(data.get('orderNumber') ?? '').trim(),
145
+ email: String(data.get('email') ?? '').trim(),
146
+ })
147
+ } catch (err) {
148
+ if (failed) failed.hidden = false
149
+ throw err
150
+ }
151
+ linkForm.hidden = true
152
+ const sent = document.querySelector<HTMLElement>('[data-testid="order-link-sent"]')
153
+ if (sent) sent.hidden = false
154
+ })
@@ -1,3 +1,4 @@
1
+ import '@nymbalhq/sdk/ns/product'
1
2
  import { NymbalAddToCart } from '@nymbalhq/web-components/elements/nymbal-add-to-cart'
2
3
  import { NymbalBreadcrumb } from '@nymbalhq/web-components/elements/nymbal-breadcrumb'
3
4
  import { NymbalImageGallery } from '@nymbalhq/web-components/elements/nymbal-image-gallery'
@@ -1,3 +1,4 @@
1
+ import '@nymbalhq/sdk/ns/product-list'
1
2
  import type { ProductSortKey } from '@nymbalhq/types'
2
3
  import { NymbalBreadcrumb } from '@nymbalhq/web-components/elements/nymbal-breadcrumb'
3
4
  import { NymbalProductFilter } from '@nymbalhq/web-components/elements/nymbal-product-filter'
@@ -1,3 +1,4 @@
1
+ import '@nymbalhq/sdk/ns/search'
1
2
  import { NymbalProductFilter } from '@nymbalhq/web-components/elements/nymbal-product-filter'
2
3
  import { NymbalSearchResults } from '@nymbalhq/web-components/elements/nymbal-search-results'
3
4
  import { client } from '../lib/client.js'
@@ -18,11 +18,15 @@ export function CheckoutView({
18
18
  }) {
19
19
  // A full load, not router.push: the order page's URL carries its key, and only a document of its own takes the
20
20
  // page's Referrer-Policy header. A soft navigation leaves it in the checkout's document, whose requests (its
21
- // script chunks among them) refer the keyed URL on.
21
+ // script chunks among them) refer the keyed URL on. A signed-in shopper's checkout answers no key: their account is
22
+ // the order's home.
22
23
  const onPlaced = useCallback((event: CustomEvent<{ orderNumber: string; orderKey?: string }>) => {
23
24
  const { orderNumber, orderKey } = event.detail
25
+ const number = encodeURIComponent(orderNumber)
24
26
  window.location.assign(
25
- `/order/${encodeURIComponent(orderNumber)}${orderKey ? `?key=${encodeURIComponent(orderKey)}` : ''}`,
27
+ orderKey
28
+ ? `/order/${number}?key=${encodeURIComponent(orderKey)}`
29
+ : `/account/orders/${number}`,
26
30
  )
27
31
  }, [])
28
32
 
@@ -0,0 +1,23 @@
1
+ import type { ShopperOrder } from '@nymbalhq/types'
2
+ import { OrderStatusRefresh } from '@/components/client/OrderStatusRefresh'
3
+ import { renderNymbal } from '@/lib/render'
4
+ import { OrderView, summaryAttributes } from './OrderView'
5
+
6
+ /** The order its key opens, rendered on the server with the elements' server HTML. */
7
+ export function OrderDetails({ order, orderKey }: { order: ShopperOrder; orderKey?: string }) {
8
+ const timeline = JSON.stringify(order.timeline ?? [])
9
+ return (
10
+ <OrderView
11
+ order={order}
12
+ timelineHtml={renderNymbal('nymbal-order-timeline', { entries: timeline }).__html}
13
+ summaryHtml={renderNymbal('nymbal-order-summary', summaryAttributes(order)).__html}
14
+ refresh={
15
+ <OrderStatusRefresh
16
+ orderNumber={order.orderNumber}
17
+ orderKey={orderKey}
18
+ status={order.status}
19
+ />
20
+ }
21
+ />
22
+ )
23
+ }
@@ -0,0 +1,90 @@
1
+ 'use client'
2
+
3
+ import { useRef, useState, type FormEvent } from 'react'
4
+ import { NymbalApiError } from '@nymbalhq/sdk'
5
+ import type { ShopperOrder } from '@nymbalhq/types'
6
+ import { getNymbalClient } from '@/lib/client'
7
+ import styles from '@/styles/pages/error.module.css'
8
+ import { OrderNotFound } from './OrderNotFound'
9
+ import { OrderView } from './OrderView'
10
+
11
+ type State =
12
+ | { kind: 'idle' | 'sending' | 'limited' | 'failed' | 'not-found' }
13
+ | { kind: 'opened'; order: ShopperOrder }
14
+
15
+ /**
16
+ * The order's key has expired: the shopper gives the order's email to open it. The browser reads the order with the
17
+ * email in a header, so it never lands in a page URL and each shopper's tries count against their own address, not
18
+ * the storefront server's. One request per click: a second submit while one is out is ignored.
19
+ */
20
+ export function OrderEmailPrompt({
21
+ orderNumber,
22
+ orderKey,
23
+ }: {
24
+ orderNumber: string
25
+ orderKey: string
26
+ }) {
27
+ const [state, setState] = useState<State>({ kind: 'idle' })
28
+ const inFlight = useRef(false)
29
+
30
+ async function onSubmit(event: FormEvent<HTMLFormElement>) {
31
+ event.preventDefault()
32
+ if (inFlight.current) return
33
+ inFlight.current = true
34
+ setState({ kind: 'sending' })
35
+ const email = String(new FormData(event.currentTarget).get('email') ?? '').trim()
36
+ try {
37
+ const order = await getNymbalClient().orders.get(orderNumber, { key: orderKey, email })
38
+ setState({ kind: 'opened', order })
39
+ } catch (err) {
40
+ // A 404 is the answer an unknown number gets: the email did not open the order.
41
+ if (err instanceof NymbalApiError && err.status === 404) setState({ kind: 'not-found' })
42
+ else if (err instanceof NymbalApiError && err.status === 429) setState({ kind: 'limited' })
43
+ else setState({ kind: 'failed' })
44
+ } finally {
45
+ inFlight.current = false
46
+ }
47
+ }
48
+
49
+ if (state.kind === 'opened') return <OrderView order={state.order} />
50
+ if (state.kind === 'not-found') return <OrderNotFound />
51
+ return (
52
+ <div className={styles.page}>
53
+ <form method="post" onSubmit={onSubmit} className={styles.wrapper}>
54
+ <h1 className={styles.title}>Open your order</h1>
55
+ <p className={styles.message}>
56
+ This order link has expired. Enter the email you gave at checkout to open the order.
57
+ </p>
58
+ <div className={styles.searchPromptInput}>
59
+ <label htmlFor="order-email">Email</label>
60
+ <input
61
+ id="order-email"
62
+ type="email"
63
+ name="email"
64
+ autoComplete="email"
65
+ required
66
+ data-testid="order-email-input"
67
+ />
68
+ </div>
69
+ {state.kind === 'limited' && (
70
+ <p className={styles.message} data-testid="order-email-limited">
71
+ Too many tries for now. Please try again in a while.
72
+ </p>
73
+ )}
74
+ {state.kind === 'failed' && (
75
+ <p className={styles.message}>We could not open the order just now. Please try again.</p>
76
+ )}
77
+ <div className={styles.actions}>
78
+ <button
79
+ type="submit"
80
+ className={styles.homeLink}
81
+ disabled={state.kind === 'sending'}
82
+ data-testid="order-email-submit"
83
+ >
84
+ Open order
85
+ </button>
86
+ </div>
87
+ </form>
88
+ </div>
89
+ )
90
+ }
@@ -0,0 +1,73 @@
1
+ 'use client'
2
+
3
+ import { useRef, useState, type FormEvent } from 'react'
4
+ import { getNymbalClient } from '@/lib/client'
5
+ import styles from '@/styles/pages/error.module.css'
6
+
7
+ type State = 'idle' | 'sending' | 'sent' | 'failed'
8
+
9
+ /**
10
+ * "Send me my order link": the store emails the order's link to the order's own email, and answers the same whatever
11
+ * matched, so the page says the same either way. One request per click: a second submit while one is out is ignored.
12
+ */
13
+ export function OrderLinkForm() {
14
+ const [state, setState] = useState<State>('idle')
15
+ const inFlight = useRef(false)
16
+
17
+ async function onSubmit(event: FormEvent<HTMLFormElement>) {
18
+ event.preventDefault()
19
+ if (inFlight.current) return
20
+ inFlight.current = true
21
+ setState('sending')
22
+ const data = new FormData(event.currentTarget)
23
+ try {
24
+ await getNymbalClient().orders.requestLink({
25
+ orderNumber: String(data.get('orderNumber') ?? '').trim(),
26
+ email: String(data.get('email') ?? '').trim(),
27
+ })
28
+ setState('sent')
29
+ } catch {
30
+ setState('failed')
31
+ } finally {
32
+ inFlight.current = false
33
+ }
34
+ }
35
+
36
+ if (state === 'sent') {
37
+ return (
38
+ <p className={styles.message} data-testid="order-link-sent">
39
+ If that number and email match an order, its link is on its way to that email.
40
+ </p>
41
+ )
42
+ }
43
+ return (
44
+ <form method="post" className={styles.searchPrompt} onSubmit={onSubmit}>
45
+ <div className={styles.searchPromptInput}>
46
+ <label htmlFor="order-link-number">Order number</label>
47
+ <input id="order-link-number" name="orderNumber" required data-testid="order-link-number" />
48
+ <label htmlFor="order-link-email">Email</label>
49
+ <input
50
+ id="order-link-email"
51
+ type="email"
52
+ name="email"
53
+ autoComplete="email"
54
+ required
55
+ data-testid="order-link-email"
56
+ />
57
+ </div>
58
+ {state === 'failed' && (
59
+ <p className={styles.message}>We could not send the link just now. Please try again.</p>
60
+ )}
61
+ <div className={styles.actions}>
62
+ <button
63
+ type="submit"
64
+ className={styles.homeLink}
65
+ disabled={state === 'sending'}
66
+ data-testid="order-link-submit"
67
+ >
68
+ Send me my order link
69
+ </button>
70
+ </div>
71
+ </form>
72
+ )
73
+ }