@anker-in/campaign-ui 0.4.5-beta.13 → 0.4.5-beta.14
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/dist/cjs/components/credits/context/hooks/useAlpcFetch.js +1 -1
- package/dist/cjs/components/credits/context/hooks/useAlpcFetch.js.map +2 -2
- package/dist/cjs/components/credits/context/hooks/useRedeemAndBuy.js +1 -1
- package/dist/cjs/components/credits/context/hooks/useRedeemAndBuy.js.map +3 -3
- package/dist/cjs/components/credits/creditsRedeemList/RedeemCouponModal.js +1 -1
- package/dist/cjs/components/credits/creditsRedeemList/RedeemCouponModal.js.map +3 -3
- package/dist/cjs/components/credits/creditsRedeemList/RedeemVirtualProductModal.js +1 -1
- package/dist/cjs/components/credits/creditsRedeemList/RedeemVirtualProductModal.js.map +2 -2
- package/dist/esm/components/credits/context/hooks/useAlpcFetch.js +1 -1
- package/dist/esm/components/credits/context/hooks/useAlpcFetch.js.map +2 -2
- package/dist/esm/components/credits/context/hooks/useRedeemAndBuy.js +1 -1
- package/dist/esm/components/credits/context/hooks/useRedeemAndBuy.js.map +3 -3
- package/dist/esm/components/credits/creditsRedeemList/RedeemCouponModal.js +1 -1
- package/dist/esm/components/credits/creditsRedeemList/RedeemCouponModal.js.map +3 -3
- package/dist/esm/components/credits/creditsRedeemList/RedeemVirtualProductModal.js +1 -1
- package/dist/esm/components/credits/creditsRedeemList/RedeemVirtualProductModal.js.map +2 -2
- package/package.json +1 -1
- package/src/components/credits/context/hooks/useAlpcFetch.ts +12 -5
- package/src/components/credits/context/hooks/useRedeemAndBuy.ts +2 -3
- package/src/components/credits/creditsRedeemList/RedeemCouponModal.tsx +2 -3
- package/src/components/credits/creditsRedeemList/RedeemVirtualProductModal.tsx +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var j=Object.create;var A=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty;var N=(t,e)=>{for(var n in e)A(t,n,{get:e[n],enumerable:!0})},M=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of v(e))!$.call(t,r)&&r!==n&&A(t,r,{get:()=>e[r],enumerable:!(a=k(e,r))||a.enumerable});return t};var S=(t,e,n)=>(n=t!=null?j(I(t)):{},M(e||!t||!t.__esModule?A(n,"default",{value:t,enumerable:!0}):n,t)),W=t=>M(A({},"__esModule",{value:!0}),t);var H={};N(H,{useAlpcFetch:()=>J,useAlpcMutation:()=>K});module.exports=W(H);var D=S(require("js-cookie")),o=require("react"),P=S(require("swr")),B=require("@anker-in/lib"),O=require("../utils"),w=require("../provider");let b;const U=t=>t&&(t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:t),x=t=>fetch((0,O.getAlpcPath)(t.locale,t.apiBaseUrl)+t.url,t.fetchOptions).then(async e=>{if(e.status<300){const n=await e.json();return U(n)}if(e.status===401&&t.onReAuth){b||(b=t.onReAuth());const n=await b;if(b=void 0,n)return fetch((0,O.getAlpcPath)(t.locale,t.apiBaseUrl)+t.url,t.fetchOptions).then(async a=>{if(a.status<300){const r=await a.json();return U(r)}if(a.status===401){t.onUnAuth&&t.onUnAuth();return}});t.onUnAuth&&t.onUnAuth();return}}),C=async(t,e,n,a)=>{let r=await fetch(`${(0,O.getAlpcPath)(t,a)}/cloud/login`,{method:"POST"}),i=await r.json(),s=U(i);if(r.status<300&&!e&&s?.code===27004){const c=D.default.get("alpcEU");if(Number(c)===1?D.default.set("alpcEU","0",{expires:30,domain:`.${n}.com`}):D.default.set("alpcEU","1",{expires:30,domain:`.${n}.com`}),r=await fetch(`${(0,O.getAlpcPath)(t,a)}/cloud/login`,{method:"POST"}),i=await r.json(),s=U(i),r.status>300)return!1}return!s?.code},z=(t,e,n={},a)=>{const r=(0,o.useRef)(!1),[i,s]=(0,o.useState)(),[c,d]=(0,o.useState)(!1),u=(0,o.useRef)(t),f=(0,o.useRef)(e),h=(0,o.useRef)(n),g=(0,o.useCallback)(async(y,T={})=>{if(console.log("[useAlpcMutation] trigger called with:",{url:u.current,fetchData:y,brand:a.current}),r.current){console.log("[useAlpcMutation] already mutating, skipping");return}if(!a.current){console.log("[useAlpcMutation] brand not available, skipping request");return}r.current=!0,d(!0);const p={...h.current,...T},{onSuccess:R,onError:m}=p||{};try{const l=await f.current(u.current,{arg:y});return s(l),d(!1),r.current=!1,R&&R(l),l}catch(l){d(!1),r.current=!1,m&&m(l)}},[]);return{isMutating:c,trigger:g,data:i}},J=(t,e)=>{const[n,a]=(0,o.useState)(!1),{removeProfile:r,alpcBrand:i,apiBaseUrl:s}=(0,w.useCreditsContext)(),{enable:c,...d}=e||{},{locale:u="",brand:f}=(0,B.useHeadlessContext)(),h=i||f,{queryKey:g=[],body:y={},headers:T,...p}=t,R=c??!0,[m,l]=g;return(0,P.default)([m,l],!R||!h?null:([F,q])=>x({url:F,locale:u,apiBaseUrl:s,fetchOptions:{method:"POST",headers:{"current-language":u,...T},body:JSON.stringify({...y,...q}),...p},onReAuth:async()=>await C(u,n,h,s)?(a(!0),!0):!1,onUnAuth(){r()}}),{revalidateOnFocus:!1,...d})},K=(t,e)=>{const[n,a]=(0,o.useState)(!1),{removeProfile:r,alpcBrand:i,apiBaseUrl:s}=(0,w.useCreditsContext)(),{locale:c="",brand:d}=(0,B.useHeadlessContext)(),u=i||d,f=(0,o.useRef)(u);f.current=u;const{url:h,initData:g,headers:y,...T}=t,p=(0,o.useRef)(g);return p.current=g,z(h,(m,l)=>f.current?x({url:m,locale:c,apiBaseUrl:s,fetchOptions:{method:"POST",headers:{"current-language":c,...y},...T,body:JSON.stringify({...p.current,...l.arg})},onReAuth:async()=>await C(c,n,f.current,s)?(a(!0),!0):!1,onUnAuth(){r()}}):Promise.resolve(void 0),e,f)};
|
|
1
|
+
"use strict";var j=Object.create;var A=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty;var N=(t,e)=>{for(var n in e)A(t,n,{get:e[n],enumerable:!0})},M=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of v(e))!$.call(t,r)&&r!==n&&A(t,r,{get:()=>e[r],enumerable:!(a=k(e,r))||a.enumerable});return t};var S=(t,e,n)=>(n=t!=null?j(I(t)):{},M(e||!t||!t.__esModule?A(n,"default",{value:t,enumerable:!0}):n,t)),W=t=>M(A({},"__esModule",{value:!0}),t);var H={};N(H,{useAlpcFetch:()=>J,useAlpcMutation:()=>K});module.exports=W(H);var D=S(require("js-cookie")),o=require("react"),P=S(require("swr")),B=require("@anker-in/lib"),O=require("../utils"),w=require("../provider");let b;const U=t=>t&&(t.data&&typeof t.data=="object"&&!Array.isArray(t.data)&&"data"in t.data?t.data:t),x=t=>fetch((0,O.getAlpcPath)(t.locale,t.apiBaseUrl)+t.url,t.fetchOptions).then(async e=>{if(e.status<300){const n=await e.json();return U(n)}if(e.status===401&&t.onReAuth){b||(b=t.onReAuth());const n=await b;if(b=void 0,n)return fetch((0,O.getAlpcPath)(t.locale,t.apiBaseUrl)+t.url,t.fetchOptions).then(async a=>{if(a.status<300){const r=await a.json();return U(r)}if(a.status===401){t.onUnAuth&&t.onUnAuth();return}});t.onUnAuth&&t.onUnAuth();return}}),C=async(t,e,n,a)=>{let r=await fetch(`${(0,O.getAlpcPath)(t,a)}/cloud/login`,{method:"POST"}),i=await r.json(),s=U(i);if(r.status<300&&!e&&s?.code===27004){const c=D.default.get("alpcEU");if(Number(c)===1?D.default.set("alpcEU","0",{expires:30,domain:`.${n}.com`}):D.default.set("alpcEU","1",{expires:30,domain:`.${n}.com`}),r=await fetch(`${(0,O.getAlpcPath)(t,a)}/cloud/login`,{method:"POST"}),i=await r.json(),s=U(i),r.status>300)return!1}return!s?.code},z=(t,e,n={},a)=>{const r=(0,o.useRef)(!1),[i,s]=(0,o.useState)(),[c,d]=(0,o.useState)(!1),u=(0,o.useRef)(t),f=(0,o.useRef)(e),h=(0,o.useRef)(n),g=(0,o.useCallback)(async(y,T={})=>{if(console.log("[useAlpcMutation] trigger called with:",{url:u.current,fetchData:y,brand:a.current}),r.current){console.log("[useAlpcMutation] already mutating, skipping");return}if(!a.current){console.log("[useAlpcMutation] brand not available, skipping request");return}r.current=!0,d(!0);const p={...h.current,...T},{onSuccess:R,onError:m}=p||{};try{const l=await f.current(u.current,{arg:y});return s(l),d(!1),r.current=!1,R&&R(l),l}catch(l){d(!1),r.current=!1,m&&m(l)}},[]);return{isMutating:c,trigger:g,data:i}},J=(t,e)=>{const[n,a]=(0,o.useState)(!1),{removeProfile:r,alpcBrand:i,apiBaseUrl:s}=(0,w.useCreditsContext)(),{enable:c,...d}=e||{},{locale:u="",brand:f}=(0,B.useHeadlessContext)(),h=i||f,{queryKey:g=[],body:y={},headers:T,...p}=t,R=c??!0,[m,l]=g;return(0,P.default)([m,l],!R||!h?null:([F,q])=>x({url:F,locale:u,apiBaseUrl:s,fetchOptions:{method:"POST",headers:{"current-language":u,...T},body:JSON.stringify({...y,...q}),...p},onReAuth:async()=>await C(u,n,h,s)?(a(!0),!0):!1,onUnAuth(){r()}}),{revalidateOnFocus:!1,...d})},K=(t,e)=>{const[n,a]=(0,o.useState)(!1),{removeProfile:r,alpcBrand:i,apiBaseUrl:s}=(0,w.useCreditsContext)(),{locale:c="",brand:d}=(0,B.useHeadlessContext)(),u=i||d,f=(0,o.useRef)(u);f.current=u;const{url:h,initData:g,headers:y,...T}=t,p=(0,o.useRef)(g);return p.current=g,z(h,(m,l)=>f.current?x({url:m,locale:c,apiBaseUrl:s,fetchOptions:{method:"POST",headers:{"current-language":c,...y},...T,body:JSON.stringify({...p.current,...l.arg})},onReAuth:async()=>await C(c,n,f.current,s)?(a(!0),!0):!1,onUnAuth(){r()}}):Promise.resolve(void 0),e,f)};
|
|
2
2
|
//# sourceMappingURL=useAlpcFetch.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/components/credits/context/hooks/useAlpcFetch.ts"],
|
|
4
|
-
"sourcesContent": ["import Cookies from 'js-cookie'\nimport { useCallback, useRef, useState } from 'react'\nimport useSWR, { type SWRConfiguration } from 'swr'\nimport { useHeadlessContext } from '@anker-in/lib'\n\nimport { getAlpcPath } from '../utils'\nimport { useCreditsContext } from '../provider'\n\ninterface UseAlpcFetchOptionsSwrOptions<TData, Error> extends SWRConfiguration<TData, Error> {\n enable?: boolean\n}\n\ninterface FetchOptions extends RequestInit {\n queryKey: [string, Record<string, any>]\n data?: Record<string, any>\n}\n\ninterface MutationOptions extends RequestInit {\n url: string\n initData: Record<string, any>\n}\n\ninterface FetcherOptions {\n url: string\n locale: string\n fetchOptions: RequestInit\n onReAuth: () => Promise<boolean>\n onUnAuth: () => void\n apiBaseUrl?: string\n}\n\nlet reAuthPromise: Promise<boolean> | undefined\n\ntype Fetcher<TData, TBody> = (url: string, data: { arg: TBody }) => Promise<TData>\n\n/**\n * \u7EDF\u4E00\u5904\u7406 ALPC \u63A5\u53E3\u8FD4\u56DE\u7684\u6570\u636E\u7ED3\u6784\n * \u517C\u5BB9\u4E00\u5C42 data \u548C\u4E24\u5C42 data \u7684\u573A\u666F\uFF1A\n * - \u4E24\u5C42 data: {data: {data: ..., code: 27004}}\n * - \u4E00\u5C42 data: {data: ..., code: 27004}\n */\nconst normalizeResponseData = (responseData: any) => {\n if (!responseData) return responseData\n\n // \u5982\u679C responseData.data \u5B58\u5728\u4E14\u662F\u4E00\u4E2A\u5BF9\u8C61\uFF08\u4E0D\u662F\u6570\u7EC4\uFF09\uFF0C\u8BF4\u660E\u662F\u4E24\u5C42 data \u7ED3\u6784\n if (responseData.data && typeof responseData.data === 'object' && !Array.isArray(responseData.data)) {\n return responseData.data\n }\n\n // \u4E00\u5C42 data \u7ED3\u6784\u6216\u5176\u4ED6\u60C5\u51B5\uFF0C\u76F4\u63A5\u8FD4\u56DE\n return responseData\n}\n\nconst fetcher = (options: FetcherOptions) => {\n return fetch(getAlpcPath(options.locale, options.apiBaseUrl) + options.url, options.fetchOptions).then(async response => {\n if (response.status < 300) {\n const responseData = await response.json()\n return normalizeResponseData(responseData)\n }\n\n // \u9519\u8BEF\u5904\u7406\n if (response.status === 401) {\n // \u91CD\u65B0\u767B\u5F55\u5C1D\u8BD5\n if (options.onReAuth) {\n if (!reAuthPromise) {\n reAuthPromise = options.onReAuth()\n }\n\n const result = await reAuthPromise\n\n reAuthPromise = undefined\n\n if (result) {\n // \u8DE8\u533A\u91CD\u65B0\u767B\u5F55\u540E\u9700\u8981\u66FF\u6362\u533A\u57DF\u6807\u5FD7\uFF0C\u6240\u4EE5\u4E0D\u80FD\u7528\u6700\u5F00\u59CB\u8BF7\u6C42\u7684\u90A3\u4E2A\u94FE\u63A5\n return fetch(getAlpcPath(options.locale, options.apiBaseUrl) + options.url, options.fetchOptions).then(async response => {\n if (response.status < 300) {\n const responseData = await response.json()\n return normalizeResponseData(responseData)\n }\n\n if (response.status === 401) {\n if (options.onUnAuth) {\n options.onUnAuth()\n }\n return\n }\n })\n } else {\n if (options.onUnAuth) {\n options.onUnAuth()\n }\n return\n }\n }\n }\n })\n}\n\nconst reAuth = async (locale: string, retry: boolean, brand: string, apiBaseUrl?: string) => {\n let reloginResponse = await fetch(`${getAlpcPath(locale, apiBaseUrl)}/cloud/login`, {\n method: 'POST',\n })\n let reloginResponseData = await reloginResponse.json()\n // \u517C\u5BB9\u4E24\u5C42 data \u7ED3\u6784\n let normalizedData = normalizeResponseData(reloginResponseData)\n\n if (reloginResponse!.status < 300 && !retry) {\n if (normalizedData?.code === 27004) {\n // \u8DE8\u533A\u767B\u5F55\u9519\u8BEF\n const alpcEUCookie = Cookies.get('alpcEU')\n\n if (Number(alpcEUCookie) === 1) {\n Cookies.set('alpcEU', '0', {\n expires: 30,\n domain: `.${brand}.com`,\n })\n } else {\n Cookies.set('alpcEU', '1', {\n expires: 30,\n domain: `.${brand}.com`,\n })\n }\n\n // \u91CD\u65B0\u5C1D\u8BD5\u6362\u533A\u767B\u5F55\n reloginResponse = await fetch(`${getAlpcPath(locale, apiBaseUrl)}/cloud/login`, {\n method: 'POST',\n })\n reloginResponseData = await reloginResponse.json()\n normalizedData = normalizeResponseData(reloginResponseData)\n\n if (reloginResponse.status > 300) {\n return false\n }\n }\n }\n if (!normalizedData?.code) {\n // \u91CD\u65B0\u767B\u5F55\u6210\u529F\n return true\n }\n\n return false\n}\n\nexport interface UseMutationConfig<TData> {\n onSuccess?: (response: TData) => any\n onError?: (error: Error) => any\n}\n\nconst useMutation = <TData, TBody>(\n url: string,\n fetcher: Fetcher<TData, TBody>,\n mutationConfig: UseMutationConfig<TData> = {},\n brandRef: React.MutableRefObject<string | undefined>\n) => {\n const innerMutating = useRef<boolean>(false)\n\n const [data, setData] = useState<TData>()\n const [isMutating, setIsMutating] = useState(false)\n\n const urlRef = useRef(url)\n const fetcherRef = useRef(fetcher)\n const configRef = useRef(mutationConfig)\n\n const trigger = useCallback(\n async (fetchData: TBody, opts: UseMutationConfig<TData> = {}) => {\n console.log('[useAlpcMutation] trigger called with:', { url: urlRef.current, fetchData, brand: brandRef.current })\n\n if (innerMutating.current) {\n console.log('[useAlpcMutation] already mutating, skipping')\n return\n }\n\n if (!brandRef.current) {\n console.log('[useAlpcMutation] brand not available, skipping request')\n return\n }\n\n innerMutating.current = true\n setIsMutating(true)\n\n const config = {\n ...configRef.current,\n ...opts,\n }\n\n const { onSuccess, onError } = config || {}\n\n try {\n const fetchResult = await fetcherRef.current(urlRef.current, {\n arg: fetchData,\n })\n setData(fetchResult)\n\n setIsMutating(false)\n innerMutating.current = false\n\n if (onSuccess) {\n onSuccess(fetchResult)\n }\n return fetchResult\n } catch (err: any) {\n setIsMutating(false)\n innerMutating.current = false\n\n if (onError) {\n onError(err)\n }\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n []\n )\n\n return {\n isMutating,\n trigger,\n data,\n }\n}\n\nexport const useAlpcFetch = <TData>(\n options: FetchOptions,\n swrOptions?: UseAlpcFetchOptionsSwrOptions<TData, Error>\n) => {\n const [retry, setRetry] = useState(false)\n const { removeProfile, alpcBrand, apiBaseUrl } = useCreditsContext()\n\n const { enable, ...otherSwrOptions } = swrOptions || {}\n\n const { locale = '', brand: headlessBrand } = useHeadlessContext()\n // \u4F18\u5148\u4F7F\u7528 creditsContext \u4E2D\u7684 alpcBrand\uFF0C\u5982\u679C\u6CA1\u6709\u5219\u4F7F\u7528 headlessConfig \u4E2D\u7684 brand\n const brand = alpcBrand || headlessBrand\n\n const { queryKey = [], body: fetchBody = {}, headers, ...fetchOptions } = options\n const fetchEnable = enable ?? true\n\n const [url, requestBody] = queryKey\n\n const context = useSWR<TData>(\n [url, requestBody],\n !fetchEnable || !brand\n ? null\n : ([requestUrl, data]: [string, Record<string, any>]) =>\n fetcher({\n url: requestUrl,\n locale,\n apiBaseUrl,\n fetchOptions: {\n method: 'POST',\n headers: {\n 'current-language': locale,\n ...headers,\n },\n body: JSON.stringify({\n ...fetchBody,\n ...data,\n }),\n ...fetchOptions,\n },\n onReAuth: async () => {\n const result = await reAuth(locale, retry, brand, apiBaseUrl)\n\n if (result) {\n setRetry(true)\n return true\n }\n\n return false\n },\n onUnAuth() {\n // \u5931\u8D25\u540E\u9000\u51FA\u767B\u5F55\n removeProfile()\n },\n }),\n {\n revalidateOnFocus: false,\n ...otherSwrOptions,\n }\n )\n\n return context\n}\n\nexport const useAlpcMutation = <TData, TBody>(options: MutationOptions, mutationOptions?: UseMutationConfig<TData>) => {\n const [retry, setRetry] = useState(false)\n const { removeProfile, alpcBrand, apiBaseUrl } = useCreditsContext()\n\n const { locale = '', brand: headlessBrand } = useHeadlessContext()\n // \u4F18\u5148\u4F7F\u7528 creditsContext \u4E2D\u7684 alpcBrand\uFF0C\u5982\u679C\u6CA1\u6709\u5219\u4F7F\u7528 headlessConfig \u4E2D\u7684 brand\n const brand = alpcBrand || headlessBrand\n const brandRef = useRef(brand)\n brandRef.current = brand\n\n const { url, initData, headers, ...fetchOptions } = options\n const initDataRef = useRef(initData)\n initDataRef.current = initData\n\n const context = useMutation<TData, TBody>(\n url,\n (requestUrl, data: { arg: TBody }) => {\n // Prevent requests when brand is not available\n if (!brandRef.current) {\n return Promise.resolve(undefined as unknown as TData)\n }\n\n return fetcher({\n url: requestUrl,\n locale,\n apiBaseUrl,\n fetchOptions: {\n method: 'POST',\n headers: {\n 'current-language': locale,\n ...headers,\n },\n ...fetchOptions,\n body: JSON.stringify({\n ...initDataRef.current,\n ...data.arg,\n }),\n },\n onReAuth: async () => {\n const result = await reAuth(locale, retry, brandRef.current!, apiBaseUrl)\n\n if (result) {\n setRetry(true)\n return true\n }\n\n return false\n },\n onUnAuth() {\n // \u5931\u8D25\u540E\u9000\u51FA\u767B\u5F55\n removeProfile()\n },\n })\n },\n mutationOptions,\n brandRef\n )\n\n return context\n}\n"],
|
|
5
|
-
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,oBAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAoB,wBACpBC,EAA8C,iBAC9CC,EAA8C,kBAC9CC,EAAmC,yBAEnCC,EAA4B,oBAC5BC,EAAkC,uBAyBlC,IAAIC,
|
|
4
|
+
"sourcesContent": ["import Cookies from 'js-cookie'\nimport { useCallback, useRef, useState } from 'react'\nimport useSWR, { type SWRConfiguration } from 'swr'\nimport { useHeadlessContext } from '@anker-in/lib'\n\nimport { getAlpcPath } from '../utils'\nimport { useCreditsContext } from '../provider'\n\ninterface UseAlpcFetchOptionsSwrOptions<TData, Error> extends SWRConfiguration<TData, Error> {\n enable?: boolean\n}\n\ninterface FetchOptions extends RequestInit {\n queryKey: [string, Record<string, any>]\n data?: Record<string, any>\n}\n\ninterface MutationOptions extends RequestInit {\n url: string\n initData: Record<string, any>\n}\n\ninterface FetcherOptions {\n url: string\n locale: string\n fetchOptions: RequestInit\n onReAuth: () => Promise<boolean>\n onUnAuth: () => void\n apiBaseUrl?: string\n}\n\nlet reAuthPromise: Promise<boolean> | undefined\n\ntype Fetcher<TData, TBody> = (url: string, data: { arg: TBody }) => Promise<TData>\n\n/**\n * \u7EDF\u4E00\u5904\u7406 ALPC \u63A5\u53E3\u8FD4\u56DE\u7684\u6570\u636E\u7ED3\u6784\n * \u517C\u5BB9\u4E00\u5C42 data \u548C\u4E24\u5C42 data \u7684\u573A\u666F\uFF1A\n * - \u4E24\u5C42 data: {data: {data: ..., code: 27004}} \u2192 \u5265\u6389\u5916\u5C42\uFF0C\u8FD4\u56DE\u5185\u5C42 {data: ..., code: 27004}\n * - \u4E00\u5C42 data: {data: ..., code: 27004} \u2192 \u76F4\u63A5\u8FD4\u56DE\uFF0C\u4E0D\u505A\u5904\u7406\n *\n * \u5224\u65AD\u4E24\u5C42\u7684\u4F9D\u636E\uFF1AresponseData.data.data \u5B58\u5728\uFF08\u5916\u5C42 data \u5185\u90E8\u8FD8\u6709\u4E00\u5C42 data\uFF09\n */\nconst normalizeResponseData = (responseData: any) => {\n if (!responseData) return responseData\n\n // \u4E24\u5C42\u7ED3\u6784\uFF1AresponseData.data \u662F\u5BF9\u8C61\uFF0C\u4E14\u5176\u5185\u90E8\u8FD8\u6709 data \u5B57\u6BB5\n if (\n responseData.data &&\n typeof responseData.data === 'object' &&\n !Array.isArray(responseData.data) &&\n 'data' in responseData.data\n ) {\n return responseData.data\n }\n\n // \u4E00\u5C42\u7ED3\u6784\uFF0C\u76F4\u63A5\u8FD4\u56DE\n return responseData\n}\n\nconst fetcher = (options: FetcherOptions) => {\n return fetch(getAlpcPath(options.locale, options.apiBaseUrl) + options.url, options.fetchOptions).then(async response => {\n if (response.status < 300) {\n const responseData = await response.json()\n return normalizeResponseData(responseData)\n }\n\n // \u9519\u8BEF\u5904\u7406\n if (response.status === 401) {\n // \u91CD\u65B0\u767B\u5F55\u5C1D\u8BD5\n if (options.onReAuth) {\n if (!reAuthPromise) {\n reAuthPromise = options.onReAuth()\n }\n\n const result = await reAuthPromise\n\n reAuthPromise = undefined\n\n if (result) {\n // \u8DE8\u533A\u91CD\u65B0\u767B\u5F55\u540E\u9700\u8981\u66FF\u6362\u533A\u57DF\u6807\u5FD7\uFF0C\u6240\u4EE5\u4E0D\u80FD\u7528\u6700\u5F00\u59CB\u8BF7\u6C42\u7684\u90A3\u4E2A\u94FE\u63A5\n return fetch(getAlpcPath(options.locale, options.apiBaseUrl) + options.url, options.fetchOptions).then(async response => {\n if (response.status < 300) {\n const responseData = await response.json()\n return normalizeResponseData(responseData)\n }\n\n if (response.status === 401) {\n if (options.onUnAuth) {\n options.onUnAuth()\n }\n return\n }\n })\n } else {\n if (options.onUnAuth) {\n options.onUnAuth()\n }\n return\n }\n }\n }\n })\n}\n\nconst reAuth = async (locale: string, retry: boolean, brand: string, apiBaseUrl?: string) => {\n let reloginResponse = await fetch(`${getAlpcPath(locale, apiBaseUrl)}/cloud/login`, {\n method: 'POST',\n })\n let reloginResponseData = await reloginResponse.json()\n // \u517C\u5BB9\u4E24\u5C42 data \u7ED3\u6784\n let normalizedData = normalizeResponseData(reloginResponseData)\n\n if (reloginResponse!.status < 300 && !retry) {\n if (normalizedData?.code === 27004) {\n // \u8DE8\u533A\u767B\u5F55\u9519\u8BEF\n const alpcEUCookie = Cookies.get('alpcEU')\n\n if (Number(alpcEUCookie) === 1) {\n Cookies.set('alpcEU', '0', {\n expires: 30,\n domain: `.${brand}.com`,\n })\n } else {\n Cookies.set('alpcEU', '1', {\n expires: 30,\n domain: `.${brand}.com`,\n })\n }\n\n // \u91CD\u65B0\u5C1D\u8BD5\u6362\u533A\u767B\u5F55\n reloginResponse = await fetch(`${getAlpcPath(locale, apiBaseUrl)}/cloud/login`, {\n method: 'POST',\n })\n reloginResponseData = await reloginResponse.json()\n normalizedData = normalizeResponseData(reloginResponseData)\n\n if (reloginResponse.status > 300) {\n return false\n }\n }\n }\n if (!normalizedData?.code) {\n // \u91CD\u65B0\u767B\u5F55\u6210\u529F\n return true\n }\n\n return false\n}\n\nexport interface UseMutationConfig<TData> {\n onSuccess?: (response: TData) => any\n onError?: (error: Error) => any\n}\n\nconst useMutation = <TData, TBody>(\n url: string,\n fetcher: Fetcher<TData, TBody>,\n mutationConfig: UseMutationConfig<TData> = {},\n brandRef: React.MutableRefObject<string | undefined>\n) => {\n const innerMutating = useRef<boolean>(false)\n\n const [data, setData] = useState<TData>()\n const [isMutating, setIsMutating] = useState(false)\n\n const urlRef = useRef(url)\n const fetcherRef = useRef(fetcher)\n const configRef = useRef(mutationConfig)\n\n const trigger = useCallback(\n async (fetchData: TBody, opts: UseMutationConfig<TData> = {}) => {\n console.log('[useAlpcMutation] trigger called with:', { url: urlRef.current, fetchData, brand: brandRef.current })\n\n if (innerMutating.current) {\n console.log('[useAlpcMutation] already mutating, skipping')\n return\n }\n\n if (!brandRef.current) {\n console.log('[useAlpcMutation] brand not available, skipping request')\n return\n }\n\n innerMutating.current = true\n setIsMutating(true)\n\n const config = {\n ...configRef.current,\n ...opts,\n }\n\n const { onSuccess, onError } = config || {}\n\n try {\n const fetchResult = await fetcherRef.current(urlRef.current, {\n arg: fetchData,\n })\n setData(fetchResult)\n\n setIsMutating(false)\n innerMutating.current = false\n\n if (onSuccess) {\n onSuccess(fetchResult)\n }\n return fetchResult\n } catch (err: any) {\n setIsMutating(false)\n innerMutating.current = false\n\n if (onError) {\n onError(err)\n }\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n []\n )\n\n return {\n isMutating,\n trigger,\n data,\n }\n}\n\nexport const useAlpcFetch = <TData>(\n options: FetchOptions,\n swrOptions?: UseAlpcFetchOptionsSwrOptions<TData, Error>\n) => {\n const [retry, setRetry] = useState(false)\n const { removeProfile, alpcBrand, apiBaseUrl } = useCreditsContext()\n\n const { enable, ...otherSwrOptions } = swrOptions || {}\n\n const { locale = '', brand: headlessBrand } = useHeadlessContext()\n // \u4F18\u5148\u4F7F\u7528 creditsContext \u4E2D\u7684 alpcBrand\uFF0C\u5982\u679C\u6CA1\u6709\u5219\u4F7F\u7528 headlessConfig \u4E2D\u7684 brand\n const brand = alpcBrand || headlessBrand\n\n const { queryKey = [], body: fetchBody = {}, headers, ...fetchOptions } = options\n const fetchEnable = enable ?? true\n\n const [url, requestBody] = queryKey\n\n const context = useSWR<TData>(\n [url, requestBody],\n !fetchEnable || !brand\n ? null\n : ([requestUrl, data]: [string, Record<string, any>]) =>\n fetcher({\n url: requestUrl,\n locale,\n apiBaseUrl,\n fetchOptions: {\n method: 'POST',\n headers: {\n 'current-language': locale,\n ...headers,\n },\n body: JSON.stringify({\n ...fetchBody,\n ...data,\n }),\n ...fetchOptions,\n },\n onReAuth: async () => {\n const result = await reAuth(locale, retry, brand, apiBaseUrl)\n\n if (result) {\n setRetry(true)\n return true\n }\n\n return false\n },\n onUnAuth() {\n // \u5931\u8D25\u540E\u9000\u51FA\u767B\u5F55\n removeProfile()\n },\n }),\n {\n revalidateOnFocus: false,\n ...otherSwrOptions,\n }\n )\n\n return context\n}\n\nexport const useAlpcMutation = <TData, TBody>(options: MutationOptions, mutationOptions?: UseMutationConfig<TData>) => {\n const [retry, setRetry] = useState(false)\n const { removeProfile, alpcBrand, apiBaseUrl } = useCreditsContext()\n\n const { locale = '', brand: headlessBrand } = useHeadlessContext()\n // \u4F18\u5148\u4F7F\u7528 creditsContext \u4E2D\u7684 alpcBrand\uFF0C\u5982\u679C\u6CA1\u6709\u5219\u4F7F\u7528 headlessConfig \u4E2D\u7684 brand\n const brand = alpcBrand || headlessBrand\n const brandRef = useRef(brand)\n brandRef.current = brand\n\n const { url, initData, headers, ...fetchOptions } = options\n const initDataRef = useRef(initData)\n initDataRef.current = initData\n\n const context = useMutation<TData, TBody>(\n url,\n (requestUrl, data: { arg: TBody }) => {\n // Prevent requests when brand is not available\n if (!brandRef.current) {\n return Promise.resolve(undefined as unknown as TData)\n }\n\n return fetcher({\n url: requestUrl,\n locale,\n apiBaseUrl,\n fetchOptions: {\n method: 'POST',\n headers: {\n 'current-language': locale,\n ...headers,\n },\n ...fetchOptions,\n body: JSON.stringify({\n ...initDataRef.current,\n ...data.arg,\n }),\n },\n onReAuth: async () => {\n const result = await reAuth(locale, retry, brandRef.current!, apiBaseUrl)\n\n if (result) {\n setRetry(true)\n return true\n }\n\n return false\n },\n onUnAuth() {\n // \u5931\u8D25\u540E\u9000\u51FA\u767B\u5F55\n removeProfile()\n },\n })\n },\n mutationOptions,\n brandRef\n )\n\n return context\n}\n"],
|
|
5
|
+
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,oBAAAC,IAAA,eAAAC,EAAAJ,GAAA,IAAAK,EAAoB,wBACpBC,EAA8C,iBAC9CC,EAA8C,kBAC9CC,EAAmC,yBAEnCC,EAA4B,oBAC5BC,EAAkC,uBAyBlC,IAAIC,EAYJ,MAAMC,EAAyBC,GACxBA,IAIHA,EAAa,MACb,OAAOA,EAAa,MAAS,UAC7B,CAAC,MAAM,QAAQA,EAAa,IAAI,GAChC,SAAUA,EAAa,KAEhBA,EAAa,KAIfA,GAGHC,EAAWC,GACR,SAAM,eAAYA,EAAQ,OAAQA,EAAQ,UAAU,EAAIA,EAAQ,IAAKA,EAAQ,YAAY,EAAE,KAAK,MAAMC,GAAY,CACvH,GAAIA,EAAS,OAAS,IAAK,CACzB,MAAMH,EAAe,MAAMG,EAAS,KAAK,EACzC,OAAOJ,EAAsBC,CAAY,CAC3C,CAGA,GAAIG,EAAS,SAAW,KAElBD,EAAQ,SAAU,CACfJ,IACHA,EAAgBI,EAAQ,SAAS,GAGnC,MAAME,EAAS,MAAMN,EAIrB,GAFAA,EAAgB,OAEZM,EAEF,OAAO,SAAM,eAAYF,EAAQ,OAAQA,EAAQ,UAAU,EAAIA,EAAQ,IAAKA,EAAQ,YAAY,EAAE,KAAK,MAAMC,GAAY,CACvH,GAAIA,EAAS,OAAS,IAAK,CACzB,MAAMH,EAAe,MAAMG,EAAS,KAAK,EACzC,OAAOJ,EAAsBC,CAAY,C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AGtE2B,EAAS,EAAI,EACN,IAGF,GAET,UAAW,CAETC,EAAc,CAChB,CACF,CAAC,EAjCQ,QAAQ,QAAQ,MAA6B,EAmCxDa,EACAhC,CACF,CAGF",
|
|
6
6
|
"names": ["useAlpcFetch_exports", "__export", "useAlpcFetch", "useAlpcMutation", "__toCommonJS", "import_js_cookie", "import_react", "import_swr", "import_lib", "import_utils", "import_provider", "reAuthPromise", "normalizeResponseData", "responseData", "fetcher", "options", "response", "result", "reAuth", "locale", "retry", "brand", "apiBaseUrl", "reloginResponse", "reloginResponseData", "normalizedData", "alpcEUCookie", "Cookies", "useMutation", "url", "mutationConfig", "brandRef", "innerMutating", "data", "setData", "isMutating", "setIsMutating", "urlRef", "fetcherRef", "configRef", "trigger", "fetchData", "opts", "config", "onSuccess", "onError", "fetchResult", "err", "swrOptions", "setRetry", "removeProfile", "alpcBrand", "enable", "otherSwrOptions", "headlessBrand", "queryKey", "fetchBody", "headers", "fetchOptions", "fetchEnable", "requestBody", "useSWR", "requestUrl", "mutationOptions", "initData", "initDataRef"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var f=Object.create;var u=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var g=Object.getOwnPropertyNames;var l=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty;var _=(r,e)=>{for(var t in e)u(r,t,{get:e[t],enumerable:!0})},d=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of g(e))!w.call(r,o)&&o!==t&&u(r,o,{get:()=>e[o],enumerable:!(n=y(e,o))||n.enumerable});return r};var C=(r,e,t)=>(t=r!=null?f(l(r)):{},d(e||!r||!r.__esModule?u(t,"default",{value:r,enumerable:!0}):t,r)),R=r=>d(u({},"__esModule",{value:!0}),r);var E={};_(E,{useRedeemAndBuy:()=>b});module.exports=R(E);var s=C(require("swr/mutation")),m=require("./useRedeemCoupon"),c=require("../provider"),p=require("@anker-in/lib");const b=(r,e)=>{const{trigger:t}=(0,m.useRedeemCoupon)(),{profile:n}=(0,c.useCreditsContext)(),{trigger:o}=(0,p.useBuyNow)({},{throwOnError:!0});return(0,s.default)("redeemAndBuy",async(V,{arg:a})=>{const i=await t({user_id:n?.user_id,rule_id:a.redeemId});if(i&&i.data?.coupon_code)o({discountCodes:[i.data.coupon_code],lineItems:[{variant:a.productVariant,quantity:a.quantity||1}]});else throw new Error(`Redeem failed: ${i?.msg}`)},e)};
|
|
2
2
|
//# sourceMappingURL=useRedeemAndBuy.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/components/credits/context/hooks/useRedeemAndBuy.ts"],
|
|
4
|
-
"sourcesContent": ["import useSWRMutation, { SWRMutationConfiguration } from 'swr/mutation'\nimport { useRedeemCoupon } from './useRedeemCoupon'\nimport type { ProductVariant } from '@anker-in/lib'\nimport { useCreditsContext } from '../provider'\nimport { useBuyNow } from '@anker-in/lib'\n\nexport const useRedeemAndBuy = (\n _: any,\n swrOptions?: SWRMutationConfiguration<undefined, Error, string, any> & {\n throwOnError?: boolean\n }\n) => {\n const { trigger } = useRedeemCoupon()\n const { profile } = useCreditsContext()\n\n const { trigger: buyNow } = useBuyNow(\n {},\n {\n throwOnError: true,\n }\n )\n\n return useSWRMutation(\n 'redeemAndBuy',\n async (\n _,\n {\n arg,\n }: {\n arg: {\n productVariant: ProductVariant\n quantity?: number\n redeemId: number\n }\n }\n ) => {\n const res = await trigger({\n user_id: profile?.user_id,\n rule_id: arg.redeemId,\n })\n
|
|
5
|
-
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAyD,2BACzDC,EAAgC,6BAEhCC,EAAkC,uBAClCC,EAA0B,yBAEnB,MAAML,EAAkB,CAC7BM,EACAC,IAGG,CACH,KAAM,CAAE,QAAAC,CAAQ,KAAI,mBAAgB,EAC9B,CAAE,QAAAC,CAAQ,KAAI,qBAAkB,EAEhC,CAAE,QAASC,CAAO,KAAI,aAC1B,CAAC,EACD,CACE,aAAc,EAChB,CACF,EAEA,SAAO,EAAAC,SACL,eACA,MACEL,EACA,CACE,IAAAM,CACF,IAOG,CACH,MAAMC,EAAM,MAAML,EAAQ,CACxB,QAASC,GAAS,QAClB,QAASG,EAAI,QACf,CAAC,
|
|
6
|
-
"names": ["useRedeemAndBuy_exports", "__export", "useRedeemAndBuy", "__toCommonJS", "import_mutation", "import_useRedeemCoupon", "import_provider", "import_lib", "_", "swrOptions", "trigger", "profile", "buyNow", "useSWRMutation", "arg", "res"
|
|
4
|
+
"sourcesContent": ["import useSWRMutation, { SWRMutationConfiguration } from 'swr/mutation'\nimport { useRedeemCoupon } from './useRedeemCoupon'\nimport type { ProductVariant } from '@anker-in/lib'\nimport { useCreditsContext } from '../provider'\nimport { useBuyNow } from '@anker-in/lib'\n\nexport const useRedeemAndBuy = (\n _: any,\n swrOptions?: SWRMutationConfiguration<undefined, Error, string, any> & {\n throwOnError?: boolean\n }\n) => {\n const { trigger } = useRedeemCoupon()\n const { profile } = useCreditsContext()\n\n const { trigger: buyNow } = useBuyNow(\n {},\n {\n throwOnError: true,\n }\n )\n\n return useSWRMutation(\n 'redeemAndBuy',\n async (\n _,\n {\n arg,\n }: {\n arg: {\n productVariant: ProductVariant\n quantity?: number\n redeemId: number\n }\n }\n ) => {\n const res = await trigger({\n user_id: profile?.user_id,\n rule_id: arg.redeemId,\n })\n if (res && res.data?.coupon_code) {\n buyNow({\n discountCodes: [res.data.coupon_code],\n lineItems: [\n {\n variant: arg.productVariant,\n quantity: arg.quantity || 1,\n },\n ],\n })\n } else {\n throw new Error(`Redeem failed: ${res?.msg}`)\n }\n },\n swrOptions\n )\n}\n"],
|
|
5
|
+
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAyD,2BACzDC,EAAgC,6BAEhCC,EAAkC,uBAClCC,EAA0B,yBAEnB,MAAML,EAAkB,CAC7BM,EACAC,IAGG,CACH,KAAM,CAAE,QAAAC,CAAQ,KAAI,mBAAgB,EAC9B,CAAE,QAAAC,CAAQ,KAAI,qBAAkB,EAEhC,CAAE,QAASC,CAAO,KAAI,aAC1B,CAAC,EACD,CACE,aAAc,EAChB,CACF,EAEA,SAAO,EAAAC,SACL,eACA,MACEL,EACA,CACE,IAAAM,CACF,IAOG,CACH,MAAMC,EAAM,MAAML,EAAQ,CACxB,QAASC,GAAS,QAClB,QAASG,EAAI,QACf,CAAC,EACD,GAAIC,GAAOA,EAAI,MAAM,YACnBH,EAAO,CACL,cAAe,CAACG,EAAI,KAAK,WAAW,EACpC,UAAW,CACT,CACE,QAASD,EAAI,eACb,SAAUA,EAAI,UAAY,CAC5B,CACF,CACF,CAAC,MAED,OAAM,IAAI,MAAM,kBAAkBC,GAAK,GAAG,EAAE,CAEhD,EACAN,CACF,CACF",
|
|
6
|
+
"names": ["useRedeemAndBuy_exports", "__export", "useRedeemAndBuy", "__toCommonJS", "import_mutation", "import_useRedeemCoupon", "import_provider", "import_lib", "_", "swrOptions", "trigger", "profile", "buyNow", "useSWRMutation", "arg", "res"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var p=Object.defineProperty;var
|
|
1
|
+
"use strict";var p=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var L=(o,e)=>{for(var i in e)p(o,i,{get:e[i],enumerable:!0})},w=(o,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of v(e))!y.call(o,t)&&t!==i&&p(o,t,{get:()=>e[t],enumerable:!(n=_(e,t))||n.enumerable});return o};var O=o=>w(p({},"__esModule",{value:!0}),o);var k={};L(k,{default:()=>P});module.exports=O(k);var m=require("react/jsx-runtime"),h=require("@anker-in/headless-ui"),d=require("react"),M=require("../context/provider"),N=require("../context/hooks/useRedeemCoupon"),a=require("../context/const"),R=require("../modal/ModalContainer"),I=require("./RedeemCouponModal/CouponInit"),F=require("./RedeemCouponModal/CouponSuccess");function T({item:o,copy:e,onError:i,...n}){const[t,C]=(0,d.useState)(),[f,s]=(0,d.useState)(),[x,l]=(0,d.useState)(!1),{profile:c,fetchCreditInfo:b}=(0,M.useCreditsContext)(),{isMutating:g,trigger:E}=(0,N.useRedeemCoupon)({onSuccess(r){if(!r){s(e.commonError);return}if(r.data?.success)C(r.data.coupon_code),b(c?.user_id);else{let u;r.code===a.AlpcErrorCode.CodeLpcShopifyCouponRuleRedeemLimit?(u=e.redeemLimitError,l(!0)):r.code===a.AlpcErrorCode.CodeLpcRuleInventoryNotEnough?(u=e.inventoryNotEnough,l(!0)):r.code===a.AlpcErrorCode.CodeLpcNotEnoughCredits?(u=e.creditsNotEnough,l(!0),b(c?.user_id)):r.code===a.AlpcErrorCode.CodeCrossSiteError&&(u=e.crossSiteError,l(!0)),s(u||e.commonError||""),i&&i(r.code)}},onError(r){s(r.message||e.commonError)}}),S=(0,d.useCallback)(async()=>{s(""),E({user_id:c?.user_id,rule_id:Number(o.alpc?.id)})},[o,c,E]);return(0,d.useEffect)(()=>()=>{l(!1),s(""),C(void 0)},[]),(0,m.jsxs)(R.CreditsModalContainer,{...n,isOpen:!!o,className:"w-[540px] md:h-auto",scrollClassName:"mb-[40px] min-l:px-0 md:mb-[24px] px-0",titleClassName:"h-[56px] bg-[#F5F5F7]",children:[t&&!g?(0,m.jsx)(F.CouponSuccess,{item:o,copy:e,couponCode:t,disabled:x,onClose:n.onClose}):(0,m.jsx)(I.CouponInit,{item:o,copy:e,loading:g,disabled:x,onConfirm:S}),f&&(0,m.jsx)("div",{className:"mx-auto max-w-full bg-white px-[48px] py-[12px] text-center text-[#FF0000] md:px-[16px]",children:(0,m.jsx)(h.Text,{className:"text-[14px] font-semibold text-[#1F2021]",html:f})})]})}var P=T;
|
|
2
2
|
//# sourceMappingURL=RedeemCouponModal.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/components/credits/creditsRedeemList/RedeemCouponModal.tsx"],
|
|
4
|
-
"sourcesContent": ["import { Text } from '@anker-in/headless-ui'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { ModalContainerProps } from '../modal/ModalContainer'\nimport { useCreditsContext } from '../context/provider'\nimport { useRedeemCoupon } from '../context/hooks/useRedeemCoupon'\nimport { AlpcErrorCode } from '../context/const'\nimport { CreditsModalContainer } from '../modal/ModalContainer'\nimport type { RedeemableItem as RedeemableItemType, RedeemModalCommon } from '../type'\nimport { CouponInit } from './RedeemCouponModal/CouponInit'\nimport { CouponSuccess } from './RedeemCouponModal/CouponSuccess'\n\nfunction RedeemCouponModal({\n item,\n copy,\n onError,\n ...props\n}: Omit<ModalContainerProps, 'isOpen'> & {\n item: RedeemableItemType\n copy: RedeemModalCommon\n onError: (code: number) => void\n}) {\n const [couponCode, setCouponCode] = useState<string>()\n const [errorInfo, setErrorInfo] = useState<string>()\n const [disabled, setDisabled] = useState(false)\n\n const { profile, fetchCreditInfo } = useCreditsContext()\n\n const { isMutating: loading, trigger } = useRedeemCoupon({\n onSuccess(responseData) {\n if (!responseData) {\n setErrorInfo(copy.commonError)\n return\n }\n\n
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,
|
|
6
|
-
"names": ["RedeemCouponModal_exports", "__export", "RedeemCouponModal_default", "__toCommonJS", "import_jsx_runtime", "import_headless_ui", "import_react", "import_provider", "import_useRedeemCoupon", "import_const", "import_ModalContainer", "import_CouponInit", "import_CouponSuccess", "RedeemCouponModal", "item", "copy", "onError", "props", "couponCode", "setCouponCode", "errorInfo", "setErrorInfo", "disabled", "setDisabled", "profile", "fetchCreditInfo", "loading", "trigger", "responseData", "
|
|
4
|
+
"sourcesContent": ["import { Text } from '@anker-in/headless-ui'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { ModalContainerProps } from '../modal/ModalContainer'\nimport { useCreditsContext } from '../context/provider'\nimport { useRedeemCoupon } from '../context/hooks/useRedeemCoupon'\nimport { AlpcErrorCode } from '../context/const'\nimport { CreditsModalContainer } from '../modal/ModalContainer'\nimport type { RedeemableItem as RedeemableItemType, RedeemModalCommon } from '../type'\nimport { CouponInit } from './RedeemCouponModal/CouponInit'\nimport { CouponSuccess } from './RedeemCouponModal/CouponSuccess'\n\nfunction RedeemCouponModal({\n item,\n copy,\n onError,\n ...props\n}: Omit<ModalContainerProps, 'isOpen'> & {\n item: RedeemableItemType\n copy: RedeemModalCommon\n onError: (code: number) => void\n}) {\n const [couponCode, setCouponCode] = useState<string>()\n const [errorInfo, setErrorInfo] = useState<string>()\n const [disabled, setDisabled] = useState(false)\n\n const { profile, fetchCreditInfo } = useCreditsContext()\n\n const { isMutating: loading, trigger } = useRedeemCoupon({\n onSuccess(responseData) {\n if (!responseData) {\n setErrorInfo(copy.commonError)\n return\n }\n\n if (responseData.data?.success) {\n setCouponCode(responseData.data.coupon_code)\n fetchCreditInfo(profile?.user_id)\n } else {\n let errorMsg\n if (responseData.code === AlpcErrorCode.CodeLpcShopifyCouponRuleRedeemLimit) {\n errorMsg = copy.redeemLimitError\n setDisabled(true)\n } else if (responseData.code === AlpcErrorCode.CodeLpcRuleInventoryNotEnough) {\n errorMsg = copy.inventoryNotEnough\n setDisabled(true)\n } else if (responseData.code === AlpcErrorCode.CodeLpcNotEnoughCredits) {\n errorMsg = copy.creditsNotEnough\n setDisabled(true)\n fetchCreditInfo(profile?.user_id)\n } else if (responseData.code === AlpcErrorCode.CodeCrossSiteError) {\n errorMsg = copy.crossSiteError\n setDisabled(true)\n }\n\n setErrorInfo(errorMsg || copy.commonError || '')\n onError && onError(responseData.code)\n }\n },\n onError(error) {\n setErrorInfo(error.message || copy.commonError)\n },\n })\n\n const handleConfirm = useCallback(async () => {\n setErrorInfo('')\n trigger({\n user_id: profile?.user_id,\n rule_id: Number(item.alpc?.id),\n })\n }, [item, profile, trigger])\n\n useEffect(() => {\n return () => {\n setDisabled(false)\n setErrorInfo('')\n setCouponCode(undefined)\n }\n }, [])\n\n return (\n <CreditsModalContainer\n {...props}\n isOpen={!!item}\n className=\"w-[540px] md:h-auto\"\n scrollClassName=\"mb-[40px] min-l:px-0 md:mb-[24px] px-0\"\n titleClassName=\"h-[56px] bg-[#F5F5F7]\"\n >\n {couponCode && !loading ? (\n <CouponSuccess item={item} copy={copy} couponCode={couponCode} disabled={disabled} onClose={props.onClose} />\n ) : (\n <CouponInit item={item} copy={copy} loading={loading} disabled={disabled} onConfirm={handleConfirm} />\n )}\n {errorInfo && (\n <div className=\"mx-auto max-w-full bg-white px-[48px] py-[12px] text-center text-[#FF0000] md:px-[16px]\">\n <Text className=\"text-[14px] font-semibold text-[#1F2021]\" html={errorInfo} />\n </div>\n )}\n </CreditsModalContainer>\n )\n}\n\nexport default RedeemCouponModal\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAgFI,IAAAI,EAAA,6BAhFJC,EAAqB,iCACrBC,EAAiD,iBAEjDC,EAAkC,+BAClCC,EAAgC,4CAChCC,EAA8B,4BAC9BC,EAAsC,mCAEtCC,EAA2B,0CAC3BC,EAA8B,6CAE9B,SAASC,EAAkB,CACzB,KAAAC,EACA,KAAAC,EACA,QAAAC,EACA,GAAGC,CACL,EAIG,CACD,KAAM,CAACC,EAAYC,CAAa,KAAI,YAAiB,EAC/C,CAACC,EAAWC,CAAY,KAAI,YAAiB,EAC7C,CAACC,EAAUC,CAAW,KAAI,YAAS,EAAK,EAExC,CAAE,QAAAC,EAAS,gBAAAC,CAAgB,KAAI,qBAAkB,EAEjD,CAAE,WAAYC,EAAS,QAAAC,CAAQ,KAAI,mBAAgB,CACvD,UAAUC,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,UAAU,0FACb,mBAAC,QAAK,UAAU,2CAA2C,KAAMA,EAAW,EAC9E,GAEJ,CAEJ,CAEA,IAAOlB,EAAQW",
|
|
6
|
+
"names": ["RedeemCouponModal_exports", "__export", "RedeemCouponModal_default", "__toCommonJS", "import_jsx_runtime", "import_headless_ui", "import_react", "import_provider", "import_useRedeemCoupon", "import_const", "import_ModalContainer", "import_CouponInit", "import_CouponSuccess", "RedeemCouponModal", "item", "copy", "onError", "props", "couponCode", "setCouponCode", "errorInfo", "setErrorInfo", "disabled", "setDisabled", "profile", "fetchCreditInfo", "loading", "trigger", "responseData", "errorMsg", "error", "handleConfirm"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var C=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var B=(
|
|
1
|
+
"use strict";var C=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var B=(r,e)=>{for(var s in e)C(r,s,{get:e[s],enumerable:!0})},z=(r,e,s,u)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of w(e))!V.call(r,a)&&a!==s&&C(r,a,{get:()=>e[a],enumerable:!(u=k(e,a))||u.enumerable});return r};var D=r=>z(C({},"__esModule",{value:!0}),r);var q={};B(q,{default:()=>U});module.exports=D(q);var l=require("react/jsx-runtime"),R=require("@anker-in/headless-ui"),d=require("react"),M=require("../context/provider"),I=require("../context/hooks/useRedeemGoGift"),S=require("../context/hooks/useRedeemProduct"),n=require("../context/const"),y=require("../modal/ModalContainer"),P=require("@anker-in/lib"),L=require("./RedeemVirtualProductModal/VirtualProductInit"),F=require("./RedeemVirtualProductModal/VirtualProductSuccess");function J({item:r,copy:e,onError:s,...u}){const[a,c]=(0,d.useState)(),[b,m]=(0,d.useState)(),[x,f]=(0,d.useState)(!1),{profile:o,fetchCreditInfo:p,gtm:E}=(0,M.useCreditsContext)(),g=r.config?.type===n.ConsumeType.GoGift,v=r.config?.type===n.ConsumeType.GiftCard,{isMutating:T,trigger:_}=(0,I.useRedeemGoGift)({onSuccess(t){if(!t){m(e?.commonError);return}const i=t.data;i?.id?(c(i.id),p(o?.user_id)):h(t.code)},onError(t){m(t.message||e?.commonError)}}),{isMutating:A,trigger:G}=(0,S.useRedeemProduct)({onSuccess(t){if(!t){m(e?.commonError);return}t?.code===0?(c("success"),p(o?.user_id)):h(t.code)},onError(){m(e?.commonError)}}),N=g?T:A,h=t=>{let i;t===n.AlpcErrorCode.CodeLpcShopifyCouponRuleRedeemLimit?(i=e?.redeemLimitError,f(!0)):t===n.AlpcErrorCode.CodeLpcRuleInventoryNotEnough?(i=e?.inventoryNotEnough,f(!0)):t===n.AlpcErrorCode.CodeLpcNotEnoughCredits?(i=e?.creditsNotEnough,f(!0),p(o?.user_id)):t===n.AlpcErrorCode.CodeCrossSiteError&&(i=e?.crossSiteError,f(!0)),m(i||e?.commonError||""),s&&s(t)},O=(0,d.useCallback)(async()=>{if(m(""),(0,P.gaTrack)({event:"ga4Event",event_name:"lp_button",member_active_status:o?.activated?"active":"not active",event_parameters:{page_group:E.pageGroup,position:"redeem virtual product modal",button_name:e.confirmButton,info:r.alpc?.id}}),g)_({user_id:o?.user_id,rule_id:Number(r.alpc?.id)});else if(v){const t={email:o?.email||"",first_name:o?.firstName||"Anker",last_name:o?.lastName||"Direct",address1:"Default Address",city:"Default City",province:"Default Province",country:"US",zip:"00000"};G({address:btoa(JSON.stringify(t)),rule_id:Number(r.alpc?.id)})}},[r,o,_,G,g,v,e.confirmButton,E.pageGroup]);return(0,d.useEffect)(()=>()=>{f(!1),m(""),c(void 0)},[]),(0,l.jsxs)(y.CreditsModalContainer,{...u,isOpen:!!r,className:"w-[540px] md:h-auto",scrollClassName:"mb-[40px] min-l:px-0 md:mb-[24px] px-0",titleClassName:"h-[56px] bg-[#F5F5F7]",children:[a&&!N?(0,l.jsx)(F.VirtualProductSuccess,{item:r,copy:e,disabled:x,onClose:u.onClose}):(0,l.jsx)(L.VirtualProductInit,{item:r,copy:e,loading:N,disabled:x,onConfirm:O}),b&&(0,l.jsx)("div",{className:"mx-auto max-w-full bg-white px-[48px] py-[12px] text-center text-[#FF0000] md:px-[16px]",children:(0,l.jsx)(R.Text,{className:"text-[14px] font-semibold text-[#1F2021]",html:b})})]})}var U=J;
|
|
2
2
|
//# sourceMappingURL=RedeemVirtualProductModal.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/components/credits/creditsRedeemList/RedeemVirtualProductModal.tsx"],
|
|
4
|
-
"sourcesContent": ["import { Text } from '@anker-in/headless-ui'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { ModalContainerProps } from '../modal/ModalContainer'\nimport { useCreditsContext } from '../context/provider'\nimport { useRedeemGoGift } from '../context/hooks/useRedeemGoGift'\nimport { useRedeemProduct } from '../context/hooks/useRedeemProduct'\nimport { AlpcErrorCode, ConsumeType } from '../context/const'\nimport { CreditsModalContainer } from '../modal/ModalContainer'\nimport type { RedeemableItem as RedeemableItemType, RedeemModalCommon } from '../type'\nimport { gaTrack } from '@anker-in/lib'\nimport { VirtualProductInit } from './RedeemVirtualProductModal/VirtualProductInit'\nimport { VirtualProductSuccess } from './RedeemVirtualProductModal/VirtualProductSuccess'\n\nfunction RedeemVirtualProductModal({\n item,\n copy,\n onError,\n ...props\n}: Omit<ModalContainerProps, 'isOpen'> & {\n item: RedeemableItemType\n copy: RedeemModalCommon\n onError: (code: number) => void\n}) {\n const [giftCardId, setGiftCardId] = useState<string>()\n const [errorInfo, setErrorInfo] = useState<string>()\n\n const [disabled, setDisabled] = useState(false)\n\n const { profile, fetchCreditInfo, gtm } = useCreditsContext()\n\n // \u5224\u65AD\u662F GoGift \u8FD8\u662F GiftCard \u7C7B\u578B\n const isGoGift = item.config?.type === ConsumeType.GoGift\n const isGiftCard = item.config?.type === ConsumeType.GiftCard\n\n // GoGift \u4F7F\u7528\u4E13\u7528\u63A5\u53E3\n const { isMutating: goGiftLoading, trigger: triggerGoGift } = useRedeemGoGift({\n onSuccess(responseData) {\n if (!responseData) {\n setErrorInfo(copy?.commonError)\n return\n }\n\n const data = responseData
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAmJI,IAAAI,EAAA,6BAnJJC,EAAqB,iCACrBC,EAAiD,iBAEjDC,EAAkC,+BAClCC,EAAgC,4CAChCC,EAAiC,6CACjCC,EAA2C,4BAC3CC,EAAsC,mCAEtCC,EAAwB,yBACxBC,EAAmC,0DACnCC,EAAsC,6DAEtC,SAASC,EAA0B,CACjC,KAAAC,EACA,KAAAC,EACA,QAAAC,EACA,GAAGC,CACL,EAIG,CACD,KAAM,CAACC,EAAYC,CAAa,KAAI,YAAiB,EAC/C,CAACC,EAAWC,CAAY,KAAI,YAAiB,EAE7C,CAACC,EAAUC,CAAW,KAAI,YAAS,EAAK,EAExC,CAAE,QAAAC,EAAS,gBAAAC,EAAiB,IAAAC,CAAI,KAAI,qBAAkB,EAGtDC,EAAWb,EAAK,QAAQ,OAAS,cAAY,OAC7Cc,EAAad,EAAK,QAAQ,OAAS,cAAY,SAG/C,CAAE,WAAYe,EAAe,QAASC,CAAc,KAAI,mBAAgB,CAC5E,UAAUC,EAAc,CACtB,GAAI,CAACA,EAAc,CACjBV,EAAaN,GAAM,WAAW,EAC9B,MACF,CAEA,MAAMiB,EAAOD,
|
|
4
|
+
"sourcesContent": ["import { Text } from '@anker-in/headless-ui'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { ModalContainerProps } from '../modal/ModalContainer'\nimport { useCreditsContext } from '../context/provider'\nimport { useRedeemGoGift } from '../context/hooks/useRedeemGoGift'\nimport { useRedeemProduct } from '../context/hooks/useRedeemProduct'\nimport { AlpcErrorCode, ConsumeType } from '../context/const'\nimport { CreditsModalContainer } from '../modal/ModalContainer'\nimport type { RedeemableItem as RedeemableItemType, RedeemModalCommon } from '../type'\nimport { gaTrack } from '@anker-in/lib'\nimport { VirtualProductInit } from './RedeemVirtualProductModal/VirtualProductInit'\nimport { VirtualProductSuccess } from './RedeemVirtualProductModal/VirtualProductSuccess'\n\nfunction RedeemVirtualProductModal({\n item,\n copy,\n onError,\n ...props\n}: Omit<ModalContainerProps, 'isOpen'> & {\n item: RedeemableItemType\n copy: RedeemModalCommon\n onError: (code: number) => void\n}) {\n const [giftCardId, setGiftCardId] = useState<string>()\n const [errorInfo, setErrorInfo] = useState<string>()\n\n const [disabled, setDisabled] = useState(false)\n\n const { profile, fetchCreditInfo, gtm } = useCreditsContext()\n\n // \u5224\u65AD\u662F GoGift \u8FD8\u662F GiftCard \u7C7B\u578B\n const isGoGift = item.config?.type === ConsumeType.GoGift\n const isGiftCard = item.config?.type === ConsumeType.GiftCard\n\n // GoGift \u4F7F\u7528\u4E13\u7528\u63A5\u53E3\n const { isMutating: goGiftLoading, trigger: triggerGoGift } = useRedeemGoGift({\n onSuccess(responseData) {\n if (!responseData) {\n setErrorInfo(copy?.commonError)\n return\n }\n\n const data = responseData.data\n if (data?.id) {\n setGiftCardId(data.id)\n fetchCreditInfo(profile?.user_id)\n } else {\n handleRedeemError(responseData.code)\n }\n },\n onError(error) {\n setErrorInfo(error.message || copy?.commonError)\n },\n })\n\n // GiftCard \u4F7F\u7528 Product \u63A5\u53E3\uFF0C\u4F46\u4E0D\u9700\u8981\u5730\u5740\n const { isMutating: productLoading, trigger: triggerProduct } = useRedeemProduct({\n onSuccess(responseData) {\n if (!responseData) {\n setErrorInfo(copy?.commonError)\n return\n }\n\n if (responseData?.code === 0) {\n setGiftCardId('success')\n fetchCreditInfo(profile?.user_id)\n } else {\n handleRedeemError(responseData.code)\n }\n },\n onError() {\n setErrorInfo(copy?.commonError)\n },\n })\n\n const loading = isGoGift ? goGiftLoading : productLoading\n\n const handleRedeemError = (code: number) => {\n let errorMsg: string | undefined\n if (code === AlpcErrorCode.CodeLpcShopifyCouponRuleRedeemLimit) {\n errorMsg = copy?.redeemLimitError\n setDisabled(true)\n } else if (code === AlpcErrorCode.CodeLpcRuleInventoryNotEnough) {\n errorMsg = copy?.inventoryNotEnough\n setDisabled(true)\n } else if (code === AlpcErrorCode.CodeLpcNotEnoughCredits) {\n errorMsg = copy?.creditsNotEnough\n setDisabled(true)\n fetchCreditInfo(profile?.user_id)\n } else if (code === AlpcErrorCode.CodeCrossSiteError) {\n errorMsg = copy?.crossSiteError\n setDisabled(true)\n }\n\n setErrorInfo(errorMsg || copy?.commonError || '')\n onError && onError(code)\n }\n\n const handleConfirm = useCallback(async () => {\n setErrorInfo('')\n\n gaTrack({\n event: 'ga4Event',\n event_name: 'lp_button',\n member_active_status: profile?.activated ? 'active' : 'not active',\n event_parameters: {\n page_group: gtm.pageGroup,\n position: 'redeem virtual product modal',\n button_name: copy.confirmButton,\n info: item.alpc?.id,\n },\n })\n\n if (isGoGift) {\n // GoGift \u7C7B\u578B\u4F7F\u7528\u4E13\u7528\u63A5\u53E3\n triggerGoGift({\n user_id: profile?.user_id,\n rule_id: Number(item.alpc?.id),\n })\n } else if (isGiftCard) {\n // GiftCard \u7C7B\u578B\u4F7F\u7528 Product \u63A5\u53E3\uFF0C\u4F20\u9012\u9ED8\u8BA4\u5730\u5740\n const defaultAddress = {\n email: profile?.email || '',\n first_name: profile?.firstName || 'Anker',\n last_name: profile?.lastName || 'Direct',\n address1: 'Default Address',\n city: 'Default City',\n province: 'Default Province',\n country: 'US',\n zip: '00000',\n }\n triggerProduct({\n address: btoa(JSON.stringify(defaultAddress)),\n rule_id: Number(item.alpc?.id),\n })\n }\n }, [item, profile, triggerGoGift, triggerProduct, isGoGift, isGiftCard, copy.confirmButton, gtm.pageGroup])\n\n useEffect(() => {\n return () => {\n setDisabled(false)\n setErrorInfo('')\n setGiftCardId(undefined)\n }\n }, [])\n\n return (\n <CreditsModalContainer\n {...props}\n isOpen={!!item}\n className=\"w-[540px] md:h-auto\"\n scrollClassName=\"mb-[40px] min-l:px-0 md:mb-[24px] px-0\"\n titleClassName=\"h-[56px] bg-[#F5F5F7]\"\n >\n {giftCardId && !loading ? (\n <VirtualProductSuccess item={item} copy={copy} disabled={disabled} onClose={props.onClose} />\n ) : (\n <VirtualProductInit item={item} copy={copy} loading={loading} disabled={disabled} onConfirm={handleConfirm} />\n )}\n {errorInfo && (\n <div className=\"mx-auto max-w-full bg-white px-[48px] py-[12px] text-center text-[#FF0000] md:px-[16px]\">\n <Text className=\"text-[14px] font-semibold text-[#1F2021]\" html={errorInfo} />\n </div>\n )}\n </CreditsModalContainer>\n )\n}\n\nexport default RedeemVirtualProductModal\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAmJI,IAAAI,EAAA,6BAnJJC,EAAqB,iCACrBC,EAAiD,iBAEjDC,EAAkC,+BAClCC,EAAgC,4CAChCC,EAAiC,6CACjCC,EAA2C,4BAC3CC,EAAsC,mCAEtCC,EAAwB,yBACxBC,EAAmC,0DACnCC,EAAsC,6DAEtC,SAASC,EAA0B,CACjC,KAAAC,EACA,KAAAC,EACA,QAAAC,EACA,GAAGC,CACL,EAIG,CACD,KAAM,CAACC,EAAYC,CAAa,KAAI,YAAiB,EAC/C,CAACC,EAAWC,CAAY,KAAI,YAAiB,EAE7C,CAACC,EAAUC,CAAW,KAAI,YAAS,EAAK,EAExC,CAAE,QAAAC,EAAS,gBAAAC,EAAiB,IAAAC,CAAI,KAAI,qBAAkB,EAGtDC,EAAWb,EAAK,QAAQ,OAAS,cAAY,OAC7Cc,EAAad,EAAK,QAAQ,OAAS,cAAY,SAG/C,CAAE,WAAYe,EAAe,QAASC,CAAc,KAAI,mBAAgB,CAC5E,UAAUC,EAAc,CACtB,GAAI,CAACA,EAAc,CACjBV,EAAaN,GAAM,WAAW,EAC9B,MACF,CAEA,MAAMiB,EAAOD,EAA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AErB,MAAMa,EAAiB,CACrB,MAAOjB,GAAS,OAAS,GACzB,WAAYA,GAAS,WAAa,QAClC,UAAWA,GAAS,UAAY,SAChC,SAAU,kBACV,KAAM,eACN,SAAU,mBACV,QAAS,KACT,IAAK,OACP,EACAY,EAAe,CACb,QAAS,KAAK,KAAK,UAAUK,CAAc,CAAC,EAC5C,QAAS,OAAO3B,EAAK,MAAM,EAAE,CAC/B,CAAC,CACH,CACF,EAAG,CAACA,EAAMU,EAASM,EAAeM,EAAgBT,EAAUC,EAAYb,EAAK,cAAeW,EAAI,SAAS,CAAC,EAE1G,sBAAU,IACD,IAAM,CACXH,EAAY,EAAK,EACjBF,EAAa,EAAE,EACfF,EAAc,MAAS,CACzB,EACC,CAAC,CAAC,KAGH,QAAC,yBACE,GAAGF,EACJ,OAAQ,CAAC,CAACH,EACV,UAAU,sBACV,gBAAgB,yCAChB,eAAe,wBAEd,UAAAI,GAAc,CAACmB,KACd,OAAC,yBAAsB,KAAMvB,EAAM,KAAMC,EAAM,SAAUO,EAAU,QAASL,EAAM,QAAS,KAE3F,OAAC,sBAAmB,KAAMH,EAAM,KAAMC,EAAM,QAASsB,EAAS,SAAUf,EAAU,UAAWkB,EAAe,EAE7GpB,MACC,OAAC,OAAI,UAAU,0FACb,mBAAC,QAAK,UAAU,2CAA2C,KAAMA,EAAW,EAC9E,GAEJ,CAEJ,CAEA,IAAOpB,EAAQa",
|
|
6
6
|
"names": ["RedeemVirtualProductModal_exports", "__export", "RedeemVirtualProductModal_default", "__toCommonJS", "import_jsx_runtime", "import_headless_ui", "import_react", "import_provider", "import_useRedeemGoGift", "import_useRedeemProduct", "import_const", "import_ModalContainer", "import_lib", "import_VirtualProductInit", "import_VirtualProductSuccess", "RedeemVirtualProductModal", "item", "copy", "onError", "props", "giftCardId", "setGiftCardId", "errorInfo", "setErrorInfo", "disabled", "setDisabled", "profile", "fetchCreditInfo", "gtm", "isGoGift", "isGiftCard", "goGiftLoading", "triggerGoGift", "responseData", "data", "handleRedeemError", "error", "productLoading", "triggerProduct", "loading", "code", "errorMsg", "handleConfirm", "defaultAddress"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import D from"js-cookie";import{useCallback as E,useRef as m,useState as O}from"react";import F from"swr";import{useHeadlessContext as B}from"@anker-in/lib";import{getAlpcPath as A}from"../utils";import{useCreditsContext as w}from"../provider";let b;const U=t=>t&&(t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:t),M=t=>fetch(A(t.locale,t.apiBaseUrl)+t.url,t.fetchOptions).then(async a=>{if(a.status<300){const n=await a.json();return U(n)}if(a.status===401&&t.onReAuth){b||(b=t.onReAuth());const n=await b;if(b=void 0,n)return fetch(A(t.locale,t.apiBaseUrl)+t.url,t.fetchOptions).then(async r=>{if(r.status<300){const e=await r.json();return U(e)}if(r.status===401){t.onUnAuth&&t.onUnAuth();return}});t.onUnAuth&&t.onUnAuth();return}}),S=async(t,a,n,r)=>{let e=await fetch(`${A(t,r)}/cloud/login`,{method:"POST"}),s=await e.json(),o=U(s);if(e.status<300&&!a&&o?.code===27004){const i=D.get("alpcEU");if(Number(i)===1?D.set("alpcEU","0",{expires:30,domain:`.${n}.com`}):D.set("alpcEU","1",{expires:30,domain:`.${n}.com`}),e=await fetch(`${A(t,r)}/cloud/login`,{method:"POST"}),s=await e.json(),o=U(s),e.status>300)return!1}return!o?.code},q=(t,a,n={},r)=>{const e=m(!1),[s,o]=O(),[i,f]=O(!1),c=m(t),l=m(a),d=m(n),h=E(async(g,T={})=>{if(console.log("[useAlpcMutation] trigger called with:",{url:c.current,fetchData:g,brand:r.current}),e.current){console.log("[useAlpcMutation] already mutating, skipping");return}if(!r.current){console.log("[useAlpcMutation] brand not available, skipping request");return}e.current=!0,f(!0);const y={...d.current,...T},{onSuccess:R,onError:p}=y||{};try{const u=await l.current(c.current,{arg:g});return o(u),f(!1),e.current=!1,R&&R(u),u}catch(u){f(!1),e.current=!1,p&&p(u)}},[]);return{isMutating:i,trigger:h,data:s}},z=(t,a)=>{const[n,r]=O(!1),{removeProfile:e,alpcBrand:s,apiBaseUrl:o}=w(),{enable:i,...f}=a||{},{locale:c="",brand:l}=B(),d=s||l,{queryKey:h=[],body:g={},headers:T,...y}=t,R=i??!0,[p,u]=h;return F([p,u],!R||!d?null:([C,P])=>M({url:C,locale:c,apiBaseUrl:o,fetchOptions:{method:"POST",headers:{"current-language":c,...T},body:JSON.stringify({...g,...P}),...y},onReAuth:async()=>await S(c,n,d,o)?(r(!0),!0):!1,onUnAuth(){e()}}),{revalidateOnFocus:!1,...f})},J=(t,a)=>{const[n,r]=O(!1),{removeProfile:e,alpcBrand:s,apiBaseUrl:o}=w(),{locale:i="",brand:f}=B(),c=s||f,l=m(c);l.current=c;const{url:d,initData:h,headers:g,...T}=t,y=m(h);return y.current=h,q(d,(p,u)=>l.current?M({url:p,locale:i,apiBaseUrl:o,fetchOptions:{method:"POST",headers:{"current-language":i,...g},...T,body:JSON.stringify({...y.current,...u.arg})},onReAuth:async()=>await S(i,n,l.current,o)?(r(!0),!0):!1,onUnAuth(){e()}}):Promise.resolve(void 0),a,l)};export{z as useAlpcFetch,J as useAlpcMutation};
|
|
1
|
+
import D from"js-cookie";import{useCallback as E,useRef as m,useState as O}from"react";import F from"swr";import{useHeadlessContext as B}from"@anker-in/lib";import{getAlpcPath as A}from"../utils";import{useCreditsContext as w}from"../provider";let b;const U=t=>t&&(t.data&&typeof t.data=="object"&&!Array.isArray(t.data)&&"data"in t.data?t.data:t),M=t=>fetch(A(t.locale,t.apiBaseUrl)+t.url,t.fetchOptions).then(async a=>{if(a.status<300){const n=await a.json();return U(n)}if(a.status===401&&t.onReAuth){b||(b=t.onReAuth());const n=await b;if(b=void 0,n)return fetch(A(t.locale,t.apiBaseUrl)+t.url,t.fetchOptions).then(async r=>{if(r.status<300){const e=await r.json();return U(e)}if(r.status===401){t.onUnAuth&&t.onUnAuth();return}});t.onUnAuth&&t.onUnAuth();return}}),S=async(t,a,n,r)=>{let e=await fetch(`${A(t,r)}/cloud/login`,{method:"POST"}),s=await e.json(),o=U(s);if(e.status<300&&!a&&o?.code===27004){const i=D.get("alpcEU");if(Number(i)===1?D.set("alpcEU","0",{expires:30,domain:`.${n}.com`}):D.set("alpcEU","1",{expires:30,domain:`.${n}.com`}),e=await fetch(`${A(t,r)}/cloud/login`,{method:"POST"}),s=await e.json(),o=U(s),e.status>300)return!1}return!o?.code},q=(t,a,n={},r)=>{const e=m(!1),[s,o]=O(),[i,f]=O(!1),c=m(t),l=m(a),d=m(n),h=E(async(g,T={})=>{if(console.log("[useAlpcMutation] trigger called with:",{url:c.current,fetchData:g,brand:r.current}),e.current){console.log("[useAlpcMutation] already mutating, skipping");return}if(!r.current){console.log("[useAlpcMutation] brand not available, skipping request");return}e.current=!0,f(!0);const y={...d.current,...T},{onSuccess:R,onError:p}=y||{};try{const u=await l.current(c.current,{arg:g});return o(u),f(!1),e.current=!1,R&&R(u),u}catch(u){f(!1),e.current=!1,p&&p(u)}},[]);return{isMutating:i,trigger:h,data:s}},z=(t,a)=>{const[n,r]=O(!1),{removeProfile:e,alpcBrand:s,apiBaseUrl:o}=w(),{enable:i,...f}=a||{},{locale:c="",brand:l}=B(),d=s||l,{queryKey:h=[],body:g={},headers:T,...y}=t,R=i??!0,[p,u]=h;return F([p,u],!R||!d?null:([C,P])=>M({url:C,locale:c,apiBaseUrl:o,fetchOptions:{method:"POST",headers:{"current-language":c,...T},body:JSON.stringify({...g,...P}),...y},onReAuth:async()=>await S(c,n,d,o)?(r(!0),!0):!1,onUnAuth(){e()}}),{revalidateOnFocus:!1,...f})},J=(t,a)=>{const[n,r]=O(!1),{removeProfile:e,alpcBrand:s,apiBaseUrl:o}=w(),{locale:i="",brand:f}=B(),c=s||f,l=m(c);l.current=c;const{url:d,initData:h,headers:g,...T}=t,y=m(h);return y.current=h,q(d,(p,u)=>l.current?M({url:p,locale:i,apiBaseUrl:o,fetchOptions:{method:"POST",headers:{"current-language":i,...g},...T,body:JSON.stringify({...y.current,...u.arg})},onReAuth:async()=>await S(i,n,l.current,o)?(r(!0),!0):!1,onUnAuth(){e()}}):Promise.resolve(void 0),a,l)};export{z as useAlpcFetch,J as useAlpcMutation};
|
|
2
2
|
//# sourceMappingURL=useAlpcFetch.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/components/credits/context/hooks/useAlpcFetch.ts"],
|
|
4
|
-
"sourcesContent": ["import Cookies from 'js-cookie'\nimport { useCallback, useRef, useState } from 'react'\nimport useSWR, { type SWRConfiguration } from 'swr'\nimport { useHeadlessContext } from '@anker-in/lib'\n\nimport { getAlpcPath } from '../utils'\nimport { useCreditsContext } from '../provider'\n\ninterface UseAlpcFetchOptionsSwrOptions<TData, Error> extends SWRConfiguration<TData, Error> {\n enable?: boolean\n}\n\ninterface FetchOptions extends RequestInit {\n queryKey: [string, Record<string, any>]\n data?: Record<string, any>\n}\n\ninterface MutationOptions extends RequestInit {\n url: string\n initData: Record<string, any>\n}\n\ninterface FetcherOptions {\n url: string\n locale: string\n fetchOptions: RequestInit\n onReAuth: () => Promise<boolean>\n onUnAuth: () => void\n apiBaseUrl?: string\n}\n\nlet reAuthPromise: Promise<boolean> | undefined\n\ntype Fetcher<TData, TBody> = (url: string, data: { arg: TBody }) => Promise<TData>\n\n/**\n * \u7EDF\u4E00\u5904\u7406 ALPC \u63A5\u53E3\u8FD4\u56DE\u7684\u6570\u636E\u7ED3\u6784\n * \u517C\u5BB9\u4E00\u5C42 data \u548C\u4E24\u5C42 data \u7684\u573A\u666F\uFF1A\n * - \u4E24\u5C42 data: {data: {data: ..., code: 27004}}\n * - \u4E00\u5C42 data: {data: ..., code: 27004}\n */\nconst normalizeResponseData = (responseData: any) => {\n if (!responseData) return responseData\n\n // \u5982\u679C responseData.data \u5B58\u5728\u4E14\u662F\u4E00\u4E2A\u5BF9\u8C61\uFF08\u4E0D\u662F\u6570\u7EC4\uFF09\uFF0C\u8BF4\u660E\u662F\u4E24\u5C42 data \u7ED3\u6784\n if (responseData.data && typeof responseData.data === 'object' && !Array.isArray(responseData.data)) {\n return responseData.data\n }\n\n // \u4E00\u5C42 data \u7ED3\u6784\u6216\u5176\u4ED6\u60C5\u51B5\uFF0C\u76F4\u63A5\u8FD4\u56DE\n return responseData\n}\n\nconst fetcher = (options: FetcherOptions) => {\n return fetch(getAlpcPath(options.locale, options.apiBaseUrl) + options.url, options.fetchOptions).then(async response => {\n if (response.status < 300) {\n const responseData = await response.json()\n return normalizeResponseData(responseData)\n }\n\n // \u9519\u8BEF\u5904\u7406\n if (response.status === 401) {\n // \u91CD\u65B0\u767B\u5F55\u5C1D\u8BD5\n if (options.onReAuth) {\n if (!reAuthPromise) {\n reAuthPromise = options.onReAuth()\n }\n\n const result = await reAuthPromise\n\n reAuthPromise = undefined\n\n if (result) {\n // \u8DE8\u533A\u91CD\u65B0\u767B\u5F55\u540E\u9700\u8981\u66FF\u6362\u533A\u57DF\u6807\u5FD7\uFF0C\u6240\u4EE5\u4E0D\u80FD\u7528\u6700\u5F00\u59CB\u8BF7\u6C42\u7684\u90A3\u4E2A\u94FE\u63A5\n return fetch(getAlpcPath(options.locale, options.apiBaseUrl) + options.url, options.fetchOptions).then(async response => {\n if (response.status < 300) {\n const responseData = await response.json()\n return normalizeResponseData(responseData)\n }\n\n if (response.status === 401) {\n if (options.onUnAuth) {\n options.onUnAuth()\n }\n return\n }\n })\n } else {\n if (options.onUnAuth) {\n options.onUnAuth()\n }\n return\n }\n }\n }\n })\n}\n\nconst reAuth = async (locale: string, retry: boolean, brand: string, apiBaseUrl?: string) => {\n let reloginResponse = await fetch(`${getAlpcPath(locale, apiBaseUrl)}/cloud/login`, {\n method: 'POST',\n })\n let reloginResponseData = await reloginResponse.json()\n // \u517C\u5BB9\u4E24\u5C42 data \u7ED3\u6784\n let normalizedData = normalizeResponseData(reloginResponseData)\n\n if (reloginResponse!.status < 300 && !retry) {\n if (normalizedData?.code === 27004) {\n // \u8DE8\u533A\u767B\u5F55\u9519\u8BEF\n const alpcEUCookie = Cookies.get('alpcEU')\n\n if (Number(alpcEUCookie) === 1) {\n Cookies.set('alpcEU', '0', {\n expires: 30,\n domain: `.${brand}.com`,\n })\n } else {\n Cookies.set('alpcEU', '1', {\n expires: 30,\n domain: `.${brand}.com`,\n })\n }\n\n // \u91CD\u65B0\u5C1D\u8BD5\u6362\u533A\u767B\u5F55\n reloginResponse = await fetch(`${getAlpcPath(locale, apiBaseUrl)}/cloud/login`, {\n method: 'POST',\n })\n reloginResponseData = await reloginResponse.json()\n normalizedData = normalizeResponseData(reloginResponseData)\n\n if (reloginResponse.status > 300) {\n return false\n }\n }\n }\n if (!normalizedData?.code) {\n // \u91CD\u65B0\u767B\u5F55\u6210\u529F\n return true\n }\n\n return false\n}\n\nexport interface UseMutationConfig<TData> {\n onSuccess?: (response: TData) => any\n onError?: (error: Error) => any\n}\n\nconst useMutation = <TData, TBody>(\n url: string,\n fetcher: Fetcher<TData, TBody>,\n mutationConfig: UseMutationConfig<TData> = {},\n brandRef: React.MutableRefObject<string | undefined>\n) => {\n const innerMutating = useRef<boolean>(false)\n\n const [data, setData] = useState<TData>()\n const [isMutating, setIsMutating] = useState(false)\n\n const urlRef = useRef(url)\n const fetcherRef = useRef(fetcher)\n const configRef = useRef(mutationConfig)\n\n const trigger = useCallback(\n async (fetchData: TBody, opts: UseMutationConfig<TData> = {}) => {\n console.log('[useAlpcMutation] trigger called with:', { url: urlRef.current, fetchData, brand: brandRef.current })\n\n if (innerMutating.current) {\n console.log('[useAlpcMutation] already mutating, skipping')\n return\n }\n\n if (!brandRef.current) {\n console.log('[useAlpcMutation] brand not available, skipping request')\n return\n }\n\n innerMutating.current = true\n setIsMutating(true)\n\n const config = {\n ...configRef.current,\n ...opts,\n }\n\n const { onSuccess, onError } = config || {}\n\n try {\n const fetchResult = await fetcherRef.current(urlRef.current, {\n arg: fetchData,\n })\n setData(fetchResult)\n\n setIsMutating(false)\n innerMutating.current = false\n\n if (onSuccess) {\n onSuccess(fetchResult)\n }\n return fetchResult\n } catch (err: any) {\n setIsMutating(false)\n innerMutating.current = false\n\n if (onError) {\n onError(err)\n }\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n []\n )\n\n return {\n isMutating,\n trigger,\n data,\n }\n}\n\nexport const useAlpcFetch = <TData>(\n options: FetchOptions,\n swrOptions?: UseAlpcFetchOptionsSwrOptions<TData, Error>\n) => {\n const [retry, setRetry] = useState(false)\n const { removeProfile, alpcBrand, apiBaseUrl } = useCreditsContext()\n\n const { enable, ...otherSwrOptions } = swrOptions || {}\n\n const { locale = '', brand: headlessBrand } = useHeadlessContext()\n // \u4F18\u5148\u4F7F\u7528 creditsContext \u4E2D\u7684 alpcBrand\uFF0C\u5982\u679C\u6CA1\u6709\u5219\u4F7F\u7528 headlessConfig \u4E2D\u7684 brand\n const brand = alpcBrand || headlessBrand\n\n const { queryKey = [], body: fetchBody = {}, headers, ...fetchOptions } = options\n const fetchEnable = enable ?? true\n\n const [url, requestBody] = queryKey\n\n const context = useSWR<TData>(\n [url, requestBody],\n !fetchEnable || !brand\n ? null\n : ([requestUrl, data]: [string, Record<string, any>]) =>\n fetcher({\n url: requestUrl,\n locale,\n apiBaseUrl,\n fetchOptions: {\n method: 'POST',\n headers: {\n 'current-language': locale,\n ...headers,\n },\n body: JSON.stringify({\n ...fetchBody,\n ...data,\n }),\n ...fetchOptions,\n },\n onReAuth: async () => {\n const result = await reAuth(locale, retry, brand, apiBaseUrl)\n\n if (result) {\n setRetry(true)\n return true\n }\n\n return false\n },\n onUnAuth() {\n // \u5931\u8D25\u540E\u9000\u51FA\u767B\u5F55\n removeProfile()\n },\n }),\n {\n revalidateOnFocus: false,\n ...otherSwrOptions,\n }\n )\n\n return context\n}\n\nexport const useAlpcMutation = <TData, TBody>(options: MutationOptions, mutationOptions?: UseMutationConfig<TData>) => {\n const [retry, setRetry] = useState(false)\n const { removeProfile, alpcBrand, apiBaseUrl } = useCreditsContext()\n\n const { locale = '', brand: headlessBrand } = useHeadlessContext()\n // \u4F18\u5148\u4F7F\u7528 creditsContext \u4E2D\u7684 alpcBrand\uFF0C\u5982\u679C\u6CA1\u6709\u5219\u4F7F\u7528 headlessConfig \u4E2D\u7684 brand\n const brand = alpcBrand || headlessBrand\n const brandRef = useRef(brand)\n brandRef.current = brand\n\n const { url, initData, headers, ...fetchOptions } = options\n const initDataRef = useRef(initData)\n initDataRef.current = initData\n\n const context = useMutation<TData, TBody>(\n url,\n (requestUrl, data: { arg: TBody }) => {\n // Prevent requests when brand is not available\n if (!brandRef.current) {\n return Promise.resolve(undefined as unknown as TData)\n }\n\n return fetcher({\n url: requestUrl,\n locale,\n apiBaseUrl,\n fetchOptions: {\n method: 'POST',\n headers: {\n 'current-language': locale,\n ...headers,\n },\n ...fetchOptions,\n body: JSON.stringify({\n ...initDataRef.current,\n ...data.arg,\n }),\n },\n onReAuth: async () => {\n const result = await reAuth(locale, retry, brandRef.current!, apiBaseUrl)\n\n if (result) {\n setRetry(true)\n return true\n }\n\n return false\n },\n onUnAuth() {\n // \u5931\u8D25\u540E\u9000\u51FA\u767B\u5F55\n removeProfile()\n },\n })\n },\n mutationOptions,\n brandRef\n )\n\n return context\n}\n"],
|
|
5
|
-
"mappings": "AAAA,OAAOA,MAAa,YACpB,OAAS,eAAAC,EAAa,UAAAC,EAAQ,YAAAC,MAAgB,QAC9C,OAAOC,MAAuC,MAC9C,OAAS,sBAAAC,MAA0B,gBAEnC,OAAS,eAAAC,MAAmB,WAC5B,OAAS,qBAAAC,MAAyB,cAyBlC,IAAIC,
|
|
4
|
+
"sourcesContent": ["import Cookies from 'js-cookie'\nimport { useCallback, useRef, useState } from 'react'\nimport useSWR, { type SWRConfiguration } from 'swr'\nimport { useHeadlessContext } from '@anker-in/lib'\n\nimport { getAlpcPath } from '../utils'\nimport { useCreditsContext } from '../provider'\n\ninterface UseAlpcFetchOptionsSwrOptions<TData, Error> extends SWRConfiguration<TData, Error> {\n enable?: boolean\n}\n\ninterface FetchOptions extends RequestInit {\n queryKey: [string, Record<string, any>]\n data?: Record<string, any>\n}\n\ninterface MutationOptions extends RequestInit {\n url: string\n initData: Record<string, any>\n}\n\ninterface FetcherOptions {\n url: string\n locale: string\n fetchOptions: RequestInit\n onReAuth: () => Promise<boolean>\n onUnAuth: () => void\n apiBaseUrl?: string\n}\n\nlet reAuthPromise: Promise<boolean> | undefined\n\ntype Fetcher<TData, TBody> = (url: string, data: { arg: TBody }) => Promise<TData>\n\n/**\n * \u7EDF\u4E00\u5904\u7406 ALPC \u63A5\u53E3\u8FD4\u56DE\u7684\u6570\u636E\u7ED3\u6784\n * \u517C\u5BB9\u4E00\u5C42 data \u548C\u4E24\u5C42 data \u7684\u573A\u666F\uFF1A\n * - \u4E24\u5C42 data: {data: {data: ..., code: 27004}} \u2192 \u5265\u6389\u5916\u5C42\uFF0C\u8FD4\u56DE\u5185\u5C42 {data: ..., code: 27004}\n * - \u4E00\u5C42 data: {data: ..., code: 27004} \u2192 \u76F4\u63A5\u8FD4\u56DE\uFF0C\u4E0D\u505A\u5904\u7406\n *\n * \u5224\u65AD\u4E24\u5C42\u7684\u4F9D\u636E\uFF1AresponseData.data.data \u5B58\u5728\uFF08\u5916\u5C42 data \u5185\u90E8\u8FD8\u6709\u4E00\u5C42 data\uFF09\n */\nconst normalizeResponseData = (responseData: any) => {\n if (!responseData) return responseData\n\n // \u4E24\u5C42\u7ED3\u6784\uFF1AresponseData.data \u662F\u5BF9\u8C61\uFF0C\u4E14\u5176\u5185\u90E8\u8FD8\u6709 data \u5B57\u6BB5\n if (\n responseData.data &&\n typeof responseData.data === 'object' &&\n !Array.isArray(responseData.data) &&\n 'data' in responseData.data\n ) {\n return responseData.data\n }\n\n // \u4E00\u5C42\u7ED3\u6784\uFF0C\u76F4\u63A5\u8FD4\u56DE\n return responseData\n}\n\nconst fetcher = (options: FetcherOptions) => {\n return fetch(getAlpcPath(options.locale, options.apiBaseUrl) + options.url, options.fetchOptions).then(async response => {\n if (response.status < 300) {\n const responseData = await response.json()\n return normalizeResponseData(responseData)\n }\n\n // \u9519\u8BEF\u5904\u7406\n if (response.status === 401) {\n // \u91CD\u65B0\u767B\u5F55\u5C1D\u8BD5\n if (options.onReAuth) {\n if (!reAuthPromise) {\n reAuthPromise = options.onReAuth()\n }\n\n const result = await reAuthPromise\n\n reAuthPromise = undefined\n\n if (result) {\n // \u8DE8\u533A\u91CD\u65B0\u767B\u5F55\u540E\u9700\u8981\u66FF\u6362\u533A\u57DF\u6807\u5FD7\uFF0C\u6240\u4EE5\u4E0D\u80FD\u7528\u6700\u5F00\u59CB\u8BF7\u6C42\u7684\u90A3\u4E2A\u94FE\u63A5\n return fetch(getAlpcPath(options.locale, options.apiBaseUrl) + options.url, options.fetchOptions).then(async response => {\n if (response.status < 300) {\n const responseData = await response.json()\n return normalizeResponseData(responseData)\n }\n\n if (response.status === 401) {\n if (options.onUnAuth) {\n options.onUnAuth()\n }\n return\n }\n })\n } else {\n if (options.onUnAuth) {\n options.onUnAuth()\n }\n return\n }\n }\n }\n })\n}\n\nconst reAuth = async (locale: string, retry: boolean, brand: string, apiBaseUrl?: string) => {\n let reloginResponse = await fetch(`${getAlpcPath(locale, apiBaseUrl)}/cloud/login`, {\n method: 'POST',\n })\n let reloginResponseData = await reloginResponse.json()\n // \u517C\u5BB9\u4E24\u5C42 data \u7ED3\u6784\n let normalizedData = normalizeResponseData(reloginResponseData)\n\n if (reloginResponse!.status < 300 && !retry) {\n if (normalizedData?.code === 27004) {\n // \u8DE8\u533A\u767B\u5F55\u9519\u8BEF\n const alpcEUCookie = Cookies.get('alpcEU')\n\n if (Number(alpcEUCookie) === 1) {\n Cookies.set('alpcEU', '0', {\n expires: 30,\n domain: `.${brand}.com`,\n })\n } else {\n Cookies.set('alpcEU', '1', {\n expires: 30,\n domain: `.${brand}.com`,\n })\n }\n\n // \u91CD\u65B0\u5C1D\u8BD5\u6362\u533A\u767B\u5F55\n reloginResponse = await fetch(`${getAlpcPath(locale, apiBaseUrl)}/cloud/login`, {\n method: 'POST',\n })\n reloginResponseData = await reloginResponse.json()\n normalizedData = normalizeResponseData(reloginResponseData)\n\n if (reloginResponse.status > 300) {\n return false\n }\n }\n }\n if (!normalizedData?.code) {\n // \u91CD\u65B0\u767B\u5F55\u6210\u529F\n return true\n }\n\n return false\n}\n\nexport interface UseMutationConfig<TData> {\n onSuccess?: (response: TData) => any\n onError?: (error: Error) => any\n}\n\nconst useMutation = <TData, TBody>(\n url: string,\n fetcher: Fetcher<TData, TBody>,\n mutationConfig: UseMutationConfig<TData> = {},\n brandRef: React.MutableRefObject<string | undefined>\n) => {\n const innerMutating = useRef<boolean>(false)\n\n const [data, setData] = useState<TData>()\n const [isMutating, setIsMutating] = useState(false)\n\n const urlRef = useRef(url)\n const fetcherRef = useRef(fetcher)\n const configRef = useRef(mutationConfig)\n\n const trigger = useCallback(\n async (fetchData: TBody, opts: UseMutationConfig<TData> = {}) => {\n console.log('[useAlpcMutation] trigger called with:', { url: urlRef.current, fetchData, brand: brandRef.current })\n\n if (innerMutating.current) {\n console.log('[useAlpcMutation] already mutating, skipping')\n return\n }\n\n if (!brandRef.current) {\n console.log('[useAlpcMutation] brand not available, skipping request')\n return\n }\n\n innerMutating.current = true\n setIsMutating(true)\n\n const config = {\n ...configRef.current,\n ...opts,\n }\n\n const { onSuccess, onError } = config || {}\n\n try {\n const fetchResult = await fetcherRef.current(urlRef.current, {\n arg: fetchData,\n })\n setData(fetchResult)\n\n setIsMutating(false)\n innerMutating.current = false\n\n if (onSuccess) {\n onSuccess(fetchResult)\n }\n return fetchResult\n } catch (err: any) {\n setIsMutating(false)\n innerMutating.current = false\n\n if (onError) {\n onError(err)\n }\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n []\n )\n\n return {\n isMutating,\n trigger,\n data,\n }\n}\n\nexport const useAlpcFetch = <TData>(\n options: FetchOptions,\n swrOptions?: UseAlpcFetchOptionsSwrOptions<TData, Error>\n) => {\n const [retry, setRetry] = useState(false)\n const { removeProfile, alpcBrand, apiBaseUrl } = useCreditsContext()\n\n const { enable, ...otherSwrOptions } = swrOptions || {}\n\n const { locale = '', brand: headlessBrand } = useHeadlessContext()\n // \u4F18\u5148\u4F7F\u7528 creditsContext \u4E2D\u7684 alpcBrand\uFF0C\u5982\u679C\u6CA1\u6709\u5219\u4F7F\u7528 headlessConfig \u4E2D\u7684 brand\n const brand = alpcBrand || headlessBrand\n\n const { queryKey = [], body: fetchBody = {}, headers, ...fetchOptions } = options\n const fetchEnable = enable ?? true\n\n const [url, requestBody] = queryKey\n\n const context = useSWR<TData>(\n [url, requestBody],\n !fetchEnable || !brand\n ? null\n : ([requestUrl, data]: [string, Record<string, any>]) =>\n fetcher({\n url: requestUrl,\n locale,\n apiBaseUrl,\n fetchOptions: {\n method: 'POST',\n headers: {\n 'current-language': locale,\n ...headers,\n },\n body: JSON.stringify({\n ...fetchBody,\n ...data,\n }),\n ...fetchOptions,\n },\n onReAuth: async () => {\n const result = await reAuth(locale, retry, brand, apiBaseUrl)\n\n if (result) {\n setRetry(true)\n return true\n }\n\n return false\n },\n onUnAuth() {\n // \u5931\u8D25\u540E\u9000\u51FA\u767B\u5F55\n removeProfile()\n },\n }),\n {\n revalidateOnFocus: false,\n ...otherSwrOptions,\n }\n )\n\n return context\n}\n\nexport const useAlpcMutation = <TData, TBody>(options: MutationOptions, mutationOptions?: UseMutationConfig<TData>) => {\n const [retry, setRetry] = useState(false)\n const { removeProfile, alpcBrand, apiBaseUrl } = useCreditsContext()\n\n const { locale = '', brand: headlessBrand } = useHeadlessContext()\n // \u4F18\u5148\u4F7F\u7528 creditsContext \u4E2D\u7684 alpcBrand\uFF0C\u5982\u679C\u6CA1\u6709\u5219\u4F7F\u7528 headlessConfig \u4E2D\u7684 brand\n const brand = alpcBrand || headlessBrand\n const brandRef = useRef(brand)\n brandRef.current = brand\n\n const { url, initData, headers, ...fetchOptions } = options\n const initDataRef = useRef(initData)\n initDataRef.current = initData\n\n const context = useMutation<TData, TBody>(\n url,\n (requestUrl, data: { arg: TBody }) => {\n // Prevent requests when brand is not available\n if (!brandRef.current) {\n return Promise.resolve(undefined as unknown as TData)\n }\n\n return fetcher({\n url: requestUrl,\n locale,\n apiBaseUrl,\n fetchOptions: {\n method: 'POST',\n headers: {\n 'current-language': locale,\n ...headers,\n },\n ...fetchOptions,\n body: JSON.stringify({\n ...initDataRef.current,\n ...data.arg,\n }),\n },\n onReAuth: async () => {\n const result = await reAuth(locale, retry, brandRef.current!, apiBaseUrl)\n\n if (result) {\n setRetry(true)\n return true\n }\n\n return false\n },\n onUnAuth() {\n // \u5931\u8D25\u540E\u9000\u51FA\u767B\u5F55\n removeProfile()\n },\n })\n },\n mutationOptions,\n brandRef\n )\n\n return context\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAOA,MAAa,YACpB,OAAS,eAAAC,EAAa,UAAAC,EAAQ,YAAAC,MAAgB,QAC9C,OAAOC,MAAuC,MAC9C,OAAS,sBAAAC,MAA0B,gBAEnC,OAAS,eAAAC,MAAmB,WAC5B,OAAS,qBAAAC,MAAyB,cAyBlC,IAAIC,EAYJ,MAAMC,EAAyBC,GACxBA,IAIHA,EAAa,MACb,OAAOA,EAAa,MAAS,UAC7B,CAAC,MAAM,QAAQA,EAAa,IAAI,GAChC,SAAUA,EAAa,KAEhBA,EAAa,KAIfA,GAGHC,EAAWC,GACR,MAAMN,EAAYM,EAAQ,OAAQA,EAAQ,UAAU,EAAIA,EAAQ,IAAKA,EAAQ,YAAY,EAAE,KAAK,MAAMC,GAAY,CACvH,GAAIA,EAAS,OAAS,IAAK,CACzB,MAAMH,EAAe,MAAMG,EAAS,KAAK,EACzC,OAAOJ,EAAsBC,CAAY,CAC3C,CAGA,GAAIG,EAAS,SAAW,KAElBD,EAAQ,SAAU,CACfJ,IACHA,EAAgBI,EAAQ,SAAS,GAGnC,MAAME,EAAS,MAAMN,EAIrB,GAFAA,EAAgB,OAEZM,EAEF,OAAO,M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ACA,aAAc,CACZ,OAAQ,OACR,QAAS,CACP,mBAAoBH,EACpB,GAAGsC,CACL,EACA,GAAGC,EACH,KAAM,KAAK,UAAU,CACnB,GAAGO,EAAY,QACf,GAAGjC,EAAK,GACV,CAAC,CACH,EACA,SAAU,SACO,MAAMd,EAAOC,EAAQC,EAAOU,EAAS,QAAUR,CAAU,GAGtE2B,EAAS,EAAI,EACN,IAGF,GAET,UAAW,CAETC,EAAc,CAChB,CACF,CAAC,EAjCQ,QAAQ,QAAQ,MAA6B,EAmCxDa,EACAjC,CACF,CAGF",
|
|
6
6
|
"names": ["Cookies", "useCallback", "useRef", "useState", "useSWR", "useHeadlessContext", "getAlpcPath", "useCreditsContext", "reAuthPromise", "normalizeResponseData", "responseData", "fetcher", "options", "response", "result", "reAuth", "locale", "retry", "brand", "apiBaseUrl", "reloginResponse", "reloginResponseData", "normalizedData", "alpcEUCookie", "useMutation", "url", "mutationConfig", "brandRef", "innerMutating", "data", "setData", "isMutating", "setIsMutating", "urlRef", "fetcherRef", "configRef", "trigger", "fetchData", "opts", "config", "onSuccess", "onError", "fetchResult", "err", "useAlpcFetch", "swrOptions", "setRetry", "removeProfile", "alpcBrand", "enable", "otherSwrOptions", "headlessBrand", "queryKey", "fetchBody", "headers", "fetchOptions", "fetchEnable", "requestBody", "requestUrl", "useAlpcMutation", "mutationOptions", "initData", "initDataRef"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import u from"swr/mutation";import{useRedeemCoupon as a}from"./useRedeemCoupon";import{useCreditsContext as d}from"../provider";import{useBuyNow as s}from"@anker-in/lib";const w=(m,t)=>{const{trigger:o}=a(),{profile:n}=d(),{trigger:i}=s({},{throwOnError:!0});return u("redeemAndBuy",async(c,{arg:e})=>{const r=await o({user_id:n?.user_id,rule_id:e.redeemId});if(r&&r.data?.coupon_code)i({discountCodes:[r.data.coupon_code],lineItems:[{variant:e.productVariant,quantity:e.quantity||1}]});else throw new Error(`Redeem failed: ${r?.msg}`)},t)};export{w as useRedeemAndBuy};
|
|
2
2
|
//# sourceMappingURL=useRedeemAndBuy.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/components/credits/context/hooks/useRedeemAndBuy.ts"],
|
|
4
|
-
"sourcesContent": ["import useSWRMutation, { SWRMutationConfiguration } from 'swr/mutation'\nimport { useRedeemCoupon } from './useRedeemCoupon'\nimport type { ProductVariant } from '@anker-in/lib'\nimport { useCreditsContext } from '../provider'\nimport { useBuyNow } from '@anker-in/lib'\n\nexport const useRedeemAndBuy = (\n _: any,\n swrOptions?: SWRMutationConfiguration<undefined, Error, string, any> & {\n throwOnError?: boolean\n }\n) => {\n const { trigger } = useRedeemCoupon()\n const { profile } = useCreditsContext()\n\n const { trigger: buyNow } = useBuyNow(\n {},\n {\n throwOnError: true,\n }\n )\n\n return useSWRMutation(\n 'redeemAndBuy',\n async (\n _,\n {\n arg,\n }: {\n arg: {\n productVariant: ProductVariant\n quantity?: number\n redeemId: number\n }\n }\n ) => {\n const res = await trigger({\n user_id: profile?.user_id,\n rule_id: arg.redeemId,\n })\n
|
|
5
|
-
"mappings": "AAAA,OAAOA,MAAkD,eACzD,OAAS,mBAAAC,MAAuB,oBAEhC,OAAS,qBAAAC,MAAyB,cAClC,OAAS,aAAAC,MAAiB,gBAEnB,MAAMC,EAAkB,CAC7BC,EACAC,IAGG,CACH,KAAM,CAAE,QAAAC,CAAQ,EAAIN,EAAgB,EAC9B,CAAE,QAAAO,CAAQ,EAAIN,EAAkB,EAEhC,CAAE,QAASO,CAAO,EAAIN,EAC1B,CAAC,EACD,CACE,aAAc,EAChB,CACF,EAEA,OAAOH,EACL,eACA,MACEK,EACA,CACE,IAAAK,CACF,IAOG,CACH,MAAMC,EAAM,MAAMJ,EAAQ,CACxB,QAASC,GAAS,QAClB,QAASE,EAAI,QACf,CAAC,
|
|
6
|
-
"names": ["useSWRMutation", "useRedeemCoupon", "useCreditsContext", "useBuyNow", "useRedeemAndBuy", "_", "swrOptions", "trigger", "profile", "buyNow", "arg", "res"
|
|
4
|
+
"sourcesContent": ["import useSWRMutation, { SWRMutationConfiguration } from 'swr/mutation'\nimport { useRedeemCoupon } from './useRedeemCoupon'\nimport type { ProductVariant } from '@anker-in/lib'\nimport { useCreditsContext } from '../provider'\nimport { useBuyNow } from '@anker-in/lib'\n\nexport const useRedeemAndBuy = (\n _: any,\n swrOptions?: SWRMutationConfiguration<undefined, Error, string, any> & {\n throwOnError?: boolean\n }\n) => {\n const { trigger } = useRedeemCoupon()\n const { profile } = useCreditsContext()\n\n const { trigger: buyNow } = useBuyNow(\n {},\n {\n throwOnError: true,\n }\n )\n\n return useSWRMutation(\n 'redeemAndBuy',\n async (\n _,\n {\n arg,\n }: {\n arg: {\n productVariant: ProductVariant\n quantity?: number\n redeemId: number\n }\n }\n ) => {\n const res = await trigger({\n user_id: profile?.user_id,\n rule_id: arg.redeemId,\n })\n if (res && res.data?.coupon_code) {\n buyNow({\n discountCodes: [res.data.coupon_code],\n lineItems: [\n {\n variant: arg.productVariant,\n quantity: arg.quantity || 1,\n },\n ],\n })\n } else {\n throw new Error(`Redeem failed: ${res?.msg}`)\n }\n },\n swrOptions\n )\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAOA,MAAkD,eACzD,OAAS,mBAAAC,MAAuB,oBAEhC,OAAS,qBAAAC,MAAyB,cAClC,OAAS,aAAAC,MAAiB,gBAEnB,MAAMC,EAAkB,CAC7BC,EACAC,IAGG,CACH,KAAM,CAAE,QAAAC,CAAQ,EAAIN,EAAgB,EAC9B,CAAE,QAAAO,CAAQ,EAAIN,EAAkB,EAEhC,CAAE,QAASO,CAAO,EAAIN,EAC1B,CAAC,EACD,CACE,aAAc,EAChB,CACF,EAEA,OAAOH,EACL,eACA,MACEK,EACA,CACE,IAAAK,CACF,IAOG,CACH,MAAMC,EAAM,MAAMJ,EAAQ,CACxB,QAASC,GAAS,QAClB,QAASE,EAAI,QACf,CAAC,EACD,GAAIC,GAAOA,EAAI,MAAM,YACnBF,EAAO,CACL,cAAe,CAACE,EAAI,KAAK,WAAW,EACpC,UAAW,CACT,CACE,QAASD,EAAI,eACb,SAAUA,EAAI,UAAY,CAC5B,CACF,CACF,CAAC,MAED,OAAM,IAAI,MAAM,kBAAkBC,GAAK,GAAG,EAAE,CAEhD,EACAL,CACF,CACF",
|
|
6
|
+
"names": ["useSWRMutation", "useRedeemCoupon", "useCreditsContext", "useBuyNow", "useRedeemAndBuy", "_", "swrOptions", "trigger", "profile", "buyNow", "arg", "res"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as s,jsxs as
|
|
1
|
+
import{jsx as s,jsxs as y}from"react/jsx-runtime";import{Text as h}from"@anker-in/headless-ui";import{useCallback as M,useEffect as N,useState as l}from"react";import{useCreditsContext as R}from"../context/provider";import{useRedeemCoupon as I}from"../context/hooks/useRedeemCoupon";import{AlpcErrorCode as n}from"../context/const";import{CreditsModalContainer as F}from"../modal/ModalContainer";import{CouponInit as S}from"./RedeemCouponModal/CouponInit";import{CouponSuccess as _}from"./RedeemCouponModal/CouponSuccess";function v({item:r,copy:o,onError:u,...a}){const[c,p]=l(),[C,t]=l(),[f,d]=l(!1),{profile:m,fetchCreditInfo:x}=R(),{isMutating:b,trigger:g}=I({onSuccess(e){if(!e){t(o.commonError);return}if(e.data?.success)p(e.data.coupon_code),x(m?.user_id);else{let i;e.code===n.CodeLpcShopifyCouponRuleRedeemLimit?(i=o.redeemLimitError,d(!0)):e.code===n.CodeLpcRuleInventoryNotEnough?(i=o.inventoryNotEnough,d(!0)):e.code===n.CodeLpcNotEnoughCredits?(i=o.creditsNotEnough,d(!0),x(m?.user_id)):e.code===n.CodeCrossSiteError&&(i=o.crossSiteError,d(!0)),t(i||o.commonError||""),u&&u(e.code)}},onError(e){t(e.message||o.commonError)}}),E=M(async()=>{t(""),g({user_id:m?.user_id,rule_id:Number(r.alpc?.id)})},[r,m,g]);return N(()=>()=>{d(!1),t(""),p(void 0)},[]),y(F,{...a,isOpen:!!r,className:"w-[540px] md:h-auto",scrollClassName:"mb-[40px] min-l:px-0 md:mb-[24px] px-0",titleClassName:"h-[56px] bg-[#F5F5F7]",children:[c&&!b?s(_,{item:r,copy:o,couponCode:c,disabled:f,onClose:a.onClose}):s(S,{item:r,copy:o,loading:b,disabled:f,onConfirm:E}),C&&s("div",{className:"mx-auto max-w-full bg-white px-[48px] py-[12px] text-center text-[#FF0000] md:px-[16px]",children:s(h,{className:"text-[14px] font-semibold text-[#1F2021]",html:C})})]})}var z=v;export{z as default};
|
|
2
2
|
//# sourceMappingURL=RedeemCouponModal.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/components/credits/creditsRedeemList/RedeemCouponModal.tsx"],
|
|
4
|
-
"sourcesContent": ["import { Text } from '@anker-in/headless-ui'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { ModalContainerProps } from '../modal/ModalContainer'\nimport { useCreditsContext } from '../context/provider'\nimport { useRedeemCoupon } from '../context/hooks/useRedeemCoupon'\nimport { AlpcErrorCode } from '../context/const'\nimport { CreditsModalContainer } from '../modal/ModalContainer'\nimport type { RedeemableItem as RedeemableItemType, RedeemModalCommon } from '../type'\nimport { CouponInit } from './RedeemCouponModal/CouponInit'\nimport { CouponSuccess } from './RedeemCouponModal/CouponSuccess'\n\nfunction RedeemCouponModal({\n item,\n copy,\n onError,\n ...props\n}: Omit<ModalContainerProps, 'isOpen'> & {\n item: RedeemableItemType\n copy: RedeemModalCommon\n onError: (code: number) => void\n}) {\n const [couponCode, setCouponCode] = useState<string>()\n const [errorInfo, setErrorInfo] = useState<string>()\n const [disabled, setDisabled] = useState(false)\n\n const { profile, fetchCreditInfo } = useCreditsContext()\n\n const { isMutating: loading, trigger } = useRedeemCoupon({\n onSuccess(responseData) {\n if (!responseData) {\n setErrorInfo(copy.commonError)\n return\n }\n\n
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["jsx", "jsxs", "Text", "useCallback", "useEffect", "useState", "useCreditsContext", "useRedeemCoupon", "AlpcErrorCode", "CreditsModalContainer", "CouponInit", "CouponSuccess", "RedeemCouponModal", "item", "copy", "onError", "props", "couponCode", "setCouponCode", "errorInfo", "setErrorInfo", "disabled", "setDisabled", "profile", "fetchCreditInfo", "loading", "trigger", "responseData", "
|
|
4
|
+
"sourcesContent": ["import { Text } from '@anker-in/headless-ui'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { ModalContainerProps } from '../modal/ModalContainer'\nimport { useCreditsContext } from '../context/provider'\nimport { useRedeemCoupon } from '../context/hooks/useRedeemCoupon'\nimport { AlpcErrorCode } from '../context/const'\nimport { CreditsModalContainer } from '../modal/ModalContainer'\nimport type { RedeemableItem as RedeemableItemType, RedeemModalCommon } from '../type'\nimport { CouponInit } from './RedeemCouponModal/CouponInit'\nimport { CouponSuccess } from './RedeemCouponModal/CouponSuccess'\n\nfunction RedeemCouponModal({\n item,\n copy,\n onError,\n ...props\n}: Omit<ModalContainerProps, 'isOpen'> & {\n item: RedeemableItemType\n copy: RedeemModalCommon\n onError: (code: number) => void\n}) {\n const [couponCode, setCouponCode] = useState<string>()\n const [errorInfo, setErrorInfo] = useState<string>()\n const [disabled, setDisabled] = useState(false)\n\n const { profile, fetchCreditInfo } = useCreditsContext()\n\n const { isMutating: loading, trigger } = useRedeemCoupon({\n onSuccess(responseData) {\n if (!responseData) {\n setErrorInfo(copy.commonError)\n return\n }\n\n if (responseData.data?.success) {\n setCouponCode(responseData.data.coupon_code)\n fetchCreditInfo(profile?.user_id)\n } else {\n let errorMsg\n if (responseData.code === AlpcErrorCode.CodeLpcShopifyCouponRuleRedeemLimit) {\n errorMsg = copy.redeemLimitError\n setDisabled(true)\n } else if (responseData.code === AlpcErrorCode.CodeLpcRuleInventoryNotEnough) {\n errorMsg = copy.inventoryNotEnough\n setDisabled(true)\n } else if (responseData.code === AlpcErrorCode.CodeLpcNotEnoughCredits) {\n errorMsg = copy.creditsNotEnough\n setDisabled(true)\n fetchCreditInfo(profile?.user_id)\n } else if (responseData.code === AlpcErrorCode.CodeCrossSiteError) {\n errorMsg = copy.crossSiteError\n setDisabled(true)\n }\n\n setErrorInfo(errorMsg || copy.commonError || '')\n onError && onError(responseData.code)\n }\n },\n onError(error) {\n setErrorInfo(error.message || copy.commonError)\n },\n })\n\n const handleConfirm = useCallback(async () => {\n setErrorInfo('')\n trigger({\n user_id: profile?.user_id,\n rule_id: Number(item.alpc?.id),\n })\n }, [item, profile, trigger])\n\n useEffect(() => {\n return () => {\n setDisabled(false)\n setErrorInfo('')\n setCouponCode(undefined)\n }\n }, [])\n\n return (\n <CreditsModalContainer\n {...props}\n isOpen={!!item}\n className=\"w-[540px] md:h-auto\"\n scrollClassName=\"mb-[40px] min-l:px-0 md:mb-[24px] px-0\"\n titleClassName=\"h-[56px] bg-[#F5F5F7]\"\n >\n {couponCode && !loading ? (\n <CouponSuccess item={item} copy={copy} couponCode={couponCode} disabled={disabled} onClose={props.onClose} />\n ) : (\n <CouponInit item={item} copy={copy} loading={loading} disabled={disabled} onConfirm={handleConfirm} />\n )}\n {errorInfo && (\n <div className=\"mx-auto max-w-full bg-white px-[48px] py-[12px] text-center text-[#FF0000] md:px-[16px]\">\n <Text className=\"text-[14px] font-semibold text-[#1F2021]\" html={errorInfo} />\n </div>\n )}\n </CreditsModalContainer>\n )\n}\n\nexport default RedeemCouponModal\n"],
|
|
5
|
+
"mappings": "AAgFI,OAQI,OAAAA,EARJ,QAAAC,MAAA,oBAhFJ,OAAS,QAAAC,MAAY,wBACrB,OAAS,eAAAC,EAAa,aAAAC,EAAW,YAAAC,MAAgB,QAEjD,OAAS,qBAAAC,MAAyB,sBAClC,OAAS,mBAAAC,MAAuB,mCAChC,OAAS,iBAAAC,MAAqB,mBAC9B,OAAS,yBAAAC,MAA6B,0BAEtC,OA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U,IACD,IAAM,CACXkB,EAAY,EAAK,EACjBF,EAAa,EAAE,EACfF,EAAc,MAAS,CACzB,EACC,CAAC,CAAC,EAGHjB,EAACQ,EAAA,CACE,GAAGO,EACJ,OAAQ,CAAC,CAACH,EACV,UAAU,sBACV,gBAAgB,yCAChB,eAAe,wBAEd,UAAAI,GAAc,CAACQ,EACdzB,EAACW,EAAA,CAAc,KAAME,EAAM,KAAMC,EAAM,WAAYG,EAAY,SAAUI,EAAU,QAASL,EAAM,QAAS,EAE3GhB,EAACU,EAAA,CAAW,KAAMG,EAAM,KAAMC,EAAM,QAASW,EAAS,SAAUJ,EAAU,UAAWS,EAAe,EAErGX,GACCnB,EAAC,OAAI,UAAU,0FACb,SAAAA,EAACE,EAAA,CAAK,UAAU,2CAA2C,KAAMiB,EAAW,EAC9E,GAEJ,CAEJ,CAEA,IAAOY,EAAQnB",
|
|
6
|
+
"names": ["jsx", "jsxs", "Text", "useCallback", "useEffect", "useState", "useCreditsContext", "useRedeemCoupon", "AlpcErrorCode", "CreditsModalContainer", "CouponInit", "CouponSuccess", "RedeemCouponModal", "item", "copy", "onError", "props", "couponCode", "setCouponCode", "errorInfo", "setErrorInfo", "disabled", "setDisabled", "profile", "fetchCreditInfo", "loading", "trigger", "responseData", "errorMsg", "error", "handleConfirm", "RedeemCouponModal_default"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as a,jsxs as B}from"react/jsx-runtime";import{Text as S}from"@anker-in/headless-ui";import{useCallback as y,useEffect as P,useState as f}from"react";import{useCreditsContext as L}from"../context/provider";import{useRedeemGoGift as F}from"../context/hooks/useRedeemGoGift";import{useRedeemProduct as T}from"../context/hooks/useRedeemProduct";import{AlpcErrorCode as s,ConsumeType as N}from"../context/const";import{CreditsModalContainer as A}from"../modal/ModalContainer";import{gaTrack as O}from"@anker-in/lib";import{VirtualProductInit as k}from"./RedeemVirtualProductModal/VirtualProductInit";import{VirtualProductSuccess as w}from"./RedeemVirtualProductModal/VirtualProductSuccess";function V({item:t,copy:r,onError:c,...p}){const[h,m]=f(),[g,n]=f(),[C,d]=f(!1),{profile:o,fetchCreditInfo:l,gtm:b}=L(),u=t.config?.type===N.GoGift,x=t.config?.type===N.GiftCard,{isMutating:R,trigger:E}=F({onSuccess(e){if(!e){n(r?.commonError);return}const i=e.data;i?.id?(m(i.id),l(o?.user_id)):G(e.code)},onError(e){n(e.message||r?.commonError)}}),{isMutating:M,trigger:v}=T({onSuccess(e){if(!e){n(r?.commonError);return}e?.code===0?(m("success"),l(o?.user_id)):G(e.code)},onError(){n(r?.commonError)}}),_=u?R:M,G=e=>{let i;e===s.CodeLpcShopifyCouponRuleRedeemLimit?(i=r?.redeemLimitError,d(!0)):e===s.CodeLpcRuleInventoryNotEnough?(i=r?.inventoryNotEnough,d(!0)):e===s.CodeLpcNotEnoughCredits?(i=r?.creditsNotEnough,d(!0),l(o?.user_id)):e===s.CodeCrossSiteError&&(i=r?.crossSiteError,d(!0)),n(i||r?.commonError||""),c&&c(e)},I=y(async()=>{if(n(""),O({event:"ga4Event",event_name:"lp_button",member_active_status:o?.activated?"active":"not active",event_parameters:{page_group:b.pageGroup,position:"redeem virtual product modal",button_name:r.confirmButton,info:t.alpc?.id}}),u)E({user_id:o?.user_id,rule_id:Number(t.alpc?.id)});else if(x){const e={email:o?.email||"",first_name:o?.firstName||"Anker",last_name:o?.lastName||"Direct",address1:"Default Address",city:"Default City",province:"Default Province",country:"US",zip:"00000"};v({address:btoa(JSON.stringify(e)),rule_id:Number(t.alpc?.id)})}},[t,o,E,v,u,x,r.confirmButton,b.pageGroup]);return P(()=>()=>{d(!1),n(""),m(void 0)},[]),B(A,{...p,isOpen:!!t,className:"w-[540px] md:h-auto",scrollClassName:"mb-[40px] min-l:px-0 md:mb-[24px] px-0",titleClassName:"h-[56px] bg-[#F5F5F7]",children:[h&&!_?a(w,{item:t,copy:r,disabled:C,onClose:p.onClose}):a(k,{item:t,copy:r,loading:_,disabled:C,onConfirm:I}),g&&a("div",{className:"mx-auto max-w-full bg-white px-[48px] py-[12px] text-center text-[#FF0000] md:px-[16px]",children:a(S,{className:"text-[14px] font-semibold text-[#1F2021]",html:g})})]})}var Y=V;export{Y as default};
|
|
2
2
|
//# sourceMappingURL=RedeemVirtualProductModal.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/components/credits/creditsRedeemList/RedeemVirtualProductModal.tsx"],
|
|
4
|
-
"sourcesContent": ["import { Text } from '@anker-in/headless-ui'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { ModalContainerProps } from '../modal/ModalContainer'\nimport { useCreditsContext } from '../context/provider'\nimport { useRedeemGoGift } from '../context/hooks/useRedeemGoGift'\nimport { useRedeemProduct } from '../context/hooks/useRedeemProduct'\nimport { AlpcErrorCode, ConsumeType } from '../context/const'\nimport { CreditsModalContainer } from '../modal/ModalContainer'\nimport type { RedeemableItem as RedeemableItemType, RedeemModalCommon } from '../type'\nimport { gaTrack } from '@anker-in/lib'\nimport { VirtualProductInit } from './RedeemVirtualProductModal/VirtualProductInit'\nimport { VirtualProductSuccess } from './RedeemVirtualProductModal/VirtualProductSuccess'\n\nfunction RedeemVirtualProductModal({\n item,\n copy,\n onError,\n ...props\n}: Omit<ModalContainerProps, 'isOpen'> & {\n item: RedeemableItemType\n copy: RedeemModalCommon\n onError: (code: number) => void\n}) {\n const [giftCardId, setGiftCardId] = useState<string>()\n const [errorInfo, setErrorInfo] = useState<string>()\n\n const [disabled, setDisabled] = useState(false)\n\n const { profile, fetchCreditInfo, gtm } = useCreditsContext()\n\n // \u5224\u65AD\u662F GoGift \u8FD8\u662F GiftCard \u7C7B\u578B\n const isGoGift = item.config?.type === ConsumeType.GoGift\n const isGiftCard = item.config?.type === ConsumeType.GiftCard\n\n // GoGift \u4F7F\u7528\u4E13\u7528\u63A5\u53E3\n const { isMutating: goGiftLoading, trigger: triggerGoGift } = useRedeemGoGift({\n onSuccess(responseData) {\n if (!responseData) {\n setErrorInfo(copy?.commonError)\n return\n }\n\n const data = responseData
|
|
5
|
-
"mappings": "AAmJI,OAQI,OAAAA,EARJ,QAAAC,MAAA,oBAnJJ,OAAS,QAAAC,MAAY,wBACrB,OAAS,eAAAC,EAAa,aAAAC,EAAW,YAAAC,MAAgB,QAEjD,OAAS,qBAAAC,MAAyB,sBAClC,OAAS,mBAAAC,MAAuB,mCAChC,OAAS,oBAAAC,MAAwB,oCACjC,OAAS,iBAAAC,EAAe,eAAAC,MAAmB,mBAC3C,OAAS,yBAAAC,MAA6B,0BAEtC,OAAS,WAAAC,MAAe,gBACxB,OAAS,sBAAAC,MAA0B,iDACnC,OAAS,yBAAAC,MAA6B,oDAEtC,SAASC,EAA0B,CACjC,KAAAC,EACA,KAAAC,EACA,QAAAC,EACA,GAAGC,CACL,EAIG,CACD,KAAM,CAACC,EAAYC,CAAa,EAAIhB,EAAiB,EAC/C,CAACiB,EAAWC,CAAY,EAAIlB,EAAiB,EAE7C,CAACmB,EAAUC,CAAW,EAAIpB,EAAS,EAAK,EAExC,CAAE,QAAAqB,EAAS,gBAAAC,EAAiB,IAAAC,CAAI,EAAItB,EAAkB,EAGtDuB,EAAWb,EAAK,QAAQ,OAASN,EAAY,OAC7CoB,EAAad,EAAK,QAAQ,OAASN,EAAY,SAG/C,CAAE,WAAYqB,EAAe,QAASC,CAAc,EAAIzB,EAAgB,CAC5E,UAAU0B,EAAc,CACtB,GAAI,CAACA,EAAc,CACjBV,EAAaN,GAAM,WAAW,EAC9B,MACF,CAEA,MAAMiB,EAAOD,
|
|
4
|
+
"sourcesContent": ["import { Text } from '@anker-in/headless-ui'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { ModalContainerProps } from '../modal/ModalContainer'\nimport { useCreditsContext } from '../context/provider'\nimport { useRedeemGoGift } from '../context/hooks/useRedeemGoGift'\nimport { useRedeemProduct } from '../context/hooks/useRedeemProduct'\nimport { AlpcErrorCode, ConsumeType } from '../context/const'\nimport { CreditsModalContainer } from '../modal/ModalContainer'\nimport type { RedeemableItem as RedeemableItemType, RedeemModalCommon } from '../type'\nimport { gaTrack } from '@anker-in/lib'\nimport { VirtualProductInit } from './RedeemVirtualProductModal/VirtualProductInit'\nimport { VirtualProductSuccess } from './RedeemVirtualProductModal/VirtualProductSuccess'\n\nfunction RedeemVirtualProductModal({\n item,\n copy,\n onError,\n ...props\n}: Omit<ModalContainerProps, 'isOpen'> & {\n item: RedeemableItemType\n copy: RedeemModalCommon\n onError: (code: number) => void\n}) {\n const [giftCardId, setGiftCardId] = useState<string>()\n const [errorInfo, setErrorInfo] = useState<string>()\n\n const [disabled, setDisabled] = useState(false)\n\n const { profile, fetchCreditInfo, gtm } = useCreditsContext()\n\n // \u5224\u65AD\u662F GoGift \u8FD8\u662F GiftCard \u7C7B\u578B\n const isGoGift = item.config?.type === ConsumeType.GoGift\n const isGiftCard = item.config?.type === ConsumeType.GiftCard\n\n // GoGift \u4F7F\u7528\u4E13\u7528\u63A5\u53E3\n const { isMutating: goGiftLoading, trigger: triggerGoGift } = useRedeemGoGift({\n onSuccess(responseData) {\n if (!responseData) {\n setErrorInfo(copy?.commonError)\n return\n }\n\n const data = responseData.data\n if (data?.id) {\n setGiftCardId(data.id)\n fetchCreditInfo(profile?.user_id)\n } else {\n handleRedeemError(responseData.code)\n }\n },\n onError(error) {\n setErrorInfo(error.message || copy?.commonError)\n },\n })\n\n // GiftCard \u4F7F\u7528 Product \u63A5\u53E3\uFF0C\u4F46\u4E0D\u9700\u8981\u5730\u5740\n const { isMutating: productLoading, trigger: triggerProduct } = useRedeemProduct({\n onSuccess(responseData) {\n if (!responseData) {\n setErrorInfo(copy?.commonError)\n return\n }\n\n if (responseData?.code === 0) {\n setGiftCardId('success')\n fetchCreditInfo(profile?.user_id)\n } else {\n handleRedeemError(responseData.code)\n }\n },\n onError() {\n setErrorInfo(copy?.commonError)\n },\n })\n\n const loading = isGoGift ? goGiftLoading : productLoading\n\n const handleRedeemError = (code: number) => {\n let errorMsg: string | undefined\n if (code === AlpcErrorCode.CodeLpcShopifyCouponRuleRedeemLimit) {\n errorMsg = copy?.redeemLimitError\n setDisabled(true)\n } else if (code === AlpcErrorCode.CodeLpcRuleInventoryNotEnough) {\n errorMsg = copy?.inventoryNotEnough\n setDisabled(true)\n } else if (code === AlpcErrorCode.CodeLpcNotEnoughCredits) {\n errorMsg = copy?.creditsNotEnough\n setDisabled(true)\n fetchCreditInfo(profile?.user_id)\n } else if (code === AlpcErrorCode.CodeCrossSiteError) {\n errorMsg = copy?.crossSiteError\n setDisabled(true)\n }\n\n setErrorInfo(errorMsg || copy?.commonError || '')\n onError && onError(code)\n }\n\n const handleConfirm = useCallback(async () => {\n setErrorInfo('')\n\n gaTrack({\n event: 'ga4Event',\n event_name: 'lp_button',\n member_active_status: profile?.activated ? 'active' : 'not active',\n event_parameters: {\n page_group: gtm.pageGroup,\n position: 'redeem virtual product modal',\n button_name: copy.confirmButton,\n info: item.alpc?.id,\n },\n })\n\n if (isGoGift) {\n // GoGift \u7C7B\u578B\u4F7F\u7528\u4E13\u7528\u63A5\u53E3\n triggerGoGift({\n user_id: profile?.user_id,\n rule_id: Number(item.alpc?.id),\n })\n } else if (isGiftCard) {\n // GiftCard \u7C7B\u578B\u4F7F\u7528 Product \u63A5\u53E3\uFF0C\u4F20\u9012\u9ED8\u8BA4\u5730\u5740\n const defaultAddress = {\n email: profile?.email || '',\n first_name: profile?.firstName || 'Anker',\n last_name: profile?.lastName || 'Direct',\n address1: 'Default Address',\n city: 'Default City',\n province: 'Default Province',\n country: 'US',\n zip: '00000',\n }\n triggerProduct({\n address: btoa(JSON.stringify(defaultAddress)),\n rule_id: Number(item.alpc?.id),\n })\n }\n }, [item, profile, triggerGoGift, triggerProduct, isGoGift, isGiftCard, copy.confirmButton, gtm.pageGroup])\n\n useEffect(() => {\n return () => {\n setDisabled(false)\n setErrorInfo('')\n setGiftCardId(undefined)\n }\n }, [])\n\n return (\n <CreditsModalContainer\n {...props}\n isOpen={!!item}\n className=\"w-[540px] md:h-auto\"\n scrollClassName=\"mb-[40px] min-l:px-0 md:mb-[24px] px-0\"\n titleClassName=\"h-[56px] bg-[#F5F5F7]\"\n >\n {giftCardId && !loading ? (\n <VirtualProductSuccess item={item} copy={copy} disabled={disabled} onClose={props.onClose} />\n ) : (\n <VirtualProductInit item={item} copy={copy} loading={loading} disabled={disabled} onConfirm={handleConfirm} />\n )}\n {errorInfo && (\n <div className=\"mx-auto max-w-full bg-white px-[48px] py-[12px] text-center text-[#FF0000] md:px-[16px]\">\n <Text className=\"text-[14px] font-semibold text-[#1F2021]\" html={errorInfo} />\n </div>\n )}\n </CreditsModalContainer>\n )\n}\n\nexport default RedeemVirtualProductModal\n"],
|
|
5
|
+
"mappings": "AAmJI,OAQI,OAAAA,EARJ,QAAAC,MAAA,oBAnJJ,OAAS,QAAAC,MAAY,wBACrB,OAAS,eAAAC,EAAa,aAAAC,EAAW,YAAAC,MAAgB,QAEjD,OAAS,qBAAAC,MAAyB,sBAClC,OAAS,mBAAAC,MAAuB,mCAChC,OAAS,oBAAAC,MAAwB,oCACjC,OAAS,iBAAAC,EAAe,eAAAC,MAAmB,mBAC3C,OAAS,yBAAAC,MAA6B,0BAEtC,OAAS,WAAAC,MAAe,gBACxB,OAAS,sBAAAC,MAA0B,iDACnC,OAAS,yBAAAC,MAA6B,oDAEtC,SAASC,EAA0B,CACjC,KAAAC,EACA,KAAAC,EACA,QAAAC,EACA,GAAGC,CACL,EAIG,CACD,KAAM,CAACC,EAAYC,CAAa,EAAIhB,EAAiB,EAC/C,CAACiB,EAAWC,CAAY,EAAIlB,EAAiB,EAE7C,CAACmB,EAAUC,CAAW,EAAIpB,EAAS,EAAK,EAExC,CAAE,QAAAqB,EAAS,gBAAAC,EAAiB,IAAAC,CAAI,EAAItB,EAAkB,EAGtDuB,EAAWb,EAAK,QAAQ,OAASN,EAAY,OAC7CoB,EAAad,EAAK,QAA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,CAChB,WAAYE,EAAI,UAChB,SAAU,+BACV,YAAaX,EAAK,cAClB,KAAMD,EAAK,MAAM,EACnB,CACF,CAAC,EAEGa,EAEFG,EAAc,CACZ,QAASN,GAAS,QAClB,QAAS,OAAOV,EAAK,MAAM,EAAE,CAC/B,CAAC,UACQc,EAAY,CAErB,MAAMa,EAAiB,CACrB,MAAOjB,GAAS,OAAS,GACzB,WAAYA,GAAS,WAAa,QAClC,UAAWA,GAAS,UAAY,SAChC,SAAU,kBACV,KAAM,eACN,SAAU,mBACV,QAAS,KACT,IAAK,OACP,EACAY,EAAe,CACb,QAAS,KAAK,KAAK,UAAUK,CAAc,CAAC,EAC5C,QAAS,OAAO3B,EAAK,MAAM,EAAE,CAC/B,CAAC,CACH,CACF,EAAG,CAACA,EAAMU,EAASM,EAAeM,EAAgBT,EAAUC,EAAYb,EAAK,cAAeW,EAAI,SAAS,CAAC,EAE1G,OAAAxB,EAAU,IACD,IAAM,CACXqB,EAAY,EAAK,EACjBF,EAAa,EAAE,EACfF,EAAc,MAAS,CACzB,EACC,CAAC,CAAC,EAGHpB,EAACU,EAAA,CACE,GAAGQ,EACJ,OAAQ,CAAC,CAACH,EACV,UAAU,sBACV,gBAAgB,yCAChB,eAAe,wBAEd,UAAAI,GAAc,CAACmB,EACdvC,EAACc,EAAA,CAAsB,KAAME,EAAM,KAAMC,EAAM,SAAUO,EAAU,QAASL,EAAM,QAAS,EAE3FnB,EAACa,EAAA,CAAmB,KAAMG,EAAM,KAAMC,EAAM,QAASsB,EAAS,SAAUf,EAAU,UAAWkB,EAAe,EAE7GpB,GACCtB,EAAC,OAAI,UAAU,0FACb,SAAAA,EAACE,EAAA,CAAK,UAAU,2CAA2C,KAAMoB,EAAW,EAC9E,GAEJ,CAEJ,CAEA,IAAOsB,EAAQ7B",
|
|
6
6
|
"names": ["jsx", "jsxs", "Text", "useCallback", "useEffect", "useState", "useCreditsContext", "useRedeemGoGift", "useRedeemProduct", "AlpcErrorCode", "ConsumeType", "CreditsModalContainer", "gaTrack", "VirtualProductInit", "VirtualProductSuccess", "RedeemVirtualProductModal", "item", "copy", "onError", "props", "giftCardId", "setGiftCardId", "errorInfo", "setErrorInfo", "disabled", "setDisabled", "profile", "fetchCreditInfo", "gtm", "isGoGift", "isGiftCard", "goGiftLoading", "triggerGoGift", "responseData", "data", "handleRedeemError", "error", "productLoading", "triggerProduct", "loading", "code", "errorMsg", "handleConfirm", "defaultAddress", "RedeemVirtualProductModal_default"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -36,18 +36,25 @@ type Fetcher<TData, TBody> = (url: string, data: { arg: TBody }) => Promise<TDat
|
|
|
36
36
|
/**
|
|
37
37
|
* 统一处理 ALPC 接口返回的数据结构
|
|
38
38
|
* 兼容一层 data 和两层 data 的场景:
|
|
39
|
-
* - 两层 data: {data: {data: ..., code: 27004}}
|
|
40
|
-
* - 一层 data: {data: ..., code: 27004}
|
|
39
|
+
* - 两层 data: {data: {data: ..., code: 27004}} → 剥掉外层,返回内层 {data: ..., code: 27004}
|
|
40
|
+
* - 一层 data: {data: ..., code: 27004} → 直接返回,不做处理
|
|
41
|
+
*
|
|
42
|
+
* 判断两层的依据:responseData.data.data 存在(外层 data 内部还有一层 data)
|
|
41
43
|
*/
|
|
42
44
|
const normalizeResponseData = (responseData: any) => {
|
|
43
45
|
if (!responseData) return responseData
|
|
44
46
|
|
|
45
|
-
//
|
|
46
|
-
if (
|
|
47
|
+
// 两层结构:responseData.data 是对象,且其内部还有 data 字段
|
|
48
|
+
if (
|
|
49
|
+
responseData.data &&
|
|
50
|
+
typeof responseData.data === 'object' &&
|
|
51
|
+
!Array.isArray(responseData.data) &&
|
|
52
|
+
'data' in responseData.data
|
|
53
|
+
) {
|
|
47
54
|
return responseData.data
|
|
48
55
|
}
|
|
49
56
|
|
|
50
|
-
//
|
|
57
|
+
// 一层结构,直接返回
|
|
51
58
|
return responseData
|
|
52
59
|
}
|
|
53
60
|
|
|
@@ -38,10 +38,9 @@ export const useRedeemAndBuy = (
|
|
|
38
38
|
user_id: profile?.user_id,
|
|
39
39
|
rule_id: arg.redeemId,
|
|
40
40
|
})
|
|
41
|
-
|
|
42
|
-
if (res && data?.coupon_code) {
|
|
41
|
+
if (res && res.data?.coupon_code) {
|
|
43
42
|
buyNow({
|
|
44
|
-
discountCodes: [data.coupon_code],
|
|
43
|
+
discountCodes: [res.data.coupon_code],
|
|
45
44
|
lineItems: [
|
|
46
45
|
{
|
|
47
46
|
variant: arg.productVariant,
|
|
@@ -32,9 +32,8 @@ function RedeemCouponModal({
|
|
|
32
32
|
return
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
setCouponCode(data.coupon_code)
|
|
35
|
+
if (responseData.data?.success) {
|
|
36
|
+
setCouponCode(responseData.data.coupon_code)
|
|
38
37
|
fetchCreditInfo(profile?.user_id)
|
|
39
38
|
} else {
|
|
40
39
|
let errorMsg
|