@ecomweb/storefront-kit 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +55 -0
- package/dist/api/client.js +162 -0
- package/dist/api/client.js.map +1 -0
- package/dist/api/index.js +7 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/proxy.js +145 -0
- package/dist/api/proxy.js.map +1 -0
- package/dist/api/response.js +55 -0
- package/dist/api/response.js.map +1 -0
- package/dist/api/server-client.js +159 -0
- package/dist/api/server-client.js.map +1 -0
- package/dist/auth/client-ip.js +44 -0
- package/dist/auth/client-ip.js.map +1 -0
- package/dist/auth/context.js +125 -0
- package/dist/auth/context.js.map +1 -0
- package/dist/auth/cookies.js +97 -0
- package/dist/auth/cookies.js.map +1 -0
- package/dist/auth/error-copy.js +49 -0
- package/dist/auth/error-copy.js.map +1 -0
- package/dist/auth/password-policy.js +29 -0
- package/dist/auth/password-policy.js.map +1 -0
- package/dist/auth/route-handlers.js +337 -0
- package/dist/auth/route-handlers.js.map +1 -0
- package/dist/auth/safe-redirect.js +20 -0
- package/dist/auth/safe-redirect.js.map +1 -0
- package/dist/auth/sdk.js +76 -0
- package/dist/auth/sdk.js.map +1 -0
- package/dist/auth/session-refresh.js +81 -0
- package/dist/auth/session-refresh.js.map +1 -0
- package/dist/auth/session.js +26 -0
- package/dist/auth/session.js.map +1 -0
- package/dist/auth/use-public-auth-config.js +29 -0
- package/dist/auth/use-public-auth-config.js.map +1 -0
- package/dist/cart/api.js +60 -0
- package/dist/cart/api.js.map +1 -0
- package/dist/cart/server-context.js +279 -0
- package/dist/cart/server-context.js.map +1 -0
- package/dist/cart/types.js +1 -0
- package/dist/cart/types.js.map +1 -0
- package/dist/cart/utils.js +49 -0
- package/dist/cart/utils.js.map +1 -0
- package/dist/checkout/get-payment-state.js +15 -0
- package/dist/checkout/get-payment-state.js.map +1 -0
- package/dist/checkout/initiate-gateway-payment.js +13 -0
- package/dist/checkout/initiate-gateway-payment.js.map +1 -0
- package/dist/checkout/order-handoff.js +61 -0
- package/dist/checkout/order-handoff.js.map +1 -0
- package/dist/checkout/payment-redirect.js +11 -0
- package/dist/checkout/payment-redirect.js.map +1 -0
- package/dist/checkout/payment-state-poll.js +45 -0
- package/dist/checkout/payment-state-poll.js.map +1 -0
- package/dist/checkout/start-gateway-redirect.js +16 -0
- package/dist/checkout/start-gateway-redirect.js.map +1 -0
- package/dist/checkout/stock-issues.js +35 -0
- package/dist/checkout/stock-issues.js.map +1 -0
- package/dist/checkout/success-state.js +15 -0
- package/dist/checkout/success-state.js.map +1 -0
- package/dist/checkout/types.js +1 -0
- package/dist/checkout/types.js.map +1 -0
- package/dist/checkout/use-checkout.js +256 -0
- package/dist/checkout/use-checkout.js.map +1 -0
- package/dist/checkout/utils.js +7 -0
- package/dist/checkout/utils.js.map +1 -0
- package/dist/config/index.js +7 -0
- package/dist/config/index.js.map +1 -0
- package/dist/config/log-level.js +8 -0
- package/dist/config/log-level.js.map +1 -0
- package/dist/config/mode.js +18 -0
- package/dist/config/mode.js.map +1 -0
- package/dist/config/public.js +115 -0
- package/dist/config/public.js.map +1 -0
- package/dist/config/schema.js +70 -0
- package/dist/config/schema.js.map +1 -0
- package/dist/config/server.js +68 -0
- package/dist/config/server.js.map +1 -0
- package/dist/config.d.ts +16 -0
- package/dist/config.js +15 -0
- package/dist/config.js.map +1 -0
- package/dist/currency.js +68 -0
- package/dist/currency.js.map +1 -0
- package/dist/index.d.ts +968 -0
- package/dist/index.js +146 -0
- package/dist/index.js.map +1 -0
- package/dist/interfaces/api.types.js +1 -0
- package/dist/interfaces/api.types.js.map +1 -0
- package/dist/interfaces/index.js +2 -0
- package/dist/interfaces/index.js.map +1 -0
- package/dist/logging.js +42 -0
- package/dist/logging.js.map +1 -0
- package/dist/middleware/create-storefront-middleware.js +175 -0
- package/dist/middleware/create-storefront-middleware.js.map +1 -0
- package/dist/middleware.d.ts +24 -0
- package/dist/middleware.js +9 -0
- package/dist/middleware.js.map +1 -0
- package/dist/mode-1ZKDELPZ.d.ts +16 -0
- package/dist/notices.js +31 -0
- package/dist/notices.js.map +1 -0
- package/dist/orders/api-client.js +32 -0
- package/dist/orders/api-client.js.map +1 -0
- package/dist/orders/derive-progress.js +36 -0
- package/dist/orders/derive-progress.js.map +1 -0
- package/dist/orders/index.js +6 -0
- package/dist/orders/index.js.map +1 -0
- package/dist/orders/types.js +13 -0
- package/dist/orders/types.js.map +1 -0
- package/dist/orders/use-order-status.js +137 -0
- package/dist/orders/use-order-status.js.map +1 -0
- package/dist/promotions/use-promotion-validation.js +106 -0
- package/dist/promotions/use-promotion-validation.js.map +1 -0
- package/dist/promotions/utils.js +40 -0
- package/dist/promotions/utils.js.map +1 -0
- package/dist/provider.js +25 -0
- package/dist/provider.js.map +1 -0
- package/dist/redirects/index.js +2 -0
- package/dist/redirects/index.js.map +1 -0
- package/dist/redirects/lookup-redirect.js +13 -0
- package/dist/redirects/lookup-redirect.js.map +1 -0
- package/dist/request/public-url.js +20 -0
- package/dist/request/public-url.js.map +1 -0
- package/dist/schema-CEMKsCwh.d.ts +52 -0
- package/dist/sdk.js +33 -0
- package/dist/sdk.js.map +1 -0
- package/dist/server/routes.js +56 -0
- package/dist/server/routes.js.map +1 -0
- package/dist/server.d.ts +58 -0
- package/dist/server.js +19 -0
- package/dist/server.js.map +1 -0
- package/dist/shipping/format-shipping-option.js +12 -0
- package/dist/shipping/format-shipping-option.js.map +1 -0
- package/dist/shipping/location-areas.js +104 -0
- package/dist/shipping/location-areas.js.map +1 -0
- package/dist/shipping/messages.js +19 -0
- package/dist/shipping/messages.js.map +1 -0
- package/dist/shipping/shipping-calculation-reducer.js +75 -0
- package/dist/shipping/shipping-calculation-reducer.js.map +1 -0
- package/dist/shipping/use-shipping-calculation.js +84 -0
- package/dist/shipping/use-shipping-calculation.js.map +1 -0
- package/dist/shipping/utils.js +18 -0
- package/dist/shipping/utils.js.map +1 -0
- package/dist/storage.js +116 -0
- package/dist/storage.js.map +1 -0
- package/dist/store/store-context.js +72 -0
- package/dist/store/store-context.js.map +1 -0
- package/dist/store-scope/index.js +33 -0
- package/dist/store-scope/index.js.map +1 -0
- package/dist/store-scope/root.js +15 -0
- package/dist/store-scope/root.js.map +1 -0
- package/dist/store-scope/store-url.js +45 -0
- package/dist/store-scope/store-url.js.map +1 -0
- package/dist/stores/basic-settings.js +67 -0
- package/dist/stores/basic-settings.js.map +1 -0
- package/dist/stores/cached.js +20 -0
- package/dist/stores/cached.js.map +1 -0
- package/dist/stores/get-store-by-host.js +38 -0
- package/dist/stores/get-store-by-host.js.map +1 -0
- package/dist/stores/index.js +7 -0
- package/dist/stores/index.js.map +1 -0
- package/dist/stores/metadata.js +19 -0
- package/dist/stores/metadata.js.map +1 -0
- package/dist/stores/store-path.js +9 -0
- package/dist/stores/store-path.js.map +1 -0
- package/dist/stores/store-suspension.js +14 -0
- package/dist/stores/store-suspension.js.map +1 -0
- package/package.json +64 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useCallback, useEffect, useState } from "react";
|
|
3
|
+
import { storeApiPath } from "../store-scope/index.js";
|
|
4
|
+
function usePublicAuthConfig(storeRef) {
|
|
5
|
+
const [config, setConfig] = useState(null);
|
|
6
|
+
const [error, setError] = useState(false);
|
|
7
|
+
const [attempt, setAttempt] = useState(0);
|
|
8
|
+
useEffect(() => {
|
|
9
|
+
let cancelled = false;
|
|
10
|
+
setError(false);
|
|
11
|
+
setConfig(null);
|
|
12
|
+
fetch(storeApiPath(storeRef, "auth/config")).then(
|
|
13
|
+
(res) => res.ok ? res.json() : Promise.reject(new Error("config fetch failed"))
|
|
14
|
+
).then((data) => {
|
|
15
|
+
if (!cancelled) setConfig(data);
|
|
16
|
+
}).catch(() => {
|
|
17
|
+
if (!cancelled) setError(true);
|
|
18
|
+
});
|
|
19
|
+
return () => {
|
|
20
|
+
cancelled = true;
|
|
21
|
+
};
|
|
22
|
+
}, [storeRef, attempt]);
|
|
23
|
+
const reload = useCallback(() => setAttempt((n) => n + 1), []);
|
|
24
|
+
return { config, error, reload };
|
|
25
|
+
}
|
|
26
|
+
export {
|
|
27
|
+
usePublicAuthConfig
|
|
28
|
+
};
|
|
29
|
+
//# sourceMappingURL=use-public-auth-config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/auth/use-public-auth-config.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport type { PublicAuthConfig } from \"@ecomweb/sdk\";\nimport { storeApiPath } from \"../store-scope\";\n\nexport interface UsePublicAuthConfigResult {\n /** `null` while loading and after a failed load — check `error` to tell them apart. */\n config: PublicAuthConfig | null;\n error: boolean;\n reload: () => void;\n}\n\n/**\n * The store's public auth config (which sign-in methods are on, and the\n * password policy). Served by the storefront's own route so no API key or\n * backend origin is needed in the browser.\n *\n * Shared by the login/register form and the checkout create-account option so\n * both gate on the same `password_enabled` / `password_policy`.\n */\nexport function usePublicAuthConfig(\n storeRef: string\n): UsePublicAuthConfigResult {\n const [config, setConfig] = useState<PublicAuthConfig | null>(null);\n const [error, setError] = useState(false);\n const [attempt, setAttempt] = useState(0);\n\n useEffect(() => {\n let cancelled = false;\n setError(false);\n setConfig(null);\n\n fetch(storeApiPath(storeRef, \"auth/config\"))\n .then(res =>\n res.ok ? res.json() : Promise.reject(new Error(\"config fetch failed\"))\n )\n .then((data: PublicAuthConfig) => {\n if (!cancelled) setConfig(data);\n })\n .catch(() => {\n // A non-ok response and a thrown fetch are both \"could not load\" —\n // the shopper has no use for the distinction.\n if (!cancelled) setError(true);\n });\n\n return () => {\n cancelled = true;\n };\n }, [storeRef, attempt]);\n\n const reload = useCallback(() => setAttempt(n => n + 1), []);\n\n return { config, error, reload };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,gBAAgB;AAEjD,SAAS,oBAAoB;AAiBtB,SAAS,oBACd,UAC2B;AAC3B,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAkC,IAAI;AAClE,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,KAAK;AACxC,QAAM,CAAC,SAAS,UAAU,IAAI,SAAS,CAAC;AAExC,YAAU,MAAM;AACd,QAAI,YAAY;AAChB,aAAS,KAAK;AACd,cAAU,IAAI;AAEd,UAAM,aAAa,UAAU,aAAa,CAAC,EACxC;AAAA,MAAK,SACJ,IAAI,KAAK,IAAI,KAAK,IAAI,QAAQ,OAAO,IAAI,MAAM,qBAAqB,CAAC;AAAA,IACvE,EACC,KAAK,CAAC,SAA2B;AAChC,UAAI,CAAC,UAAW,WAAU,IAAI;AAAA,IAChC,CAAC,EACA,MAAM,MAAM;AAGX,UAAI,CAAC,UAAW,UAAS,IAAI;AAAA,IAC/B,CAAC;AAEH,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,UAAU,OAAO,CAAC;AAEtB,QAAM,SAAS,YAAY,MAAM,WAAW,OAAK,IAAI,CAAC,GAAG,CAAC,CAAC;AAE3D,SAAO,EAAE,QAAQ,OAAO,OAAO;AACjC;","names":[]}
|
package/dist/cart/api.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createStoreSdk } from "../sdk.js";
|
|
2
|
+
class CartApiService {
|
|
3
|
+
getSessionId() {
|
|
4
|
+
if (typeof window === "undefined") return "";
|
|
5
|
+
let sessionId = localStorage.getItem("cart_session_id");
|
|
6
|
+
if (!sessionId) {
|
|
7
|
+
sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
8
|
+
localStorage.setItem("cart_session_id", sessionId);
|
|
9
|
+
}
|
|
10
|
+
return sessionId;
|
|
11
|
+
}
|
|
12
|
+
async getCart(storeRef, isAuth) {
|
|
13
|
+
return createStoreSdk(storeRef).cart.getCart(
|
|
14
|
+
storeRef,
|
|
15
|
+
this.getSessionId(),
|
|
16
|
+
isAuth
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
async addToCart(storeRef, data, isAuth) {
|
|
20
|
+
return createStoreSdk(storeRef).cart.addItem(
|
|
21
|
+
storeRef,
|
|
22
|
+
data,
|
|
23
|
+
this.getSessionId(),
|
|
24
|
+
isAuth
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
async updateCartItem(storeRef, itemId, data, isAuth) {
|
|
28
|
+
return createStoreSdk(storeRef).cart.updateItem(
|
|
29
|
+
storeRef,
|
|
30
|
+
itemId,
|
|
31
|
+
data,
|
|
32
|
+
this.getSessionId(),
|
|
33
|
+
isAuth
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
async removeFromCart(storeRef, itemId, isAuth) {
|
|
37
|
+
return createStoreSdk(storeRef).cart.removeItem(
|
|
38
|
+
storeRef,
|
|
39
|
+
itemId,
|
|
40
|
+
this.getSessionId(),
|
|
41
|
+
isAuth
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
async clearCart(storeRef, isAuth) {
|
|
45
|
+
return createStoreSdk(storeRef).cart.clear(
|
|
46
|
+
storeRef,
|
|
47
|
+
this.getSessionId(),
|
|
48
|
+
isAuth
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
/** Always authenticated: merging a guest cart needs an identity to merge into. */
|
|
52
|
+
async mergeCarts(storeRef) {
|
|
53
|
+
return createStoreSdk(storeRef).cart.merge(storeRef, this.getSessionId());
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const cartApiService = new CartApiService();
|
|
57
|
+
export {
|
|
58
|
+
cartApiService
|
|
59
|
+
};
|
|
60
|
+
//# sourceMappingURL=api.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/cart/api.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\n\nexport type {\n CartApiItem,\n CartApiResponse,\n AddToCartRequest,\n UpdateCartItemRequest,\n} from \"@ecomweb/sdk\";\n\nexport interface MergeCartsRequest {\n // No body needed, user_id comes from header\n}\n\n/**\n * Plain module, not a component, so it cannot read React context or an\n * httpOnly cookie. `storeRef` and `isAuth` are therefore explicit parameters\n * supplied by `CartProvider`. When `isAuth` is true the SDK takes the\n * JWT-guarded `/stores/:ref/cart` branch, which reaches the backend through the\n * same-origin proxy (`lib/api/proxy.ts`) — that is what attaches the bearer\n * token server-side.\n */\nclass CartApiService {\n private getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n\n let sessionId = localStorage.getItem(\"cart_session_id\");\n if (!sessionId) {\n sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n localStorage.setItem(\"cart_session_id\", sessionId);\n }\n return sessionId;\n }\n\n async getCart(storeRef: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.getCart(\n storeRef,\n this.getSessionId(),\n isAuth\n );\n }\n\n async addToCart(\n storeRef: string,\n data: Parameters<ReturnType<typeof createStoreSdk>[\"cart\"][\"addItem\"]>[1],\n isAuth: boolean\n ) {\n return createStoreSdk(storeRef).cart.addItem(\n storeRef,\n data,\n this.getSessionId(),\n isAuth\n );\n }\n\n async updateCartItem(\n storeRef: string,\n itemId: string,\n data: Parameters<\n ReturnType<typeof createStoreSdk>[\"cart\"][\"updateItem\"]\n >[2],\n isAuth: boolean\n ) {\n return createStoreSdk(storeRef).cart.updateItem(\n storeRef,\n itemId,\n data,\n this.getSessionId(),\n isAuth\n );\n }\n\n async removeFromCart(storeRef: string, itemId: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.removeItem(\n storeRef,\n itemId,\n this.getSessionId(),\n isAuth\n );\n }\n\n async clearCart(storeRef: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.clear(\n storeRef,\n this.getSessionId(),\n isAuth\n );\n }\n\n /** Always authenticated: merging a guest cart needs an identity to merge into. */\n async mergeCarts(storeRef: string) {\n return createStoreSdk(storeRef).cart.merge(storeRef, this.getSessionId());\n }\n}\n\nexport const cartApiService = new CartApiService();\n"],"mappings":"AAAA,SAAS,sBAAsB;AAqB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AI,eAAe;","names":[]}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx } from "react/jsx-runtime";
|
|
3
|
+
import {
|
|
4
|
+
createContext,
|
|
5
|
+
useContext,
|
|
6
|
+
useReducer,
|
|
7
|
+
useEffect,
|
|
8
|
+
useCallback
|
|
9
|
+
} from "react";
|
|
10
|
+
import { useNotify } from "../notices.js";
|
|
11
|
+
import { cartApiService } from "./api.js";
|
|
12
|
+
const cartReducer = (state, action) => {
|
|
13
|
+
switch (action.type) {
|
|
14
|
+
case "SET_LOADING":
|
|
15
|
+
return {
|
|
16
|
+
...state,
|
|
17
|
+
isLoading: action.payload
|
|
18
|
+
};
|
|
19
|
+
case "LOAD_CART": {
|
|
20
|
+
const cart = action.payload;
|
|
21
|
+
const items = cart.items.map((item) => ({
|
|
22
|
+
id: item.id,
|
|
23
|
+
productId: item.product_id,
|
|
24
|
+
variantId: item.variant_id ?? void 0,
|
|
25
|
+
name: item.product_name,
|
|
26
|
+
price: item.price,
|
|
27
|
+
originalPrice: item.original_price,
|
|
28
|
+
image: item.product_image,
|
|
29
|
+
quantity: item.quantity,
|
|
30
|
+
variantName: item.variant_name,
|
|
31
|
+
variantOptions: item.variant_options,
|
|
32
|
+
promotions: item.promotions,
|
|
33
|
+
bestPromotion: item.best_promotion
|
|
34
|
+
}));
|
|
35
|
+
return {
|
|
36
|
+
...state,
|
|
37
|
+
items,
|
|
38
|
+
total: cart.total,
|
|
39
|
+
subtotal: cart.subtotal,
|
|
40
|
+
originalSubtotal: cart.original_subtotal,
|
|
41
|
+
discountAmount: cart.discount_amount,
|
|
42
|
+
shippingFee: cart.shipping_fee,
|
|
43
|
+
itemCount: cart.item_count,
|
|
44
|
+
cartId: cart.id,
|
|
45
|
+
isLoading: false
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
case "SET_SESSION_ID":
|
|
49
|
+
return {
|
|
50
|
+
...state,
|
|
51
|
+
sessionId: action.payload
|
|
52
|
+
};
|
|
53
|
+
case "CLEAR_CART":
|
|
54
|
+
return {
|
|
55
|
+
...state,
|
|
56
|
+
items: [],
|
|
57
|
+
total: 0,
|
|
58
|
+
subtotal: 0,
|
|
59
|
+
originalSubtotal: 0,
|
|
60
|
+
discountAmount: 0,
|
|
61
|
+
shippingFee: 0,
|
|
62
|
+
itemCount: 0,
|
|
63
|
+
cartId: void 0
|
|
64
|
+
};
|
|
65
|
+
default:
|
|
66
|
+
return state;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const CartContext = createContext(void 0);
|
|
70
|
+
function CartProvider({
|
|
71
|
+
children,
|
|
72
|
+
storeRef,
|
|
73
|
+
userId
|
|
74
|
+
}) {
|
|
75
|
+
const isAuth = !!userId;
|
|
76
|
+
const notify = useNotify();
|
|
77
|
+
const [state, dispatch] = useReducer(cartReducer, {
|
|
78
|
+
items: [],
|
|
79
|
+
total: 0,
|
|
80
|
+
subtotal: 0,
|
|
81
|
+
originalSubtotal: 0,
|
|
82
|
+
discountAmount: 0,
|
|
83
|
+
shippingFee: 0,
|
|
84
|
+
itemCount: 0,
|
|
85
|
+
isLoading: true
|
|
86
|
+
// Start with loading true to show loading state on initial render
|
|
87
|
+
});
|
|
88
|
+
useEffect(() => {
|
|
89
|
+
if (!userId && !state.sessionId) {
|
|
90
|
+
const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
91
|
+
dispatch({ type: "SET_SESSION_ID", payload: sessionId });
|
|
92
|
+
}
|
|
93
|
+
}, [userId, state.sessionId]);
|
|
94
|
+
const loadCart = useCallback(async () => {
|
|
95
|
+
if (!storeRef) return;
|
|
96
|
+
dispatch({ type: "SET_LOADING", payload: true });
|
|
97
|
+
try {
|
|
98
|
+
const cart = await cartApiService.getCart(storeRef, isAuth);
|
|
99
|
+
if (cart) {
|
|
100
|
+
dispatch({ type: "LOAD_CART", payload: cart });
|
|
101
|
+
} else {
|
|
102
|
+
dispatch({ type: "SET_LOADING", payload: false });
|
|
103
|
+
}
|
|
104
|
+
} catch (error) {
|
|
105
|
+
console.error("Failed to load cart:", error);
|
|
106
|
+
dispatch({ type: "SET_LOADING", payload: false });
|
|
107
|
+
}
|
|
108
|
+
}, [storeRef, isAuth]);
|
|
109
|
+
useEffect(() => {
|
|
110
|
+
loadCart();
|
|
111
|
+
}, [loadCart]);
|
|
112
|
+
const addItem = async (item) => {
|
|
113
|
+
if (!storeRef) return;
|
|
114
|
+
try {
|
|
115
|
+
await cartApiService.addToCart(
|
|
116
|
+
storeRef,
|
|
117
|
+
{
|
|
118
|
+
product_id: item.productId,
|
|
119
|
+
variant_id: item.variantId,
|
|
120
|
+
quantity: item.quantity || 1
|
|
121
|
+
},
|
|
122
|
+
isAuth
|
|
123
|
+
);
|
|
124
|
+
await loadCart();
|
|
125
|
+
notify({
|
|
126
|
+
kind: "success",
|
|
127
|
+
code: "cart.item_added",
|
|
128
|
+
title: "\u0110\xE3 th\xEAm v\xE0o gi\u1ECF h\xE0ng",
|
|
129
|
+
description: `${item.name} \u0111\xE3 \u0111\u01B0\u1EE3c th\xEAm v\xE0o gi\u1ECF h\xE0ng c\u1EE7a b\u1EA1n`,
|
|
130
|
+
data: { productName: item.name }
|
|
131
|
+
});
|
|
132
|
+
} catch (error) {
|
|
133
|
+
console.error("Failed to add item to cart:", error);
|
|
134
|
+
notify({
|
|
135
|
+
kind: "error",
|
|
136
|
+
code: "cart.add_failed",
|
|
137
|
+
title: "L\u1ED7i",
|
|
138
|
+
description: "Kh\xF4ng th\u1EC3 th\xEAm s\u1EA3n ph\u1EA9m v\xE0o gi\u1ECF h\xE0ng"
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
const reorderItems = async (items) => {
|
|
143
|
+
if (!storeRef) return { added: 0, total: items.length };
|
|
144
|
+
let added = 0;
|
|
145
|
+
for (const item of items) {
|
|
146
|
+
try {
|
|
147
|
+
await cartApiService.addToCart(
|
|
148
|
+
storeRef,
|
|
149
|
+
{
|
|
150
|
+
product_id: item.product_id,
|
|
151
|
+
variant_id: item.variant_id,
|
|
152
|
+
quantity: item.quantity
|
|
153
|
+
},
|
|
154
|
+
isAuth
|
|
155
|
+
);
|
|
156
|
+
added += 1;
|
|
157
|
+
} catch (error) {
|
|
158
|
+
console.error("Reorder skipped an item:", error);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
await loadCart();
|
|
162
|
+
return { added, total: items.length };
|
|
163
|
+
};
|
|
164
|
+
const removeItem = async (id) => {
|
|
165
|
+
if (!storeRef) return;
|
|
166
|
+
const item = state.items.find((item2) => item2.id === id);
|
|
167
|
+
try {
|
|
168
|
+
await cartApiService.removeFromCart(storeRef, id, isAuth);
|
|
169
|
+
await loadCart();
|
|
170
|
+
if (item) {
|
|
171
|
+
notify({
|
|
172
|
+
kind: "success",
|
|
173
|
+
code: "cart.item_removed",
|
|
174
|
+
title: "\u0110\xE3 x\xF3a kh\u1ECFi gi\u1ECF h\xE0ng",
|
|
175
|
+
description: `${item.name} \u0111\xE3 \u0111\u01B0\u1EE3c x\xF3a kh\u1ECFi gi\u1ECF h\xE0ng`,
|
|
176
|
+
data: { productName: item.name }
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
} catch (error) {
|
|
180
|
+
console.error("Failed to remove item from cart:", error);
|
|
181
|
+
notify({
|
|
182
|
+
kind: "error",
|
|
183
|
+
code: "cart.remove_failed",
|
|
184
|
+
title: "L\u1ED7i",
|
|
185
|
+
description: "Kh\xF4ng th\u1EC3 x\xF3a s\u1EA3n ph\u1EA9m kh\u1ECFi gi\u1ECF h\xE0ng"
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
const updateQuantity = async (id, quantity) => {
|
|
190
|
+
if (!storeRef) return;
|
|
191
|
+
try {
|
|
192
|
+
await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);
|
|
193
|
+
await loadCart();
|
|
194
|
+
} catch (error) {
|
|
195
|
+
console.error("Failed to update item quantity:", error);
|
|
196
|
+
notify({
|
|
197
|
+
kind: "error",
|
|
198
|
+
code: "cart.update_failed",
|
|
199
|
+
title: "L\u1ED7i",
|
|
200
|
+
description: "Kh\xF4ng th\u1EC3 c\u1EADp nh\u1EADt s\u1ED1 l\u01B0\u1EE3ng s\u1EA3n ph\u1EA9m"
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
const clearCart = async (notifyCleared = true) => {
|
|
205
|
+
if (!storeRef) return;
|
|
206
|
+
try {
|
|
207
|
+
await cartApiService.clearCart(storeRef, isAuth);
|
|
208
|
+
dispatch({ type: "CLEAR_CART" });
|
|
209
|
+
if (notifyCleared) {
|
|
210
|
+
notify({
|
|
211
|
+
kind: "success",
|
|
212
|
+
code: "cart.cleared",
|
|
213
|
+
title: "\u0110\xE3 x\xF3a gi\u1ECF h\xE0ng",
|
|
214
|
+
description: "T\u1EA5t c\u1EA3 s\u1EA3n ph\u1EA9m \u0111\xE3 \u0111\u01B0\u1EE3c x\xF3a kh\u1ECFi gi\u1ECF h\xE0ng"
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
} catch (error) {
|
|
218
|
+
console.error("Failed to clear cart:", error);
|
|
219
|
+
notify({
|
|
220
|
+
kind: "error",
|
|
221
|
+
code: "cart.clear_failed",
|
|
222
|
+
title: "L\u1ED7i",
|
|
223
|
+
description: "Kh\xF4ng th\u1EC3 x\xF3a gi\u1ECF h\xE0ng"
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
const refreshCart = async () => {
|
|
228
|
+
await loadCart();
|
|
229
|
+
};
|
|
230
|
+
const mergeCarts = async (_userId) => {
|
|
231
|
+
if (!storeRef || !state.sessionId) return;
|
|
232
|
+
try {
|
|
233
|
+
await cartApiService.mergeCarts(storeRef);
|
|
234
|
+
await loadCart();
|
|
235
|
+
notify({
|
|
236
|
+
kind: "success",
|
|
237
|
+
code: "cart.merged",
|
|
238
|
+
title: "\u0110\xE3 \u0111\u1ED3ng b\u1ED9 gi\u1ECF h\xE0ng",
|
|
239
|
+
description: "Gi\u1ECF h\xE0ng \u0111\xE3 \u0111\u01B0\u1EE3c \u0111\u1ED3ng b\u1ED9 v\u1EDBi t\xE0i kho\u1EA3n c\u1EE7a b\u1EA1n"
|
|
240
|
+
});
|
|
241
|
+
} catch (error) {
|
|
242
|
+
console.error("Failed to merge carts:", error);
|
|
243
|
+
notify({
|
|
244
|
+
kind: "error",
|
|
245
|
+
code: "cart.merge_failed",
|
|
246
|
+
title: "L\u1ED7i",
|
|
247
|
+
description: "Kh\xF4ng th\u1EC3 \u0111\u1ED3ng b\u1ED9 gi\u1ECF h\xE0ng"
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
return /* @__PURE__ */ jsx(
|
|
252
|
+
CartContext.Provider,
|
|
253
|
+
{
|
|
254
|
+
value: {
|
|
255
|
+
...state,
|
|
256
|
+
addItem,
|
|
257
|
+
removeItem,
|
|
258
|
+
updateQuantity,
|
|
259
|
+
clearCart,
|
|
260
|
+
refreshCart,
|
|
261
|
+
mergeCarts,
|
|
262
|
+
reorderItems
|
|
263
|
+
},
|
|
264
|
+
children
|
|
265
|
+
}
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
function useCart() {
|
|
269
|
+
const context = useContext(CartContext);
|
|
270
|
+
if (context === void 0) {
|
|
271
|
+
throw new Error("useCart must be used within a CartProvider");
|
|
272
|
+
}
|
|
273
|
+
return context;
|
|
274
|
+
}
|
|
275
|
+
export {
|
|
276
|
+
CartProvider,
|
|
277
|
+
useCart
|
|
278
|
+
};
|
|
279
|
+
//# sourceMappingURL=server-context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/cart/server-context.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useReducer,\n useEffect,\n useCallback,\n type ReactNode,\n} from \"react\";\nimport { useNotify } from \"../notices\";\nimport { CartItem } from \"./types\";\nimport { cartApiService, CartApiResponse, CartApiItem } from \"./api\";\n\ninterface CartState {\n items: CartItem[];\n total: number;\n subtotal: number;\n originalSubtotal: number;\n discountAmount: number;\n shippingFee: number;\n itemCount: number;\n isLoading: boolean;\n cartId?: string;\n sessionId?: string;\n}\n\ntype CartAction =\n | { type: \"SET_LOADING\"; payload: boolean }\n | { type: \"LOAD_CART\"; payload: CartApiResponse }\n | { type: \"SET_SESSION_ID\"; payload: string }\n | { type: \"CLEAR_CART\" };\n\nconst cartReducer = (state: CartState, action: CartAction): CartState => {\n switch (action.type) {\n case \"SET_LOADING\":\n return {\n ...state,\n isLoading: action.payload,\n };\n\n case \"LOAD_CART\": {\n const cart = action.payload;\n const items: CartItem[] = cart.items.map((item: CartApiItem) => ({\n id: item.id,\n productId: item.product_id,\n variantId: item.variant_id ?? undefined,\n name: item.product_name,\n price: item.price,\n originalPrice: item.original_price,\n image: item.product_image,\n quantity: item.quantity,\n variantName: item.variant_name,\n variantOptions: item.variant_options,\n promotions: item.promotions,\n bestPromotion: item.best_promotion,\n }));\n\n return {\n ...state,\n items,\n total: cart.total,\n subtotal: cart.subtotal,\n originalSubtotal: cart.original_subtotal,\n discountAmount: cart.discount_amount,\n shippingFee: cart.shipping_fee,\n itemCount: cart.item_count,\n cartId: cart.id,\n isLoading: false,\n };\n }\n\n case \"SET_SESSION_ID\":\n return {\n ...state,\n sessionId: action.payload,\n };\n\n case \"CLEAR_CART\":\n return {\n ...state,\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n cartId: undefined,\n };\n\n default:\n return state;\n }\n};\n\ninterface CartContextType extends CartState {\n addItem: (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => Promise<void>;\n removeItem: (id: string) => Promise<void>;\n updateQuantity: (id: string, quantity: number) => Promise<void>;\n /** Pass false to skip the \"cart cleared\" notice (e.g. after checkout). */\n clearCart: (notifyCleared?: boolean) => Promise<void>;\n refreshCart: () => Promise<void>;\n mergeCarts: (userId: string) => Promise<void>;\n reorderItems: (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ) => Promise<{ added: number; total: number }>;\n}\n\nconst CartContext = createContext<CartContextType | undefined>(undefined);\n\ninterface CartProviderProps {\n children: ReactNode;\n storeRef: string;\n userId?: string;\n}\n\nexport function CartProvider({\n children,\n storeRef,\n userId,\n}: CartProviderProps) {\n // A signed-in shopper gets the identity-scoped cart; everyone else gets the\n // session-id cart. `userId` comes from the auth context one level up\n // (StoreCartProvider) — this module can never read the httpOnly cookie itself.\n const isAuth = !!userId;\n const notify = useNotify();\n const [state, dispatch] = useReducer(cartReducer, {\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n isLoading: true, // Start with loading true to show loading state on initial render\n });\n\n // Generate session ID for anonymous users\n useEffect(() => {\n if (!userId && !state.sessionId) {\n const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n dispatch({ type: \"SET_SESSION_ID\", payload: sessionId });\n }\n }, [userId, state.sessionId]);\n\n // Load cart from server\n const loadCart = useCallback(async () => {\n if (!storeRef) return;\n\n dispatch({ type: \"SET_LOADING\", payload: true });\n try {\n const cart = await cartApiService.getCart(storeRef, isAuth);\n\n if (cart) {\n dispatch({ type: \"LOAD_CART\", payload: cart });\n } else {\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n } catch (error) {\n console.error(\"Failed to load cart:\", error);\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n }, [storeRef, isAuth]);\n\n // Load cart on mount and when dependencies change\n useEffect(() => {\n loadCart();\n }, [loadCart]);\n\n const addItem = async (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => {\n if (!storeRef) return;\n\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.productId,\n variant_id: item.variantId,\n quantity: item.quantity || 1,\n },\n isAuth\n );\n\n // Refresh cart after adding item\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.item_added\",\n title: \"Đã thêm vào giỏ hàng\",\n description: `${item.name} đã được thêm vào giỏ hàng của bạn`,\n data: { productName: item.name },\n });\n } catch (error) {\n console.error(\"Failed to add item to cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.add_failed\",\n title: \"Lỗi\",\n description: \"Không thể thêm sản phẩm vào giỏ hàng\",\n });\n }\n };\n\n /**\n * Add every line of a past order back to the cart.\n *\n * Deliberately not a loop over addItem: that notifies per item and swallows\n * its errors, so a reorder would fire one notice per line and the caller\n * could never report a shortfall. This refreshes once and returns counts.\n */\n const reorderItems = async (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ): Promise<{ added: number; total: number }> => {\n if (!storeRef) return { added: 0, total: items.length };\n\n let added = 0;\n for (const item of items) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id,\n quantity: item.quantity,\n },\n isAuth\n );\n added += 1;\n } catch (error) {\n // Product deleted, out of stock, or repriced since purchase. Skip it —\n // the caller reports the shortfall rather than failing the reorder.\n console.error(\"Reorder skipped an item:\", error);\n }\n }\n\n await loadCart();\n return { added, total: items.length };\n };\n\n const removeItem = async (id: string) => {\n if (!storeRef) return;\n\n const item = state.items.find(item => item.id === id);\n\n try {\n await cartApiService.removeFromCart(storeRef, id, isAuth);\n\n // Refresh cart after removing item\n await loadCart();\n\n if (item) {\n notify({\n kind: \"success\",\n code: \"cart.item_removed\",\n title: \"Đã xóa khỏi giỏ hàng\",\n description: `${item.name} đã được xóa khỏi giỏ hàng`,\n data: { productName: item.name },\n });\n }\n } catch (error) {\n console.error(\"Failed to remove item from cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.remove_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa sản phẩm khỏi giỏ hàng\",\n });\n }\n };\n\n const updateQuantity = async (id: string, quantity: number) => {\n if (!storeRef) return;\n\n try {\n await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);\n\n // Refresh cart after updating quantity\n await loadCart();\n } catch (error) {\n console.error(\"Failed to update item quantity:\", error);\n notify({\n kind: \"error\",\n code: \"cart.update_failed\",\n title: \"Lỗi\",\n description: \"Không thể cập nhật số lượng sản phẩm\",\n });\n }\n };\n\n const clearCart = async (notifyCleared: boolean = true) => {\n if (!storeRef) return;\n\n try {\n await cartApiService.clearCart(storeRef, isAuth);\n\n dispatch({ type: \"CLEAR_CART\" });\n\n if (notifyCleared) {\n notify({\n kind: \"success\",\n code: \"cart.cleared\",\n title: \"Đã xóa giỏ hàng\",\n description: \"Tất cả sản phẩm đã được xóa khỏi giỏ hàng\",\n });\n }\n } catch (error) {\n console.error(\"Failed to clear cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.clear_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa giỏ hàng\",\n });\n }\n };\n\n const refreshCart = async () => {\n await loadCart();\n };\n\n const mergeCarts = async (_userId: string) => {\n if (!storeRef || !state.sessionId) return;\n\n try {\n await cartApiService.mergeCarts(storeRef);\n\n // Refresh cart after merging\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.merged\",\n title: \"Đã đồng bộ giỏ hàng\",\n description: \"Giỏ hàng đã được đồng bộ với tài khoản của bạn\",\n });\n } catch (error) {\n console.error(\"Failed to merge carts:\", error);\n notify({\n kind: \"error\",\n code: \"cart.merge_failed\",\n title: \"Lỗi\",\n description: \"Không thể đồng bộ giỏ hàng\",\n });\n }\n };\n\n return (\n <CartContext.Provider\n value={{\n ...state,\n addItem,\n removeItem,\n updateQuantity,\n clearCart,\n refreshCart,\n mergeCarts,\n reorderItems,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\nexport function useCart() {\n const context = useContext(CartContext);\n if (context === undefined) {\n throw new Error(\"useCart must be used within a CartProvider\");\n }\n return context;\n}\n"],"mappings":";AAiWI;AA/VJ;AAAA,EACE;AAAA,EACA;AAAA,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QAAQ;AAGxC,YAAM,SAAS;AAEf,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH,SAAS,OAAO;AACd,cAAQ,MAAM,0BAA0B,KAAK;AAC7C,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SACE;AAAA,IAAC,YAAY;AAAA,IAAZ;AAAA,MACC,OAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAEO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AACA,SAAO;AACT;","names":["item"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
function generateCartItemId(productId, variantId) {
|
|
2
|
+
if (variantId) {
|
|
3
|
+
return `${productId}-${variantId}`;
|
|
4
|
+
}
|
|
5
|
+
return `${productId}`;
|
|
6
|
+
}
|
|
7
|
+
function createCartItemFromVariant(productId, productName, productImage, variant, variantName, variantOptions) {
|
|
8
|
+
return {
|
|
9
|
+
id: generateCartItemId(productId, variant.id),
|
|
10
|
+
productId,
|
|
11
|
+
variantId: variant.id,
|
|
12
|
+
name: productName,
|
|
13
|
+
price: variant.price,
|
|
14
|
+
originalPrice: variant.price,
|
|
15
|
+
// You might want to add original_price to variants
|
|
16
|
+
image: productImage,
|
|
17
|
+
quantity: 1,
|
|
18
|
+
variantName,
|
|
19
|
+
variantOptions
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function createCartItemFromProduct(productId, productName, productImage, price, originalPrice) {
|
|
23
|
+
return {
|
|
24
|
+
id: generateCartItemId(productId),
|
|
25
|
+
productId,
|
|
26
|
+
name: productName,
|
|
27
|
+
price,
|
|
28
|
+
originalPrice,
|
|
29
|
+
image: productImage,
|
|
30
|
+
quantity: 1
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function isVariantItem(item) {
|
|
34
|
+
return item.variantId !== void 0;
|
|
35
|
+
}
|
|
36
|
+
function getVariantDisplayName(variantOptions) {
|
|
37
|
+
if (!variantOptions || variantOptions.length === 0) {
|
|
38
|
+
return "";
|
|
39
|
+
}
|
|
40
|
+
return variantOptions.map((option) => `${option.optionName}: ${option.optionValue}`).join(", ");
|
|
41
|
+
}
|
|
42
|
+
export {
|
|
43
|
+
createCartItemFromProduct,
|
|
44
|
+
createCartItemFromVariant,
|
|
45
|
+
generateCartItemId,
|
|
46
|
+
getVariantDisplayName,
|
|
47
|
+
isVariantItem
|
|
48
|
+
};
|
|
49
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/cart/utils.ts"],"sourcesContent":["import type { ProductVariant } from \"@ecomweb/sdk\";\n\nimport { CartItem } from \"./types\";\n\n/**\n * Generate a unique cart item ID for a product variant\n */\nexport function generateCartItemId(\n productId: number,\n variantId?: number\n): string {\n if (variantId) {\n return `${productId}-${variantId}`;\n }\n return `${productId}`;\n}\n\n/**\n * Create a cart item from a product variant\n */\nexport function createCartItemFromVariant(\n productId: number,\n productName: string,\n productImage: string | undefined,\n variant: ProductVariant,\n variantName?: string,\n variantOptions?: Array<{ optionName: string; optionValue: string }>\n): CartItem {\n return {\n id: generateCartItemId(productId, variant.id),\n productId,\n variantId: variant.id,\n name: productName,\n price: variant.price,\n originalPrice: variant.price, // You might want to add original_price to variants\n image: productImage,\n quantity: 1,\n variantName,\n variantOptions,\n };\n}\n\n/**\n * Create a cart item from a simple product (no variants)\n */\nexport function createCartItemFromProduct(\n productId: number,\n productName: string,\n productImage: string | undefined,\n price: number,\n originalPrice?: number\n): CartItem {\n return {\n id: generateCartItemId(productId),\n productId,\n name: productName,\n price,\n originalPrice,\n image: productImage,\n quantity: 1,\n };\n}\n\n/**\n * Check if a cart item is a variant\n */\nexport function isVariantItem(item: CartItem): boolean {\n return item.variantId !== undefined;\n}\n\n/**\n * Get display name for variant options\n */\nexport function getVariantDisplayName(\n variantOptions?: Array<{ optionName: string; optionValue: string }>\n): string {\n if (!variantOptions || variantOptions.length === 0) {\n return \"\";\n }\n\n return variantOptions\n .map(option => `${option.optionName}: ${option.optionValue}`)\n .join(\", \");\n}\n"],"mappings":"AAOO,SAAS,mBACd,WACA,WACQ;AACR,MAAI,WAAW;AACb,WAAO,GAAG,SAAS,IAAI,SAAS;AAAA,EAClC;AACA,SAAO,GAAG,SAAS;AACrB;AAKO,SAAS,0BACd,WACA,aACA,cACA,SACA,aACA,gBACU;AACV,SAAO;AAAA,IACL,IAAI,mBAAmB,WAAW,QAAQ,EAAE;AAAA,IAC5C;AAAA,IACA,WAAW,QAAQ;AAAA,IACnB,MAAM;AAAA,IACN,OAAO,QAAQ;AAAA,IACf,eAAe,QAAQ;AAAA;AAAA,IACvB,OAAO;AAAA,IACP,UAAU;AAAA,IACV;AAAA,IACA;AAAA,EACF;AACF;AAKO,SAAS,0BACd,WACA,aACA,cACA,OACA,eACU;AACV,SAAO;AAAA,IACL,IAAI,mBAAmB,SAAS;AAAA,IAChC;AAAA,IACA,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,UAAU;AAAA,EACZ;AACF;AAKO,SAAS,cAAc,MAAyB;AACrD,SAAO,KAAK,cAAc;AAC5B;AAKO,SAAS,sBACd,gBACQ;AACR,MAAI,CAAC,kBAAkB,eAAe,WAAW,GAAG;AAClD,WAAO;AAAA,EACT;AAEA,SAAO,eACJ,IAAI,YAAU,GAAG,OAAO,UAAU,KAAK,OAAO,WAAW,EAAE,EAC3D,KAAK,IAAI;AACd;","names":[]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { publicApiClient } from "../api/client.js";
|
|
2
|
+
import { unwrap } from "../api/response.js";
|
|
3
|
+
async function getPaymentState(storeRef, order_code) {
|
|
4
|
+
const res = await publicApiClient.get(
|
|
5
|
+
// `order_code` carries a `#` prefix by default in this system — left
|
|
6
|
+
// unencoded, it truncates the URL (everything from `#` on is treated
|
|
7
|
+
// as a fragment) and the request silently hits a different route.
|
|
8
|
+
`/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`
|
|
9
|
+
);
|
|
10
|
+
return unwrap(res);
|
|
11
|
+
}
|
|
12
|
+
export {
|
|
13
|
+
getPaymentState
|
|
14
|
+
};
|
|
15
|
+
//# sourceMappingURL=get-payment-state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/checkout/get-payment-state.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport type { PaymentStateResult } from \"./payment-state-poll\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.getPaymentState`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-sdk` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * — see `lib/checkout/initiate-gateway-payment.ts` for the full story\n * (same pinned commit, same missing module). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.getPaymentState()`'s request/response\n * shape exactly (same path, same result shape) so that once the SDK bump\n * lands, the fix is: delete this file, delete this import in\n * `payment-state-poll`'s caller, and call\n * `sdk.payments.getPaymentState(...)` instead — the call site already reads\n * as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.getPaymentState`.\n */\nexport async function getPaymentState(\n storeRef: string,\n order_code: string\n): Promise<PaymentStateResult> {\n const res = await publicApiClient.get<PaymentStateResult>(\n // `order_code` carries a `#` prefix by default in this system — left\n // unencoded, it truncates the URL (everything from `#` on is treated\n // as a fragment) and the request silently hits a different route.\n `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AAyBvB,eAAsB,gBACpB,UACA,YAC6B;AAC7B,QAAM,MAAM,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA,IAIhC,kBAAkB,mBAAmB,QAAQ,CAAC,WAAW,mBAAmB,UAAU,CAAC;AAAA,EACzF;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { publicApiClient } from "../api/client.js";
|
|
2
|
+
import { unwrap } from "../api/response.js";
|
|
3
|
+
async function initiateGatewayPayment(storeRef, input) {
|
|
4
|
+
const res = await publicApiClient.post(
|
|
5
|
+
`/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,
|
|
6
|
+
{ order_code: input.order_code, provider_code: input.provider_code }
|
|
7
|
+
);
|
|
8
|
+
return unwrap(res);
|
|
9
|
+
}
|
|
10
|
+
export {
|
|
11
|
+
initiateGatewayPayment
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=initiate-gateway-payment.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/checkout/initiate-gateway-payment.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.initiate`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-sdk` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * (confirmed: nothing under `node_modules/@ecomweb/sdk/src` references\n * `payments`, `provider_code`, or `redirect_url`). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.initiate()`'s request/response shape\n * exactly (same path, same body keys, same result shape) so that once the\n * SDK bump lands, the fix is: delete this file, delete this import in\n * `checkout-page-client.tsx`, and call `sdk.payments.initiate(...)` instead\n * — the call site already reads as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.initiate`.\n */\nexport interface InitiatePaymentResult {\n payment_id: number;\n redirect_url: string;\n}\n\nexport async function initiateGatewayPayment(\n storeRef: string,\n input: { order_code: string; provider_code: string }\n): Promise<InitiatePaymentResult> {\n const res = await publicApiClient.post<InitiatePaymentResult>(\n `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,\n { order_code: input.order_code, provider_code: input.provider_code }\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AA4BvB,eAAsB,uBACpB,UACA,OACgC;AAChC,QAAM,MAAM,MAAM,gBAAgB;AAAA,IAChC,kBAAkB,mBAAmB,QAAQ,CAAC;AAAA,IAC9C,EAAE,YAAY,MAAM,YAAY,eAAe,MAAM,cAAc;AAAA,EACrE;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
const HANDOFF_KEY = "ecw:order-handoff";
|
|
2
|
+
const MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
3
|
+
function writeOrderHandoff(handoff) {
|
|
4
|
+
try {
|
|
5
|
+
window.localStorage.setItem(
|
|
6
|
+
HANDOFF_KEY,
|
|
7
|
+
JSON.stringify({ ...handoff, written_at: Date.now() })
|
|
8
|
+
);
|
|
9
|
+
} catch {
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function readOrderHandoff(order_code) {
|
|
13
|
+
if (!order_code) return null;
|
|
14
|
+
let raw = null;
|
|
15
|
+
try {
|
|
16
|
+
raw = window.localStorage.getItem(HANDOFF_KEY);
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
if (!raw) return null;
|
|
21
|
+
let parsed;
|
|
22
|
+
try {
|
|
23
|
+
parsed = JSON.parse(raw);
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
return matchHandoff(parsed, order_code, Date.now());
|
|
28
|
+
}
|
|
29
|
+
function matchHandoff(parsed, order_code, now) {
|
|
30
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
31
|
+
const h = parsed;
|
|
32
|
+
if (typeof h.order_code !== "string" || h.order_code !== order_code) return null;
|
|
33
|
+
if (typeof h.payment_method !== "string" || h.payment_method.length === 0) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
if (typeof h.total !== "number" || !Number.isFinite(h.total)) return null;
|
|
37
|
+
if (typeof h.written_at !== "number" || now - h.written_at > MAX_AGE_MS) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
order_code: h.order_code,
|
|
42
|
+
payment_method: h.payment_method,
|
|
43
|
+
provider_code: typeof h.provider_code === "string" && h.provider_code.length > 0 ? h.provider_code : null,
|
|
44
|
+
total: h.total,
|
|
45
|
+
currency_code: typeof h.currency_code === "string" && h.currency_code.length > 0 ? h.currency_code : "VND",
|
|
46
|
+
written_at: h.written_at
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function clearOrderHandoff() {
|
|
50
|
+
try {
|
|
51
|
+
window.localStorage.removeItem(HANDOFF_KEY);
|
|
52
|
+
} catch {
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export {
|
|
56
|
+
clearOrderHandoff,
|
|
57
|
+
matchHandoff,
|
|
58
|
+
readOrderHandoff,
|
|
59
|
+
writeOrderHandoff
|
|
60
|
+
};
|
|
61
|
+
//# sourceMappingURL=order-handoff.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/checkout/order-handoff.ts"],"sourcesContent":["/**\n * Carries what the success screen needs from the checkout page that placed\n * the order.\n *\n * Why this exists: gateway methods reach `/order-success` through the\n * provider and the API's return endpoint, so that page knows only the order\n * code. Offline methods (cod, bank_transfer) now navigate there directly, and\n * the screen has to know which method was used and how much to ask for.\n *\n * Why not read it from the API: the obvious candidate,\n * `GET /public/stores/:ref/orders/:code/payment-state`, deliberately\n * allow-lists its response down to two status fields, because it sits behind\n * only the public storefront key and order codes are sequential. Putting an\n * amount there would let anyone enumerate a store's order values. This data\n * never leaves the shopper's own browser instead.\n *\n * Replaces the older \"recent-order\" key, which nothing had written for a long\n * time while the success page still read it, so `orderInfo` there was always\n * null.\n */\nconst HANDOFF_KEY = \"ecw:order-handoff\";\n\n/** Older handoffs are ignored rather than shown against a newer order. */\nconst MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\nexport interface OrderHandoff {\n order_code: string;\n /** `cod`, `bank_transfer`, or a gateway code. */\n payment_method: string;\n /** Non-null only for gateway-backed methods. */\n provider_code: string | null;\n total: number;\n currency_code: string;\n written_at: number;\n}\n\nexport function writeOrderHandoff(\n handoff: Omit<OrderHandoff, \"written_at\">\n): void {\n try {\n window.localStorage.setItem(\n HANDOFF_KEY,\n JSON.stringify({ ...handoff, written_at: Date.now() })\n );\n } catch {\n // Private mode, quota, or storage disabled. The success screen falls back\n // to its order-code-only rendering, so losing this is a degradation and\n // never a failure.\n }\n}\n\n/**\n * Returns the handoff only if it is present, well-formed, fresh, and for the\n * order being shown. Any mismatch yields null: showing one order's amount on\n * another order's screen would be worse than showing no amount at all.\n */\nexport function readOrderHandoff(order_code: string | null): OrderHandoff | null {\n if (!order_code) return null;\n let raw: string | null = null;\n try {\n raw = window.localStorage.getItem(HANDOFF_KEY);\n } catch {\n return null;\n }\n if (!raw) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n return matchHandoff(parsed, order_code, Date.now());\n}\n\n/**\n * The validation half of readOrderHandoff, split out so it can be tested\n * without a DOM or a clock. Exported for that reason only.\n */\nexport function matchHandoff(\n parsed: unknown,\n order_code: string,\n now: number\n): OrderHandoff | null {\n if (!parsed || typeof parsed !== \"object\") return null;\n const h = parsed as Record<string, unknown>;\n\n if (typeof h.order_code !== \"string\" || h.order_code !== order_code) return null;\n if (typeof h.payment_method !== \"string\" || h.payment_method.length === 0) {\n return null;\n }\n if (typeof h.total !== \"number\" || !Number.isFinite(h.total)) return null;\n if (typeof h.written_at !== \"number\" || now - h.written_at > MAX_AGE_MS) {\n return null;\n }\n\n return {\n order_code: h.order_code,\n payment_method: h.payment_method,\n provider_code:\n typeof h.provider_code === \"string\" && h.provider_code.length > 0\n ? h.provider_code\n : null,\n total: h.total,\n currency_code:\n typeof h.currency_code === \"string\" && h.currency_code.length > 0\n ? h.currency_code\n : \"VND\",\n written_at: h.written_at,\n };\n}\n\nexport function clearOrderHandoff(): void {\n try {\n window.localStorage.removeItem(HANDOFF_KEY);\n } catch {\n // Nothing to do; a stale entry expires on its own.\n }\n}\n"],"mappings":"AAoBA,MAAM,cAAc;AAGpB,MAAM,aAAa,KAAK,KAAK,KAAK;AAa3B,SAAS,kBACd,SACM;AACN,MAAI;AACF,WAAO,aAAa;AAAA,MAClB;AAAA,MACA,KAAK,UAAU,EAAE,GAAG,SAAS,YAAY,KAAK,IAAI,EAAE,CAAC;AAAA,IACvD;AAAA,EACF,QAAQ;AAAA,EAIR;AACF;AAOO,SAAS,iBAAiB,YAAgD;AAC/E,MAAI,CAAC,WAAY,QAAO;AACxB,MAAI,MAAqB;AACzB,MAAI;AACF,UAAM,OAAO,aAAa,QAAQ,WAAW;AAAA,EAC/C,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,CAAC,IAAK,QAAO;AAEjB,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,GAAG;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO,aAAa,QAAQ,YAAY,KAAK,IAAI,CAAC;AACpD;AAMO,SAAS,aACd,QACA,YACA,KACqB;AACrB,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU,QAAO;AAClD,QAAM,IAAI;AAEV,MAAI,OAAO,EAAE,eAAe,YAAY,EAAE,eAAe,WAAY,QAAO;AAC5E,MAAI,OAAO,EAAE,mBAAmB,YAAY,EAAE,eAAe,WAAW,GAAG;AACzE,WAAO;AAAA,EACT;AACA,MAAI,OAAO,EAAE,UAAU,YAAY,CAAC,OAAO,SAAS,EAAE,KAAK,EAAG,QAAO;AACrE,MAAI,OAAO,EAAE,eAAe,YAAY,MAAM,EAAE,aAAa,YAAY;AACvE,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,YAAY,EAAE;AAAA,IACd,gBAAgB,EAAE;AAAA,IAClB,eACE,OAAO,EAAE,kBAAkB,YAAY,EAAE,cAAc,SAAS,IAC5D,EAAE,gBACF;AAAA,IACN,OAAO,EAAE;AAAA,IACT,eACE,OAAO,EAAE,kBAAkB,YAAY,EAAE,cAAc,SAAS,IAC5D,EAAE,gBACF;AAAA,IACN,YAAY,EAAE;AAAA,EAChB;AACF;AAEO,SAAS,oBAA0B;AACxC,MAAI;AACF,WAAO,aAAa,WAAW,WAAW;AAAA,EAC5C,QAAQ;AAAA,EAER;AACF;","names":[]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
function getPaymentRedirectIntent(method, order_code) {
|
|
2
|
+
const provider_code = method?.provider_code;
|
|
3
|
+
if (!provider_code) {
|
|
4
|
+
return null;
|
|
5
|
+
}
|
|
6
|
+
return { provider_code, order_code };
|
|
7
|
+
}
|
|
8
|
+
export {
|
|
9
|
+
getPaymentRedirectIntent
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=payment-redirect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/checkout/payment-redirect.ts"],"sourcesContent":["/**\n * Decides whether a just-placed checkout should send the shopper to a\n * payment gateway, or leave today's inline \"order placed\" success flow\n * untouched.\n *\n * Deliberately pure: no network call, no `window` access. The page\n * component (`checkout-page-client.tsx`) performs the actual redirect once\n * this function tells it to.\n */\n\n/**\n * The pinned `@ecomweb/sdk` version's `StorePaymentMethod` type does not yet\n * declare `provider_code` (see `lib/checkout/initiate-gateway-payment.ts` for\n * the full story — the SDK PR that adds it is not merged, and this repo's\n * lockfile pins an older commit). The backend already returns the field on\n * `GET /public/stores/:storeRef/payment-methods` today, so this function is\n * typed against only the one field it actually needs rather than the SDK's\n * (currently stale) full type, and the call site casts to this shape.\n */\nexport interface PaymentMethodWithProviderCode {\n provider_code?: string | null;\n}\n\nexport interface PaymentRedirectIntent {\n readonly provider_code: string;\n readonly order_code: string;\n}\n\n/**\n * A payment method with a non-null `provider_code` is gateway-backed\n * (OnePay, MoMo, ...) and the shopper must be sent to the provider to pay.\n * A method without one (`cod`, `bank_transfer`) is settled offline — the\n * existing inline success screen is correct for it and this returns `null`.\n *\n * The returned intent carries `order_code`, never an order id: the\n * `payments/initiate` endpoint is keyed on it deliberately, because the\n * storefront API key authenticates the store rather than the shopper and a\n * raw sequential id would let a caller enumerate a store's orders.\n */\nexport function getPaymentRedirectIntent(\n method: PaymentMethodWithProviderCode | null | undefined,\n order_code: string\n): PaymentRedirectIntent | null {\n const provider_code = method?.provider_code;\n if (!provider_code) {\n return null;\n }\n\n return { provider_code, order_code };\n}\n"],"mappings":"AAuCO,SAAS,yBACd,QACA,YAC8B;AAC9B,QAAM,gBAAgB,QAAQ;AAC9B,MAAI,CAAC,eAAe;AAClB,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,eAAe,WAAW;AACrC;","names":[]}
|