@thorprovider/storefront 0.10.0 → 0.11.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 +8 -5
- package/assets/templates/app/app/globals.css +0 -1
- package/assets/templates/app/lib/__STOREFRONT__/account-session.core.ts +4 -2
- package/assets/templates/app/lib/__STOREFRONT__/account-user.core.ts +2 -1
- package/assets/templates/app/lib/__STOREFRONT__/actions.ts +73 -11
- package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +18 -2
- package/assets/templates/app/lib/__STOREFRONT__/confirmation.core.ts +38 -3
- package/assets/templates/app/lib/__STOREFRONT__/order-detail-aftersales.ts +55 -0
- package/assets/templates/app/lib/__STOREFRONT__/order-detail-capabilities.ts +79 -0
- package/assets/templates/app/lib/__STOREFRONT__/order-detail-mapper.ts +13 -2
- package/assets/templates/app/lib/__STOREFRONT__/order-detail-money.ts +39 -0
- package/assets/templates/app/lib/__STOREFRONT__/order-detail-reorder.ts +62 -0
- package/assets/templates/views/account/assembly/index.skeleton.tsx +3 -0
- package/assets/templates/views/account/assembly/registry.skeleton.tsx +115 -4
- package/assets/templates/views/account/content.ts +6 -0
- package/assets/templates/views/account/index.tsx +3 -0
- package/assets/templates/views/account/order-detail-flows.defaults.ts +106 -0
- package/assets/templates/views/account/order-detail-invoice.ts +136 -0
- package/assets/templates/views/account/order-detail-sheet.tsx +100 -0
- package/assets/templates/views/account/order-detail-sheets.tsx +122 -0
- package/assets/templates/views/account/order-detail.client.tsx +401 -1
- package/assets/templates/views/account/registry.tsx +115 -4
- package/assets/templates/views/account/schema.ts +2 -0
- package/assets/templates/views/home/content.ts +3 -1
- package/assets/templates/views/product/data.ts +13 -6
- package/assets/templates/views/product/index.tsx +3 -3
- package/bin/storefront.js +5 -4
- package/package.json +1 -1
- package/scripts/candidate.mjs +8 -4
- package/scripts/mock-capabilities.mjs +22 -0
- package/scripts/reconcile.mjs +5 -2
- package/scripts/render-templates.mjs +126 -43
package/README.md
CHANGED
|
@@ -205,11 +205,14 @@ storefront feature add customer-addresses # refused when the backend lacks man
|
|
|
205
205
|
```
|
|
206
206
|
|
|
207
207
|
A failed probe records no list (unknown), so capability-gated features stay
|
|
208
|
-
uninstallable until `storefront setup` succeeds again.
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
`storefront
|
|
208
|
+
uninstallable until `storefront setup` succeeds again. In **mock mode** there is no
|
|
209
|
+
endpoint to probe, so `setup` records the mock provider's own flags: the modules the
|
|
210
|
+
mock genuinely supports (profile updates, address book, order history) install, and the
|
|
211
|
+
ones it refuses truthfully (email change, password change, saved payment methods) stay
|
|
212
|
+
out. `storefront doctor` re-probes and reports an installed feature whose capability the
|
|
213
|
+
backend no longer advertises. Features also declare `requires` (a module needs its host
|
|
214
|
+
feature) and `adapter.needs` (callables checked against the adapter/commerce surface),
|
|
215
|
+
and a held feature is inspectable with `storefront features --json` but never installable.
|
|
213
216
|
|
|
214
217
|
The guest flow is backend-authoritative end to end: the signed host cookie binds a
|
|
215
218
|
persistent backend cart; the PDP adds the explicitly selected variant; the cart and
|
|
@@ -20,15 +20,17 @@ import type { Customer } from '@thorprovider/types'
|
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
22
|
* The display allowlist. Zod strips unknown keys on parse, so a backend
|
|
23
|
-
* customer projects to exactly these
|
|
23
|
+
* customer projects to exactly these fields. An absent optional name is
|
|
24
24
|
* normalized to null (never undefined) so the projection is stable to
|
|
25
|
-
* serialize.
|
|
25
|
+
* serialize. `createdAt` is the display-only join date the account header
|
|
26
|
+
* renders ("Cliente desde …"); it is a public account fact, never a credential.
|
|
26
27
|
*/
|
|
27
28
|
export const accountIdentitySchema = z.object({
|
|
28
29
|
id: z.string().min(1),
|
|
29
30
|
email: z.string().min(1),
|
|
30
31
|
firstName: z.string().nullish().transform((value) => value ?? null),
|
|
31
32
|
lastName: z.string().nullish().transform((value) => value ?? null),
|
|
33
|
+
createdAt: z.string().nullish().transform((value) => value ?? null),
|
|
32
34
|
})
|
|
33
35
|
|
|
34
36
|
/** The only customer fields permitted in projected/serialized account state. */
|
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
//
|
|
6
6
|
// The navbar account menu renders `@thorprovider/blocks`' `StoreUser`
|
|
7
7
|
// (`{ name, email, avatar?, initials }`), which differs from the allowlisted
|
|
8
|
-
// identity (`{ id, email, firstName|null, lastName|null }`).
|
|
8
|
+
// identity (`{ id, email, firstName|null, lastName|null, createdAt|null }`).
|
|
9
|
+
// The mapping lives
|
|
9
10
|
// in this DERIVED module — regenerated by the CLI — rather than in the
|
|
10
11
|
// user-owned `mappers.ts` (seeded once, never rewritten by `reconcile`, so a new
|
|
11
12
|
// required export there would break older storefronts on upgrade).
|
|
@@ -19,6 +19,7 @@ import type { AccountAddressView, AccountOrderView, CartLineState } from './stat
|
|
|
19
19
|
import type {
|
|
20
20
|
Address,
|
|
21
21
|
CheckoutAddressOption,
|
|
22
|
+
CheckoutPaymentPlanItem,
|
|
22
23
|
CreateAddressData,
|
|
23
24
|
Customer,
|
|
24
25
|
PaymentMethod,
|
|
@@ -94,6 +95,7 @@ import {
|
|
|
94
95
|
} from './session'
|
|
95
96
|
import type { AccountProfileMetadataPatch, AccountProfilePayload } from './account-profile'
|
|
96
97
|
import { toOrderDetailSnapshot } from './order-detail-mapper'
|
|
98
|
+
import { toReorderLines, type ReorderOrderResult } from './order-detail-reorder'
|
|
97
99
|
|
|
98
100
|
// A `'use server'` module may export ONLY async functions. Next/Turbopack's
|
|
99
101
|
// server-actions transform registers every export as a runtime server
|
|
@@ -437,6 +439,53 @@ export async function addToCartByHandleAction(input: {
|
|
|
437
439
|
}
|
|
438
440
|
}
|
|
439
441
|
|
|
442
|
+
/**
|
|
443
|
+
* Re-add a stored order to the cart, addressed by its backend id.
|
|
444
|
+
*
|
|
445
|
+
* The ownership-scoped read is the only source of variants and quantities; the
|
|
446
|
+
* client never sends either. Adds are sequential because each one rewrites the
|
|
447
|
+
* cart, and a rejected variant is reported as a skipped line instead of being
|
|
448
|
+
* dropped or retried blindly.
|
|
449
|
+
*/
|
|
450
|
+
export async function reorderOrderAction(input: {
|
|
451
|
+
orderId: string
|
|
452
|
+
}): Promise<ReorderOrderResult> {
|
|
453
|
+
const orderId = typeof input?.orderId === 'string' ? input.orderId.trim() : ''
|
|
454
|
+
if (!orderId) return { ok: false, error: 'Pedido no encontrado.' }
|
|
455
|
+
|
|
456
|
+
const context = getStoreContext()
|
|
457
|
+
const token = await readAuthToken(context)
|
|
458
|
+
if (!token) return { ok: false, error: 'Inicia sesión para repetir esta compra.' }
|
|
459
|
+
|
|
460
|
+
try {
|
|
461
|
+
const order = await loadCustomerOrderDetail(token, orderId, context)
|
|
462
|
+
const { lines, skipped } = toReorderLines(order)
|
|
463
|
+
if (lines.length === 0) return { ok: true, added: 0, skipped }
|
|
464
|
+
|
|
465
|
+
const { cartId, context: cartContext, provider } = await ensureActiveCartId()
|
|
466
|
+
let added = 0
|
|
467
|
+
for (const line of lines) {
|
|
468
|
+
try {
|
|
469
|
+
await addVariant(cartId, line.variantId, line.quantity, cartContext, provider)
|
|
470
|
+
added += line.quantity
|
|
471
|
+
} catch (error) {
|
|
472
|
+
skipped.push({ title: line.title, reason: toError(error, 'No se pudo agregar') })
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return { ok: true, added, skipped }
|
|
476
|
+
} catch (error) {
|
|
477
|
+
logServerError('reorderOrderAction', error)
|
|
478
|
+
const code = errorCode(error)
|
|
479
|
+
if (code === 'ORDER_DETAIL_NOT_FOUND' || code === 'RESOURCE_NOT_FOUND') {
|
|
480
|
+
return { ok: false, error: 'Pedido no encontrado.' }
|
|
481
|
+
}
|
|
482
|
+
if (code === 'ORDER_DETAIL_FORBIDDEN' || code === 'AUTH_UNAUTHENTICATED') {
|
|
483
|
+
return { ok: false, error: 'Inicia sesión para repetir esta compra.' }
|
|
484
|
+
}
|
|
485
|
+
return { ok: false, error: toError(error, 'No se pudo repetir la compra.') }
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
440
489
|
/** Set a backend cart line to an ABSOLUTE quantity by its line-item id. */
|
|
441
490
|
export async function setLineQuantityAction(input: {
|
|
442
491
|
lineId: string
|
|
@@ -1137,7 +1186,11 @@ async function clearConfirmedSession(
|
|
|
1137
1186
|
* a committed order as a retryable failure.
|
|
1138
1187
|
*/
|
|
1139
1188
|
export async function placeOrderAction(
|
|
1140
|
-
input: {
|
|
1189
|
+
input: {
|
|
1190
|
+
shippingGroups?: ShippingGroupSelection[]
|
|
1191
|
+
paymentMethodId?: string
|
|
1192
|
+
payments?: CheckoutPaymentPlanItem[]
|
|
1193
|
+
} = {},
|
|
1141
1194
|
): Promise<PlaceOrderResult> {
|
|
1142
1195
|
try {
|
|
1143
1196
|
const { cartId, context, provider, customerId } = await ensureActiveCartId({
|
|
@@ -1151,9 +1204,13 @@ export async function placeOrderAction(
|
|
|
1151
1204
|
}
|
|
1152
1205
|
}
|
|
1153
1206
|
|
|
1207
|
+
const paymentPlan =
|
|
1208
|
+
Array.isArray(input.payments) && input.payments.length > 0
|
|
1209
|
+
? input.payments
|
|
1210
|
+
: undefined
|
|
1154
1211
|
const paymentMethodId =
|
|
1155
1212
|
typeof input.paymentMethodId === 'string' ? input.paymentMethodId.trim() : ''
|
|
1156
|
-
if (!paymentMethodId) {
|
|
1213
|
+
if (!paymentPlan && !paymentMethodId) {
|
|
1157
1214
|
return {
|
|
1158
1215
|
status: 'error',
|
|
1159
1216
|
message: 'Selecciona un método de pago antes de confirmar.',
|
|
@@ -1186,21 +1243,26 @@ export async function placeOrderAction(
|
|
|
1186
1243
|
}
|
|
1187
1244
|
}
|
|
1188
1245
|
}
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1246
|
+
// A payment plan defines every instrument with an exact amount; the
|
|
1247
|
+
// backend creates and authorizes the sessions. The legacy single-method
|
|
1248
|
+
// path keeps working when no plan is supplied.
|
|
1249
|
+
if (!paymentPlan) {
|
|
1250
|
+
try {
|
|
1251
|
+
await applyPayment(cartId, paymentMethodId, context, provider)
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
logServerError('applyPayment', error)
|
|
1254
|
+
return {
|
|
1255
|
+
status: 'error',
|
|
1256
|
+
message: toError(error, 'No se pudo iniciar el pago.'),
|
|
1257
|
+
code: 'PAYMENT_METHOD_REJECTED',
|
|
1258
|
+
}
|
|
1197
1259
|
}
|
|
1198
1260
|
}
|
|
1199
1261
|
// Thread the request's customer token (design D11) so an authenticated
|
|
1200
1262
|
// checkout is attributed to the session customer; guests complete the same
|
|
1201
1263
|
// tokenless provider as before.
|
|
1202
1264
|
const customerToken = await readAuthToken(context)
|
|
1203
|
-
const result = await completeOrder(cartId, context, customerToken)
|
|
1265
|
+
const result = await completeOrder(cartId, context, customerToken, paymentPlan)
|
|
1204
1266
|
if (result.status !== 'order') return result
|
|
1205
1267
|
if (!(await clearConfirmedSession(context, cartId))) {
|
|
1206
1268
|
return {
|
|
@@ -22,6 +22,8 @@ import type {
|
|
|
22
22
|
Address,
|
|
23
23
|
Cart,
|
|
24
24
|
CheckoutAddressOption,
|
|
25
|
+
CheckoutPaymentPlanItem,
|
|
26
|
+
CheckoutPaymentSummary,
|
|
25
27
|
CreateAddressData,
|
|
26
28
|
Customer,
|
|
27
29
|
LoginCredentials,
|
|
@@ -148,6 +150,7 @@ export type PlaceOrderResult =
|
|
|
148
150
|
order: StorefrontOrder
|
|
149
151
|
lines: StorefrontOrderLineView[]
|
|
150
152
|
confirmation: StorefrontConfirmation
|
|
153
|
+
paymentSummary?: CheckoutPaymentSummary
|
|
151
154
|
}
|
|
152
155
|
| { status: 'error'; message: string; code?: string }
|
|
153
156
|
| { status: 'cart-error'; message: string; code?: string }
|
|
@@ -299,6 +302,7 @@ export function toPlaceOrderResult(result: CartCompletionResult): PlaceOrderResu
|
|
|
299
302
|
order: toStorefrontOrder(result.order),
|
|
300
303
|
lines: toOrderLines(result.order),
|
|
301
304
|
confirmation: toStorefrontConfirmation(result.order),
|
|
305
|
+
...(result.paymentSummary ? { paymentSummary: result.paymentSummary } : {}),
|
|
302
306
|
}
|
|
303
307
|
}
|
|
304
308
|
if (result.type === 'cart') {
|
|
@@ -643,6 +647,7 @@ export async function completeOrder(
|
|
|
643
647
|
cartId: string,
|
|
644
648
|
context: StoreContext = getStoreContext(),
|
|
645
649
|
customerToken?: string | null,
|
|
650
|
+
payments?: CheckoutPaymentPlanItem[],
|
|
646
651
|
): Promise<PlaceOrderResult> {
|
|
647
652
|
assertBackendConfigured()
|
|
648
653
|
// The host owns the auth cookie and threads the request's customer token
|
|
@@ -650,7 +655,12 @@ export async function completeOrder(
|
|
|
650
655
|
// customer (mock) or links it server-side (Medusa). A tokenless completion
|
|
651
656
|
// builds exactly the provider the previous token-blind default built.
|
|
652
657
|
return toPlaceOrderResult(
|
|
653
|
-
await completeCart(
|
|
658
|
+
await completeCart(
|
|
659
|
+
cartId,
|
|
660
|
+
context,
|
|
661
|
+
getCommerceClientWithToken(customerToken ?? null),
|
|
662
|
+
payments,
|
|
663
|
+
),
|
|
654
664
|
)
|
|
655
665
|
}
|
|
656
666
|
|
|
@@ -664,10 +674,16 @@ export async function reconcileOrder(
|
|
|
664
674
|
cartId: string,
|
|
665
675
|
context: StoreContext = getStoreContext(),
|
|
666
676
|
customerToken?: string | null,
|
|
677
|
+
payments?: CheckoutPaymentPlanItem[],
|
|
667
678
|
): Promise<PlaceOrderResult> {
|
|
668
679
|
assertBackendConfigured()
|
|
669
680
|
return toPlaceOrderResult(
|
|
670
|
-
await reconcileCart(
|
|
681
|
+
await reconcileCart(
|
|
682
|
+
cartId,
|
|
683
|
+
context,
|
|
684
|
+
getCommerceClientWithToken(customerToken ?? null),
|
|
685
|
+
payments,
|
|
686
|
+
),
|
|
671
687
|
)
|
|
672
688
|
}
|
|
673
689
|
|
|
@@ -41,6 +41,15 @@ export interface StorefrontConfirmationGroup {
|
|
|
41
41
|
lines: StorefrontConfirmationLine[]
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
export interface StorefrontConfirmationPayment {
|
|
45
|
+
id: string
|
|
46
|
+
providerId: string
|
|
47
|
+
label: string
|
|
48
|
+
amountCents?: number
|
|
49
|
+
status: 'authorized' | 'captured' | 'canceled' | 'pending'
|
|
50
|
+
capturedAt?: string
|
|
51
|
+
}
|
|
52
|
+
|
|
44
53
|
export interface StorefrontConfirmationPromotion {
|
|
45
54
|
id: string
|
|
46
55
|
label: string
|
|
@@ -65,6 +74,8 @@ export interface StorefrontConfirmation {
|
|
|
65
74
|
address: StorefrontConfirmationAddress | null
|
|
66
75
|
paymentLabel: string
|
|
67
76
|
paymentDetail: string
|
|
77
|
+
/** Per-instrument breakdown when the order reports multiple payments. */
|
|
78
|
+
payments?: StorefrontConfirmationPayment[]
|
|
68
79
|
billingLabel: string
|
|
69
80
|
billingDetail: string
|
|
70
81
|
customerName: string
|
|
@@ -149,10 +160,33 @@ export function toStorefrontConfirmation(order: Order): StorefrontConfirmation {
|
|
|
149
160
|
order.deliveryGroups?.length
|
|
150
161
|
? order.deliveryGroups.every((group) => group.mode === 'pickup')
|
|
151
162
|
: order.shippingMethod?.mode === 'pickup'
|
|
152
|
-
const
|
|
153
|
-
|
|
163
|
+
const labelForPayment = (payment: {
|
|
164
|
+
providerId?: string
|
|
165
|
+
label?: string
|
|
166
|
+
}): string =>
|
|
167
|
+
payment.providerId === APPROVED_MANUAL_TEST_PROVIDER_ID
|
|
154
168
|
? 'Pago manual TEST'
|
|
155
|
-
:
|
|
169
|
+
: payment.label ?? ''
|
|
170
|
+
const payments: StorefrontConfirmationPayment[] = (order.payments ?? []).map(
|
|
171
|
+
(payment) => {
|
|
172
|
+
const amountCents = moneyToCents(payment.amount)
|
|
173
|
+
return {
|
|
174
|
+
id: payment.id,
|
|
175
|
+
providerId: payment.providerId,
|
|
176
|
+
label: labelForPayment(payment),
|
|
177
|
+
...(amountCents !== undefined ? { amountCents } : {}),
|
|
178
|
+
status: payment.status,
|
|
179
|
+
...(payment.capturedAt ? { capturedAt: payment.capturedAt } : {}),
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
)
|
|
183
|
+
const paymentLabel =
|
|
184
|
+
payments.length > 0
|
|
185
|
+
? payments
|
|
186
|
+
.map((payment) => payment.label)
|
|
187
|
+
.filter((label) => label.trim() !== '')
|
|
188
|
+
.join(' + ')
|
|
189
|
+
: labelForPayment(order.payment ?? {})
|
|
156
190
|
|
|
157
191
|
// One confirmation entry per confirmed backend group, preserving each
|
|
158
192
|
// group's mode, method, detail, fee and line membership. Line membership is
|
|
@@ -228,6 +262,7 @@ export function toStorefrontConfirmation(order: Order): StorefrontConfirmation {
|
|
|
228
262
|
: null,
|
|
229
263
|
paymentLabel,
|
|
230
264
|
paymentDetail: order.payment?.detail ?? '',
|
|
265
|
+
...(payments.length > 0 ? { payments } : {}),
|
|
231
266
|
billingLabel: billing ? billing.label || 'Dirección de facturación' : '',
|
|
232
267
|
billingDetail: billing ? addressDetail(billing) : '',
|
|
233
268
|
customerName,
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { AfterSalesLine } from '@thorprovider/blocks'
|
|
2
|
+
|
|
3
|
+
import { fromMinor } from './order-detail-money'
|
|
4
|
+
import type { OrderDetailOrder } from '@thorprovider/blocks/ports'
|
|
5
|
+
|
|
6
|
+
const DELIVERED_STATUSES = new Set(['delivered', 'partially_delivered'])
|
|
7
|
+
const RETURNED_STATUSES = new Set(['requested', 'approved', 'in_transit', 'received', 'completed'])
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Project the order snapshot into the lines the after-sales flow may offer.
|
|
11
|
+
*
|
|
12
|
+
* `delivered` comes from the fulfilment allocations the backend reported;
|
|
13
|
+
* `returnable` subtracts units already in a live return case, so the flow can
|
|
14
|
+
* never ask for more than the shopper still holds. Rejected cases release their
|
|
15
|
+
* units again. Both numbers are computed here, never in the block.
|
|
16
|
+
*/
|
|
17
|
+
export function toAfterSalesLines(order: OrderDetailOrder): AfterSalesLine[] {
|
|
18
|
+
const returned = new Map<string, number>()
|
|
19
|
+
for (const entry of order.cases ?? []) {
|
|
20
|
+
if (entry.type !== 'return' || !RETURNED_STATUSES.has(entry.status)) continue
|
|
21
|
+
for (const line of entry.lines) {
|
|
22
|
+
returned.set(line.lineId, (returned.get(line.lineId) ?? 0) + line.quantity)
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const delivered = new Map<string, number>()
|
|
27
|
+
for (const fulfillment of order.fulfillments ?? []) {
|
|
28
|
+
if (!DELIVERED_STATUSES.has(fulfillment.status)) continue
|
|
29
|
+
for (const allocation of fulfillment.allocations) {
|
|
30
|
+
delivered.set(
|
|
31
|
+
allocation.lineId,
|
|
32
|
+
(delivered.get(allocation.lineId) ?? 0) + allocation.quantity,
|
|
33
|
+
)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return (order.lines ?? []).map((line) => {
|
|
38
|
+
const deliveredQuantity = delivered.get(line.id) ?? 0
|
|
39
|
+
const returnable = Math.max(0, deliveredQuantity - (returned.get(line.id) ?? 0))
|
|
40
|
+
return {
|
|
41
|
+
id: line.id,
|
|
42
|
+
name: line.name,
|
|
43
|
+
...(line.sku ? { sku: line.sku } : {}),
|
|
44
|
+
...(line.image ? { image: line.image } : {}),
|
|
45
|
+
// The block speaks the canonical decimal `Money`; the snapshot speaks
|
|
46
|
+
// integer minor units.
|
|
47
|
+
unitPrice: {
|
|
48
|
+
amount: fromMinor(line.unitPrice.applied.amount, line.unitPrice.applied.currency),
|
|
49
|
+
currencyCode: line.unitPrice.applied.currency,
|
|
50
|
+
},
|
|
51
|
+
delivered: deliveredQuantity,
|
|
52
|
+
returnable,
|
|
53
|
+
}
|
|
54
|
+
})
|
|
55
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { OrderActionId, OrderDocument } from '@thorprovider/blocks/ports'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Host capability gate for the order-detail route.
|
|
5
|
+
*
|
|
6
|
+
* The delivered surface renders one control per action in `availableActions`, so
|
|
7
|
+
* an action that reaches the snapshot without a host handler becomes a dead
|
|
8
|
+
* control. This list is therefore the single source of truth for what the host
|
|
9
|
+
* can really serve: project actions through it, and register exactly one handler
|
|
10
|
+
* per entry in the route panel.
|
|
11
|
+
*/
|
|
12
|
+
export const ORDER_DETAIL_HOST_ACTIONS: readonly OrderActionId[] = [
|
|
13
|
+
'reorder',
|
|
14
|
+
'invoice',
|
|
15
|
+
'track',
|
|
16
|
+
'pay-balance',
|
|
17
|
+
'support',
|
|
18
|
+
'return',
|
|
19
|
+
'exchange',
|
|
20
|
+
'problem',
|
|
21
|
+
'cancel',
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
/** Support destination declared by the store. Empty string hides the action. */
|
|
25
|
+
export const ORDER_DETAIL_SUPPORT_HREF = '/contact'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The actions the host can serve.
|
|
29
|
+
*
|
|
30
|
+
* An empty support destination means the store publishes no contact page, so
|
|
31
|
+
* `support` is dropped from the projection instead of becoming a button whose
|
|
32
|
+
* handler has nowhere to go.
|
|
33
|
+
*/
|
|
34
|
+
export function orderDetailHostActions(
|
|
35
|
+
supportHref: string = ORDER_DETAIL_SUPPORT_HREF,
|
|
36
|
+
): readonly OrderActionId[] {
|
|
37
|
+
if (supportHref !== '') return ORDER_DETAIL_HOST_ACTIONS
|
|
38
|
+
return ORDER_DETAIL_HOST_ACTIONS.filter((action) => action !== 'support')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Project an authorised action set through the host's real capabilities. */
|
|
42
|
+
export function projectHostActions(
|
|
43
|
+
actions: readonly OrderActionId[],
|
|
44
|
+
supportHref: string = ORDER_DETAIL_SUPPORT_HREF,
|
|
45
|
+
): OrderActionId[] {
|
|
46
|
+
const served = orderDetailHostActions(supportHref)
|
|
47
|
+
return actions.filter((action) => served.includes(action))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Documents the demo storefront can actually open.
|
|
52
|
+
*
|
|
53
|
+
* Medusa issues no invoice or receipt file, so these exist only for mock orders,
|
|
54
|
+
* where the host renders a printable demonstration sheet from the snapshot. A
|
|
55
|
+
* live order keeps `documents: []`: an invented invoice on a real storefront
|
|
56
|
+
* would be a defect, not a placeholder.
|
|
57
|
+
*/
|
|
58
|
+
export function orderDetailDemoDocuments(
|
|
59
|
+
order: { number: string; createdAt: string },
|
|
60
|
+
isMock: boolean,
|
|
61
|
+
): OrderDocument[] {
|
|
62
|
+
if (!isMock) return []
|
|
63
|
+
return [
|
|
64
|
+
{
|
|
65
|
+
id: `${order.number}-invoice`,
|
|
66
|
+
kind: 'invoice',
|
|
67
|
+
label: `Factura ${order.number}`,
|
|
68
|
+
issuedAt: order.createdAt,
|
|
69
|
+
available: true,
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
id: `${order.number}-receipt`,
|
|
73
|
+
kind: 'receipt',
|
|
74
|
+
label: `Recibo ${order.number}`,
|
|
75
|
+
issuedAt: order.createdAt,
|
|
76
|
+
available: true,
|
|
77
|
+
},
|
|
78
|
+
]
|
|
79
|
+
}
|
|
@@ -32,6 +32,7 @@ import type {
|
|
|
32
32
|
TaxLine,
|
|
33
33
|
Transaction,
|
|
34
34
|
} from '@thorprovider/blocks/ports'
|
|
35
|
+
import { orderDetailDemoDocuments, projectHostActions } from './order-detail-capabilities'
|
|
35
36
|
|
|
36
37
|
type Money = OrderDetailMoney
|
|
37
38
|
type FulfillmentStatus = OrderDetailFulfillmentStatus
|
|
@@ -606,6 +607,10 @@ export function toOrderDetailSnapshot(order: Order): OrderDetailSnapshot {
|
|
|
606
607
|
|
|
607
608
|
const shippingAddress = toDetailAddress(order.shippingAddress)
|
|
608
609
|
const billingAddress = toDetailAddress(order.billingAddress)
|
|
610
|
+
const documents = orderDetailDemoDocuments(
|
|
611
|
+
{ number: order.orderNumber, createdAt: order.createdAt },
|
|
612
|
+
isMock,
|
|
613
|
+
)
|
|
609
614
|
const detail: OrderDetailOrder = {
|
|
610
615
|
id: order.id,
|
|
611
616
|
number: order.orderNumber,
|
|
@@ -623,7 +628,7 @@ export function toOrderDetailSnapshot(order: Order): OrderDetailSnapshot {
|
|
|
623
628
|
adjustments,
|
|
624
629
|
transactions,
|
|
625
630
|
cases,
|
|
626
|
-
documents
|
|
631
|
+
documents,
|
|
627
632
|
revisions: [],
|
|
628
633
|
totals: {
|
|
629
634
|
itemsSubtotal: subtotal,
|
|
@@ -635,7 +640,13 @@ export function toOrderDetailSnapshot(order: Order): OrderDetailSnapshot {
|
|
|
635
640
|
adjustments: zero(currency),
|
|
636
641
|
total,
|
|
637
642
|
},
|
|
638
|
-
availableActions:
|
|
643
|
+
availableActions: projectHostActions(
|
|
644
|
+
toActionSet({ commercial, paymentStatus, logistics, returns }).filter(
|
|
645
|
+
(action) =>
|
|
646
|
+
action !== 'invoice' ||
|
|
647
|
+
documents.some((document) => document.kind === 'invoice' && document.available),
|
|
648
|
+
),
|
|
649
|
+
),
|
|
639
650
|
}
|
|
640
651
|
|
|
641
652
|
return { order: detail }
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Currency-aware conversion between the snapshot's integer minor units and the
|
|
3
|
+
* canonical decimal `Money` the blocks speak.
|
|
4
|
+
*
|
|
5
|
+
* Dividing by 100 is only right for the currencies that happen to have two
|
|
6
|
+
* fraction digits. JPY has none and KWD has three, so the exponent comes from
|
|
7
|
+
* `Intl.NumberFormat`, the same source the platform uses to render the symbol.
|
|
8
|
+
*/
|
|
9
|
+
export function currencyDigits(currency: string): number {
|
|
10
|
+
try {
|
|
11
|
+
return (
|
|
12
|
+
new Intl.NumberFormat('en-US', {
|
|
13
|
+
style: 'currency',
|
|
14
|
+
currency,
|
|
15
|
+
}).resolvedOptions().maximumFractionDigits ?? 2
|
|
16
|
+
)
|
|
17
|
+
} catch {
|
|
18
|
+
return 2
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const scale = (currency: string): number => 10 ** currencyDigits(currency)
|
|
23
|
+
|
|
24
|
+
/** Minor units → canonical decimal string, e.g. `12600, 'USD' → '126.00'`. */
|
|
25
|
+
export function fromMinor(amount: number, currency: string): string {
|
|
26
|
+
const digits = currencyDigits(currency)
|
|
27
|
+
return (amount / scale(currency)).toFixed(digits)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Minor units → locale-formatted amount. */
|
|
31
|
+
export function formatMinor(amount: number, currency: string, locale: string): string {
|
|
32
|
+
try {
|
|
33
|
+
return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(
|
|
34
|
+
amount / scale(currency),
|
|
35
|
+
)
|
|
36
|
+
} catch {
|
|
37
|
+
return `${fromMinor(amount, currency)} ${currency}`
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Order } from '@thorprovider/types'
|
|
2
|
+
|
|
3
|
+
/** One cart line a reorder would add, derived from the stored order. */
|
|
4
|
+
export type ReorderLine = {
|
|
5
|
+
variantId: string
|
|
6
|
+
quantity: number
|
|
7
|
+
title: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type ReorderSkip = { title: string; reason: string }
|
|
11
|
+
|
|
12
|
+
export type ReorderOrderResult =
|
|
13
|
+
| { ok: true; added: number; skipped: ReorderSkip[] }
|
|
14
|
+
| { ok: false; error: string }
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Project a stored order into cart lines.
|
|
18
|
+
*
|
|
19
|
+
* The backend order is the only source: the browser sends an order id, never
|
|
20
|
+
* variants or quantities. A line without a backend variant cannot be re-added,
|
|
21
|
+
* and an empty quantity means there is nothing to buy — both are reported so the
|
|
22
|
+
* shopper sees what was left out instead of a clean "added" claim.
|
|
23
|
+
*/
|
|
24
|
+
export function toReorderLines(order: Order): {
|
|
25
|
+
lines: ReorderLine[]
|
|
26
|
+
skipped: ReorderSkip[]
|
|
27
|
+
} {
|
|
28
|
+
const lines: ReorderLine[] = []
|
|
29
|
+
const skipped: ReorderSkip[] = []
|
|
30
|
+
|
|
31
|
+
for (const item of order.items ?? []) {
|
|
32
|
+
const quantity = Math.max(0, Math.floor(Number(item.quantity) || 0))
|
|
33
|
+
if (!item.variantId) {
|
|
34
|
+
skipped.push({ title: item.title, reason: 'Sin variante disponible' })
|
|
35
|
+
continue
|
|
36
|
+
}
|
|
37
|
+
if (quantity === 0) {
|
|
38
|
+
skipped.push({ title: item.title, reason: 'Sin unidades disponibles' })
|
|
39
|
+
continue
|
|
40
|
+
}
|
|
41
|
+
lines.push({ variantId: item.variantId, quantity, title: item.title })
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return { lines, skipped }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Run the reorder server action, turning a transport failure into the same
|
|
49
|
+
* readable result the UI already renders. A rejected server-action call is not
|
|
50
|
+
* an exception the shopper can act on, and it must never look like success.
|
|
51
|
+
*/
|
|
52
|
+
export async function runReorder(
|
|
53
|
+
action: (input: { orderId: string }) => Promise<ReorderOrderResult>,
|
|
54
|
+
orderId: string,
|
|
55
|
+
fallback = 'No se pudo repetir la compra.',
|
|
56
|
+
): Promise<ReorderOrderResult> {
|
|
57
|
+
try {
|
|
58
|
+
return await action({ orderId })
|
|
59
|
+
} catch {
|
|
60
|
+
return { ok: false, error: fallback }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -24,6 +24,7 @@ import { registry } from './registry'
|
|
|
24
24
|
import { sectionData } from './sections-data'
|
|
25
25
|
import { accountContent } from './content'
|
|
26
26
|
import { orderDetailDefaults } from './order-detail.defaults'
|
|
27
|
+
import { orderDetailFlowLabels, orderDetailSupport } from './order-detail-flows.defaults'
|
|
27
28
|
import { fulfillmentEvidenceDefaults } from './fulfillment-evidence.defaults'
|
|
28
29
|
import { accountOrdersAdvancedDefaults } from './orders-advanced.defaults'@@SECTION_IMPORTS@@
|
|
29
30
|
import {
|
|
@@ -59,6 +60,8 @@ const elements: Record<string, StorefrontElement> = {
|
|
|
59
60
|
props: {
|
|
60
61
|
orderId: { $state: '/orderDetailId' },
|
|
61
62
|
...orderDetailDefaults,
|
|
63
|
+
supportHref: orderDetailSupport.href,
|
|
64
|
+
flows: orderDetailFlowLabels,
|
|
62
65
|
},
|
|
63
66
|
},
|
|
64
67
|
// Headless account boundary. It is fixed infrastructure, not a selectable
|