@ecomweb/storefront-kit 0.9.0 → 0.10.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 +28 -1
- package/dist/auth/error-copy.js +4 -1
- package/dist/auth/error-copy.js.map +1 -1
- package/dist/checkout/quote-changed.js +16 -0
- package/dist/checkout/quote-changed.js.map +1 -0
- package/dist/checkout/use-checkout.js +36 -5
- package/dist/checkout/use-checkout.js.map +1 -1
- package/dist/index.d.ts +84 -3
- package/dist/index.js +25 -1
- package/dist/index.js.map +1 -1
- package/dist/orders/index.js +17 -1
- package/dist/orders/index.js.map +1 -1
- package/dist/orders/shipment-tracking.js +80 -0
- package/dist/orders/shipment-tracking.js.map +1 -0
- package/dist/shipping/format-shipping-option.js +28 -0
- package/dist/shipping/format-shipping-option.js.map +1 -1
- package/dist/shipping/messages.js +2 -0
- package/dist/shipping/messages.js.map +1 -1
- package/dist/shipping/option-id.js +7 -0
- package/dist/shipping/option-id.js.map +1 -0
- package/dist/shipping/shipping-calculation-reducer.js +60 -12
- package/dist/shipping/shipping-calculation-reducer.js.map +1 -1
- package/dist/shipping/use-shipping-calculation.js +38 -5
- package/dist/shipping/use-shipping-calculation.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -46,7 +46,34 @@ export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();
|
|
|
46
46
|
Wrap the store layout in `<StorefrontKitProvider store={store} onNotice={…}>`;
|
|
47
47
|
`onNotice` receives the kit's messages (item added, request failed) for your
|
|
48
48
|
toasts. `useCheckout().placeOrder()` returns `redirect`, `redirect_failed`,
|
|
49
|
-
`success`, `stock_issues` or `
|
|
49
|
+
`success`, `stock_issues`, `error`, `quote_changed` or `busy`, and your page decides what to show.
|
|
50
|
+
|
|
51
|
+
## Carrier shipping options and tracking
|
|
52
|
+
|
|
53
|
+
Carrier-calculated options (AllinGo) are opt-in:
|
|
54
|
+
`useCheckout({ includeCarrierOptions: true })`. Without it you get fixed rates
|
|
55
|
+
only, as before. When on:
|
|
56
|
+
|
|
57
|
+
- Key and select options by `optionIdOf(option)`, not `rate_id`
|
|
58
|
+
(`shipping.selectedOptionId`, `shipping.selectOption`). `selectRate` is
|
|
59
|
+
deprecated and only reaches fixed rates.
|
|
60
|
+
- Render each option with `describeShippingOption`. Logo and track links are
|
|
61
|
+
`http(s)` only.
|
|
62
|
+
- `placeOrder()` sends `shipping_service_id` and `shipping_quoted_amount` for a
|
|
63
|
+
carrier option. If the carrier price moved, the API answers 409
|
|
64
|
+
`SHIPPING_QUOTE_CHANGED`; the kit swaps in the new options and returns
|
|
65
|
+
`{ kind: "quote_changed" }`. The new amounts are merged into the list by
|
|
66
|
+
option id (other options are kept; the API re-checks them at placement).
|
|
67
|
+
Nothing was placed: show the new price and make the buyer confirm again. An
|
|
68
|
+
unavailable rate surfaces as an `error` with code
|
|
69
|
+
`ORDER_SHIPPING_RATE_UNAVAILABLE`, and the kit re-quotes the options.
|
|
70
|
+
|
|
71
|
+
On order pages, `deriveShipmentTracking(order)` builds the tracking view,
|
|
72
|
+
`canCustomerCancel(order)` follows the API's `can_cancel`, and
|
|
73
|
+
`isHandedToCarrier(order)` says whether the parcel has left the merchant.
|
|
74
|
+
`isCarrierShipment(order)` is false for a manual shipment (status `null`: show
|
|
75
|
+
only carrier and tracking number), and `shipmentEventLabel(event)` gives an
|
|
76
|
+
event's text with a neutral fallback.
|
|
50
77
|
|
|
51
78
|
## Metafields and metaobjects
|
|
52
79
|
|
package/dist/auth/error-copy.js
CHANGED
|
@@ -17,7 +17,10 @@ const ERROR_COPY = {
|
|
|
17
17
|
ORDER_NOT_FOUND: "Kh\xF4ng t\xECm th\u1EA5y \u0111\u01A1n h\xE0ng n\xE0y.",
|
|
18
18
|
ORDER_NOT_CANCELLABLE: "\u0110\u01A1n h\xE0ng n\xE0y kh\xF4ng th\u1EC3 hu\u1EF7 \u0111\u01B0\u1EE3c n\u1EEFa.",
|
|
19
19
|
INSUFFICIENT_INVENTORY: "M\u1ED9t s\u1ED1 s\u1EA3n ph\u1EA9m kh\xF4ng \u0111\u1EE7 h\xE0ng.",
|
|
20
|
-
ORDER_PROMOTION_NOT_APPLICABLE: "M\xE3 gi\u1EA3m gi\xE1 kh\xF4ng c\xF2n d\xF9ng \u0111\u01B0\u1EE3c cho \u0111\u01A1n n\xE0y n\xEAn \u0111\xE3 \u0111\u01B0\u1EE3c g\u1EE1. Vui l\xF2ng ki\u1EC3m tra l\u1EA1i t\u1ED5ng ti\u1EC1n r\u1ED3i \u0111\u1EB7t h\xE0ng."
|
|
20
|
+
ORDER_PROMOTION_NOT_APPLICABLE: "M\xE3 gi\u1EA3m gi\xE1 kh\xF4ng c\xF2n d\xF9ng \u0111\u01B0\u1EE3c cho \u0111\u01A1n n\xE0y n\xEAn \u0111\xE3 \u0111\u01B0\u1EE3c g\u1EE1. Vui l\xF2ng ki\u1EC3m tra l\u1EA1i t\u1ED5ng ti\u1EC1n r\u1ED3i \u0111\u1EB7t h\xE0ng.",
|
|
21
|
+
SHIPPING_QUOTE_CHANGED: "Ph\xED v\u1EADn chuy\u1EC3n \u0111\xE3 thay \u0111\u1ED5i. Vui l\xF2ng ki\u1EC3m tra l\u1EA1i r\u1ED3i \u0111\u1EB7t h\xE0ng.",
|
|
22
|
+
ORDER_SHIPPING_RATE_UNAVAILABLE: "Ph\u01B0\u01A1ng th\u1EE9c v\u1EADn chuy\u1EC3n \u0111\xE3 ch\u1ECDn kh\xF4ng c\xF2n kh\u1EA3 d\u1EE5ng. Vui l\xF2ng ch\u1ECDn l\u1EA1i.",
|
|
23
|
+
ORDER_CANCEL_BLOCKED_BY_SHIPMENT: "\u0110\u01A1n \u0111\xE3 \u0111\u01B0\u1EE3c giao cho h\xE3ng v\u1EADn chuy\u1EC3n, kh\xF4ng th\u1EC3 hu\u1EF7. Vui l\xF2ng li\xEAn h\u1EC7 c\u1EEDa h\xE0ng."
|
|
21
24
|
};
|
|
22
25
|
const STATUS_COPY = {
|
|
23
26
|
0: "Kh\xF4ng th\u1EC3 k\u1EBFt n\u1ED1i m\xE1y ch\u1EE7. Vui l\xF2ng ki\u1EC3m tra k\u1EBFt n\u1ED1i m\u1EA1ng.",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/auth/error-copy.ts"],"sourcesContent":["/**\n * Shopper-facing copy for backend errors.\n *\n * Project rule: backend exception messages are written in English and are\n * never shown to a shopper. The backend serialises every business error as\n * `{ code, message, details, timestamp }` (see `src/common/exceptions/` in the\n * api repo) and `code` is the stable identifier — this module is the single\n * place that turns one into Vietnamese.\n *\n * The fallback is always a generic Vietnamese sentence. Never fall back to the\n * backend's `message`.\n */\n\nexport const GENERIC_ERROR_COPY = \"Đã xảy ra lỗi. Vui lòng thử lại.\";\n\n/**\n * Keyed by the backend's stable `code`. Sources, read directly rather than\n * guessed:\n * - `AUTH_*` — `src/modules/customer-auth/domain/constants/auth.constants.ts`\n * (`AUTH_ERROR`).\n * - `ACCESS_DENIED` — `AuthorizationException.accessDenied()`, thrown by\n * `customer-addresses.controller.ts` on an address the caller does not own.\n * - `<RESOURCE>_NOT_FOUND` — `ResourceNotFoundException`, whose code is\n * `${resource.toUpperCase()}_NOT_FOUND`. `Address` and `Order` are the two\n * resources the storefront's authenticated routes can produce.\n * - `VALIDATION_FAILED` — `ValidationException`.\n * - `ORDER_NOT_CANCELLABLE` — `ORDER_ERROR.NOT_CANCELLABLE`\n * (`src/modules/orders/domain/constants/order-error.constants.ts`),\n * thrown by `OrderCancelCommandHandler` when a customer tries to cancel\n * an order outside pending/confirmed/processing.\n * - `INSUFFICIENT_INVENTORY`: `InsufficientInventoryException`\n * (`src/modules/inventory/domain/exceptions/`), thrown when an order asks\n * for more of a deny-policy variant than is available.\n * - `ORDER_PROMOTION_NOT_APPLICABLE`: `ORDER_ERROR.PROMOTION_NOT_APPLICABLE`,\n * thrown by `OrderComputationService.applyPromotionCode` when the applied\n * code can no longer be redeemed at placement (expired, used up, the cart\n * changed). `useCheckout` drops the code when it sees this.\n */\nconst ERROR_COPY: Record<string, string> = {\n AUTH_INVALID_CREDENTIALS: \"Email hoặc mật khẩu không đúng.\",\n AUTH_ACCOUNT_LOCKED: \"Quá nhiều lần thử. Vui lòng thử lại sau 15 phút.\",\n AUTH_EMAIL_NOT_VERIFIED: \"Vui lòng xác thực email của bạn trước.\",\n AUTH_METHOD_DISABLED:\n \"Phương thức đăng nhập này không khả dụng cho cửa hàng này.\",\n AUTH_TOKEN_INVALID: \"Mã xác thực không hợp lệ hoặc đã được sử dụng.\",\n AUTH_TOKEN_EXPIRED: \"Mã xác thực đã hết hạn. Vui lòng yêu cầu mã mới.\",\n AUTH_SESSION_EXPIRED: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n AUTH_WEAK_PASSWORD: \"Mật khẩu chưa đáp ứng yêu cầu của cửa hàng.\",\n AUTH_RATE_LIMITED: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n AUTH_STORE_MISMATCH:\n \"Phiên đăng nhập không thuộc cửa hàng này. Vui lòng đăng nhập lại.\",\n AUTH_EMAIL_TAKEN: \"Email này đã được sử dụng.\",\n\n ACCESS_DENIED: \"Bạn không có quyền thực hiện thao tác này.\",\n VALIDATION_FAILED: \"Thông tin chưa hợp lệ. Vui lòng kiểm tra lại.\",\n ADDRESS_NOT_FOUND: \"Không tìm thấy địa chỉ này.\",\n ORDER_NOT_FOUND: \"Không tìm thấy đơn hàng này.\",\n ORDER_NOT_CANCELLABLE: \"Đơn hàng này không thể huỷ được nữa.\",\n INSUFFICIENT_INVENTORY: \"Một số sản phẩm không đủ hàng.\",\n ORDER_PROMOTION_NOT_APPLICABLE:\n \"Mã giảm giá không còn dùng được cho đơn này nên đã được gỡ. Vui lòng kiểm tra lại tổng tiền rồi đặt hàng.\",\n};\n\n/**\n * Nest's built-in `UnauthorizedException` / `ForbiddenException` (thrown by\n * `TenantUserAuthGuard`, `StorefrontApiKeyGuard` and the `@CurrentCustomer`\n * decorator) carry no `code` at all — only a status and English prose. Status\n * is the only stable signal there.\n */\nconst STATUS_COPY: Record<number, string> = {\n 0: \"Không thể kết nối máy chủ. Vui lòng kiểm tra kết nối mạng.\",\n 401: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n 403: \"Bạn không có quyền thực hiện thao tác này.\",\n 404: \"Không tìm thấy dữ liệu yêu cầu.\",\n 429: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n 500: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 502: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 503: \"Máy chủ đang bận. Vui lòng thử lại sau.\",\n 504: \"Máy chủ phản hồi quá lâu. Vui lòng thử lại.\",\n};\n\n/** Maps a backend error code to Vietnamese copy. */\nexport function errorCopy(\n code: string | null | undefined,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n return (code && ERROR_COPY[code]) || fallback;\n}\n\n/**\n * The same mapping for a caught throwable. `ApiClientError` (thrown by the\n * SDK's `unwrap`) carries `code` and `statusCode`; `lib/auth/context.tsx`\n * surfaces `{ message, code }`. Anything else falls through to `fallback`.\n *\n * The caught value's own `message` is deliberately never used: it is either\n * the backend's English prose or an axios internal string.\n */\nexport function errorCopyFor(\n error: unknown,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n if (!error || typeof error !== \"object\") return fallback;\n\n const { code, statusCode } = error as {\n code?: unknown;\n statusCode?: unknown;\n };\n\n if (typeof code === \"string\" && ERROR_COPY[code]) return ERROR_COPY[code];\n if (typeof statusCode === \"number\" && STATUS_COPY[statusCode]) {\n return STATUS_COPY[statusCode];\n }\n\n return fallback;\n}\n"],"mappings":"AAaO,MAAM,qBAAqB;
|
|
1
|
+
{"version":3,"sources":["../../src/auth/error-copy.ts"],"sourcesContent":["/**\n * Shopper-facing copy for backend errors.\n *\n * Project rule: backend exception messages are written in English and are\n * never shown to a shopper. The backend serialises every business error as\n * `{ code, message, details, timestamp }` (see `src/common/exceptions/` in the\n * api repo) and `code` is the stable identifier — this module is the single\n * place that turns one into Vietnamese.\n *\n * The fallback is always a generic Vietnamese sentence. Never fall back to the\n * backend's `message`.\n */\n\nexport const GENERIC_ERROR_COPY = \"Đã xảy ra lỗi. Vui lòng thử lại.\";\n\n/**\n * Keyed by the backend's stable `code`. Sources, read directly rather than\n * guessed:\n * - `AUTH_*` — `src/modules/customer-auth/domain/constants/auth.constants.ts`\n * (`AUTH_ERROR`).\n * - `ACCESS_DENIED` — `AuthorizationException.accessDenied()`, thrown by\n * `customer-addresses.controller.ts` on an address the caller does not own.\n * - `<RESOURCE>_NOT_FOUND` — `ResourceNotFoundException`, whose code is\n * `${resource.toUpperCase()}_NOT_FOUND`. `Address` and `Order` are the two\n * resources the storefront's authenticated routes can produce.\n * - `VALIDATION_FAILED` — `ValidationException`.\n * - `ORDER_NOT_CANCELLABLE` — `ORDER_ERROR.NOT_CANCELLABLE`\n * (`src/modules/orders/domain/constants/order-error.constants.ts`),\n * thrown by `OrderCancelCommandHandler` when a customer tries to cancel\n * an order outside pending/confirmed/processing.\n * - `INSUFFICIENT_INVENTORY`: `InsufficientInventoryException`\n * (`src/modules/inventory/domain/exceptions/`), thrown when an order asks\n * for more of a deny-policy variant than is available.\n * - `ORDER_PROMOTION_NOT_APPLICABLE`: `ORDER_ERROR.PROMOTION_NOT_APPLICABLE`,\n * thrown by `OrderComputationService.applyPromotionCode` when the applied\n * code can no longer be redeemed at placement (expired, used up, the cart\n * changed). `useCheckout` drops the code when it sees this.\n * - `SHIPPING_QUOTE_CHANGED` and `ORDER_SHIPPING_RATE_UNAVAILABLE`:\n * `SHIPPING_ERROR_CODES` in `@ecomweb/sdk`, returned by order creation\n * when the carrier's price moved since the quote (409, `details.options`\n * holds the new ones; `useCheckout` handles it as `quote_changed`) or the\n * chosen rate can no longer be quoted.\n * - `ORDER_CANCEL_BLOCKED_BY_SHIPMENT`: `ORDER_SHIPMENT_ERROR_CODES` in\n * `@ecomweb/sdk`, returned when a customer cancels an order whose carrier\n * shipment is already in progress.\n */\nconst ERROR_COPY: Record<string, string> = {\n AUTH_INVALID_CREDENTIALS: \"Email hoặc mật khẩu không đúng.\",\n AUTH_ACCOUNT_LOCKED: \"Quá nhiều lần thử. Vui lòng thử lại sau 15 phút.\",\n AUTH_EMAIL_NOT_VERIFIED: \"Vui lòng xác thực email của bạn trước.\",\n AUTH_METHOD_DISABLED:\n \"Phương thức đăng nhập này không khả dụng cho cửa hàng này.\",\n AUTH_TOKEN_INVALID: \"Mã xác thực không hợp lệ hoặc đã được sử dụng.\",\n AUTH_TOKEN_EXPIRED: \"Mã xác thực đã hết hạn. Vui lòng yêu cầu mã mới.\",\n AUTH_SESSION_EXPIRED: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n AUTH_WEAK_PASSWORD: \"Mật khẩu chưa đáp ứng yêu cầu của cửa hàng.\",\n AUTH_RATE_LIMITED: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n AUTH_STORE_MISMATCH:\n \"Phiên đăng nhập không thuộc cửa hàng này. Vui lòng đăng nhập lại.\",\n AUTH_EMAIL_TAKEN: \"Email này đã được sử dụng.\",\n\n ACCESS_DENIED: \"Bạn không có quyền thực hiện thao tác này.\",\n VALIDATION_FAILED: \"Thông tin chưa hợp lệ. Vui lòng kiểm tra lại.\",\n ADDRESS_NOT_FOUND: \"Không tìm thấy địa chỉ này.\",\n ORDER_NOT_FOUND: \"Không tìm thấy đơn hàng này.\",\n ORDER_NOT_CANCELLABLE: \"Đơn hàng này không thể huỷ được nữa.\",\n INSUFFICIENT_INVENTORY: \"Một số sản phẩm không đủ hàng.\",\n ORDER_PROMOTION_NOT_APPLICABLE:\n \"Mã giảm giá không còn dùng được cho đơn này nên đã được gỡ. Vui lòng kiểm tra lại tổng tiền rồi đặt hàng.\",\n SHIPPING_QUOTE_CHANGED:\n \"Phí vận chuyển đã thay đổi. Vui lòng kiểm tra lại rồi đặt hàng.\",\n ORDER_SHIPPING_RATE_UNAVAILABLE:\n \"Phương thức vận chuyển đã chọn không còn khả dụng. Vui lòng chọn lại.\",\n ORDER_CANCEL_BLOCKED_BY_SHIPMENT:\n \"Đơn đã được giao cho hãng vận chuyển, không thể huỷ. Vui lòng liên hệ cửa hàng.\",\n};\n\n/**\n * Nest's built-in `UnauthorizedException` / `ForbiddenException` (thrown by\n * `TenantUserAuthGuard`, `StorefrontApiKeyGuard` and the `@CurrentCustomer`\n * decorator) carry no `code` at all — only a status and English prose. Status\n * is the only stable signal there.\n */\nconst STATUS_COPY: Record<number, string> = {\n 0: \"Không thể kết nối máy chủ. Vui lòng kiểm tra kết nối mạng.\",\n 401: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n 403: \"Bạn không có quyền thực hiện thao tác này.\",\n 404: \"Không tìm thấy dữ liệu yêu cầu.\",\n 429: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n 500: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 502: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 503: \"Máy chủ đang bận. Vui lòng thử lại sau.\",\n 504: \"Máy chủ phản hồi quá lâu. Vui lòng thử lại.\",\n};\n\n/** Maps a backend error code to Vietnamese copy. */\nexport function errorCopy(\n code: string | null | undefined,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n return (code && ERROR_COPY[code]) || fallback;\n}\n\n/**\n * The same mapping for a caught throwable. `ApiClientError` (thrown by the\n * SDK's `unwrap`) carries `code` and `statusCode`; `lib/auth/context.tsx`\n * surfaces `{ message, code }`. Anything else falls through to `fallback`.\n *\n * The caught value's own `message` is deliberately never used: it is either\n * the backend's English prose or an axios internal string.\n */\nexport function errorCopyFor(\n error: unknown,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n if (!error || typeof error !== \"object\") return fallback;\n\n const { code, statusCode } = error as {\n code?: unknown;\n statusCode?: unknown;\n };\n\n if (typeof code === \"string\" && ERROR_COPY[code]) return ERROR_COPY[code];\n if (typeof statusCode === \"number\" && STATUS_COPY[statusCode]) {\n return STATUS_COPY[statusCode];\n }\n\n return fallback;\n}\n"],"mappings":"AAaO,MAAM,qBAAqB;AAiClC,MAAM,aAAqC;AAAA,EACzC,0BAA0B;AAAA,EAC1B,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EACzB,sBACE;AAAA,EACF,oBAAoB;AAAA,EACpB,oBAAoB;AAAA,EACpB,sBAAsB;AAAA,EACtB,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,qBACE;AAAA,EACF,kBAAkB;AAAA,EAElB,eAAe;AAAA,EACf,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,uBAAuB;AAAA,EACvB,wBAAwB;AAAA,EACxB,gCACE;AAAA,EACF,wBACE;AAAA,EACF,iCACE;AAAA,EACF,kCACE;AACJ;AAQA,MAAM,cAAsC;AAAA,EAC1C,GAAG;AAAA,EACH,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAGO,SAAS,UACd,MACA,WAAmB,oBACX;AACR,SAAQ,QAAQ,WAAW,IAAI,KAAM;AACvC;AAUO,SAAS,aACd,OACA,WAAmB,oBACX;AACR,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,QAAM,EAAE,MAAM,WAAW,IAAI;AAK7B,MAAI,OAAO,SAAS,YAAY,WAAW,IAAI,EAAG,QAAO,WAAW,IAAI;AACxE,MAAI,OAAO,eAAe,YAAY,YAAY,UAAU,GAAG;AAC7D,WAAO,YAAY,UAAU;AAAA,EAC/B;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { SHIPPING_ERROR_CODES } from "@ecomweb/sdk";
|
|
2
|
+
function quoteChangedOptionsFrom(error) {
|
|
3
|
+
if (!error || typeof error !== "object") return null;
|
|
4
|
+
const { code, details } = error;
|
|
5
|
+
if (code !== SHIPPING_ERROR_CODES.QUOTE_CHANGED) return null;
|
|
6
|
+
const raw = details?.options;
|
|
7
|
+
if (!Array.isArray(raw) || raw.length === 0) return null;
|
|
8
|
+
const valid = raw.every(
|
|
9
|
+
(o) => !!o && typeof o === "object" && typeof o.rate_id === "number" && typeof o.amount === "number"
|
|
10
|
+
);
|
|
11
|
+
return valid ? raw : null;
|
|
12
|
+
}
|
|
13
|
+
export {
|
|
14
|
+
quoteChangedOptionsFrom
|
|
15
|
+
};
|
|
16
|
+
//# sourceMappingURL=quote-changed.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/checkout/quote-changed.ts"],"sourcesContent":["import { SHIPPING_ERROR_CODES, type ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * The options the API now offers, read off a 409 SHIPPING_QUOTE_CHANGED.\n * Null for any other error, or when `details.options` is missing, empty or\n * has an entry without a numeric `rate_id` and `amount`; the caller then\n * treats it as a plain error. Duck-typed like `insufficientItemsFrom`.\n */\nexport function quoteChangedOptionsFrom(\n error: unknown\n): ShippingOption[] | null {\n if (!error || typeof error !== \"object\") return null;\n const { code, details } = error as { code?: unknown; details?: unknown };\n if (code !== SHIPPING_ERROR_CODES.QUOTE_CHANGED) return null;\n\n const raw = (details as { options?: unknown } | null | undefined)?.options;\n if (!Array.isArray(raw) || raw.length === 0) return null;\n\n const valid = raw.every(\n o =>\n !!o &&\n typeof o === \"object\" &&\n typeof (o as ShippingOption).rate_id === \"number\" &&\n typeof (o as ShippingOption).amount === \"number\"\n );\n return valid ? (raw as ShippingOption[]) : null;\n}\n"],"mappings":"AAAA,SAAS,4BAAiD;AAQnD,SAAS,wBACd,OACyB;AACzB,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,MAAI,SAAS,qBAAqB,cAAe,QAAO;AAExD,QAAM,MAAO,SAAsD;AACnE,MAAI,CAAC,MAAM,QAAQ,GAAG,KAAK,IAAI,WAAW,EAAG,QAAO;AAEpD,QAAM,QAAQ,IAAI;AAAA,IAChB,OACE,CAAC,CAAC,KACF,OAAO,MAAM,YACb,OAAQ,EAAqB,YAAY,YACzC,OAAQ,EAAqB,WAAW;AAAA,EAC5C;AACA,SAAO,QAAS,MAA2B;AAC7C;","names":[]}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
3
|
+
import {
|
|
4
|
+
SHIPPING_ERROR_CODES
|
|
5
|
+
} from "@ecomweb/sdk";
|
|
3
6
|
import { useAuth } from "../auth/context.js";
|
|
4
7
|
import { useCart } from "../cart/server-context.js";
|
|
5
8
|
import { useNotify } from "../notices.js";
|
|
@@ -14,6 +17,7 @@ import {
|
|
|
14
17
|
getPaymentRedirectIntent
|
|
15
18
|
} from "./payment-redirect.js";
|
|
16
19
|
import { startGatewayRedirect } from "./start-gateway-redirect.js";
|
|
20
|
+
import { quoteChangedOptionsFrom } from "./quote-changed.js";
|
|
17
21
|
import { insufficientItemsFrom, stockIssuesByLine } from "./stock-issues.js";
|
|
18
22
|
import { getPaymentMethod } from "./utils.js";
|
|
19
23
|
const defaultNavigateToGateway = (url) => {
|
|
@@ -22,6 +26,7 @@ const defaultNavigateToGateway = (url) => {
|
|
|
22
26
|
function useCheckout({
|
|
23
27
|
province,
|
|
24
28
|
ward,
|
|
29
|
+
includeCarrierOptions = false,
|
|
25
30
|
navigateToGateway = defaultNavigateToGateway
|
|
26
31
|
}) {
|
|
27
32
|
const store = useStoreData();
|
|
@@ -59,7 +64,8 @@ function useCheckout({
|
|
|
59
64
|
ward,
|
|
60
65
|
subtotal,
|
|
61
66
|
totalWeight,
|
|
62
|
-
itemsCount: items.length
|
|
67
|
+
itemsCount: items.length,
|
|
68
|
+
includeCarrierOptions
|
|
63
69
|
});
|
|
64
70
|
const promotionState = usePromotionValidation({
|
|
65
71
|
storeRef: store.ref,
|
|
@@ -109,7 +115,9 @@ function useCheckout({
|
|
|
109
115
|
inFlight.current = true;
|
|
110
116
|
setIsSubmitting(true);
|
|
111
117
|
setStockIssues({});
|
|
118
|
+
const quoteRequestId = shippingQuote.currentRequestId();
|
|
112
119
|
try {
|
|
120
|
+
const shippingOption = shippingQuote.selectedOption;
|
|
113
121
|
const orderData = {
|
|
114
122
|
cart_id: cartId || void 0,
|
|
115
123
|
customer_name: input.fullName,
|
|
@@ -125,10 +133,17 @@ function useCheckout({
|
|
|
125
133
|
// The shopper's choice of rate is real input; the API prices it and
|
|
126
134
|
// rejects a rate_id that isn't one it just quoted for this address
|
|
127
135
|
// and cart. useShippingCalculation clears the selection the moment an
|
|
128
|
-
// input it was quoted against changes, so this is either
|
|
129
|
-
// (omitted, the API picks) or
|
|
130
|
-
|
|
131
|
-
|
|
136
|
+
// input it was quoted against changes, so this is either nothing
|
|
137
|
+
// (omitted, the API picks) or an option from the matching quote.
|
|
138
|
+
// A carrier option also names its service and the amount the shopper
|
|
139
|
+
// saw; after a quote_changed that is the replaced amount, so the
|
|
140
|
+
// retry confirms the new price.
|
|
141
|
+
...shippingOption && {
|
|
142
|
+
shipping_rate_id: shippingOption.rate_id,
|
|
143
|
+
...shippingOption.carrier_service_id && {
|
|
144
|
+
shipping_service_id: shippingOption.carrier_service_id,
|
|
145
|
+
shipping_quoted_amount: shippingOption.amount
|
|
146
|
+
}
|
|
132
147
|
},
|
|
133
148
|
notes: input.notes || void 0,
|
|
134
149
|
promotion_id: promotionState.appliedPromotion?.id || void 0,
|
|
@@ -182,10 +197,22 @@ function useCheckout({
|
|
|
182
197
|
setStockIssues(issues);
|
|
183
198
|
return { kind: "stock_issues", issues };
|
|
184
199
|
}
|
|
200
|
+
const changed = quoteChangedOptionsFrom(error);
|
|
201
|
+
if (changed) {
|
|
202
|
+
shippingQuote.replaceOptions(
|
|
203
|
+
changed,
|
|
204
|
+
shippingQuote.selectedOptionId,
|
|
205
|
+
quoteRequestId
|
|
206
|
+
);
|
|
207
|
+
return { kind: "quote_changed" };
|
|
208
|
+
}
|
|
185
209
|
const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
186
210
|
if (code === "ORDER_PROMOTION_NOT_APPLICABLE") {
|
|
187
211
|
promotionState.removePromoCode();
|
|
188
212
|
}
|
|
213
|
+
if (code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE || code === SHIPPING_ERROR_CODES.QUOTE_CHANGED) {
|
|
214
|
+
shippingQuote.retryCalculation();
|
|
215
|
+
}
|
|
189
216
|
return {
|
|
190
217
|
kind: "error",
|
|
191
218
|
message: error instanceof Error ? error.message : String(error),
|
|
@@ -221,7 +248,11 @@ function useCheckout({
|
|
|
221
248
|
isCalculating: shippingQuote.isCalculatingShipping,
|
|
222
249
|
hasCalculated: shippingQuote.hasCalculatedShipping,
|
|
223
250
|
calculationFailed: shippingQuote.calculationFailed,
|
|
251
|
+
/** @deprecated Use selectOption. */
|
|
224
252
|
selectRate: shippingQuote.handleShippingRateSelect,
|
|
253
|
+
selectedOptionId: shippingQuote.selectedOptionId,
|
|
254
|
+
selectedOption: shippingQuote.selectedOption,
|
|
255
|
+
selectOption: shippingQuote.handleShippingOptionSelect,
|
|
225
256
|
retry: shippingQuote.retryCalculation
|
|
226
257
|
},
|
|
227
258
|
promotion: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { PaymentMethod, StorePaymentMethod } from \"@ecomweb/sdk\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n\n try {\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either null\n // (omitted, the API picks) or a rate from the matching quote.\n ...(shippingQuote.selectedShippingRate && {\n shipping_rate_id: shippingQuote.selectedShippingRate,\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown. Keeping the code would fail every retry the same way.\n if (code === \"ORDER_PROMOTION_NOT_APPLICABLE\") {\n promotionState.removePromoCode();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n selectRate: shippingQuote.handleShippingRateSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AA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,EACF,GAAG,CAAC,eAAe,UAAU,CAAC;AAEhC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU;AAAA,MACR,KAAK,cAAc;AAAA,MACnB,SAAS,cAAc;AAAA,MACvB,cAAc,cAAc;AAAA,MAC5B,eAAe,cAAc;AAAA,MAC7B,eAAe,cAAc;AAAA,MAC7B,mBAAmB,cAAc;AAAA,MACjC,YAAY,cAAc;AAAA,MAC1B,OAAO,cAAc;AAAA,IACvB;AAAA,IACA,WAAW;AAAA,MACT,MAAM,eAAe;AAAA,MACrB,SAAS,eAAe;AAAA,MACxB,SAAS,eAAe;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,cAAc,eAAe;AAAA,MAC7B,OAAO,eAAe;AAAA,MACtB,UAAU,eAAe;AAAA,MACzB,QAAQ,eAAe;AAAA,MACvB,iBAAiB,eAAe;AAAA,IAClC;AAAA;AAAA;AAAA,IAGA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,cAAc;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown. Keeping the code would fail every retry the same way.\n if (code === \"ORDER_PROMOTION_NOT_APPLICABLE\") {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,8BAA8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.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
|
2
2
|
import * as react from 'react';
|
|
3
3
|
import { ReactNode, ReactElement } from 'react';
|
|
4
4
|
import * as _ecomweb_sdk from '@ecomweb/sdk';
|
|
5
|
-
import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, OrderStatus, Order, CreateOrderRequest, LocationAreasResponse, LocationArea, StoreConfig, ThemeValues, WithMetafields, StorefrontMetafields, ResolvedMetaobjectRef, ResolvedMetaobjectStub, StorefrontMetaobjectEntry, MetaobjectListParams, MetaobjectListResult, RichTextRoot } from '@ecomweb/sdk';
|
|
5
|
+
import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, ShippingOption, OrderStatus, Order, CreateOrderRequest, ShipmentStatus, OrderShipmentSummary, LocationAreasResponse, LocationArea, StoreConfig, ThemeValues, WithMetafields, StorefrontMetafields, ResolvedMetaobjectRef, ResolvedMetaobjectStub, StorefrontMetaobjectEntry, MetaobjectListParams, MetaobjectListResult, RichTextRoot } from '@ecomweb/sdk';
|
|
6
6
|
import currencyJs from 'currency.js';
|
|
7
7
|
import { AxiosRequestConfig, AxiosInstance } from 'axios';
|
|
8
8
|
export { AnyThemeDefinition, BlogIndexSlotProps, BlogPostSlotProps, CollectionPageSlotProps, CollectionSearchParams, ContentPageSlotProps, HomePageSlotProps, LayoutSlotProps, NotFoundProps, ProductCardProps, ProductPageSlotProps, ThemeClientComponents, ThemeComponents, ThemeDefinition, ThemeInfo, ThemeSlot, ThemeSlotName, ThemeSlotProps, defineSchema, defineTheme } from './theme.js';
|
|
@@ -151,6 +151,9 @@ interface PlacedOrder {
|
|
|
151
151
|
* one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied
|
|
152
152
|
* code has already been removed, so the shopper sees the real total before
|
|
153
153
|
* placing again.
|
|
154
|
+
* - quote_changed: nothing was placed; the shipping options were replaced with
|
|
155
|
+
* the API's new prices and the selection kept where possible; show
|
|
156
|
+
* `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.
|
|
154
157
|
* - busy: an earlier placeOrder is still running; this call did nothing.
|
|
155
158
|
*/
|
|
156
159
|
type PlaceOrderResult = {
|
|
@@ -168,6 +171,8 @@ type PlaceOrderResult = {
|
|
|
168
171
|
kind: "error";
|
|
169
172
|
message: string;
|
|
170
173
|
code?: string;
|
|
174
|
+
} | {
|
|
175
|
+
kind: "quote_changed";
|
|
171
176
|
} | {
|
|
172
177
|
kind: "busy";
|
|
173
178
|
};
|
|
@@ -175,6 +180,11 @@ interface UseCheckoutOptions {
|
|
|
175
180
|
/** The address fields shipping is quoted against (codes, may be empty). */
|
|
176
181
|
province: string;
|
|
177
182
|
ward: string;
|
|
183
|
+
/**
|
|
184
|
+
* Ask the API for carrier-quoted shipping options too. Off by default;
|
|
185
|
+
* passed to `useShippingCalculation`.
|
|
186
|
+
*/
|
|
187
|
+
includeCarrierOptions?: boolean;
|
|
178
188
|
/** Leaves for the payment provider; defaults to a full-page navigation. */
|
|
179
189
|
navigateToGateway?: (url: string) => void;
|
|
180
190
|
}
|
|
@@ -183,7 +193,7 @@ interface UseCheckoutOptions {
|
|
|
183
193
|
* totals, placing the order and the payment-provider hand-off. The app
|
|
184
194
|
* renders the form and decides what to show for each PlaceOrderResult.
|
|
185
195
|
*/
|
|
186
|
-
declare function useCheckout({ province, ward, navigateToGateway, }: UseCheckoutOptions): {
|
|
196
|
+
declare function useCheckout({ province, ward, includeCarrierOptions, navigateToGateway, }: UseCheckoutOptions): {
|
|
187
197
|
items: CartItem[];
|
|
188
198
|
isCartLoading: boolean;
|
|
189
199
|
paymentMethods: StorePaymentMethod[];
|
|
@@ -195,7 +205,11 @@ declare function useCheckout({ province, ward, navigateToGateway, }: UseCheckout
|
|
|
195
205
|
isCalculating: boolean;
|
|
196
206
|
hasCalculated: boolean;
|
|
197
207
|
calculationFailed: boolean;
|
|
208
|
+
/** @deprecated Use selectOption. */
|
|
198
209
|
selectRate: (rateId: number) => void;
|
|
210
|
+
selectedOptionId: string | null;
|
|
211
|
+
selectedOption: _ecomweb_sdk.ShippingOption | null;
|
|
212
|
+
selectOption: (optionId: string) => void;
|
|
199
213
|
retry: () => Promise<void>;
|
|
200
214
|
};
|
|
201
215
|
promotion: {
|
|
@@ -640,6 +654,21 @@ declare function pollPaymentState(options: PollPaymentStateOptions): Promise<Pol
|
|
|
640
654
|
*/
|
|
641
655
|
declare function getPaymentState(storeRef: string, order_code: string): Promise<PaymentStateResult>;
|
|
642
656
|
|
|
657
|
+
/**
|
|
658
|
+
* The options the API now offers, read off a 409 SHIPPING_QUOTE_CHANGED.
|
|
659
|
+
* Null for any other error, or when `details.options` is missing, empty or
|
|
660
|
+
* has an entry without a numeric `rate_id` and `amount`; the caller then
|
|
661
|
+
* treats it as a plain error. Duck-typed like `insufficientItemsFrom`.
|
|
662
|
+
*/
|
|
663
|
+
declare function quoteChangedOptionsFrom(error: unknown): ShippingOption[] | null;
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* The stable identity of a shipping option. Carrier-backed rates can offer
|
|
667
|
+
* several options under one `rate_id`, so the API sends `option_id`; older
|
|
668
|
+
* APIs don't, and `rate_id` alone is unique there.
|
|
669
|
+
*/
|
|
670
|
+
declare function optionIdOf(option: ShippingOption): string;
|
|
671
|
+
|
|
643
672
|
/**
|
|
644
673
|
* Turns the API's 409 INSUFFICIENT_INVENTORY into per-line shopper copy.
|
|
645
674
|
*
|
|
@@ -673,6 +702,44 @@ declare const publicOrdersApi: {
|
|
|
673
702
|
createStoreOrder(storeRef: string, data: Omit<CreateOrderRequest, "store_id">, isAuth: boolean): Promise<OrderWithItems>;
|
|
674
703
|
};
|
|
675
704
|
|
|
705
|
+
/** The API's SHIPMENT_STATUS_LABEL_VI, copied exactly so badge and events agree. */
|
|
706
|
+
declare const SHIPMENT_STATUS_LABELS: Record<ShipmentStatus, string>;
|
|
707
|
+
declare const TRACKING_MESSAGES: {
|
|
708
|
+
readonly title: "Vận chuyển";
|
|
709
|
+
readonly trackingNumber: "Mã vận đơn";
|
|
710
|
+
readonly trackLink: "Theo dõi đơn hàng";
|
|
711
|
+
readonly handedToCarrier: "Đơn đã được giao cho hãng vận chuyển";
|
|
712
|
+
readonly noEvents: "Chưa có cập nhật từ hãng vận chuyển";
|
|
713
|
+
readonly eventFallback: "Cập nhật vận chuyển";
|
|
714
|
+
};
|
|
715
|
+
interface ShipmentTrackingView {
|
|
716
|
+
carrierName: string | null;
|
|
717
|
+
carrierLogoUrl: string | null;
|
|
718
|
+
serviceName: string | null;
|
|
719
|
+
trackingNumber: string | null;
|
|
720
|
+
trackLink: string | null;
|
|
721
|
+
statusLabel: string | null;
|
|
722
|
+
events: OrderShipmentSummary["events"];
|
|
723
|
+
}
|
|
724
|
+
declare function deriveShipmentTracking(order: Order): ShipmentTrackingView | null;
|
|
725
|
+
declare function canCustomerCancel(order: Order): boolean;
|
|
726
|
+
declare function isHandedToCarrier(order: Order): boolean;
|
|
727
|
+
/**
|
|
728
|
+
* True only for a carrier-booked shipment. The API also sends `order.shipment`
|
|
729
|
+
* for a manual shipment (carrier and tracking number typed by the merchant),
|
|
730
|
+
* with `status: null` and no events; that one has no carrier timeline to show.
|
|
731
|
+
*/
|
|
732
|
+
declare function isCarrierShipment(order: Order): boolean;
|
|
733
|
+
/**
|
|
734
|
+
* The text of one tracking event. A blank label falls back to the event's own
|
|
735
|
+
* status label when it carries a known one, else to neutral copy -- never the
|
|
736
|
+
* shipment's current status, which is not what that event reported.
|
|
737
|
+
*/
|
|
738
|
+
declare function shipmentEventLabel(event: {
|
|
739
|
+
label?: string | null;
|
|
740
|
+
status?: string | null;
|
|
741
|
+
}): string;
|
|
742
|
+
|
|
676
743
|
type CreatedOrder = Awaited<ReturnType<typeof publicOrdersApi.createStoreOrder>>;
|
|
677
744
|
interface OrderSuccessInfo {
|
|
678
745
|
order: CreatedOrder;
|
|
@@ -778,6 +845,18 @@ declare function createStoreSdk(storeRef: string): {
|
|
|
778
845
|
* plain vitest spec.
|
|
779
846
|
*/
|
|
780
847
|
declare function formatShippingAmount(amount: number, freeLabel: string, locale: string, currency: SupportedCurrency | string): string;
|
|
848
|
+
interface ShippingOptionDisplay {
|
|
849
|
+
title: string;
|
|
850
|
+
carrierName: string | null;
|
|
851
|
+
carrierLogoUrl: string | null;
|
|
852
|
+
eta: string | null;
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* What an option row shows: title, carrier (when carrier-quoted) and an ETA.
|
|
856
|
+
* The carrier's own label wins over the fixed-rate day range. The carrier
|
|
857
|
+
* line names the service too: one carrier can offer several at one price.
|
|
858
|
+
*/
|
|
859
|
+
declare function describeShippingOption(option: ShippingOption): ShippingOptionDisplay;
|
|
781
860
|
|
|
782
861
|
/**
|
|
783
862
|
* Location data is fetched in two steps rather than all at once: the 34
|
|
@@ -830,6 +909,8 @@ declare const SHIPPING_MESSAGES: Readonly<{
|
|
|
830
909
|
failedHint: "Kết nối có thể đang gián đoạn. Vui lòng thử lại.";
|
|
831
910
|
retry: "Thử lại";
|
|
832
911
|
free: "Miễn phí";
|
|
912
|
+
quoteChanged: "Phí vận chuyển đã thay đổi";
|
|
913
|
+
quoteChangedHint: "Vui lòng kiểm tra lại phí vận chuyển mới rồi đặt hàng.";
|
|
833
914
|
estimate: "Dự kiến giao: {min} đến {max} ngày";
|
|
834
915
|
}>;
|
|
835
916
|
/** Fills in the `{min}`/`{max}` placeholders in `SHIPPING_MESSAGES.estimate`. */
|
|
@@ -1087,4 +1168,4 @@ declare function getLogLevel(): LogLevel;
|
|
|
1087
1168
|
declare function shouldLog(currentLevel: LogLevel, messageLevel: LogLevel): boolean;
|
|
1088
1169
|
declare function applyConsoleFilter(level?: LogLevel): void;
|
|
1089
1170
|
|
|
1090
|
-
export { type BankAccountView, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderHandoffSummary, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, RichText, type RichTextProps, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, SUSPENDED_STORE_METADATA, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, THEME_PREVIEW_FRAME_ATTR, THEME_PREVIEW_MESSAGE, ThemePreviewBridge, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, createStoreSdk, deriveOrderProgress, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getMetaobject, getMetaobjects, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isStoreSuspendedError, loadWards, metafield, metaobjectField, money, pollPaymentState, publicApiClient, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOptionalThemeId, useOptionalThemeKey, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
|
|
1171
|
+
export { type BankAccountView, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderHandoffSummary, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, RichText, type RichTextProps, SHIPMENT_STATUS_LABELS, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, SUSPENDED_STORE_METADATA, type ShipmentTrackingView, type ShippingOptionDisplay, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, THEME_PREVIEW_FRAME_ATTR, THEME_PREVIEW_MESSAGE, TRACKING_MESSAGES, ThemePreviewBridge, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, canCustomerCancel, createStoreSdk, deriveOrderProgress, deriveShipmentTracking, describeShippingOption, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getMetaobject, getMetaobjects, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isCarrierShipment, isHandedToCarrier, isStoreSuspendedError, loadWards, metafield, metaobjectField, money, optionIdOf, pollPaymentState, publicApiClient, quoteChangedOptionsFrom, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shipmentEventLabel, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOptionalThemeId, useOptionalThemeKey, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
|
package/dist/index.js
CHANGED
|
@@ -24,6 +24,8 @@ import { useCart } from "./cart/server-context.js";
|
|
|
24
24
|
import { getPaymentState } from "./checkout/get-payment-state.js";
|
|
25
25
|
import { readOrderHandoff } from "./checkout/order-handoff.js";
|
|
26
26
|
import { pollPaymentState } from "./checkout/payment-state-poll.js";
|
|
27
|
+
import { quoteChangedOptionsFrom } from "./checkout/quote-changed.js";
|
|
28
|
+
import { optionIdOf } from "./shipping/option-id.js";
|
|
27
29
|
import { STOCK_ISSUE_TOAST_DESCRIPTION } from "./checkout/stock-issues.js";
|
|
28
30
|
import {
|
|
29
31
|
resolveInitialState,
|
|
@@ -42,9 +44,21 @@ import {
|
|
|
42
44
|
deriveOrderProgress
|
|
43
45
|
} from "./orders/derive-progress.js";
|
|
44
46
|
import { STATUS_OPTIONS } from "./orders/types.js";
|
|
47
|
+
import {
|
|
48
|
+
SHIPMENT_STATUS_LABELS,
|
|
49
|
+
TRACKING_MESSAGES,
|
|
50
|
+
canCustomerCancel,
|
|
51
|
+
deriveShipmentTracking,
|
|
52
|
+
isCarrierShipment,
|
|
53
|
+
isHandedToCarrier,
|
|
54
|
+
shipmentEventLabel
|
|
55
|
+
} from "./orders/shipment-tracking.js";
|
|
45
56
|
import { getPromotionDescription } from "./promotions/utils.js";
|
|
46
57
|
import { createStoreSdk, sdk } from "./sdk.js";
|
|
47
|
-
import {
|
|
58
|
+
import {
|
|
59
|
+
formatShippingAmount,
|
|
60
|
+
describeShippingOption
|
|
61
|
+
} from "./shipping/format-shipping-option.js";
|
|
48
62
|
import {
|
|
49
63
|
loadWards,
|
|
50
64
|
searchTextFor,
|
|
@@ -94,6 +108,7 @@ export {
|
|
|
94
108
|
DEFAULT_REDIRECT,
|
|
95
109
|
ORDER_PROGRESS_STEPS,
|
|
96
110
|
RichText,
|
|
111
|
+
SHIPMENT_STATUS_LABELS,
|
|
97
112
|
SHIPPING_MESSAGES,
|
|
98
113
|
STATUS_OPTIONS,
|
|
99
114
|
STOCK_ISSUE_TOAST_DESCRIPTION,
|
|
@@ -101,15 +116,19 @@ export {
|
|
|
101
116
|
StorefrontKitProvider,
|
|
102
117
|
THEME_PREVIEW_FRAME_ATTR,
|
|
103
118
|
THEME_PREVIEW_MESSAGE,
|
|
119
|
+
TRACKING_MESSAGES,
|
|
104
120
|
ThemePreviewBridge,
|
|
105
121
|
ThemeSettingsProvider,
|
|
106
122
|
ThemeStyle,
|
|
107
123
|
applyConsoleFilter,
|
|
108
124
|
buildStoreUrl,
|
|
125
|
+
canCustomerCancel,
|
|
109
126
|
createStoreSdk,
|
|
110
127
|
defineSchema,
|
|
111
128
|
defineTheme,
|
|
112
129
|
deriveOrderProgress,
|
|
130
|
+
deriveShipmentTracking,
|
|
131
|
+
describeShippingOption,
|
|
113
132
|
errorCopy,
|
|
114
133
|
errorCopyFor,
|
|
115
134
|
findProvinceByCodeOrName,
|
|
@@ -128,13 +147,17 @@ export {
|
|
|
128
147
|
getPasswordPolicyHints,
|
|
129
148
|
getPaymentState,
|
|
130
149
|
getPromotionDescription,
|
|
150
|
+
isCarrierShipment,
|
|
151
|
+
isHandedToCarrier,
|
|
131
152
|
isStoreSuspendedError,
|
|
132
153
|
loadWards,
|
|
133
154
|
metafield,
|
|
134
155
|
metaobjectField,
|
|
135
156
|
money,
|
|
157
|
+
optionIdOf,
|
|
136
158
|
pollPaymentState,
|
|
137
159
|
publicApiClient,
|
|
160
|
+
quoteChangedOptionsFrom,
|
|
138
161
|
readBasicSettings,
|
|
139
162
|
readOrderHandoff,
|
|
140
163
|
refFromPathname,
|
|
@@ -148,6 +171,7 @@ export {
|
|
|
148
171
|
safeRedirectPath,
|
|
149
172
|
sdk,
|
|
150
173
|
searchTextFor,
|
|
174
|
+
shipmentEventLabel,
|
|
151
175
|
shouldLog,
|
|
152
176
|
shouldPollForConfirmation,
|
|
153
177
|
storeApiPath,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport {
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { quoteChangedOptionsFrom } from \"./checkout/quote-changed\";\nexport { optionIdOf } from \"./shipping/option-id\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./orders/shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./orders/shipment-tracking\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport {\n formatShippingAmount,\n describeShippingOption,\n type ShippingOptionDisplay,\n} from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n BlogIndexSlotProps,\n BlogPostSlotProps,\n CollectionPageSlotProps,\n CollectionSearchParams,\n ContentPageSlotProps,\n NotFoundProps,\n ProductCardProps,\n ProductPageSlotProps,\n ThemeClientComponents,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useOptionalThemeId,\n useOptionalThemeKey,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport {\n THEME_PREVIEW_FRAME_ATTR,\n THEME_PREVIEW_MESSAGE,\n ThemePreviewBridge,\n} from \"./theme/preview-bridge\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAS/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,QAAQ,oBAAoB;AACrC,SAAS,eAAe;AACxB,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAKjC,SAAS,wBAAwB;AACjC,SAAS,+BAA+B;AACxC,SAAS,kBAAkB;AAC3B,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,cAAc,iBAAiB;AACzD,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,cAAc,mBAAmB;AAqB1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAW,uBAAuB;AAC3C,SAAS,eAAe,sBAAsB;AAC9C,SAAS,gBAAgB;AAEzB,SAAS,YAAY,qBAAqB;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
|
package/dist/orders/index.js
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
export * from "./types.js";
|
|
2
2
|
import { publicOrdersApi } from "./api-client.js";
|
|
3
|
+
import {
|
|
4
|
+
SHIPMENT_STATUS_LABELS,
|
|
5
|
+
TRACKING_MESSAGES,
|
|
6
|
+
canCustomerCancel,
|
|
7
|
+
deriveShipmentTracking,
|
|
8
|
+
isCarrierShipment,
|
|
9
|
+
isHandedToCarrier,
|
|
10
|
+
shipmentEventLabel
|
|
11
|
+
} from "./shipment-tracking.js";
|
|
3
12
|
export {
|
|
4
|
-
|
|
13
|
+
SHIPMENT_STATUS_LABELS,
|
|
14
|
+
TRACKING_MESSAGES,
|
|
15
|
+
canCustomerCancel,
|
|
16
|
+
deriveShipmentTracking,
|
|
17
|
+
isCarrierShipment,
|
|
18
|
+
isHandedToCarrier,
|
|
19
|
+
publicOrdersApi,
|
|
20
|
+
shipmentEventLabel
|
|
5
21
|
};
|
|
6
22
|
//# sourceMappingURL=index.js.map
|
package/dist/orders/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/orders/index.ts"],"sourcesContent":["// Orders API - Pure API Client Architecture\n// Store-based objects pattern - All operations are store-scoped\n// All operations use backend API exclusively - no direct database calls\n// Supabase used only for auth and storage\n\n// Types (sourced from consolidated interface as single source of truth)\nexport * from \"./types\";\n\n// API Clients (store-scoped operations)\nexport { publicOrdersApi } from \"./api-client\";\n"],"mappings":"AAMA,cAAc;AAGd,SAAS,uBAAuB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/orders/index.ts"],"sourcesContent":["// Orders API - Pure API Client Architecture\n// Store-based objects pattern - All operations are store-scoped\n// All operations use backend API exclusively - no direct database calls\n// Supabase used only for auth and storage\n\n// Types (sourced from consolidated interface as single source of truth)\nexport * from \"./types\";\n\n// API Clients (store-scoped operations)\nexport { publicOrdersApi } from \"./api-client\";\n\n// Shipment tracking view and customer cancel rule\nexport {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./shipment-tracking\";\n"],"mappings":"AAMA,cAAc;AAGd,SAAS,uBAAuB;AAGhC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":[]}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
const SHIPMENT_STATUS_LABELS = {
|
|
2
|
+
booked: "\u0110\xE3 t\u1EA1o v\u1EADn \u0111\u01A1n",
|
|
3
|
+
picked_up: "\u0110\xE3 l\u1EA5y h\xE0ng",
|
|
4
|
+
in_transit: "\u0110ang v\u1EADn chuy\u1EC3n",
|
|
5
|
+
out_for_delivery: "\u0110ang giao h\xE0ng",
|
|
6
|
+
delivered: "\u0110\xE3 giao",
|
|
7
|
+
failed: "Giao h\xE0ng th\u1EA5t b\u1EA1i",
|
|
8
|
+
returned: "\u0110\xE3 ho\xE0n h\xE0ng",
|
|
9
|
+
cancelled: "\u0110\xE3 h\u1EE7y"
|
|
10
|
+
};
|
|
11
|
+
const TRACKING_MESSAGES = {
|
|
12
|
+
title: "V\u1EADn chuy\u1EC3n",
|
|
13
|
+
trackingNumber: "M\xE3 v\u1EADn \u0111\u01A1n",
|
|
14
|
+
trackLink: "Theo d\xF5i \u0111\u01A1n h\xE0ng",
|
|
15
|
+
handedToCarrier: "\u0110\u01A1n \u0111\xE3 \u0111\u01B0\u1EE3c giao cho h\xE3ng v\u1EADn chuy\u1EC3n",
|
|
16
|
+
noEvents: "Ch\u01B0a c\xF3 c\u1EADp nh\u1EADt t\u1EEB h\xE3ng v\u1EADn chuy\u1EC3n",
|
|
17
|
+
eventFallback: "C\u1EADp nh\u1EADt v\u1EADn chuy\u1EC3n"
|
|
18
|
+
};
|
|
19
|
+
const CANCELLABLE_STATUSES = ["pending", "confirmed", "processing"];
|
|
20
|
+
const ENDED_STATUSES = ["cancelled", "failed", "returned"];
|
|
21
|
+
function httpLinkOrNull(link) {
|
|
22
|
+
return link && /^https?:\/\//i.test(link.trim()) ? link.trim() : null;
|
|
23
|
+
}
|
|
24
|
+
function labelOrNull(status) {
|
|
25
|
+
if (!status) return null;
|
|
26
|
+
return Object.prototype.hasOwnProperty.call(SHIPMENT_STATUS_LABELS, status) ? SHIPMENT_STATUS_LABELS[status] : null;
|
|
27
|
+
}
|
|
28
|
+
function deriveShipmentTracking(order) {
|
|
29
|
+
const shipment = order.shipment;
|
|
30
|
+
if (shipment === null) return null;
|
|
31
|
+
if (shipment) {
|
|
32
|
+
return {
|
|
33
|
+
carrierName: shipment.carrier_name ?? null,
|
|
34
|
+
carrierLogoUrl: httpLinkOrNull(shipment.carrier_logo_url),
|
|
35
|
+
serviceName: shipment.service_name ?? null,
|
|
36
|
+
trackingNumber: shipment.tracking_number ?? null,
|
|
37
|
+
trackLink: httpLinkOrNull(shipment.track_link),
|
|
38
|
+
statusLabel: labelOrNull(shipment.status),
|
|
39
|
+
events: shipment.events ?? []
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
if (order.shipping_carrier || order.tracking_number) {
|
|
43
|
+
return {
|
|
44
|
+
carrierName: order.shipping_carrier ?? null,
|
|
45
|
+
carrierLogoUrl: null,
|
|
46
|
+
serviceName: null,
|
|
47
|
+
trackingNumber: order.tracking_number ?? null,
|
|
48
|
+
trackLink: null,
|
|
49
|
+
statusLabel: null,
|
|
50
|
+
events: []
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
function canCustomerCancel(order) {
|
|
56
|
+
if (typeof order.can_cancel === "boolean") return order.can_cancel;
|
|
57
|
+
return CANCELLABLE_STATUSES.includes(order.order_status);
|
|
58
|
+
}
|
|
59
|
+
function isHandedToCarrier(order) {
|
|
60
|
+
const status = order.shipment?.status;
|
|
61
|
+
return !!status && !ENDED_STATUSES.includes(status);
|
|
62
|
+
}
|
|
63
|
+
function isCarrierShipment(order) {
|
|
64
|
+
return order.shipment?.status != null;
|
|
65
|
+
}
|
|
66
|
+
function shipmentEventLabel(event) {
|
|
67
|
+
const label = event.label?.trim();
|
|
68
|
+
if (label) return label;
|
|
69
|
+
return labelOrNull(event.status) ?? TRACKING_MESSAGES.eventFallback;
|
|
70
|
+
}
|
|
71
|
+
export {
|
|
72
|
+
SHIPMENT_STATUS_LABELS,
|
|
73
|
+
TRACKING_MESSAGES,
|
|
74
|
+
canCustomerCancel,
|
|
75
|
+
deriveShipmentTracking,
|
|
76
|
+
isCarrierShipment,
|
|
77
|
+
isHandedToCarrier,
|
|
78
|
+
shipmentEventLabel
|
|
79
|
+
};
|
|
80
|
+
//# sourceMappingURL=shipment-tracking.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/orders/shipment-tracking.ts"],"sourcesContent":["import type { Order, OrderShipmentSummary, ShipmentStatus } from \"@ecomweb/sdk\";\n\n/** The API's SHIPMENT_STATUS_LABEL_VI, copied exactly so badge and events agree. */\nexport const SHIPMENT_STATUS_LABELS: Record<ShipmentStatus, string> = {\n booked: \"Đã tạo vận đơn\",\n picked_up: \"Đã lấy hàng\",\n in_transit: \"Đang vận chuyển\",\n out_for_delivery: \"Đang giao hàng\",\n delivered: \"Đã giao\",\n failed: \"Giao hàng thất bại\",\n returned: \"Đã hoàn hàng\",\n cancelled: \"Đã hủy\",\n};\n\nexport const TRACKING_MESSAGES = {\n title: \"Vận chuyển\",\n trackingNumber: \"Mã vận đơn\",\n trackLink: \"Theo dõi đơn hàng\",\n handedToCarrier: \"Đơn đã được giao cho hãng vận chuyển\",\n noEvents: \"Chưa có cập nhật từ hãng vận chuyển\",\n eventFallback: \"Cập nhật vận chuyển\",\n} as const;\n\nexport interface ShipmentTrackingView {\n carrierName: string | null;\n carrierLogoUrl: string | null;\n serviceName: string | null;\n trackingNumber: string | null;\n trackLink: string | null;\n statusLabel: string | null;\n events: OrderShipmentSummary[\"events\"];\n}\n\nconst CANCELLABLE_STATUSES = [\"pending\", \"confirmed\", \"processing\"];\nconst ENDED_STATUSES: string[] = [\"cancelled\", \"failed\", \"returned\"];\n\nfunction httpLinkOrNull(link: string | null | undefined): string | null {\n return link && /^https?:\\/\\//i.test(link.trim()) ? link.trim() : null;\n}\n\nfunction labelOrNull(status: string | null | undefined): string | null {\n if (!status) return null;\n return Object.prototype.hasOwnProperty.call(SHIPMENT_STATUS_LABELS, status)\n ? SHIPMENT_STATUS_LABELS[status as ShipmentStatus]\n : null;\n}\n\nexport function deriveShipmentTracking(\n order: Order,\n): ShipmentTrackingView | null {\n const shipment = order.shipment;\n // An explicit `shipment: null` means the API decided there is nothing to show\n // (e.g. a cancelled waybill); the order's own fields are only a fallback for\n // an older API that does not send `shipment` at all.\n if (shipment === null) return null;\n if (shipment) {\n return {\n carrierName: shipment.carrier_name ?? null,\n carrierLogoUrl: httpLinkOrNull(shipment.carrier_logo_url),\n serviceName: shipment.service_name ?? null,\n trackingNumber: shipment.tracking_number ?? null,\n trackLink: httpLinkOrNull(shipment.track_link),\n statusLabel: labelOrNull(shipment.status),\n events: shipment.events ?? [],\n };\n }\n if (order.shipping_carrier || order.tracking_number) {\n return {\n carrierName: order.shipping_carrier ?? null,\n carrierLogoUrl: null,\n serviceName: null,\n trackingNumber: order.tracking_number ?? null,\n trackLink: null,\n statusLabel: null,\n events: [],\n };\n }\n return null;\n}\n\nexport function canCustomerCancel(order: Order): boolean {\n if (typeof order.can_cancel === \"boolean\") return order.can_cancel;\n return CANCELLABLE_STATUSES.includes(order.order_status);\n}\n\nexport function isHandedToCarrier(order: Order): boolean {\n const status = order.shipment?.status;\n return !!status && !ENDED_STATUSES.includes(status);\n}\n\n/**\n * True only for a carrier-booked shipment. The API also sends `order.shipment`\n * for a manual shipment (carrier and tracking number typed by the merchant),\n * with `status: null` and no events; that one has no carrier timeline to show.\n */\nexport function isCarrierShipment(order: Order): boolean {\n return order.shipment?.status != null;\n}\n\n/**\n * The text of one tracking event. A blank label falls back to the event's own\n * status label when it carries a known one, else to neutral copy -- never the\n * shipment's current status, which is not what that event reported.\n */\nexport function shipmentEventLabel(event: {\n label?: string | null;\n status?: string | null;\n}): string {\n const label = event.label?.trim();\n if (label) return label;\n return labelOrNull(event.status) ?? TRACKING_MESSAGES.eventFallback;\n}\n"],"mappings":"AAGO,MAAM,yBAAyD;AAAA,EACpE,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,QAAQ;AAAA,EAC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,qBAAqB,SAAS,MAAM,YAAY;AACzD;AAEO,SAAS,kBAAkB,OAAuB;AACvD,QAAM,SAAS,MAAM,UAAU;AAC/B,SAAO,CAAC,CAAC,UAAU,CAAC,eAAe,SAAS,MAAM;AACpD;AAOO,SAAS,kBAAkB,OAAuB;AACvD,SAAO,MAAM,UAAU,UAAU;AACnC;AAOO,SAAS,mBAAmB,OAGxB;AACT,QAAM,QAAQ,MAAM,OAAO,KAAK;AAChC,MAAI,MAAO,QAAO;AAClB,SAAO,YAAY,MAAM,MAAM,KAAK,kBAAkB;AACxD;","names":[]}
|
|
@@ -1,11 +1,39 @@
|
|
|
1
1
|
import { formatPrice } from "../currency.js";
|
|
2
|
+
import { formatShippingEstimate } from "./messages.js";
|
|
2
3
|
function isFreeShippingRate(amount) {
|
|
3
4
|
return amount === 0;
|
|
4
5
|
}
|
|
5
6
|
function formatShippingAmount(amount, freeLabel, locale, currency) {
|
|
6
7
|
return isFreeShippingRate(amount) ? freeLabel : formatPrice(amount, locale, currency);
|
|
7
8
|
}
|
|
9
|
+
function safeHttpUrl(url) {
|
|
10
|
+
if (!url) return null;
|
|
11
|
+
try {
|
|
12
|
+
const { protocol } = new URL(url);
|
|
13
|
+
return protocol === "http:" || protocol === "https:" ? url : null;
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function describeShippingOption(option) {
|
|
19
|
+
let eta = null;
|
|
20
|
+
if (option.estimated_label) {
|
|
21
|
+
eta = option.estimated_label;
|
|
22
|
+
} else if (option.estimated_days_min != null) {
|
|
23
|
+
eta = formatShippingEstimate(
|
|
24
|
+
option.estimated_days_min,
|
|
25
|
+
option.estimated_days_max ?? option.estimated_days_min
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
title: option.display_name,
|
|
30
|
+
carrierName: option.carrier_name ? [option.carrier_name, option.carrier_service_name].filter(Boolean).join(" \xB7 ") : null,
|
|
31
|
+
carrierLogoUrl: safeHttpUrl(option.carrier_logo_url),
|
|
32
|
+
eta
|
|
33
|
+
};
|
|
34
|
+
}
|
|
8
35
|
export {
|
|
36
|
+
describeShippingOption,
|
|
9
37
|
formatShippingAmount,
|
|
10
38
|
isFreeShippingRate
|
|
11
39
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/shipping/format-shipping-option.ts"],"sourcesContent":["import { formatPrice, type SupportedCurrency } from \"../currency\";\n\n/**\n * A free shipping rate is a VALUE comparison (amount === 0), not a rate\n * type the API tags for us. There is no \"FREE\" rate_type in the shipping\n * vocabulary on purpose — see @ecomweb/sdk's shipping types.\n */\nexport function isFreeShippingRate(amount: number): boolean {\n return amount === 0;\n}\n\n/**\n * Renders a shipping option's price for display: the free label when the\n * rate is free, the house money format otherwise.\n *\n * `freeLabel` is passed in (see lib/shipping/messages.ts) rather than\n * hardcoded here, so this stays a pure, generic function reachable from a\n * plain vitest spec.\n */\nexport function formatShippingAmount(\n amount: number,\n freeLabel: string,\n locale: string,\n currency: SupportedCurrency | string\n): string {\n return isFreeShippingRate(amount)\n ? freeLabel\n : formatPrice(amount, locale, currency);\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/shipping/format-shipping-option.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\nimport { formatPrice, type SupportedCurrency } from \"../currency\";\nimport { formatShippingEstimate } from \"./messages\";\n\n/**\n * A free shipping rate is a VALUE comparison (amount === 0), not a rate\n * type the API tags for us. There is no \"FREE\" rate_type in the shipping\n * vocabulary on purpose — see @ecomweb/sdk's shipping types.\n */\nexport function isFreeShippingRate(amount: number): boolean {\n return amount === 0;\n}\n\n/**\n * Renders a shipping option's price for display: the free label when the\n * rate is free, the house money format otherwise.\n *\n * `freeLabel` is passed in (see lib/shipping/messages.ts) rather than\n * hardcoded here, so this stays a pure, generic function reachable from a\n * plain vitest spec.\n */\nexport function formatShippingAmount(\n amount: number,\n freeLabel: string,\n locale: string,\n currency: SupportedCurrency | string\n): string {\n return isFreeShippingRate(amount)\n ? freeLabel\n : formatPrice(amount, locale, currency);\n}\n\nexport interface ShippingOptionDisplay {\n title: string;\n carrierName: string | null;\n carrierLogoUrl: string | null;\n eta: string | null;\n}\n\n/** Carrier-provided URLs are untrusted: only http(s) may reach an <img src>. */\nfunction safeHttpUrl(url: string | null | undefined): string | null {\n if (!url) return null;\n try {\n const { protocol } = new URL(url);\n return protocol === \"http:\" || protocol === \"https:\" ? url : null;\n } catch {\n return null;\n }\n}\n\n/**\n * What an option row shows: title, carrier (when carrier-quoted) and an ETA.\n * The carrier's own label wins over the fixed-rate day range. The carrier\n * line names the service too: one carrier can offer several at one price.\n */\nexport function describeShippingOption(\n option: ShippingOption\n): ShippingOptionDisplay {\n let eta: string | null = null;\n if (option.estimated_label) {\n eta = option.estimated_label;\n } else if (option.estimated_days_min != null) {\n eta = formatShippingEstimate(\n option.estimated_days_min,\n option.estimated_days_max ?? option.estimated_days_min\n );\n }\n return {\n title: option.display_name,\n carrierName: option.carrier_name\n ? [option.carrier_name, option.carrier_service_name]\n .filter(Boolean)\n .join(\" · \")\n : null,\n carrierLogoUrl: safeHttpUrl(option.carrier_logo_url),\n eta,\n };\n}\n"],"mappings":"AACA,SAAS,mBAA2C;AACpD,SAAS,8BAA8B;AAOhC,SAAS,mBAAmB,QAAyB;AAC1D,SAAO,WAAW;AACpB;AAUO,SAAS,qBACd,QACA,WACA,QACA,UACQ;AACR,SAAO,mBAAmB,MAAM,IAC5B,YACA,YAAY,QAAQ,QAAQ,QAAQ;AAC1C;AAUA,SAAS,YAAY,KAA+C;AAClE,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,EAAE,SAAS,IAAI,IAAI,IAAI,GAAG;AAChC,WAAO,aAAa,WAAW,aAAa,WAAW,MAAM;AAAA,EAC/D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOO,SAAS,uBACd,QACuB;AACvB,MAAI,MAAqB;AACzB,MAAI,OAAO,iBAAiB;AAC1B,UAAM,OAAO;AAAA,EACf,WAAW,OAAO,sBAAsB,MAAM;AAC5C,UAAM;AAAA,MACJ,OAAO;AAAA,MACP,OAAO,sBAAsB,OAAO;AAAA,IACtC;AAAA,EACF;AACA,SAAO;AAAA,IACL,OAAO,OAAO;AAAA,IACd,aAAa,OAAO,eAChB,CAAC,OAAO,cAAc,OAAO,oBAAoB,EAC9C,OAAO,OAAO,EACd,KAAK,QAAK,IACb;AAAA,IACJ,gBAAgB,YAAY,OAAO,gBAAgB;AAAA,IACnD;AAAA,EACF;AACF;","names":[]}
|
|
@@ -7,6 +7,8 @@ const SHIPPING_MESSAGES = Object.freeze({
|
|
|
7
7
|
failedHint: "K\u1EBFt n\u1ED1i c\xF3 th\u1EC3 \u0111ang gi\xE1n \u0111o\u1EA1n. Vui l\xF2ng th\u1EED l\u1EA1i.",
|
|
8
8
|
retry: "Th\u1EED l\u1EA1i",
|
|
9
9
|
free: "Mi\u1EC5n ph\xED",
|
|
10
|
+
quoteChanged: "Ph\xED v\u1EADn chuy\u1EC3n \u0111\xE3 thay \u0111\u1ED5i",
|
|
11
|
+
quoteChangedHint: "Vui l\xF2ng ki\u1EC3m tra l\u1EA1i ph\xED v\u1EADn chuy\u1EC3n m\u1EDBi r\u1ED3i \u0111\u1EB7t h\xE0ng.",
|
|
10
12
|
estimate: "D\u1EF1 ki\u1EBFn giao: {min} \u0111\u1EBFn {max} ng\xE0y"
|
|
11
13
|
});
|
|
12
14
|
function formatShippingEstimate(min, max) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/shipping/messages.ts"],"sourcesContent":["/**\n * Checkout shipping strings, extracted from the components that used to\n * hardcode them inline. This is NOT an i18n layer -- the storefront has no\n * i18n infrastructure (no next-intl, no locale routing, no message\n * catalog), and bootstrapping one is out of scope for a shipping-vocabulary\n * change. This just gets every shipping string into one place so a real\n * i18n task can source from here later instead of hunting through JSX.\n *\n * `estimate` is a template: interpolate `{min}` and `{max}` yourself.\n */\nexport const SHIPPING_MESSAGES = Object.freeze({\n title: \"Phương thức vận chuyển\",\n prompt: \"Vui lòng nhập địa chỉ giao hàng để xem phương thức vận chuyển\",\n empty: \"Không có phương thức vận chuyển phù hợp\",\n emptyHint:\n \"Vui lòng kiểm tra lại địa chỉ giao hàng hoặc liên hệ với cửa hàng.\",\n failed: \"Không thể tính phí vận chuyển\",\n failedHint: \"Kết nối có thể đang gián đoạn. Vui lòng thử lại.\",\n retry: \"Thử lại\",\n free: \"Miễn phí\",\n estimate: \"Dự kiến giao: {min} đến {max} ngày\",\n});\n\n/** Fills in the `{min}`/`{max}` placeholders in `SHIPPING_MESSAGES.estimate`. */\nexport function formatShippingEstimate(min: number, max: number): string {\n return SHIPPING_MESSAGES.estimate\n .replace(\"{min}\", String(min))\n .replace(\"{max}\", String(max));\n}\n"],"mappings":"AAUO,MAAM,oBAAoB,OAAO,OAAO;AAAA,EAC7C,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WACE;AAAA,EACF,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,MAAM;AAAA,EACN,UAAU;AACZ,CAAC;AAGM,SAAS,uBAAuB,KAAa,KAAqB;AACvE,SAAO,kBAAkB,SACtB,QAAQ,SAAS,OAAO,GAAG,CAAC,EAC5B,QAAQ,SAAS,OAAO,GAAG,CAAC;AACjC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/shipping/messages.ts"],"sourcesContent":["/**\n * Checkout shipping strings, extracted from the components that used to\n * hardcode them inline. This is NOT an i18n layer -- the storefront has no\n * i18n infrastructure (no next-intl, no locale routing, no message\n * catalog), and bootstrapping one is out of scope for a shipping-vocabulary\n * change. This just gets every shipping string into one place so a real\n * i18n task can source from here later instead of hunting through JSX.\n *\n * `estimate` is a template: interpolate `{min}` and `{max}` yourself.\n */\nexport const SHIPPING_MESSAGES = Object.freeze({\n title: \"Phương thức vận chuyển\",\n prompt: \"Vui lòng nhập địa chỉ giao hàng để xem phương thức vận chuyển\",\n empty: \"Không có phương thức vận chuyển phù hợp\",\n emptyHint:\n \"Vui lòng kiểm tra lại địa chỉ giao hàng hoặc liên hệ với cửa hàng.\",\n failed: \"Không thể tính phí vận chuyển\",\n failedHint: \"Kết nối có thể đang gián đoạn. Vui lòng thử lại.\",\n retry: \"Thử lại\",\n free: \"Miễn phí\",\n quoteChanged: \"Phí vận chuyển đã thay đổi\",\n quoteChangedHint: \"Vui lòng kiểm tra lại phí vận chuyển mới rồi đặt hàng.\",\n estimate: \"Dự kiến giao: {min} đến {max} ngày\",\n});\n\n/** Fills in the `{min}`/`{max}` placeholders in `SHIPPING_MESSAGES.estimate`. */\nexport function formatShippingEstimate(min: number, max: number): string {\n return SHIPPING_MESSAGES.estimate\n .replace(\"{min}\", String(min))\n .replace(\"{max}\", String(max));\n}\n"],"mappings":"AAUO,MAAM,oBAAoB,OAAO,OAAO;AAAA,EAC7C,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WACE;AAAA,EACF,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,MAAM;AAAA,EACN,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB,UAAU;AACZ,CAAC;AAGM,SAAS,uBAAuB,KAAa,KAAqB;AACvE,SAAO,kBAAkB,SACtB,QAAQ,SAAS,OAAO,GAAG,CAAC,EAC5B,QAAQ,SAAS,OAAO,GAAG,CAAC;AACjC;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/shipping/option-id.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * The stable identity of a shipping option. Carrier-backed rates can offer\n * several options under one `rate_id`, so the API sends `option_id`; older\n * APIs don't, and `rate_id` alone is unique there.\n */\nexport function optionIdOf(option: ShippingOption): string {\n return option.option_id ?? String(option.rate_id);\n}\n"],"mappings":"AAOO,SAAS,WAAW,QAAgC;AACzD,SAAO,OAAO,aAAa,OAAO,OAAO,OAAO;AAClD;","names":[]}
|
|
@@ -1,12 +1,26 @@
|
|
|
1
|
+
import { optionIdOf } from "./option-id.js";
|
|
1
2
|
const initialShippingCalculationState = {
|
|
2
3
|
shippingFee: 0,
|
|
3
4
|
isCalculatingShipping: false,
|
|
4
5
|
hasCalculatedShipping: false,
|
|
5
6
|
shippingOptions: [],
|
|
6
7
|
selectedShippingRate: null,
|
|
8
|
+
selectedOptionId: null,
|
|
7
9
|
requestId: 0,
|
|
8
10
|
calculationFailed: false
|
|
9
11
|
};
|
|
12
|
+
function selectFrom(options, preferId) {
|
|
13
|
+
const preferred = preferId === null ? void 0 : options.find((option) => optionIdOf(option) === preferId);
|
|
14
|
+
const chosen = preferred ?? options.reduce(
|
|
15
|
+
(best, option) => !best || option.amount < best.amount ? option : best,
|
|
16
|
+
null
|
|
17
|
+
);
|
|
18
|
+
return chosen ? {
|
|
19
|
+
optionId: optionIdOf(chosen),
|
|
20
|
+
rateId: chosen.rate_id,
|
|
21
|
+
fee: chosen.amount
|
|
22
|
+
} : { optionId: null, rateId: null, fee: 0 };
|
|
23
|
+
}
|
|
10
24
|
function shippingCalculationReducer(state, action) {
|
|
11
25
|
switch (action.type) {
|
|
12
26
|
case "RESET":
|
|
@@ -24,10 +38,7 @@ function shippingCalculationReducer(state, action) {
|
|
|
24
38
|
case "CALCULATION_SUCCEEDED": {
|
|
25
39
|
if (action.requestId !== state.requestId) return state;
|
|
26
40
|
const { options } = action;
|
|
27
|
-
const
|
|
28
|
-
(best, option) => !best || option.amount < best.amount ? option : best,
|
|
29
|
-
null
|
|
30
|
-
);
|
|
41
|
+
const picked = selectFrom(options, null);
|
|
31
42
|
return {
|
|
32
43
|
...state,
|
|
33
44
|
shippingOptions: options,
|
|
@@ -35,10 +46,36 @@ function shippingCalculationReducer(state, action) {
|
|
|
35
46
|
isCalculatingShipping: false,
|
|
36
47
|
// Auto-select the cheapest option. This also revalidates the
|
|
37
48
|
// selection on every successful recalculation: it is always
|
|
38
|
-
// replaced with
|
|
39
|
-
// so a stale
|
|
40
|
-
|
|
41
|
-
|
|
49
|
+
// replaced with an option guaranteed to belong to THIS response,
|
|
50
|
+
// so a stale selection from an earlier quote can never linger.
|
|
51
|
+
selectedOptionId: picked.optionId,
|
|
52
|
+
selectedShippingRate: picked.rateId,
|
|
53
|
+
shippingFee: picked.fee,
|
|
54
|
+
calculationFailed: false
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
case "QUOTE_REPLACED": {
|
|
58
|
+
if (action.requestId !== state.requestId) return state;
|
|
59
|
+
const incoming = new Map(action.options.map((o) => [optionIdOf(o), o]));
|
|
60
|
+
const merged = state.shippingOptions.map(
|
|
61
|
+
(o) => incoming.get(optionIdOf(o)) ?? o
|
|
62
|
+
);
|
|
63
|
+
const known = new Set(state.shippingOptions.map(optionIdOf));
|
|
64
|
+
for (const o of action.options) {
|
|
65
|
+
if (!known.has(optionIdOf(o))) {
|
|
66
|
+
known.add(optionIdOf(o));
|
|
67
|
+
merged.push(o);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const picked = selectFrom(merged, action.preferOptionId);
|
|
71
|
+
return {
|
|
72
|
+
...state,
|
|
73
|
+
shippingOptions: merged,
|
|
74
|
+
hasCalculatedShipping: true,
|
|
75
|
+
isCalculatingShipping: false,
|
|
76
|
+
selectedOptionId: picked.optionId,
|
|
77
|
+
selectedShippingRate: picked.rateId,
|
|
78
|
+
shippingFee: picked.fee,
|
|
42
79
|
calculationFailed: false
|
|
43
80
|
};
|
|
44
81
|
}
|
|
@@ -49,10 +86,23 @@ function shippingCalculationReducer(state, action) {
|
|
|
49
86
|
shippingFee: 0,
|
|
50
87
|
shippingOptions: [],
|
|
51
88
|
selectedShippingRate: null,
|
|
89
|
+
selectedOptionId: null,
|
|
52
90
|
hasCalculatedShipping: false,
|
|
53
91
|
isCalculatingShipping: false,
|
|
54
92
|
calculationFailed: true
|
|
55
93
|
};
|
|
94
|
+
case "OPTION_SELECTED": {
|
|
95
|
+
const option = state.shippingOptions.find(
|
|
96
|
+
(opt) => optionIdOf(opt) === action.optionId
|
|
97
|
+
);
|
|
98
|
+
if (!option) return state;
|
|
99
|
+
return {
|
|
100
|
+
...state,
|
|
101
|
+
selectedOptionId: optionIdOf(option),
|
|
102
|
+
selectedShippingRate: option.rate_id,
|
|
103
|
+
shippingFee: option.amount
|
|
104
|
+
};
|
|
105
|
+
}
|
|
56
106
|
case "RATE_SELECTED": {
|
|
57
107
|
const option = state.shippingOptions.find(
|
|
58
108
|
(opt) => opt.rate_id === action.rateId
|
|
@@ -60,10 +110,8 @@ function shippingCalculationReducer(state, action) {
|
|
|
60
110
|
return {
|
|
61
111
|
...state,
|
|
62
112
|
selectedShippingRate: action.rateId,
|
|
63
|
-
|
|
64
|
-
//
|
|
65
|
-
// dispatches a rate_id it just rendered from shippingOptions),
|
|
66
|
-
// kept explicit rather than silently coercing the fee to 0.
|
|
113
|
+
selectedOptionId: option ? optionIdOf(option) : state.selectedOptionId,
|
|
114
|
+
// Preserves the previous fee if the id doesn't match a known option.
|
|
67
115
|
shippingFee: option ? option.amount : state.shippingFee
|
|
68
116
|
};
|
|
69
117
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/shipping/shipping-calculation-reducer.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * State backing `useShippingCalculation`. Kept as one object (not five\n * separate `useState`s) so the transitions below are a single pure\n * function -- reachable from a plain vitest spec instead of only being\n * exercisable by rendering the hook.\n */\nexport interface ShippingCalculationState {\n shippingFee: number;\n isCalculatingShipping: boolean;\n hasCalculatedShipping: boolean;\n shippingOptions: ShippingOption[];\n selectedShippingRate: number | null;\n /**\n * Identifies the quote currently considered current. Bumped by RESET and\n * by CALCULATION_STARTED; a response carrying an older id is discarded.\n * Without this, a slow request issued for the PREVIOUS address could land\n * after a newer one and restore its options, its rate id, and an\n * enabled submit button.\n */\n requestId: number;\n /**\n * The last quote attempt failed. Distinct from \"not quoted yet\": submit\n * is blocked in both cases, but only this one should offer a retry.\n * Without it a transient failure left checkout disabled with no way\n * forward short of editing the address or reloading the page.\n */\n calculationFailed: boolean;\n}\n\nexport const initialShippingCalculationState: ShippingCalculationState = {\n shippingFee: 0,\n isCalculatingShipping: false,\n hasCalculatedShipping: false,\n shippingOptions: [],\n selectedShippingRate: null,\n requestId: 0,\n calculationFailed: false,\n};\n\nexport type ShippingCalculationAction =\n /**\n * The address or cart changed. Dispatched synchronously, before the\n * caller's debounce timer even starts -- this is what guarantees a rate\n * id from the PREVIOUS quote can never survive to be submitted against\n * the NEW address: between an input change and the next quote landing,\n * there is no selected rate at all, only ever a stale one or a fresh\n * one. Also covers the \"address/cart incomplete\" early-out.\n */\n | { type: \"RESET\" }\n | { type: \"CALCULATION_STARTED\" }\n | {\n type: \"CALCULATION_SUCCEEDED\";\n options: ShippingOption[];\n requestId: number;\n }\n | { type: \"CALCULATION_FAILED\"; requestId: number }\n /** The shopper picked a specific option out of the current quote. */\n | { type: \"RATE_SELECTED\"; rateId: number };\n\nexport function shippingCalculationReducer(\n state: ShippingCalculationState,\n action: ShippingCalculationAction\n): ShippingCalculationState {\n switch (action.type) {\n case \"RESET\":\n // Keep counting up: a response from before the reset must still be\n // recognisable as stale.\n return {\n ...initialShippingCalculationState,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_STARTED\":\n return {\n ...state,\n isCalculatingShipping: true,\n calculationFailed: false,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_SUCCEEDED\": {\n if (action.requestId !== state.requestId) return state;\n const { options } = action;\n // The cheapest option (the API's order breaks ties), as shoppers\n // expect: a free rate is never passed over for a paid one.\n const cheapest = options.reduce<(typeof options)[number] | null>(\n (best, option) =>\n !best || option.amount < best.amount ? option : best,\n null\n );\n return {\n ...state,\n shippingOptions: options,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n // Auto-select the cheapest option. This also revalidates the\n // selection on every successful recalculation: it is always\n // replaced with a rate_id guaranteed to belong to THIS response,\n // so a stale rate from an earlier quote can never linger.\n selectedShippingRate: cheapest ? cheapest.rate_id : null,\n shippingFee: cheapest ? cheapest.amount : 0,\n calculationFailed: false,\n };\n }\n\n case \"CALCULATION_FAILED\":\n if (action.requestId !== state.requestId) return state;\n return {\n ...state,\n shippingFee: 0,\n shippingOptions: [],\n selectedShippingRate: null,\n hasCalculatedShipping: false,\n isCalculatingShipping: false,\n calculationFailed: true,\n };\n\n case \"RATE_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => opt.rate_id === action.rateId\n );\n return {\n ...state,\n selectedShippingRate: action.rateId,\n // Preserves the previous fee if the id doesn't match a known\n // option -- shouldn't happen in practice (the UI only ever\n // dispatches a rate_id it just rendered from shippingOptions),\n // kept explicit rather than silently coercing the fee to 0.\n shippingFee: option ? option.amount : state.shippingFee,\n };\n }\n\n default:\n return state;\n }\n}\n"],"mappings":"AA+BO,MAAM,kCAA4D;AAAA,EACvE,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,uBAAuB;AAAA,EACvB,iBAAiB,CAAC;AAAA,EAClB,sBAAsB;AAAA,EACtB,WAAW;AAAA,EACX,mBAAmB;AACrB;AAsBO,SAAS,2BACd,OACA,QAC0B;AAC1B,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AAGH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,WAAW,MAAM,YAAY;AAAA,MAC/B;AAAA,IAEF,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,QACnB,WAAW,MAAM,YAAY;AAAA,MAC/B;AAAA,IAEF,KAAK,yBAAyB;AAC5B,UAAI,OAAO,cAAc,MAAM,UAAW,QAAO;AACjD,YAAM,EAAE,QAAQ,IAAI;AAGpB,YAAM,WAAW,QAAQ;AAAA,QACvB,CAAC,MAAM,WACL,CAAC,QAAQ,OAAO,SAAS,KAAK,SAAS,SAAS;AAAA,QAClD;AAAA,MACF;AACA,aAAO;AAAA,QACL,GAAG;AAAA,QACH,iBAAiB;AAAA,QACjB,uBAAuB;AAAA,QACvB,uBAAuB;AAAA;AAAA;AAAA;AAAA;AAAA,QAKvB,sBAAsB,WAAW,SAAS,UAAU;AAAA,QACpD,aAAa,WAAW,SAAS,SAAS;AAAA,QAC1C,mBAAmB;AAAA,MACrB;AAAA,IACF;AAAA,IAEA,KAAK;AACH,UAAI,OAAO,cAAc,MAAM,UAAW,QAAO;AACjD,aAAO;AAAA,QACL,GAAG;AAAA,QACH,aAAa;AAAA,QACb,iBAAiB,CAAC;AAAA,QAClB,sBAAsB;AAAA,QACtB,uBAAuB;AAAA,QACvB,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,MACrB;AAAA,IAEF,KAAK,iBAAiB;AACpB,YAAM,SAAS,MAAM,gBAAgB;AAAA,QACnC,SAAO,IAAI,YAAY,OAAO;AAAA,MAChC;AACA,aAAO;AAAA,QACL,GAAG;AAAA,QACH,sBAAsB,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,QAK7B,aAAa,SAAS,OAAO,SAAS,MAAM;AAAA,MAC9C;AAAA,IACF;AAAA,IAEA;AACE,aAAO;AAAA,EACX;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/shipping/shipping-calculation-reducer.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\nimport { optionIdOf } from \"./option-id\";\n\n/**\n * State backing `useShippingCalculation`. Kept as one object (not five\n * separate `useState`s) so the transitions below are a single pure\n * function -- reachable from a plain vitest spec instead of only being\n * exercisable by rendering the hook.\n */\nexport interface ShippingCalculationState {\n shippingFee: number;\n isCalculatingShipping: boolean;\n hasCalculatedShipping: boolean;\n shippingOptions: ShippingOption[];\n /** The `rate_id` of the selected option; kept for existing callers. */\n selectedShippingRate: number | null;\n /**\n * The selected option's identity (`optionIdOf`). Several carrier options\n * can share one `rate_id`, so this, not the rate id, picks the option.\n */\n selectedOptionId: string | null;\n /**\n * Identifies the quote currently considered current. Bumped by RESET and\n * by CALCULATION_STARTED; a response carrying an older id is discarded.\n * Without this, a slow request issued for the PREVIOUS address could land\n * after a newer one and restore its options, its rate id, and an\n * enabled submit button.\n */\n requestId: number;\n /**\n * The last quote attempt failed. Distinct from \"not quoted yet\": submit\n * is blocked in both cases, but only this one should offer a retry.\n * Without it a transient failure left checkout disabled with no way\n * forward short of editing the address or reloading the page.\n */\n calculationFailed: boolean;\n}\n\nexport const initialShippingCalculationState: ShippingCalculationState = {\n shippingFee: 0,\n isCalculatingShipping: false,\n hasCalculatedShipping: false,\n shippingOptions: [],\n selectedShippingRate: null,\n selectedOptionId: null,\n requestId: 0,\n calculationFailed: false,\n};\n\nexport type ShippingCalculationAction =\n /**\n * The address or cart changed. Dispatched synchronously, before the\n * caller's debounce timer even starts -- this is what guarantees a rate\n * id from the PREVIOUS quote can never survive to be submitted against\n * the NEW address: between an input change and the next quote landing,\n * there is no selected rate at all, only ever a stale one or a fresh\n * one. Also covers the \"address/cart incomplete\" early-out.\n */\n | { type: \"RESET\" }\n | { type: \"CALCULATION_STARTED\" }\n | {\n type: \"CALCULATION_SUCCEEDED\";\n options: ShippingOption[];\n requestId: number;\n }\n | { type: \"CALCULATION_FAILED\"; requestId: number }\n /**\n * The current quote was re-priced (e.g. the API reported a changed\n * quote). Judged against the current `requestId` like\n * CALCULATION_SUCCEEDED, and does not bump it. MERGES by option id: the\n * given options replace matching entries, other existing options are\n * kept (the API re-checks their amounts at placement), and new ones are\n * appended. Keeps `preferOptionId` selected when it is still offered, else\n * the cheapest option.\n */\n | {\n type: \"QUOTE_REPLACED\";\n options: ShippingOption[];\n requestId: number;\n preferOptionId: string | null;\n }\n /** The shopper picked a specific option out of the current quote. */\n | { type: \"OPTION_SELECTED\"; optionId: string }\n /** @deprecated Use OPTION_SELECTED. Selects the first option with this rate_id. */\n | { type: \"RATE_SELECTED\"; rateId: number };\n\ninterface Selection {\n optionId: string | null;\n rateId: number | null;\n fee: number;\n}\n\n/**\n * Picks `preferId` when it is among `options`, else the cheapest option\n * (the API's order breaks ties), as shoppers expect: a free rate is never\n * passed over for a paid one.\n */\nfunction selectFrom(\n options: ShippingOption[],\n preferId: string | null\n): Selection {\n const preferred =\n preferId === null\n ? undefined\n : options.find(option => optionIdOf(option) === preferId);\n const chosen =\n preferred ??\n options.reduce<ShippingOption | null>(\n (best, option) => (!best || option.amount < best.amount ? option : best),\n null\n );\n return chosen\n ? {\n optionId: optionIdOf(chosen),\n rateId: chosen.rate_id,\n fee: chosen.amount,\n }\n : { optionId: null, rateId: null, fee: 0 };\n}\n\nexport function shippingCalculationReducer(\n state: ShippingCalculationState,\n action: ShippingCalculationAction\n): ShippingCalculationState {\n switch (action.type) {\n case \"RESET\":\n // Keep counting up: a response from before the reset must still be\n // recognisable as stale.\n return {\n ...initialShippingCalculationState,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_STARTED\":\n return {\n ...state,\n isCalculatingShipping: true,\n calculationFailed: false,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_SUCCEEDED\": {\n if (action.requestId !== state.requestId) return state;\n const { options } = action;\n const picked = selectFrom(options, null);\n return {\n ...state,\n shippingOptions: options,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n // Auto-select the cheapest option. This also revalidates the\n // selection on every successful recalculation: it is always\n // replaced with an option guaranteed to belong to THIS response,\n // so a stale selection from an earlier quote can never linger.\n selectedOptionId: picked.optionId,\n selectedShippingRate: picked.rateId,\n shippingFee: picked.fee,\n calculationFailed: false,\n };\n }\n\n case \"QUOTE_REPLACED\": {\n if (action.requestId !== state.requestId) return state;\n const incoming = new Map(action.options.map(o => [optionIdOf(o), o]));\n const merged = state.shippingOptions.map(\n o => incoming.get(optionIdOf(o)) ?? o\n );\n const known = new Set(state.shippingOptions.map(optionIdOf));\n for (const o of action.options) {\n if (!known.has(optionIdOf(o))) {\n known.add(optionIdOf(o));\n merged.push(o);\n }\n }\n const picked = selectFrom(merged, action.preferOptionId);\n return {\n ...state,\n shippingOptions: merged,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n selectedOptionId: picked.optionId,\n selectedShippingRate: picked.rateId,\n shippingFee: picked.fee,\n calculationFailed: false,\n };\n }\n\n case \"CALCULATION_FAILED\":\n if (action.requestId !== state.requestId) return state;\n return {\n ...state,\n shippingFee: 0,\n shippingOptions: [],\n selectedShippingRate: null,\n selectedOptionId: null,\n hasCalculatedShipping: false,\n isCalculatingShipping: false,\n calculationFailed: true,\n };\n\n case \"OPTION_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => optionIdOf(opt) === action.optionId\n );\n // An id that isn't in the current quote is ignored: the UI only\n // dispatches ids it just rendered from shippingOptions.\n if (!option) return state;\n return {\n ...state,\n selectedOptionId: optionIdOf(option),\n selectedShippingRate: option.rate_id,\n shippingFee: option.amount,\n };\n }\n\n case \"RATE_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => opt.rate_id === action.rateId\n );\n return {\n ...state,\n selectedShippingRate: action.rateId,\n selectedOptionId: option ? optionIdOf(option) : state.selectedOptionId,\n // Preserves the previous fee if the id doesn't match a known option.\n shippingFee: option ? option.amount : state.shippingFee,\n };\n }\n\n default:\n return state;\n }\n}\n"],"mappings":"AACA,SAAS,kBAAkB;AAqCpB,MAAM,kCAA4D;AAAA,EACvE,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,uBAAuB;AAAA,EACvB,iBAAiB,CAAC;AAAA,EAClB,sBAAsB;AAAA,EACtB,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,mBAAmB;AACrB;AAkDA,SAAS,WACP,SACA,UACW;AACX,QAAM,YACJ,aAAa,OACT,SACA,QAAQ,KAAK,YAAU,WAAW,MAAM,MAAM,QAAQ;AAC5D,QAAM,SACJ,aACA,QAAQ;AAAA,IACN,CAAC,MAAM,WAAY,CAAC,QAAQ,OAAO,SAAS,KAAK,SAAS,SAAS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|
|
|
1
1
|
import { sdk } from "../sdk.js";
|
|
2
|
-
import { useReducer, useEffect, useCallback, useRef } from "react";
|
|
2
|
+
import { useReducer, useEffect, useCallback, useRef, useMemo } from "react";
|
|
3
3
|
import { SHIPPING_MESSAGES } from "./messages.js";
|
|
4
4
|
import { useNotify } from "../notices.js";
|
|
5
|
+
import { optionIdOf } from "./option-id.js";
|
|
5
6
|
import {
|
|
6
7
|
shippingCalculationReducer,
|
|
7
8
|
initialShippingCalculationState
|
|
@@ -12,7 +13,8 @@ function useShippingCalculation({
|
|
|
12
13
|
ward,
|
|
13
14
|
subtotal,
|
|
14
15
|
totalWeight,
|
|
15
|
-
itemsCount
|
|
16
|
+
itemsCount,
|
|
17
|
+
includeCarrierOptions = false
|
|
16
18
|
}) {
|
|
17
19
|
const [state, dispatch] = useReducer(
|
|
18
20
|
shippingCalculationReducer,
|
|
@@ -23,7 +25,7 @@ function useShippingCalculation({
|
|
|
23
25
|
stateRef.current = state;
|
|
24
26
|
useEffect(() => {
|
|
25
27
|
dispatch({ type: "RESET" });
|
|
26
|
-
}, [city, ward, subtotal, totalWeight]);
|
|
28
|
+
}, [city, ward, subtotal, totalWeight, includeCarrierOptions]);
|
|
27
29
|
const calculateShippingFee = useCallback(async () => {
|
|
28
30
|
if (!city || !ward || itemsCount === 0) {
|
|
29
31
|
dispatch({ type: "RESET" });
|
|
@@ -37,7 +39,8 @@ function useShippingCalculation({
|
|
|
37
39
|
ward_id: ward,
|
|
38
40
|
subtotal,
|
|
39
41
|
currency: "VND",
|
|
40
|
-
weight_gr: totalWeight
|
|
42
|
+
weight_gr: totalWeight,
|
|
43
|
+
...includeCarrierOptions && { include_carrier_options: true }
|
|
41
44
|
});
|
|
42
45
|
dispatch({ type: "CALCULATION_SUCCEEDED", options, requestId: next });
|
|
43
46
|
} catch (error) {
|
|
@@ -51,7 +54,16 @@ function useShippingCalculation({
|
|
|
51
54
|
description: SHIPPING_MESSAGES.failedHint
|
|
52
55
|
});
|
|
53
56
|
}
|
|
54
|
-
}, [
|
|
57
|
+
}, [
|
|
58
|
+
city,
|
|
59
|
+
ward,
|
|
60
|
+
itemsCount,
|
|
61
|
+
storeRef,
|
|
62
|
+
subtotal,
|
|
63
|
+
totalWeight,
|
|
64
|
+
includeCarrierOptions,
|
|
65
|
+
notify
|
|
66
|
+
]);
|
|
55
67
|
useEffect(() => {
|
|
56
68
|
const timeoutId = setTimeout(() => {
|
|
57
69
|
calculateShippingFee();
|
|
@@ -61,6 +73,22 @@ function useShippingCalculation({
|
|
|
61
73
|
const handleShippingRateSelect = useCallback((rateId) => {
|
|
62
74
|
dispatch({ type: "RATE_SELECTED", rateId });
|
|
63
75
|
}, []);
|
|
76
|
+
const handleShippingOptionSelect = useCallback((optionId) => {
|
|
77
|
+
dispatch({ type: "OPTION_SELECTED", optionId });
|
|
78
|
+
}, []);
|
|
79
|
+
const replaceOptions = useCallback(
|
|
80
|
+
(options, preferOptionId, requestId) => {
|
|
81
|
+
dispatch({ type: "QUOTE_REPLACED", options, requestId, preferOptionId });
|
|
82
|
+
},
|
|
83
|
+
[]
|
|
84
|
+
);
|
|
85
|
+
const currentRequestId = useCallback(() => stateRef.current.requestId, []);
|
|
86
|
+
const selectedOption = useMemo(
|
|
87
|
+
() => state.selectedOptionId === null ? null : state.shippingOptions.find(
|
|
88
|
+
(o) => optionIdOf(o) === state.selectedOptionId
|
|
89
|
+
) ?? null,
|
|
90
|
+
[state.shippingOptions, state.selectedOptionId]
|
|
91
|
+
);
|
|
64
92
|
return {
|
|
65
93
|
shippingFee: state.shippingFee,
|
|
66
94
|
isCalculatingShipping: state.isCalculatingShipping,
|
|
@@ -68,6 +96,11 @@ function useShippingCalculation({
|
|
|
68
96
|
shippingOptions: state.shippingOptions,
|
|
69
97
|
selectedShippingRate: state.selectedShippingRate,
|
|
70
98
|
calculationFailed: state.calculationFailed,
|
|
99
|
+
selectedOptionId: state.selectedOptionId,
|
|
100
|
+
selectedOption,
|
|
101
|
+
handleShippingOptionSelect,
|
|
102
|
+
replaceOptions,
|
|
103
|
+
currentRequestId,
|
|
71
104
|
handleShippingRateSelect,
|
|
72
105
|
/**
|
|
73
106
|
* Re-run the quote with the inputs unchanged. The debounced effect only
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef } from \"react\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [city
|
|
1
|
+
{"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef, useMemo } from \"react\";\nimport type { ShippingOption } from \"@ecomweb/sdk\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport { optionIdOf } from \"./option-id\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n /**\n * Ask the API for carrier-quoted options too. Off by default so stores\n * that have not updated send exactly the body they always did.\n */\n includeCarrierOptions?: boolean;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n includeCarrierOptions = false,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n ...(includeCarrierOptions && { include_carrier_options: true }),\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [\n city,\n ward,\n itemsCount,\n storeRef,\n subtotal,\n totalWeight,\n includeCarrierOptions,\n notify,\n ]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n const handleShippingOptionSelect = useCallback((optionId: string) => {\n dispatch({ type: \"OPTION_SELECTED\", optionId });\n }, []);\n\n const replaceOptions = useCallback(\n (\n options: ShippingOption[],\n preferOptionId: string | null,\n requestId: number\n ) => {\n dispatch({ type: \"QUOTE_REPLACED\", options, requestId, preferOptionId });\n },\n []\n );\n\n const currentRequestId = useCallback(() => stateRef.current.requestId, []);\n\n const selectedOption = useMemo(\n () =>\n state.selectedOptionId === null\n ? null\n : (state.shippingOptions.find(\n o => optionIdOf(o) === state.selectedOptionId\n ) ?? null),\n [state.shippingOptions, state.selectedOptionId]\n );\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n selectedOptionId: state.selectedOptionId,\n selectedOption,\n handleShippingOptionSelect,\n replaceOptions,\n currentRequestId,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,YAAY,WAAW,aAAa,QAAQ,eAAe;AAEpE,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAgBA,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,wBAAwB;AAC1B,GA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O,MAAM,aAAa,SAAS;AAAA,EACrC,GAAG,CAAC,oBAAoB,CAAC;AAGzB,QAAM,2BAA2B,YAAY,CAAC,WAAmB;AAC/D,aAAS,EAAE,MAAM,iBAAiB,OAAO,CAAC;AAAA,EAC5C,GAAG,CAAC,CAAC;AAEL,QAAM,6BAA6B,YAAY,CAAC,aAAqB;AACnE,aAAS,EAAE,MAAM,mBAAmB,SAAS,CAAC;AAAA,EAChD,GAAG,CAAC,CAAC;AAEL,QAAM,iBAAiB;AAAA,IACrB,CACE,SACA,gBACA,cACG;AACH,eAAS,EAAE,MAAM,kBAAkB,SAAS,WAAW,eAAe,CAAC;AAAA,IACzE;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,mBAAmB,YAAY,MAAM,SAAS,QAAQ,WAAW,CAAC,CAAC;AAEzE,QAAM,iBAAiB;AAAA,IACrB,MACE,MAAM,qBAAqB,OACvB,OACC,MAAM,gBAAgB;AAAA,MACrB,OAAK,WAAW,CAAC,MAAM,MAAM;AAAA,IAC/B,KAAK;AAAA,IACX,CAAC,MAAM,iBAAiB,MAAM,gBAAgB;AAAA,EAChD;AAEA,SAAO;AAAA,IACL,aAAa,MAAM;AAAA,IACnB,uBAAuB,MAAM;AAAA,IAC7B,uBAAuB,MAAM;AAAA,IAC7B,iBAAiB,MAAM;AAAA,IACvB,sBAAsB,MAAM;AAAA,IAC5B,mBAAmB,MAAM;AAAA,IACzB,kBAAkB,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecomweb/storefront-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"currency.js": "^2.0.4",
|
|
48
48
|
"server-only": "^0.0.1",
|
|
49
49
|
"zod": "^4.1.12",
|
|
50
|
-
"@ecomweb/sdk": "^0.
|
|
50
|
+
"@ecomweb/sdk": "^0.10.0"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"next": ">=16",
|