Browse Source
feat: implement match profile overlay, add Amiri fonts, and integrate discount validation logic.
master
feat: implement match profile overlay, add Amiri fonts, and integrate discount validation logic.
master
54 changed files with 2607 additions and 756 deletions
-
BINpublic/fonts/Amiri/Amiri-Bold.ttf
-
BINpublic/fonts/Amiri/Amiri-BoldItalic.ttf
-
BINpublic/fonts/Amiri/Amiri-Italic.ttf
-
BINpublic/fonts/Amiri/Amiri-Regular.ttf
-
93public/fonts/Amiri/OFL.txt
-
29src/app/candidate-contact/candidate-contact-client.tsx
-
5src/app/finding-match/finding-match-client.tsx
-
30src/app/layout.tsx
-
6src/app/marriage-advisors/page.tsx
-
456src/app/new-match/new-match-client.tsx
-
40src/app/new-match/profile/page.tsx
-
18src/app/request-accepted/request-accepted-client.tsx
-
23src/app/request-sent/request-sent-client.tsx
-
25src/components/Componentes/data-error-state.tsx
-
218src/components/Componentes/discount-widget.tsx
-
27src/components/Componentes/information-sheet.tsx
-
140src/components/Componentes/match-profile-overlay.test.tsx
-
77src/components/Componentes/match-profile-overlay.tsx
-
185src/components/Componentes/navigation-button.tsx
-
59src/components/Componentes/page-header.tsx
-
4src/components/Componentes/sticky-header.tsx
-
108src/components/Componentes/subscription-required-sheet.tsx
-
17src/components/Componentes/support-access.ts
-
648src/components/Componentes/token-switcher.tsx
-
27src/hooks/marriage/use-habcoin-inventory.ts
-
28src/hooks/marriage/use-habcoin-payment.ts
-
22src/hooks/marriage/use-profile-main.ts
-
77src/hooks/marriage/use-validate-discount.ts
-
26src/lib/webview-actions.test.ts
-
14src/lib/webview-actions.ts
-
18src/translations/locales/ar.json
-
18src/translations/locales/az.json
-
18src/translations/locales/bn.json
-
18src/translations/locales/da.json
-
18src/translations/locales/de.json
-
17src/translations/locales/en.json
-
18src/translations/locales/es.json
-
17src/translations/locales/fa.json
-
18src/translations/locales/fr.json
-
18src/translations/locales/gu.json
-
18src/translations/locales/ha.json
-
21src/translations/locales/he.json
-
18src/translations/locales/hi.json
-
21src/translations/locales/id.json
-
21src/translations/locales/ks.json
-
21src/translations/locales/pt.json
-
17src/translations/locales/ru.json
-
21src/translations/locales/sw.json
-
21src/translations/locales/tg.json
-
21src/translations/locales/tr.json
-
21src/translations/locales/ul.json
-
21src/translations/locales/ur.json
-
21src/translations/locales/uz.json
-
18src/translations/locales/zh.json
@ -0,0 +1,93 @@ |
|||
Copyright 2010-2022 The Amiri Project Authors (https://github.com/aliftype/amiri). |
|||
|
|||
This Font Software is licensed under the SIL Open Font License, Version 1.1. |
|||
This license is copied below, and is also available with a FAQ at: |
|||
https://openfontlicense.org |
|||
|
|||
|
|||
----------------------------------------------------------- |
|||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 |
|||
----------------------------------------------------------- |
|||
|
|||
PREAMBLE |
|||
The goals of the Open Font License (OFL) are to stimulate worldwide |
|||
development of collaborative font projects, to support the font creation |
|||
efforts of academic and linguistic communities, and to provide a free and |
|||
open framework in which fonts may be shared and improved in partnership |
|||
with others. |
|||
|
|||
The OFL allows the licensed fonts to be used, studied, modified and |
|||
redistributed freely as long as they are not sold by themselves. The |
|||
fonts, including any derivative works, can be bundled, embedded, |
|||
redistributed and/or sold with any software provided that any reserved |
|||
names are not used by derivative works. The fonts and derivatives, |
|||
however, cannot be released under any other type of license. The |
|||
requirement for fonts to remain under this license does not apply |
|||
to any document created using the fonts or their derivatives. |
|||
|
|||
DEFINITIONS |
|||
"Font Software" refers to the set of files released by the Copyright |
|||
Holder(s) under this license and clearly marked as such. This may |
|||
include source files, build scripts and documentation. |
|||
|
|||
"Reserved Font Name" refers to any names specified as such after the |
|||
copyright statement(s). |
|||
|
|||
"Original Version" refers to the collection of Font Software components as |
|||
distributed by the Copyright Holder(s). |
|||
|
|||
"Modified Version" refers to any derivative made by adding to, deleting, |
|||
or substituting -- in part or in whole -- any of the components of the |
|||
Original Version, by changing formats or by porting the Font Software to a |
|||
new environment. |
|||
|
|||
"Author" refers to any designer, engineer, programmer, technical |
|||
writer or other person who contributed to the Font Software. |
|||
|
|||
PERMISSION & CONDITIONS |
|||
Permission is hereby granted, free of charge, to any person obtaining |
|||
a copy of the Font Software, to use, study, copy, merge, embed, modify, |
|||
redistribute, and sell modified and unmodified copies of the Font |
|||
Software, subject to the following conditions: |
|||
|
|||
1) Neither the Font Software nor any of its individual components, |
|||
in Original or Modified Versions, may be sold by itself. |
|||
|
|||
2) Original or Modified Versions of the Font Software may be bundled, |
|||
redistributed and/or sold with any software, provided that each copy |
|||
contains the above copyright notice and this license. These can be |
|||
included either as stand-alone text files, human-readable headers or |
|||
in the appropriate machine-readable metadata fields within text or |
|||
binary files as long as those fields can be easily viewed by the user. |
|||
|
|||
3) No Modified Version of the Font Software may use the Reserved Font |
|||
Name(s) unless explicit written permission is granted by the corresponding |
|||
Copyright Holder. This restriction only applies to the primary font name as |
|||
presented to the users. |
|||
|
|||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font |
|||
Software shall not be used to promote, endorse or advertise any |
|||
Modified Version, except to acknowledge the contribution(s) of the |
|||
Copyright Holder(s) and the Author(s) or with their explicit written |
|||
permission. |
|||
|
|||
5) The Font Software, modified or unmodified, in part or in whole, |
|||
must be distributed entirely under this license, and must not be |
|||
distributed under any other license. The requirement for fonts to |
|||
remain under this license does not apply to any document created |
|||
using the Font Software. |
|||
|
|||
TERMINATION |
|||
This license becomes null and void if any of the above conditions are |
|||
not met. |
|||
|
|||
DISCLAIMER |
|||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
|||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF |
|||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT |
|||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE |
|||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, |
|||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL |
|||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
|||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM |
|||
OTHER DEALINGS IN THE FONT SOFTWARE. |
|||
@ -0,0 +1,218 @@ |
|||
"use client"; |
|||
|
|||
import { useState } from "react"; |
|||
import { useI18n } from "@/translations/provider"; |
|||
import { |
|||
type CheckDiscountResult, |
|||
useValidateDiscountMutation, |
|||
} from "@/hooks/marriage/use-validate-discount"; |
|||
|
|||
export interface DiscountWidgetProps { |
|||
objectId: number | string; |
|||
service?: string; |
|||
onDiscountApplied?: (result: CheckDiscountResult) => void; |
|||
onDiscountCleared?: () => void; |
|||
className?: string; |
|||
} |
|||
|
|||
export function DiscountWidget({ |
|||
objectId, |
|||
service = "marriagesubscriptionplan", |
|||
onDiscountApplied, |
|||
onDiscountCleared, |
|||
className = "", |
|||
}: DiscountWidgetProps) { |
|||
const { dictionary: t } = useI18n(); |
|||
const [isExpanded, setIsExpanded] = useState(false); |
|||
const [code, setCode] = useState(""); |
|||
const [discountStatus, setDiscountStatus] = useState< |
|||
"initial" | "empty" | "loading" | "success" | "failed" |
|||
>("initial"); |
|||
const [discountResult, setDiscountResult] = |
|||
useState<CheckDiscountResult | null>(null); |
|||
const [errorMessage, setErrorMessage] = useState<string | null>(null); |
|||
|
|||
const validateMutation = useValidateDiscountMutation(); |
|||
|
|||
const handleApply = async () => { |
|||
const trimmed = code.trim(); |
|||
if (!trimmed) { |
|||
setDiscountStatus("empty"); |
|||
setErrorMessage(t["This field is required"] || "This field is required"); |
|||
return; |
|||
} |
|||
|
|||
setDiscountStatus("loading"); |
|||
setErrorMessage(null); |
|||
|
|||
try { |
|||
const result = await validateMutation.mutateAsync({ |
|||
code: trimmed, |
|||
objectId, |
|||
service, |
|||
}); |
|||
|
|||
if (result.valid) { |
|||
setDiscountStatus("success"); |
|||
setDiscountResult(result); |
|||
setErrorMessage(null); |
|||
onDiscountApplied?.(result); |
|||
} else { |
|||
setDiscountStatus("failed"); |
|||
setDiscountResult(null); |
|||
setErrorMessage(result.message || "Invalid discount code"); |
|||
} |
|||
} catch (err: any) { |
|||
setDiscountStatus("failed"); |
|||
setDiscountResult(null); |
|||
setErrorMessage( |
|||
err?.response?.data?.detail || err?.message || "Invalid discount code", |
|||
); |
|||
} |
|||
}; |
|||
|
|||
const handleClear = () => { |
|||
setCode(""); |
|||
setDiscountStatus("initial"); |
|||
setDiscountResult(null); |
|||
setErrorMessage(null); |
|||
onDiscountCleared?.(); |
|||
}; |
|||
|
|||
const getBorderAndRing = () => { |
|||
switch (discountStatus) { |
|||
case "success": |
|||
return "border-[#00AC78] ring-1 ring-[#00AC78]"; |
|||
case "failed": |
|||
case "empty": |
|||
return "border-[#F0445B] ring-1 ring-[#F0445B]"; |
|||
default: |
|||
return "border-[#D0D5DD] hover:border-[#98A2B3] focus-within:border-[#F0445B] focus-within:ring-1 focus-within:ring-[#F0445B]"; |
|||
} |
|||
}; |
|||
|
|||
return ( |
|||
<div className={`w-full ${className}`}> |
|||
{/* ── Collapsible Header ── */} |
|||
<button |
|||
type="button" |
|||
onClick={() => setIsExpanded((prev) => !prev)} |
|||
className="flex w-full items-center justify-between py-3.5 text-left transition-colors cursor-pointer select-none" |
|||
> |
|||
<div className="flex items-center gap-3"> |
|||
{/* Coupon icon */} |
|||
<svg |
|||
width="18" |
|||
height="18" |
|||
viewBox="0 0 18 18" |
|||
fill="none" |
|||
xmlns="http://www.w3.org/2000/svg" |
|||
className={`shrink-0 transition-colors ${ |
|||
isExpanded ? "text-[#747474]" : "text-[#F0445B]" |
|||
}`}
|
|||
> |
|||
<path |
|||
fillRule="evenodd" |
|||
clipRule="evenodd" |
|||
d="M1.60714 3.21429C1.60714 2.94686 1.82314 2.73214 2.08671 2.73214H15.9133C16.1769 2.73214 16.3929 2.94686 16.3929 3.21429V5.91943C15.8137 6.19949 15.3252 6.6371 14.9834 7.18208C14.6416 7.72706 14.4603 8.35734 14.4603 9.00064C14.4603 9.64395 14.6416 10.2742 14.9834 10.8192C15.3252 11.3642 15.8137 11.8018 16.3929 12.0819V14.7857C16.393 14.8489 16.3808 14.9114 16.3567 14.9698C16.3327 15.0282 16.2975 15.0813 16.2529 15.1261C16.2084 15.1709 16.1555 15.2064 16.0972 15.2308C16.0389 15.2551 15.9764 15.2677 15.9133 15.2679H2.08671C2.02357 15.2677 1.96107 15.2551 1.9028 15.2308C1.84452 15.2064 1.79161 15.1709 1.74707 15.1261C1.70254 15.0813 1.66726 15.0282 1.64325 14.9698C1.61924 14.9114 1.60697 14.8489 1.60714 14.7857V12.0909C2.19152 11.8129 2.68514 11.3751 3.03076 10.828C3.37637 10.2809 3.55982 9.64709 3.55982 9C3.55982 8.3529 3.37637 7.71907 3.03076 7.172C2.68514 6.62493 2.19152 6.18705 1.60714 5.90914V3.21429ZM2.08671 1.125C0.933429 1.125 0 2.06229 0 3.21429V6.46714C0 6.83229 0.246857 7.15114 0.599143 7.24371C0.987519 7.34535 1.33125 7.57285 1.57657 7.89063C1.82189 8.20841 1.95496 8.59855 1.95496 9C1.95496 9.40145 1.82189 9.79159 1.57657 10.1094C1.33125 10.4271 0.987519 10.6546 0.599143 10.7563C0.427554 10.8014 0.275728 10.9021 0.167347 11.0426C0.0589657 11.183 0.000124048 11.3554 0 11.5329L0 14.7857C0 15.939 0.933429 16.875 2.08671 16.875H15.9133C17.0666 16.875 18 15.939 18 14.7857V11.5277C18 11.3514 17.9419 11.1799 17.8348 11.0398C17.7277 10.8997 17.5775 10.7987 17.4073 10.7524C17.0222 10.6483 16.6822 10.4202 16.4398 10.1034C16.1973 9.78667 16.066 9.39889 16.066 9C16.066 8.60111 16.1973 8.21333 16.4398 7.89658C16.6822 7.57983 17.0222 7.35174 17.4073 7.24757C17.5775 7.20129 17.7277 7.10032 17.8348 6.96021C17.9419 6.8201 18 6.64865 18 6.47229V3.21429C18 2.06229 17.0666 1.125 15.9133 1.125H2.08671ZM12.7826 5.21743C12.708 5.14279 12.6194 5.08358 12.5218 5.04318C12.4243 5.00279 12.3198 4.98199 12.2143 4.98199C12.1087 4.98199 12.0042 5.00279 11.9067 5.04318C11.8092 5.08358 11.7206 5.14279 11.646 5.21743L5.21743 11.646C5.1428 11.7206 5.0836 11.8092 5.04321 11.9067C5.00282 12.0042 4.98204 12.1087 4.98204 12.2143C4.98204 12.3198 5.00282 12.4243 5.04321 12.5218C5.0836 12.6193 5.1428 12.7079 5.21743 12.7826C5.29206 12.8572 5.38065 12.9164 5.47816 12.9568C5.57567 12.9972 5.68017 13.018 5.78571 13.018C5.89125 13.018 5.99576 12.9972 6.09327 12.9568C6.19077 12.9164 6.27937 12.8572 6.354 12.7826L12.7826 6.354C12.8572 6.27938 12.9164 6.19078 12.9568 6.09328C12.9972 5.99577 13.018 5.89126 13.018 5.78571C13.018 5.68017 12.9972 5.57566 12.9568 5.47815C12.9164 5.38064 12.8572 5.29205 12.7826 5.21743ZM4.98214 6.42857C4.98214 6.23862 5.01956 6.05054 5.09225 5.87505C5.16494 5.69956 5.27148 5.54011 5.40579 5.40579C5.54011 5.27148 5.69956 5.16494 5.87505 5.09225C6.05054 5.01956 6.23862 4.98214 6.42857 4.98214C6.61852 4.98214 6.80661 5.01956 6.9821 5.09225C7.15758 5.16494 7.31704 5.27148 7.45135 5.40579C7.58566 5.54011 7.69221 5.69956 7.7649 5.87505C7.83759 6.05054 7.875 6.23862 7.875 6.42857C7.875 6.81219 7.72261 7.18009 7.45135 7.45135C7.18009 7.72261 6.81219 7.875 6.42857 7.875C6.04495 7.875 5.67705 7.72261 5.40579 7.45135C5.13453 7.18009 4.98214 6.81219 4.98214 6.42857ZM11.5714 10.125C11.1878 10.125 10.8199 10.2774 10.5486 10.5486C10.2774 10.8199 10.125 11.1878 10.125 11.5714C10.125 11.955 10.2774 12.3229 10.5486 12.5942C10.8199 12.8655 11.1878 13.0179 11.5714 13.0179C11.955 13.0179 12.3229 12.8655 12.5942 12.5942C12.8655 12.3229 13.0179 11.955 13.0179 11.5714C13.0179 11.1878 12.8655 10.8199 12.5942 10.5486C12.3229 10.2774 11.955 10.125 11.5714 10.125Z" |
|||
fill="currentColor" |
|||
/> |
|||
</svg> |
|||
|
|||
<span |
|||
className={`text-[14px] font-bold transition-colors ${ |
|||
isExpanded ? "text-[#747474]" : "text-[#F0445B]" |
|||
}`}
|
|||
> |
|||
{t["Do you have a discount code?"] || |
|||
"Do you have a discount code?"} |
|||
</span> |
|||
</div> |
|||
|
|||
{/* Arrow expand icon */} |
|||
<svg |
|||
aria-hidden="true" |
|||
className={`size-5 transition-transform duration-300 ${ |
|||
isExpanded ? "rotate-180 text-[#747474]" : "rotate-0 text-[#F0445B]" |
|||
}`}
|
|||
viewBox="0 0 24 24" |
|||
fill="none" |
|||
stroke="currentColor" |
|||
strokeWidth={2.5} |
|||
strokeLinecap="round" |
|||
strokeLinejoin="round" |
|||
> |
|||
<path d="m6 9 6 6 6-6" /> |
|||
</svg> |
|||
</button> |
|||
|
|||
{/* ── Expanded Form Body ── */} |
|||
{isExpanded && ( |
|||
<div className="pt-1 pb-2 w-full"> |
|||
<div |
|||
className={`flex h-[52px] w-full items-center rounded-[12px] border bg-white px-4 transition-all ${getBorderAndRing()}`} |
|||
> |
|||
<input |
|||
type="text" |
|||
dir="ltr" |
|||
value={code} |
|||
disabled={discountStatus === "loading" || discountResult !== null} |
|||
onChange={(e) => { |
|||
setCode(e.target.value); |
|||
if (discountStatus !== "initial") { |
|||
setDiscountStatus("initial"); |
|||
setErrorMessage(null); |
|||
} |
|||
}} |
|||
onKeyDown={(e) => { |
|||
if (e.key === "Enter" && discountResult === null) { |
|||
e.preventDefault(); |
|||
handleApply(); |
|||
} |
|||
}} |
|||
placeholder={ |
|||
t["Enter discount code..."] || "Enter discount code..." |
|||
} |
|||
className="h-full flex-1 bg-transparent text-[15px] font-medium text-[#181818] outline-none placeholder:text-[#98A2B3] disabled:opacity-70 min-w-0" |
|||
/> |
|||
|
|||
{discountStatus === "loading" ? ( |
|||
<div className="shrink-0 pl-3"> |
|||
<div className="size-4.5 animate-spin rounded-full border-2 border-[#F0445B] border-t-transparent" /> |
|||
</div> |
|||
) : discountResult !== null ? ( |
|||
<button |
|||
type="button" |
|||
onClick={handleClear} |
|||
className="shrink-0 pl-3 text-[15px] font-semibold text-[#F0445B] hover:opacity-80 transition-opacity cursor-pointer" |
|||
> |
|||
{t["Clear"] || "Clear"} |
|||
</button> |
|||
) : ( |
|||
<button |
|||
type="button" |
|||
onClick={handleApply} |
|||
className="shrink-0 pl-3 text-[15px] font-semibold text-[#F0445B] hover:opacity-80 transition-opacity cursor-pointer" |
|||
> |
|||
{t["Apply"] || "Apply"} |
|||
</button> |
|||
)} |
|||
</div> |
|||
|
|||
{/* Status Message */} |
|||
{errorMessage && ( |
|||
<p className="mt-2 text-start text-[13px] font-medium text-[#D44747] leading-normal"> |
|||
{errorMessage} |
|||
</p> |
|||
)} |
|||
|
|||
{discountStatus === "success" && discountResult?.message && ( |
|||
<p className="mt-2 text-start text-[13px] font-medium text-[#00AC78] leading-normal"> |
|||
{discountResult.message} |
|||
</p> |
|||
)} |
|||
</div> |
|||
)} |
|||
</div> |
|||
); |
|||
} |
|||
@ -0,0 +1,140 @@ |
|||
import { act, cleanup, render, renderHook, screen } from "@testing-library/react"; |
|||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
|||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; |
|||
import { I18nProvider } from "@/translations/provider"; |
|||
import { |
|||
MatchProfileOverlay, |
|||
useMatchProfileOverlay, |
|||
} from "./match-profile-overlay"; |
|||
|
|||
vi.mock("next/navigation", () => ({ |
|||
useRouter: () => ({ |
|||
push: vi.fn(), |
|||
replace: vi.fn(), |
|||
back: vi.fn(), |
|||
}), |
|||
})); |
|||
|
|||
vi.mock("@/hooks/marriage/use-profile-main", () => ({ |
|||
useMarriageProfileQuery: () => ({ |
|||
data: { |
|||
status: "matched", |
|||
gender: "female", |
|||
active_case: { case_id: "test-case-1", status: "introduced" }, |
|||
match_summary: { |
|||
gender: "male", |
|||
public_info: [{ key: "full_name", label: "نام", value: "علی احمدی" }], |
|||
}, |
|||
}, |
|||
isLoading: false, |
|||
refetch: vi.fn(), |
|||
}), |
|||
})); |
|||
|
|||
vi.mock("@/hooks/marriage/use-case-respond", () => ({ |
|||
useRespondToMarriageCaseMutation: () => ({ |
|||
mutateAsync: vi.fn(), |
|||
isPending: false, |
|||
}), |
|||
})); |
|||
|
|||
function createWrapper() { |
|||
const queryClient = new QueryClient({ |
|||
defaultOptions: { |
|||
queries: { retry: false }, |
|||
}, |
|||
}); |
|||
|
|||
return function Wrapper({ children }: { children: React.ReactNode }) { |
|||
return ( |
|||
<QueryClientProvider client={queryClient}> |
|||
<I18nProvider locale="fa">{children}</I18nProvider> |
|||
</QueryClientProvider> |
|||
); |
|||
}; |
|||
} |
|||
|
|||
describe("MatchProfileOverlay & useMatchProfileOverlay", () => { |
|||
beforeEach(() => { |
|||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); |
|||
vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => { |
|||
return setTimeout(() => cb(Date.now()), 0); |
|||
}); |
|||
vi.stubGlobal("cancelAnimationFrame", (id: number) => { |
|||
clearTimeout(id); |
|||
}); |
|||
document.body.className = ""; |
|||
}); |
|||
|
|||
afterEach(() => { |
|||
cleanup(); |
|||
vi.restoreAllMocks(); |
|||
vi.useRealTimers(); |
|||
document.body.className = ""; |
|||
}); |
|||
|
|||
it("hook manages open and close state with history sync", () => { |
|||
const { result } = renderHook(() => useMatchProfileOverlay()); |
|||
|
|||
expect(result.current.isProfileOpen).toBe(false); |
|||
|
|||
act(() => { |
|||
result.current.openProfile(); |
|||
}); |
|||
|
|||
expect(result.current.isProfileOpen).toBe(true); |
|||
|
|||
act(() => { |
|||
result.current.closeProfile(); |
|||
}); |
|||
|
|||
expect(result.current.isProfileOpen).toBe(false); |
|||
}); |
|||
|
|||
it("renders overlay dialog and profile page when open is true", () => { |
|||
const handleClose = vi.fn(); |
|||
const wrapper = createWrapper(); |
|||
|
|||
render( |
|||
<MatchProfileOverlay open={true} onClose={handleClose} />, |
|||
{ wrapper }, |
|||
); |
|||
|
|||
act(() => { |
|||
vi.advanceTimersByTime(16); |
|||
}); |
|||
|
|||
const overlay = screen.getByRole("dialog"); |
|||
expect(overlay).toBeInTheDocument(); |
|||
expect(overlay).toHaveClass("section-overlay"); |
|||
expect(document.body.classList.contains("section-overlay-open")).toBe(true); |
|||
}); |
|||
|
|||
it("handles closing animation and removes body class when open becomes false", () => { |
|||
const handleClose = vi.fn(); |
|||
const wrapper = createWrapper(); |
|||
|
|||
const { rerender } = render( |
|||
<MatchProfileOverlay open={true} onClose={handleClose} />, |
|||
{ wrapper }, |
|||
); |
|||
|
|||
act(() => { |
|||
vi.advanceTimersByTime(16); |
|||
}); |
|||
|
|||
expect(screen.getByRole("dialog")).toHaveAttribute("data-state", "open"); |
|||
expect(document.body.classList.contains("section-overlay-open")).toBe(true); |
|||
|
|||
rerender(<MatchProfileOverlay open={false} onClose={handleClose} />); |
|||
|
|||
expect(screen.getByRole("dialog")).toHaveAttribute("data-state", "closing"); |
|||
expect(document.body.classList.contains("section-overlay-open")).toBe(false); |
|||
|
|||
act(() => { |
|||
vi.advanceTimersByTime(210); |
|||
}); |
|||
|
|||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); |
|||
}); |
|||
}); |
|||
@ -0,0 +1,77 @@ |
|||
"use client"; |
|||
|
|||
import { useCallback, useEffect, useState } from "react"; |
|||
import NewMatchProfilePage from "@/app/new-match/profile/page"; |
|||
import SectionOverlayHost from "@/components/Componentes/section-overlay-host"; |
|||
import { useHardwareBackHandler } from "@/hooks/use-hardware-back-handler"; |
|||
|
|||
export type MatchProfileOverlayProps = { |
|||
open: boolean; |
|||
onClose: () => void; |
|||
}; |
|||
|
|||
/** |
|||
* Hook to manage Match Profile ("More detail") slide-in overlay state. |
|||
* Syncs with browser history (?profile=open) and intercepts hardware back in Flutter. |
|||
*/ |
|||
export function useMatchProfileOverlay() { |
|||
const [isProfileOpen, setIsProfileOpen] = useState(false); |
|||
|
|||
useEffect(() => { |
|||
const readProfileFromUrl = () => { |
|||
if (typeof window === "undefined") return; |
|||
const params = new URLSearchParams(window.location.search); |
|||
setIsProfileOpen(params.get("profile") === "open"); |
|||
}; |
|||
|
|||
readProfileFromUrl(); |
|||
window.addEventListener("popstate", readProfileFromUrl); |
|||
return () => window.removeEventListener("popstate", readProfileFromUrl); |
|||
}, []); |
|||
|
|||
const openProfile = useCallback(() => { |
|||
setIsProfileOpen(true); |
|||
if (typeof window !== "undefined") { |
|||
const url = new URL(window.location.href); |
|||
url.searchParams.set("profile", "open"); |
|||
window.history.pushState({ profile: "open" }, "", url.toString()); |
|||
} |
|||
}, []); |
|||
|
|||
const closeProfile = useCallback(() => { |
|||
if (typeof window !== "undefined") { |
|||
const params = new URLSearchParams(window.location.search); |
|||
if (params.get("profile") === "open") { |
|||
setIsProfileOpen(false); |
|||
window.history.back(); |
|||
return; |
|||
} |
|||
} |
|||
setIsProfileOpen(false); |
|||
}, []); |
|||
|
|||
// Intercept hardware back in Flutter WebView when profile overlay is open
|
|||
useHardwareBackHandler(() => { |
|||
closeProfile(); |
|||
return true; // handled: keep WebView screen open
|
|||
}, isProfileOpen); |
|||
|
|||
return { |
|||
isProfileOpen, |
|||
openProfile, |
|||
closeProfile, |
|||
}; |
|||
} |
|||
|
|||
export function MatchProfileOverlay({ |
|||
open, |
|||
onClose, |
|||
}: MatchProfileOverlayProps) { |
|||
return ( |
|||
<SectionOverlayHost open={open} onClose={onClose}> |
|||
<NewMatchProfilePage onClose={onClose} /> |
|||
</SectionOverlayHost> |
|||
); |
|||
} |
|||
|
|||
export default MatchProfileOverlay; |
|||
@ -1,23 +1,8 @@ |
|||
import type { MarriageProfile } from "@/hooks/marriage/types"; |
|||
|
|||
/** |
|||
* Support is unavailable until a user has finished their profile. Women gain |
|||
* access on the waiting screen; men additionally need a currently valid |
|||
* subscription. |
|||
* Support is accessible for users across all main screens. |
|||
*/ |
|||
export function hasSupportAccess(profile?: MarriageProfile): boolean { |
|||
if (!profile || !["waiting", "in_case", "matched"].includes(profile.status)) { |
|||
return false; |
|||
} |
|||
|
|||
if (profile.gender === "female") { |
|||
return true; |
|||
} |
|||
|
|||
const subscription = profile.active_subscription; |
|||
return ( |
|||
profile.gender === "male" && |
|||
subscription?.is_active === true && |
|||
subscription.is_valid === true |
|||
); |
|||
} |
|||
@ -6,6 +6,9 @@ import { MdOutlineSwitchAccount } from "react-icons/md"; |
|||
import { getClientCookie, setClientCookie } from "@/lib/cookies"; |
|||
import { setCachedMarriageEntryPath } from "@/lib/entry-route-cache"; |
|||
|
|||
// ─────────────────────────────────────────────────────────────────────────────
|
|||
// ۱. توکنهای ثابت سیستم (System Preset Tokens)
|
|||
// ─────────────────────────────────────────────────────────────────────────────
|
|||
export const FEMALE_TOKEN = "545f61bb3e061ccb9b19f84715eb1b1ed4740331"; |
|||
export const MALE_TOKEN = "f3a7543b44ef0a713d1ee0d4f7866b3825cf1308"; |
|||
export const MALE_2_TOKEN = "56cd0fceb93f7cecf7ffa84c590135026cf54a1d"; |
|||
@ -15,32 +18,130 @@ export const MALE_EMAIL = "[email protected]"; |
|||
export const MALE_2_EMAIL = "[email protected]"; |
|||
|
|||
const TOKEN_COOKIE_NAME = "HABIB_TOKEN"; |
|||
const DEV_CUSTOM_TOKENS_STORAGE_KEY = "HABIB_DEV_CUSTOM_TOKENS_V1"; |
|||
const DEV_ACTIVE_NAME_STORAGE_KEY = "HABIB_DEV_ACTIVE_NAME_V1"; |
|||
const DEV_ACTIVE_EMOJI_STORAGE_KEY = "HABIB_DEV_ACTIVE_EMOJI_V1"; |
|||
|
|||
type WindowWithHabibToken = Window & { |
|||
HABIB_TOKEN?: string; |
|||
}; |
|||
|
|||
export interface DevAccountItem { |
|||
id?: number | null; |
|||
token: string; |
|||
title: string; |
|||
subtitle?: string; |
|||
emoji?: string; |
|||
isCustom?: boolean; |
|||
} |
|||
|
|||
// ─────────────────────────────────────────────────────────────────────────────
|
|||
// ۲. لیست حسابهای پیشفرض و Inline درون کد:
|
|||
// هر توسعهدهنده میتواند توکنهای تستی جدید خود را همراه با نام دلخواه به این آرایه اضافه کند.
|
|||
// ─────────────────────────────────────────────────────────────────────────────
|
|||
export const PRESET_DEV_ACCOUNTS: DevAccountItem[] = [ |
|||
{ |
|||
id: 17119, |
|||
token: MALE_TOKEN, |
|||
title: "حساب آقا", |
|||
subtitle: MALE_EMAIL, |
|||
emoji: "👨", |
|||
}, |
|||
{ |
|||
id: 146024, |
|||
token: MALE_2_TOKEN, |
|||
title: "حساب آقا ۲", |
|||
subtitle: MALE_2_EMAIL, |
|||
emoji: "👨", |
|||
}, |
|||
{ |
|||
id: 147714, |
|||
token: FEMALE_TOKEN, |
|||
title: "حساب خانم", |
|||
subtitle: FEMALE_EMAIL, |
|||
emoji: "👩", |
|||
}, |
|||
// نمونه افزودن توکن جدید Inline در کد:
|
|||
// {
|
|||
// token: "YOUR_DEV_TOKEN_HERE",
|
|||
// title: "حساب تست طلاق",
|
|||
// subtitle: "تست مرحله ۳",
|
|||
// emoji: "🧪",
|
|||
// },
|
|||
]; |
|||
|
|||
const AVAILABLE_EMOJIS = ["🔑", "👨", "👩", "👤", "🧪", "⚡", "🎯", "🚀"]; |
|||
|
|||
function normalizeToken(token?: string | null): string { |
|||
if (!token) return ""; |
|||
let clean = decodeURIComponent(token).trim(); |
|||
if (clean.startsWith('"') && clean.endsWith('"')) { |
|||
clean = clean.slice(1, -1).trim(); |
|||
} |
|||
if (clean.toLowerCase().startsWith("token ")) { |
|||
clean = clean.slice(6).trim(); |
|||
} |
|||
return clean; |
|||
} |
|||
|
|||
type TokenSwitcherProps = { |
|||
variant?: "default" | "transparent"; |
|||
className?: string; |
|||
inlineAccounts?: DevAccountItem[]; |
|||
}; |
|||
|
|||
export function TokenSwitcher({ |
|||
variant = "default", |
|||
className, |
|||
inlineAccounts = [], |
|||
}: TokenSwitcherProps) { |
|||
const [mounted, setMounted] = useState(false); |
|||
const [isOpen, setIsOpen] = useState(false); |
|||
const [currentToken, setCurrentToken] = useState<string>(""); |
|||
const [activeStoredName, setActiveStoredName] = useState<string>(""); |
|||
const [activeStoredEmoji, setActiveStoredEmoji] = useState<string>(""); |
|||
const [savedCustomAccounts, setSavedCustomAccounts] = useState< |
|||
DevAccountItem[] |
|||
>([]); |
|||
const [customTitleInput, setCustomTitleInput] = useState<string>(""); |
|||
const [customTokenInput, setCustomTokenInput] = useState<string>(""); |
|||
const [isCustomInputOpen, setIsCustomInputOpen] = useState(false); |
|||
const [selectedEmoji, setSelectedEmoji] = useState<string>("🔑"); |
|||
|
|||
useEffect(() => { |
|||
setMounted(true); |
|||
if (typeof window !== "undefined") { |
|||
const token = |
|||
(window as any).HABIB_TOKEN ?? |
|||
const win = window as WindowWithHabibToken; |
|||
const rawToken = |
|||
win.HABIB_TOKEN ?? |
|||
getClientCookie(TOKEN_COOKIE_NAME) ?? |
|||
getClientCookie("habib_token") ?? |
|||
sessionStorage.getItem(TOKEN_COOKIE_NAME) ?? |
|||
""; |
|||
setCurrentToken(token); |
|||
const norm = normalizeToken(rawToken); |
|||
setCurrentToken(norm); |
|||
|
|||
try { |
|||
const savedName = window.localStorage.getItem( |
|||
DEV_ACTIVE_NAME_STORAGE_KEY, |
|||
); |
|||
const savedEmoji = window.localStorage.getItem( |
|||
DEV_ACTIVE_EMOJI_STORAGE_KEY, |
|||
); |
|||
if (savedName) setActiveStoredName(savedName); |
|||
if (savedEmoji) setActiveStoredEmoji(savedEmoji); |
|||
|
|||
const saved = window.localStorage.getItem( |
|||
DEV_CUSTOM_TOKENS_STORAGE_KEY, |
|||
); |
|||
if (saved) { |
|||
const parsed = JSON.parse(saved); |
|||
if (Array.isArray(parsed)) { |
|||
setSavedCustomAccounts(parsed); |
|||
} |
|||
} |
|||
} catch (e) { |
|||
console.error("Failed to load dev saved custom accounts:", e); |
|||
} |
|||
} |
|||
}, []); |
|||
|
|||
@ -48,60 +149,169 @@ export function TokenSwitcher({ |
|||
return null; |
|||
} |
|||
|
|||
const isMale = currentToken === MALE_TOKEN; |
|||
const isMale2 = currentToken === MALE_2_TOKEN; |
|||
const isFemale = currentToken === FEMALE_TOKEN; |
|||
const isNoToken = currentToken === "NO_TOKEN" || !currentToken; |
|||
const isCustomToken = |
|||
!isMale && !isMale2 && !isFemale && !isNoToken; |
|||
|
|||
const handleSelectToken = (newToken: string) => { |
|||
const trimmed = newToken.trim(); |
|||
if (!trimmed) return; |
|||
|
|||
const persistCustomAccounts = (accounts: DevAccountItem[]) => { |
|||
setSavedCustomAccounts(accounts); |
|||
if (typeof window !== "undefined") { |
|||
try { |
|||
window.localStorage.setItem( |
|||
DEV_CUSTOM_TOKENS_STORAGE_KEY, |
|||
JSON.stringify(accounts), |
|||
); |
|||
} catch (e) { |
|||
console.warn("Failed to persist custom accounts:", e); |
|||
} |
|||
} |
|||
}; |
|||
|
|||
const safeClearStorage = (keepName?: string, keepEmoji?: string) => { |
|||
if (typeof window === "undefined") return; |
|||
try { |
|||
const savedTokens = window.localStorage.getItem( |
|||
DEV_CUSTOM_TOKENS_STORAGE_KEY, |
|||
); |
|||
window.localStorage.clear(); |
|||
window.sessionStorage.clear(); |
|||
if (savedTokens) { |
|||
window.localStorage.setItem(DEV_CUSTOM_TOKENS_STORAGE_KEY, savedTokens); |
|||
} |
|||
if (keepName) { |
|||
window.localStorage.setItem(DEV_ACTIVE_NAME_STORAGE_KEY, keepName); |
|||
} |
|||
if (keepEmoji) { |
|||
window.localStorage.setItem(DEV_ACTIVE_EMOJI_STORAGE_KEY, keepEmoji); |
|||
} |
|||
} catch (e) { |
|||
console.error("Failed to clear storage", e); |
|||
console.error("Failed to clear storage safely:", e); |
|||
} |
|||
}; |
|||
|
|||
const allAccounts: DevAccountItem[] = [ |
|||
...PRESET_DEV_ACCOUNTS, |
|||
...inlineAccounts, |
|||
...savedCustomAccounts, |
|||
]; |
|||
|
|||
const normCurrent = normalizeToken(currentToken); |
|||
const activeAccount = allAccounts.find( |
|||
(acc) => normalizeToken(acc.token) === normCurrent, |
|||
); |
|||
const isNoToken = |
|||
normCurrent === "NO_TOKEN" || !normCurrent || normCurrent === ""; |
|||
|
|||
const handleSelectToken = ( |
|||
newToken: string, |
|||
accountTitle?: string, |
|||
accountEmoji?: string, |
|||
) => { |
|||
const cleanToken = normalizeToken(newToken); |
|||
if (!cleanToken && cleanToken !== "NO_TOKEN") return; |
|||
|
|||
// Find account info if title was not explicitly passed
|
|||
const targetAccount = allAccounts.find( |
|||
(acc) => normalizeToken(acc.token) === cleanToken, |
|||
); |
|||
const resolvedTitle = |
|||
accountTitle || |
|||
(cleanToken === "NO_TOKEN" |
|||
? "کاربر بدون توکن" |
|||
: targetAccount?.title || "حساب سفارشی"); |
|||
const resolvedEmoji = |
|||
accountEmoji || |
|||
(cleanToken === "NO_TOKEN" ? "👤" : targetAccount?.emoji || "🔑"); |
|||
|
|||
if (typeof window !== "undefined") { |
|||
safeClearStorage(resolvedTitle, resolvedEmoji); |
|||
|
|||
setCachedMarriageEntryPath(null); |
|||
setClientCookie(TOKEN_COOKIE_NAME, trimmed); |
|||
setClientCookie("habib_token", trimmed); |
|||
setClientCookie(TOKEN_COOKIE_NAME, cleanToken); |
|||
setClientCookie("habib_token", cleanToken); |
|||
try { |
|||
sessionStorage.setItem(TOKEN_COOKIE_NAME, trimmed); |
|||
sessionStorage.setItem(TOKEN_COOKIE_NAME, cleanToken); |
|||
} catch (e) { |
|||
console.warn("sessionStorage is not accessible:", e); |
|||
} |
|||
(window as any).HABIB_TOKEN = trimmed; |
|||
setCurrentToken(trimmed); |
|||
(window as WindowWithHabibToken).HABIB_TOKEN = cleanToken; |
|||
setCurrentToken(cleanToken); |
|||
setActiveStoredName(resolvedTitle); |
|||
setActiveStoredEmoji(resolvedEmoji); |
|||
setIsOpen(false); |
|||
|
|||
window.location.replace("/"); |
|||
} |
|||
}; |
|||
|
|||
const handleAddAndSelectAccount = (e?: React.FormEvent) => { |
|||
if (e) e.preventDefault(); |
|||
const cleanToken = normalizeToken(customTokenInput); |
|||
if (!cleanToken) return; |
|||
|
|||
const cleanTitle = |
|||
customTitleInput.trim() || `حساب سفارشی (${cleanToken.slice(0, 6)}...)`; |
|||
|
|||
const newAccount: DevAccountItem = { |
|||
token: cleanToken, |
|||
title: cleanTitle, |
|||
emoji: selectedEmoji, |
|||
isCustom: true, |
|||
}; |
|||
|
|||
const updated = [ |
|||
newAccount, |
|||
...savedCustomAccounts.filter( |
|||
(a) => normalizeToken(a.token) !== cleanToken, |
|||
), |
|||
]; |
|||
persistCustomAccounts(updated); |
|||
setCustomTitleInput(""); |
|||
setCustomTokenInput(""); |
|||
handleSelectToken(cleanToken, cleanTitle, selectedEmoji); |
|||
}; |
|||
|
|||
const handleSaveAccountOnly = () => { |
|||
const cleanToken = normalizeToken(customTokenInput); |
|||
if (!cleanToken) return; |
|||
|
|||
const cleanTitle = |
|||
customTitleInput.trim() || `حساب سفارشی (${cleanToken.slice(0, 6)}...)`; |
|||
|
|||
const newAccount: DevAccountItem = { |
|||
token: cleanToken, |
|||
title: cleanTitle, |
|||
emoji: selectedEmoji, |
|||
isCustom: true, |
|||
}; |
|||
|
|||
const updated = [ |
|||
newAccount, |
|||
...savedCustomAccounts.filter( |
|||
(a) => normalizeToken(a.token) !== cleanToken, |
|||
), |
|||
]; |
|||
persistCustomAccounts(updated); |
|||
setCustomTitleInput(""); |
|||
setCustomTokenInput(""); |
|||
}; |
|||
|
|||
const handleDeleteCustomAccount = (tokenToDelete: string) => { |
|||
const cleanDelete = normalizeToken(tokenToDelete); |
|||
const updated = savedCustomAccounts.filter( |
|||
(acc) => normalizeToken(acc.token) !== cleanDelete, |
|||
); |
|||
persistCustomAccounts(updated); |
|||
}; |
|||
|
|||
const handleResetUser = async (userId: number | null, label: string) => { |
|||
const message = |
|||
userId !== null |
|||
? `آیا از پاک کردن تمامی اطلاعات هویتی، پاسخها و پیشرفت این کاربر (${label}) و شروع مجدد از مرحله اول آنبوردینگ مطمئن هستید؟` |
|||
: `آیا از پاک کردن تمامی اطلاعات محلی و کوکیهای مربوط به این حالت (بدون توکن) و شروع مجدد مطمئن هستید؟`; |
|||
: `آیا از پاک کردن تمامی اطلاعات محلی و کوکیهای مربوط به این حالت (${label}) و شروع مجدد مطمئن هستید؟`; |
|||
|
|||
if (!window.confirm(message)) { |
|||
return; |
|||
} |
|||
|
|||
try { |
|||
if (typeof window !== "undefined") { |
|||
try { |
|||
window.localStorage.clear(); |
|||
window.sessionStorage.clear(); |
|||
} catch (e) { |
|||
console.error("Failed to clear storage", e); |
|||
} |
|||
} |
|||
safeClearStorage(); |
|||
|
|||
if (userId !== null) { |
|||
const response = await fetch("/api/dev-reset-profile", { |
|||
@ -128,63 +338,45 @@ export function TokenSwitcher({ |
|||
? MALE_2_TOKEN |
|||
: "NO_TOKEN"; |
|||
|
|||
setCachedMarriageEntryPath(null); |
|||
setClientCookie(TOKEN_COOKIE_NAME, targetToken); |
|||
setClientCookie("habib_token", targetToken); |
|||
if (typeof window !== "undefined") { |
|||
try { |
|||
sessionStorage.setItem(TOKEN_COOKIE_NAME, targetToken); |
|||
} catch (e) { |
|||
console.warn("sessionStorage is not accessible:", e); |
|||
} |
|||
(window as any).HABIB_TOKEN = targetToken; |
|||
setCurrentToken(targetToken); |
|||
} |
|||
const targetAccount = allAccounts.find( |
|||
(a) => normalizeToken(a.token) === normalizeToken(targetToken), |
|||
); |
|||
const targetTitle = targetAccount?.title || label; |
|||
const targetEmoji = targetAccount?.emoji || "🔑"; |
|||
|
|||
setIsOpen(false); |
|||
window.location.replace("/"); |
|||
handleSelectToken(targetToken, targetTitle, targetEmoji); |
|||
} catch (error) { |
|||
console.error("Failed to reset user:", error); |
|||
alert("خطایی در انجام عملیات رخ داد."); |
|||
} |
|||
}; |
|||
|
|||
const mainAccounts = [ |
|||
{ |
|||
id: 17119, |
|||
token: MALE_TOKEN, |
|||
title: "حساب آقا", |
|||
subtitle: MALE_EMAIL, |
|||
emoji: "👨", |
|||
isActive: isMale, |
|||
}, |
|||
{ |
|||
id: 146024, |
|||
token: MALE_2_TOKEN, |
|||
title: "حساب آقا ۲", |
|||
subtitle: MALE_2_EMAIL, |
|||
emoji: "👨", |
|||
isActive: isMale2, |
|||
}, |
|||
{ |
|||
id: 147714, |
|||
token: FEMALE_TOKEN, |
|||
title: "حساب خانم", |
|||
subtitle: FEMALE_EMAIL, |
|||
emoji: "👩", |
|||
isActive: isFemale, |
|||
}, |
|||
]; |
|||
// ─────────────────────────────────────────────────────────────────────────
|
|||
// عنوان و نام نمایشی روی Badge بسته شده (Floating Closed Badge Label)
|
|||
// ─────────────────────────────────────────────────────────────────────────
|
|||
const getFloatingButtonLabel = () => { |
|||
if (isNoToken) { |
|||
return "بدون توکن 👤"; |
|||
} |
|||
if (activeAccount) { |
|||
return `${activeAccount.title} ${activeAccount.emoji || "🔑"}`; |
|||
} |
|||
if (activeStoredName) { |
|||
return `${activeStoredName} ${activeStoredEmoji || "🔑"}`; |
|||
} |
|||
return "حساب سفارشی 🔑"; |
|||
}; |
|||
|
|||
return ( |
|||
<> |
|||
{/* Floating Badge (وقتی بسته است فقط نام حساب و ایموجی را نمایش میدهد) */} |
|||
<button |
|||
type="button" |
|||
onClick={() => setIsOpen(true)} |
|||
aria-label="تغییر توکن کاربر (تست)" |
|||
title="تغییر توکن (آقا / خانم)" |
|||
title="تغییر توکن کاربر (محیط توسعه)" |
|||
className={[ |
|||
"fixed top-4 left-4 z-[99999] inline-flex items-center gap-1.5 rounded-[15px] px-3 py-2 text-xs font-bold transition-all active:scale-95 shadow-md border border-slate-200/80 dark:border-slate-700/80 backdrop-blur-md", |
|||
"fixed top-4 left-4 z-[99999] inline-flex items-center gap-2 rounded-[15px] px-3.5 py-2 text-xs font-extrabold transition-all active:scale-95 shadow-md border border-slate-200/80 dark:border-slate-700/80 backdrop-blur-md max-w-[260px] cursor-pointer", |
|||
variant === "transparent" |
|||
? "bg-black/40 text-white hover:bg-black/50" |
|||
: "bg-white/95 text-slate-800 hover:bg-white dark:bg-slate-900/95 dark:text-slate-100", |
|||
@ -193,33 +385,31 @@ export function TokenSwitcher({ |
|||
.filter(Boolean) |
|||
.join(" ")} |
|||
> |
|||
<MdOutlineSwitchAccount className="size-5 text-rose-500" /> |
|||
<span> |
|||
{isMale |
|||
? "آقا 👨" |
|||
: isMale2 |
|||
? "آقا ۲ 👨" |
|||
: isFemale |
|||
? "خانم 👩" |
|||
: isNoToken |
|||
? "بدون توکن 👤" |
|||
: "سفارشی 🔑"} |
|||
</span> |
|||
<MdOutlineSwitchAccount className="size-5 text-rose-500 shrink-0" /> |
|||
<span className="truncate">{getFloatingButtonLabel()}</span> |
|||
</button> |
|||
|
|||
{isOpen && ( |
|||
<div |
|||
className="fixed inset-0 z-[100000] flex items-center justify-center bg-black/60 p-4 backdrop-blur-xs animate-in fade-in duration-200" |
|||
<div className="fixed inset-0 z-[100000] flex items-center justify-center p-4 animate-in fade-in duration-200"> |
|||
{/* Backdrop Button */} |
|||
<button |
|||
type="button" |
|||
aria-label="بستن پنجره" |
|||
onClick={() => setIsOpen(false)} |
|||
> |
|||
className="fixed inset-0 bg-black/60 backdrop-blur-xs cursor-default" |
|||
/> |
|||
|
|||
{/* Modal Container */} |
|||
<div |
|||
className="w-full max-w-sm rounded-2xl bg-white p-5 shadow-2xl dark:bg-slate-900 border border-slate-100 dark:border-slate-800 max-h-[90vh] flex flex-col" |
|||
onClick={(e) => e.stopPropagation()} |
|||
className="relative z-10 w-full max-w-md rounded-2xl bg-white shadow-2xl dark:bg-slate-900 border border-slate-100 dark:border-slate-800 max-h-[90vh] flex flex-col overflow-hidden text-right" |
|||
dir="rtl" |
|||
role="dialog" |
|||
aria-modal="true" |
|||
> |
|||
{/* Modal Header */} |
|||
<div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 dark:border-slate-800 shrink-0 bg-slate-50/50 dark:bg-slate-900/50"> |
|||
<div className="flex items-center gap-3"> |
|||
<div className="size-10 rounded-xl bg-rose-500/10 text-rose-500 flex items-center justify-center"> |
|||
<div className="size-10 rounded-xl bg-rose-500/10 text-rose-500 flex items-center justify-center shrink-0"> |
|||
<MdOutlineSwitchAccount className="size-5" /> |
|||
</div> |
|||
<div> |
|||
@ -227,49 +417,61 @@ export function TokenSwitcher({ |
|||
انتخاب حساب کاربری (تست) |
|||
</h3> |
|||
<p className="text-xs text-slate-500 dark:text-slate-400"> |
|||
تغییر سریع پروفایل و توکن جهت تست |
|||
تغییر سریع پروفایل، نامگذاری و مدیریت توکنها |
|||
</p> |
|||
</div> |
|||
</div> |
|||
<button |
|||
type="button" |
|||
onClick={() => setIsOpen(false)} |
|||
className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-sm p-1" |
|||
className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-sm p-1 cursor-pointer" |
|||
> |
|||
<IoClose className="size-5" /> |
|||
</button> |
|||
</div> |
|||
|
|||
{/* Scrollable Account Cards */} |
|||
<div className="flex-1 overflow-y-auto px-5 py-4 space-y-2.5 min-h-0"> |
|||
{/* Main Predefined Accounts */} |
|||
{mainAccounts.map((acc) => ( |
|||
{/* Scrollable Content */} |
|||
<div className="flex-1 overflow-y-auto px-5 py-4 space-y-4 min-h-0"> |
|||
{/* Predefined System Accounts */} |
|||
<div className="space-y-2"> |
|||
<div className="text-[11px] font-bold text-slate-400 dark:text-slate-500 px-1"> |
|||
حسابهای پیشفرض سیستم |
|||
</div> |
|||
<div className="space-y-2"> |
|||
{PRESET_DEV_ACCOUNTS.map((acc) => { |
|||
const isActive = normalizeToken(acc.token) === normCurrent; |
|||
return ( |
|||
<div |
|||
key={acc.token} |
|||
className={[ |
|||
"flex items-center justify-between gap-3 p-3 rounded-2xl border transition-all select-none", |
|||
acc.isActive |
|||
isActive |
|||
? "border-rose-500 bg-rose-50/70 dark:bg-rose-950/40 shadow-xs ring-1 ring-rose-500/30" |
|||
: "border-slate-200 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-700 bg-white dark:bg-slate-800/80 hover:bg-slate-50/60 dark:hover:bg-slate-800", |
|||
].join(" ")} |
|||
> |
|||
<div |
|||
onClick={() => handleSelectToken(acc.token)} |
|||
className="flex-1 min-w-0 flex items-center gap-3 text-right cursor-pointer" |
|||
<button |
|||
type="button" |
|||
onClick={() => |
|||
handleSelectToken(acc.token, acc.title, acc.emoji) |
|||
} |
|||
className="flex-1 min-w-0 flex items-center gap-3 text-right cursor-pointer bg-transparent border-0 p-0 text-inherit" |
|||
> |
|||
<div className="size-11 rounded-xl bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-2xl shrink-0 border border-slate-200/60 dark:border-slate-700/60 shadow-3xs"> |
|||
{acc.emoji} |
|||
{acc.emoji || "👨"} |
|||
</div> |
|||
<div className="flex-1 min-w-0 flex flex-col justify-center gap-0.5 text-right"> |
|||
<span className="text-sm font-bold text-slate-900 dark:text-white leading-tight"> |
|||
{acc.title} |
|||
</span> |
|||
{acc.subtitle && ( |
|||
<span |
|||
className="text-xs text-slate-500 dark:text-slate-400 font-medium truncate block leading-tight text-right" |
|||
dir="ltr" |
|||
> |
|||
{acc.subtitle} |
|||
</span> |
|||
)} |
|||
<span |
|||
className="text-[10px] font-mono text-slate-400 dark:text-slate-500 truncate block text-left leading-tight" |
|||
dir="ltr" |
|||
@ -277,17 +479,19 @@ export function TokenSwitcher({ |
|||
{acc.token} |
|||
</span> |
|||
</div> |
|||
</div> |
|||
</button> |
|||
|
|||
<div className="flex items-center gap-1.5 shrink-0 pr-1"> |
|||
{acc.isActive && ( |
|||
{isActive && ( |
|||
<span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-rose-500 text-white shadow-xs"> |
|||
فعال |
|||
</span> |
|||
)} |
|||
<button |
|||
type="button" |
|||
onClick={() => handleResetUser(acc.id, acc.title)} |
|||
onClick={() => |
|||
handleResetUser(acc.id ?? null, acc.title) |
|||
} |
|||
title="پاک کردن اطلاعات و شروع مجدد" |
|||
className="size-8 rounded-lg flex items-center justify-center text-slate-400 hover:text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-950/40 transition-colors cursor-pointer" |
|||
> |
|||
@ -295,18 +499,149 @@ export function TokenSwitcher({ |
|||
</button> |
|||
</div> |
|||
</div> |
|||
))} |
|||
); |
|||
})} |
|||
</div> |
|||
</div> |
|||
|
|||
{/* Custom Active Token Card (if any custom token is set) */} |
|||
{isCustomToken && ( |
|||
{/* Inline Passed Accounts (if any) */} |
|||
{inlineAccounts.length > 0 && ( |
|||
<div className="space-y-2"> |
|||
<div className="text-[11px] font-bold text-slate-400 dark:text-slate-500 px-1"> |
|||
حسابهای کد (Inline) |
|||
</div> |
|||
<div className="space-y-2"> |
|||
{inlineAccounts.map((acc) => { |
|||
const isActive = |
|||
normalizeToken(acc.token) === normCurrent; |
|||
return ( |
|||
<div |
|||
key={acc.token} |
|||
className={[ |
|||
"flex items-center justify-between gap-3 p-3 rounded-2xl border transition-all select-none", |
|||
isActive |
|||
? "border-rose-500 bg-rose-50/70 dark:bg-rose-950/40 shadow-xs ring-1 ring-rose-500/30" |
|||
: "border-slate-200 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-700 bg-white dark:bg-slate-800/80 hover:bg-slate-50/60 dark:hover:bg-slate-800", |
|||
].join(" ")} |
|||
> |
|||
<button |
|||
type="button" |
|||
onClick={() => |
|||
handleSelectToken(acc.token, acc.title, acc.emoji) |
|||
} |
|||
className="flex-1 min-w-0 flex items-center gap-3 text-right cursor-pointer bg-transparent border-0 p-0 text-inherit" |
|||
> |
|||
<div className="size-11 rounded-xl bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-2xl shrink-0 border border-slate-200/60 dark:border-slate-700/60 shadow-3xs"> |
|||
{acc.emoji || "🔑"} |
|||
</div> |
|||
<div className="flex-1 min-w-0 flex flex-col justify-center gap-0.5 text-right"> |
|||
<span className="text-sm font-bold text-slate-900 dark:text-white leading-tight"> |
|||
{acc.title} |
|||
</span> |
|||
<span |
|||
className="text-[10px] font-mono text-slate-400 dark:text-slate-500 truncate block text-left leading-tight" |
|||
dir="ltr" |
|||
> |
|||
{acc.token} |
|||
</span> |
|||
</div> |
|||
</button> |
|||
|
|||
<div className="flex items-center gap-1.5 shrink-0 pr-1"> |
|||
{isActive && ( |
|||
<span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-rose-500 text-white shadow-xs"> |
|||
فعال |
|||
</span> |
|||
)} |
|||
</div> |
|||
</div> |
|||
); |
|||
})} |
|||
</div> |
|||
</div> |
|||
)} |
|||
|
|||
{/* Saved Custom Named Accounts */} |
|||
{savedCustomAccounts.length > 0 && ( |
|||
<div className="space-y-2"> |
|||
<div className="text-[11px] font-bold text-slate-400 dark:text-slate-500 px-1"> |
|||
حسابهای سفارشی شما |
|||
</div> |
|||
<div className="space-y-2"> |
|||
{savedCustomAccounts.map((acc) => { |
|||
const isActive = |
|||
normalizeToken(acc.token) === normCurrent; |
|||
return ( |
|||
<div |
|||
key={acc.token} |
|||
className={[ |
|||
"flex items-center justify-between gap-3 p-3 rounded-2xl border transition-all select-none", |
|||
isActive |
|||
? "border-rose-500 bg-rose-50/70 dark:bg-rose-950/40 shadow-xs ring-1 ring-rose-500/30" |
|||
: "border-slate-200 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-700 bg-white dark:bg-slate-800/80 hover:bg-slate-50/60 dark:hover:bg-slate-800", |
|||
].join(" ")} |
|||
> |
|||
<button |
|||
type="button" |
|||
onClick={() => |
|||
handleSelectToken(acc.token, acc.title, acc.emoji) |
|||
} |
|||
className="flex-1 min-w-0 flex items-center gap-3 text-right cursor-pointer bg-transparent border-0 p-0 text-inherit" |
|||
> |
|||
<div className="size-11 rounded-xl bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-2xl shrink-0 border border-slate-200/60 dark:border-slate-700/60 shadow-3xs"> |
|||
{acc.emoji || "🔑"} |
|||
</div> |
|||
<div className="flex-1 min-w-0 flex flex-col justify-center gap-0.5 text-right"> |
|||
<span className="text-sm font-bold text-slate-900 dark:text-white leading-tight"> |
|||
{acc.title} |
|||
</span> |
|||
<span |
|||
className="text-[10px] font-mono text-slate-400 dark:text-slate-500 truncate block text-left leading-tight" |
|||
dir="ltr" |
|||
> |
|||
{acc.token} |
|||
</span> |
|||
</div> |
|||
</button> |
|||
|
|||
<div className="flex items-center gap-1.5 shrink-0 pr-1"> |
|||
{isActive && ( |
|||
<span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-rose-500 text-white shadow-xs"> |
|||
فعال |
|||
</span> |
|||
)} |
|||
<button |
|||
type="button" |
|||
onClick={() => |
|||
handleDeleteCustomAccount(acc.token) |
|||
} |
|||
title="حذف از لیست حسابهای سفارشی" |
|||
className="size-8 rounded-lg flex items-center justify-center text-slate-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-950/40 transition-colors cursor-pointer" |
|||
> |
|||
<IoTrashOutline className="size-4" /> |
|||
</button> |
|||
</div> |
|||
</div> |
|||
); |
|||
})} |
|||
</div> |
|||
</div> |
|||
)} |
|||
|
|||
{/* Unnamed Active Custom Token (if any active token not in list) */} |
|||
{!activeAccount && !isNoToken && ( |
|||
<div className="space-y-2"> |
|||
<div className="text-[11px] font-bold text-slate-400 dark:text-slate-500 px-1"> |
|||
توکن فعال فعلی |
|||
</div> |
|||
<div className="flex items-center justify-between gap-3 p-3 rounded-2xl border border-rose-500 bg-rose-50/70 dark:bg-rose-950/40 shadow-xs ring-1 ring-rose-500/30 select-none"> |
|||
<div className="flex-1 min-w-0 flex items-center gap-3 text-right"> |
|||
<div className="size-11 rounded-xl bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-2xl shrink-0 border border-slate-200/60 dark:border-slate-700/60 shadow-3xs"> |
|||
🔑 |
|||
{activeStoredEmoji || "🔑"} |
|||
</div> |
|||
<div className="flex-1 min-w-0 flex flex-col justify-center gap-0.5 text-right"> |
|||
<span className="text-sm font-bold text-slate-900 dark:text-white leading-tight"> |
|||
توکن سفارشی |
|||
{activeStoredName || "توکن سفارشی فعال"} |
|||
</span> |
|||
<span |
|||
className="text-[10px] font-mono text-slate-500 dark:text-slate-400 truncate block text-left leading-tight" |
|||
@ -331,9 +666,14 @@ export function TokenSwitcher({ |
|||
</button> |
|||
</div> |
|||
</div> |
|||
</div> |
|||
)} |
|||
|
|||
{/* No Token Option Card */} |
|||
<div className="space-y-2"> |
|||
<div className="text-[11px] font-bold text-slate-400 dark:text-slate-500 px-1"> |
|||
حالت بدون احراز هویت |
|||
</div> |
|||
<div |
|||
className={[ |
|||
"flex items-center justify-between gap-3 p-3 rounded-2xl border transition-all select-none", |
|||
@ -342,9 +682,12 @@ export function TokenSwitcher({ |
|||
: "border-slate-200 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-700 bg-white dark:bg-slate-800/80 hover:bg-slate-50/60 dark:hover:bg-slate-800", |
|||
].join(" ")} |
|||
> |
|||
<div |
|||
onClick={() => handleSelectToken("NO_TOKEN")} |
|||
className="flex-1 min-w-0 flex items-center gap-3 text-right cursor-pointer" |
|||
<button |
|||
type="button" |
|||
onClick={() => |
|||
handleSelectToken("NO_TOKEN", "کاربر بدون توکن", "👤") |
|||
} |
|||
className="flex-1 min-w-0 flex items-center gap-3 text-right cursor-pointer bg-transparent border-0 p-0 text-inherit" |
|||
> |
|||
<div className="size-11 rounded-xl bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-2xl shrink-0 border border-slate-200/60 dark:border-slate-700/60 shadow-3xs"> |
|||
👤 |
|||
@ -354,10 +697,10 @@ export function TokenSwitcher({ |
|||
کاربر بدون توکن |
|||
</span> |
|||
<span className="text-xs text-slate-500 dark:text-slate-400 font-medium truncate block leading-tight"> |
|||
حالت مهمان / بدون احراز هویت |
|||
حالت مهمان / کاربر جدید بدون لاگین |
|||
</span> |
|||
</div> |
|||
</div> |
|||
</button> |
|||
|
|||
<div className="flex items-center gap-1.5 shrink-0 pr-1"> |
|||
{isNoToken && ( |
|||
@ -375,37 +718,84 @@ export function TokenSwitcher({ |
|||
</button> |
|||
</div> |
|||
</div> |
|||
</div> |
|||
|
|||
{/* Custom Token Input Section */} |
|||
<div className="rounded-2xl border border-dashed border-slate-300 dark:border-slate-700 p-3.5 bg-slate-50/70 dark:bg-slate-800/40 space-y-2.5 mt-3"> |
|||
{/* Add New Custom Named Token Form */} |
|||
<form |
|||
onSubmit={handleAddAndSelectAccount} |
|||
className="rounded-2xl border border-dashed border-slate-300 dark:border-slate-700 p-4 bg-slate-50/70 dark:bg-slate-800/40 space-y-3" |
|||
> |
|||
<div className="flex items-center justify-between"> |
|||
<div className="flex items-center gap-2 text-xs font-bold text-slate-700 dark:text-slate-300"> |
|||
<IoKeyOutline className="size-4 text-amber-500" /> |
|||
<span>افزودن یا تنظیم توکن دلخواه:</span> |
|||
<span>افزودن حساب تستی با نام دلخواه:</span> |
|||
</div> |
|||
</div> |
|||
|
|||
{/* Emoji Selector */} |
|||
<div className="flex items-center gap-1.5 overflow-x-auto pb-1"> |
|||
<span className="text-[11px] text-slate-500 dark:text-slate-400 shrink-0 ml-1"> |
|||
آیکون: |
|||
</span> |
|||
{AVAILABLE_EMOJIS.map((emoji) => ( |
|||
<button |
|||
key={emoji} |
|||
type="button" |
|||
onClick={() => setSelectedEmoji(emoji)} |
|||
className={[ |
|||
"size-7 rounded-lg text-sm flex items-center justify-center transition-all cursor-pointer", |
|||
selectedEmoji === emoji |
|||
? "bg-rose-500/20 ring-1 ring-rose-500 scale-110 shadow-3xs" |
|||
: "bg-white dark:bg-slate-900 hover:bg-slate-100 dark:hover:bg-slate-800 border border-slate-200 dark:border-slate-700", |
|||
].join(" ")} |
|||
> |
|||
{emoji} |
|||
</button> |
|||
))} |
|||
</div> |
|||
<div className="flex items-center gap-2"> |
|||
|
|||
{/* Title Input */} |
|||
<div> |
|||
<input |
|||
type="text" |
|||
value={customTitleInput} |
|||
onChange={(e) => setCustomTitleInput(e.target.value)} |
|||
placeholder="نام یا عنوان حساب (مثلاً: تست طلاق، کاربر سناریو ۲)" |
|||
className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-xs text-slate-800 dark:text-slate-200 outline-none focus:border-rose-500 focus:ring-1 focus:ring-rose-500/20 transition-all placeholder:text-slate-400 placeholder:text-[11px]" |
|||
/> |
|||
</div> |
|||
|
|||
{/* Token Input */} |
|||
<div> |
|||
<input |
|||
type="text" |
|||
value={customTokenInput} |
|||
onChange={(e) => setCustomTokenInput(e.target.value)} |
|||
placeholder="توکن ۳۲/۴۰ کاراکتری..." |
|||
placeholder="رشته توکن (۳۲ یا ۴۰ کاراکتری)..." |
|||
dir="ltr" |
|||
className="flex-1 min-w-0 rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-xs font-mono text-slate-800 dark:text-slate-200 outline-none focus:border-rose-500 focus:ring-1 focus:ring-rose-500/20 transition-all placeholder:text-slate-400 placeholder:text-[11px]" |
|||
onKeyDown={(e) => { |
|||
if (e.key === "Enter" && customTokenInput.trim()) { |
|||
handleSelectToken(customTokenInput); |
|||
} |
|||
}} |
|||
className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-xs font-mono text-slate-800 dark:text-slate-200 outline-none focus:border-rose-500 focus:ring-1 focus:ring-rose-500/20 transition-all placeholder:text-slate-400 placeholder:text-[11px]" |
|||
/> |
|||
</div> |
|||
|
|||
{/* Action Buttons */} |
|||
<div className="flex items-center gap-2 pt-1"> |
|||
<button |
|||
type="submit" |
|||
disabled={!customTokenInput.trim()} |
|||
className="flex-1 rounded-xl bg-rose-500 hover:bg-rose-600 active:scale-95 py-2 text-xs font-bold text-white shadow-xs disabled:opacity-40 disabled:cursor-not-allowed transition-all cursor-pointer text-center" |
|||
> |
|||
ذخیره و ورود به حساب |
|||
</button> |
|||
<button |
|||
type="button" |
|||
disabled={!customTokenInput.trim()} |
|||
onClick={() => handleSelectToken(customTokenInput)} |
|||
className="rounded-xl bg-rose-500 hover:bg-rose-600 active:scale-95 px-4 py-2 text-xs font-bold text-white shadow-xs disabled:opacity-40 disabled:cursor-not-allowed transition-all shrink-0 cursor-pointer" |
|||
onClick={handleSaveAccountOnly} |
|||
className="rounded-xl border border-slate-300 dark:border-slate-600 hover:bg-slate-100 dark:hover:bg-slate-700 active:scale-95 px-3 py-2 text-xs font-medium text-slate-700 dark:text-slate-300 disabled:opacity-40 disabled:cursor-not-allowed transition-all cursor-pointer shrink-0" |
|||
> |
|||
اعمال |
|||
فقط ذخیره در لیست |
|||
</button> |
|||
</div> |
|||
</div> |
|||
</form> |
|||
</div> |
|||
|
|||
{/* Modal Footer */} |
|||
|
|||
@ -0,0 +1,27 @@ |
|||
"use client"; |
|||
|
|||
import { useQuery, type UseQueryOptions } from "@tanstack/react-query"; |
|||
import { http } from "@/lib/http"; |
|||
|
|||
export type HabcoinInventory = { |
|||
coin_balance: number; |
|||
}; |
|||
|
|||
export async function getHabcoinInventory(): Promise<HabcoinInventory> { |
|||
const { data } = await http.get<HabcoinInventory>("/habcoin/inventory/"); |
|||
return data; |
|||
} |
|||
|
|||
export function useHabcoinInventoryQuery( |
|||
options?: Omit< |
|||
UseQueryOptions<HabcoinInventory, Error>, |
|||
"queryKey" | "queryFn" |
|||
>, |
|||
) { |
|||
return useQuery({ |
|||
queryKey: ["habcoin", "inventory"], |
|||
queryFn: getHabcoinInventory, |
|||
staleTime: 15 * 1000, |
|||
...options, |
|||
}); |
|||
} |
|||
@ -0,0 +1,77 @@ |
|||
"use client"; |
|||
|
|||
import { useMutation } from "@tanstack/react-query"; |
|||
import { http } from "@/lib/http"; |
|||
import type { MutationOptions } from "./options"; |
|||
|
|||
const HABCOIN_SERVICE = "marriagesubscriptionplan" as const; |
|||
|
|||
export interface CheckDiscountResult { |
|||
valid: boolean; |
|||
code: string; |
|||
originalPrice: number; |
|||
discountedPrice: number; |
|||
discountAmount: number; |
|||
discountPercentage: number; |
|||
message?: string; |
|||
} |
|||
|
|||
export interface ValidateDiscountParams { |
|||
code: string; |
|||
objectId: number | string; |
|||
service?: string; |
|||
} |
|||
|
|||
export async function validateDiscountCode({ |
|||
code, |
|||
objectId, |
|||
service = HABCOIN_SERVICE, |
|||
}: ValidateDiscountParams): Promise<CheckDiscountResult> { |
|||
try { |
|||
const { data } = await http.post<any>("/habcoin/validate-discount/", { |
|||
code, |
|||
service, |
|||
object_id: objectId, |
|||
}); |
|||
|
|||
return { |
|||
valid: Boolean(data?.valid ?? true), |
|||
code, |
|||
originalPrice: Number(data?.original_price ?? 0), |
|||
discountedPrice: Number(data?.discounted_price ?? 0), |
|||
discountAmount: Number(data?.discount_amount ?? 0), |
|||
discountPercentage: Number(data?.discount_percentage ?? 0), |
|||
message: data?.message || undefined, |
|||
}; |
|||
} catch (err: any) { |
|||
const responseData = err?.response?.data; |
|||
const errors = responseData?.errors; |
|||
const message = |
|||
errors?.code?.[0] || |
|||
errors?.service?.[0] || |
|||
errors?.object_id?.[0] || |
|||
responseData?.detail || |
|||
responseData?.message || |
|||
err?.message || |
|||
"Invalid discount code"; |
|||
|
|||
return { |
|||
valid: false, |
|||
code, |
|||
originalPrice: 0, |
|||
discountedPrice: 0, |
|||
discountAmount: 0, |
|||
discountPercentage: 0, |
|||
message, |
|||
}; |
|||
} |
|||
} |
|||
|
|||
export function useValidateDiscountMutation( |
|||
options?: MutationOptions<CheckDiscountResult, ValidateDiscountParams>, |
|||
) { |
|||
return useMutation({ |
|||
...options, |
|||
mutationFn: validateDiscountCode, |
|||
}); |
|||
} |
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue