完善个人中心页面

This commit is contained in:
Eamon
2026-09-04 13:21:47 +08:00
parent 6d6d300203
commit f59e929843
27 changed files with 614 additions and 414 deletions

View File

@@ -27,6 +27,7 @@
"tailwindcss": "^4.3.0",
"tw-animate-css": "^1.4.0",
"zod": "^4.4.3",
"zustand": "^5.0.15",
},
"devDependencies": {
"@biomejs/biome": "2.4.16",
@@ -1258,6 +1259,8 @@
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "https://registry.npmmirror.com/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
"zustand": ["zustand@5.0.15", "https://registry.npmmirror.com/zustand/-/zustand-5.0.15.tgz", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A=="],
"zwitch": ["zwitch@2.0.4", "https://registry.npmmirror.com/zwitch/-/zwitch-2.0.4.tgz", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
"@dotenvx/dotenvx/commander": ["commander@11.1.0", "https://registry.npmmirror.com/commander/-/commander-11.1.0.tgz", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],

View File

@@ -30,7 +30,8 @@
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.0",
"tw-animate-css": "^1.4.0",
"zod": "^4.4.3"
"zod": "^4.4.3",
"zustand": "^5.0.15"
},
"devDependencies": {
"@biomejs/biome": "2.4.16",

View File

@@ -18,6 +18,7 @@ import {
import { type ReactNode, useState } from "react"
import { Link } from "react-router-dom"
import ProfileOrLogin from "@/components/profileOrLogin"
import { useLayoutStore } from "@/components/stores/layout"
import { Button } from "@/components/ui/button"
import {
Tooltip,
@@ -27,11 +28,10 @@ import {
} from "@/components/ui/tooltip"
import { cn } from "@/lib/utils"
import logoAvatar from "./assets/logo-avatar.svg"
import { useLayout } from "./layout-context"
import { AdminNavMenu } from "./nav-menu"
export function Shell(props: { children: ReactNode }) {
const { navbar } = useLayout()
const navbar = useLayoutStore(state => state.navbar)
return (
<div
data-expand={navbar}
@@ -50,7 +50,7 @@ export function Shell(props: { children: ReactNode }) {
}
export function Content(props: { children: ReactNode }) {
const { navbar } = useLayout()
const navbar = useLayoutStore(state => state.navbar)
return (
<div
data-expand={navbar}
@@ -68,7 +68,8 @@ export function Content(props: { children: ReactNode }) {
}
export function Mask() {
const { navbar, setNavbar } = useLayout()
const navbar = useLayoutStore(state => state.navbar)
const setNavbar = useLayoutStore(state => state.setNavbar)
return (
<button
data-expand={navbar}
@@ -85,7 +86,8 @@ export function Mask() {
}
export function Header() {
const { navbar, toggleNavbar } = useLayout()
const navbar = useLayoutStore(state => state.navbar)
const toggleNavbar = useLayoutStore(state => state.toggleNavbar)
return (
<header className="flex-none h-16 flex items-stretch">
<div className="flex-none flex items-center">
@@ -108,7 +110,7 @@ export function Header() {
}
export function Navbar() {
const { navbar } = useLayout()
const navbar = useLayoutStore(state => state.navbar)
return (
<nav
@@ -248,7 +250,7 @@ function NavItem(props: {
expand?: boolean
}) {
const [open, setOpen] = useState(false)
const { setNavbar } = useLayout()
const setNavbar = useLayoutStore(state => state.setNavbar)
const handleOpenChange = (open: boolean) => {
if (!props.expand) {

View File

@@ -1,38 +0,0 @@
import type {
AccountInfo,
ConsumptionStats,
DashboardBalance,
IpAccountStats,
} from "@/lib/models/dashboard"
// TODO: 后端仪表盘接口就绪后删除(见 src/api/dashboard.ts)
export const MOCK_BALANCE: DashboardBalance = {
balance: 68.0,
hCoin: 68.0,
}
export const MOCK_ACCOUNT_INFO: AccountInfo = {
phone: "191****1234",
qq: "123456123",
wechat: "123456123",
email: "123456123@qq.com",
taobao: "123456123",
}
export const MOCK_CONSUMPTION: ConsumptionStats = {
today: 30.0,
month: 30.0,
todayRefund: 30.0,
year: 30.0,
todayRecharge: 30.0,
monthRecharge: 30.0,
monthRefund: 30.0,
}
export const MOCK_IP_STATS: IpAccountStats = {
using: 30,
total: 50,
expired: 20,
yearConsumption: 30,
}

View File

@@ -1,15 +1,14 @@
import { Check } from "lucide-react"
import { type ReactNode, useEffect, useState } from "react"
import { fetchAgreementStatus, fetchRealNameStatus } from "@/api/agreement"
import { getUserInfo } from "@/api/token"
import type { UserInfoRecord } from "@/api/token"
import AgreementDialog from "@/components/composites/dialogs/agreementDialog"
import {
EditInfoDialog,
type EditInfoValues,
} from "@/components/composites/dialogs/editInfoDialog"
import { ChangePwdDialog } from "@/components/composites/dialogs/changePwdDialog"
import { EditInfoDialog } from "@/components/composites/dialogs/editInfoDialog"
import RealNameDialog from "@/components/composites/dialogs/realNameDialog"
import Page from "@/components/page"
import { QrCodeImage } from "@/components/qrCodeImage"
import { useDashboardStore } from "@/components/stores/dashboard"
import { useProfileStore } from "@/components/stores/profile"
import { Button } from "@/components/ui/button"
import {
Dialog,
@@ -17,6 +16,12 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import type {
AccountInfo,
ConsumptionStats,
DashboardBalance,
IpAccountStats,
} from "@/lib/models/dashboard"
import { cn } from "@/lib/utils"
import b3 from "../assets/b3.webp"
import b5 from "../assets/b5.webp"
@@ -29,12 +34,6 @@ import b11 from "../assets/b11.webp"
import b12 from "../assets/b12.webp"
import banner from "../assets/banner.webp"
import banner2 from "../assets/banner2.webp"
import {
MOCK_ACCOUNT_INFO,
MOCK_BALANCE,
MOCK_CONSUMPTION,
MOCK_IP_STATS,
} from "./mock"
const fmt = (n: number) => n.toFixed(2)
@@ -44,9 +43,8 @@ const MANAGER_QR_URLS: Record<number, string> = {
1017: "https://work.weixin.qq.com/u/vc7e4f48bc9e52e3d0?v=4.1.8.133653",
}
function readUserInfo() {
const raw = getUserInfo<Record<string, unknown>>()
const info = (raw ?? {}) as Record<string, unknown>
function readUserInfo(userInfo: UserInfoRecord | null) {
const info = userInfo ?? {}
const phone = String(
info.Phone ??
info.LoginCode ??
@@ -66,54 +64,67 @@ function readUserInfo() {
}
}
const num = (value: unknown) =>
typeof value === "number" && Number.isFinite(value) ? value : 0
export default function DashboardPage() {
// ========== 数据定义(待接口就绪后改为 useEffect 拉取) ==========
const balanceData = MOCK_BALANCE
const accountInfo = MOCK_ACCOUNT_INFO
const consumptionData = MOCK_CONSUMPTION
const ipAccountData = MOCK_IP_STATS
const { phone, managerQrUrl } = readUserInfo()
// 实名认证状态(php-api /agent/index/isverify)、网络安全协议签署状态
// (php-api /tencent/index/get_is_upload)
const [verified, setVerified] = useState<boolean | null>(null)
const [agreementSigned, setAgreementSigned] = useState<boolean | null>(null)
const refreshVerifyState = () => {
if (!phone) return
void fetchRealNameStatus(phone).then(res => {
if (res.success) setVerified(res.data)
})
}
const refreshAgreementState = () => {
void fetchAgreementStatus().then(res => {
if (res.success) setAgreementSigned(res.data)
})
}
const apiIndex = useDashboardStore(state => state.data)
const agreementSigned = useDashboardStore(state => state.agreementSigned)
const refresh = useDashboardStore(state => state.refresh)
const refreshAgreement = useDashboardStore(state => state.refreshAgreement)
const sessionUserInfo = useProfileStore(state => state.userInfo)
// 页面挂载时加载一次账户总览与协议签署状态
useEffect(() => {
if (phone) {
void fetchRealNameStatus(phone).then(res => {
if (res.success) setVerified(res.data)
})
void refresh()
void refreshAgreement()
}, [refresh, refreshAgreement])
const user = apiIndex?.UserModel
const statistic = apiIndex?.Statistic
const account = apiIndex?.AccountModel
const balanceData: DashboardBalance = {
balance: num(user?.RestAmount),
hCoin: num(user?.ju_money),
}
void fetchAgreementStatus().then(res => {
if (res.success) setAgreementSigned(res.data)
})
}, [phone])
const accountInfo: AccountInfo = {
phone: String(user?.LoginCode ?? user?.Phone ?? ""),
qq: String(user?.QQ ?? ""),
wechat: String(user?.Wx ?? ""),
email: String(user?.Email ?? ""),
taobao: "",
}
const consumptionData: ConsumptionStats = {
today: num(statistic?.TodayExpend),
todayRefund: num(statistic?.TodayRefund),
todayRecharge: num(statistic?.TodayCharege),
month: num(statistic?.MonthExpend),
monthRefund: num(statistic?.MonthRefund),
monthRecharge: num(statistic?.MonthCharege),
year: num(statistic?.YearExpend),
}
const ipAccountData: IpAccountStats = {
total: num(account?.TotalCount),
expired: num(account?.ExpriedCount),
using: Math.max(num(account?.TotalCount) - num(account?.ExpriedCount), 0),
yearConsumption: 0,
}
const { phone, managerQrUrl } = readUserInfo(sessionUserInfo)
// 实名认证状态:(0-未认证;1-已认证;2-已禁用)
const verified = user ? user.is_verify === 1 : null
const [editDialogOpen, setEditDialogOpen] = useState(false)
const [changePwdOpen, setChangePwdOpen] = useState(false)
const [realNameOpen, setRealNameOpen] = useState(false)
const [agreementOpen, setAgreementOpen] = useState(false)
const [managerQrOpen, setManagerQrOpen] = useState(false)
const handleSaveInfo = (data: EditInfoValues) => {
// TODO: 接入 src/api/user.ts updateUserProfile
void data
}
// 未返回状态(请求中/失败/无手机号)时默认按「未实名/未签署」展示,
// 接口成功后自动更新为真实状态
const verifyBadge = (() => {
@@ -168,9 +179,22 @@ export default function DashboardPage() {
<div className="flex min-w-0 items-center gap-2.5">
<h3 className="shrink-0 text-base font-semibold">账户信息</h3>
{verifyBadge}
{user?.is_agent === 1 && (
<span className="inline-flex shrink-0 items-center rounded-full bg-emerald-50 px-2 py-0.5 text-xs font-medium text-emerald-600">
经销商
</span>
)}
</div>
<div className="flex shrink-0 items-center gap-4">
{agreementAction()}
{user?.is_agent === 1 && (
<a
href="/user/api"
className="shrink-0 text-xs text-blue-600 hover:text-blue-700"
>
代理商API接口
</a>
)}
<Button
size="sm"
variant="outline"
@@ -184,41 +208,11 @@ export default function DashboardPage() {
<div className="grid grid-cols-1 md:grid-cols-2">
<div className="flex items-center gap-4 p-5 md:border-r md:border-dashed md:border-gray-200">
<div className="flex w-1/2 shrink-0 flex-col items-center gap-1.5">
<p className="text-center text-[11px] leading-4 text-muted-foreground">
扫二维码联系
<br />
我的客户经理
</p>
<div className="group relative">
<button
type="button"
onClick={() => managerQrUrl && setManagerQrOpen(true)}
className="block size-16 overflow-hidden rounded-lg border border-gray-200"
>
{managerQrUrl ? (
<QrCodeImage text={managerQrUrl} size={64} />
) : (
<img
src="/logo.png"
alt="账号二维码"
className="size-full object-cover"
/>
)}
</button>
{managerQrUrl && (
<div className="pointer-events-none absolute left-20 top-0 z-50 hidden rounded-lg border border-gray-200 bg-white p-2 shadow-lg group-hover:block max-md:hidden">
<QrCodeImage text={managerQrUrl} size={200} />
</div>
)}
</div>
</div>
<div className="flex w-1/2 min-w-0 flex-col justify-center gap-3">
<div className="min-w-0">
<p className="text-xs text-muted-foreground">手机号/用户名</p>
<p className="mt-0.5 truncate text-base font-medium">
{phone || accountInfo.phone}
{accountInfo.phone || phone}
</p>
</div>
<div>
@@ -227,7 +221,7 @@ export default function DashboardPage() {
<span className="font-mono text-sm">********</span>
<button
type="button"
onClick={() => setEditDialogOpen(true)}
onClick={() => setChangePwdOpen(true)}
className="shrink-0 text-xs text-blue-600 hover:text-blue-700"
>
修改密码
@@ -376,17 +370,24 @@ export default function DashboardPage() {
<EditInfoDialog
open={editDialogOpen}
onOpenChange={setEditDialogOpen}
onSave={handleSaveInfo}
initialData={{
qq: accountInfo.qq,
wechat: accountInfo.wechat,
taobao: accountInfo.taobao,
email: accountInfo.email,
}}
onSaved={refresh}
/>
<ChangePwdDialog open={changePwdOpen} onOpenChange={setChangePwdOpen} />
<RealNameDialog
open={realNameOpen}
onOpenChange={setRealNameOpen}
onVerified={refreshVerifyState}
onVerified={refresh}
/>
<AgreementDialog
open={agreementOpen}
onOpenChange={setAgreementOpen}
onSigned={refreshAgreementState}
onSigned={refreshAgreement}
/>
<Dialog open={managerQrOpen} onOpenChange={setManagerQrOpen}>
<DialogContent className="sm:max-w-xs">

View File

@@ -1,59 +1,24 @@
import { type ReactNode, useEffect } from "react"
import { useLayout } from "./layout-context"
type Breakpoints = {
sm: boolean
md: boolean
lg: boolean
xl: boolean
}
const breakpoints: Breakpoints = { sm: false, md: false, lg: false, xl: false }
export function useBreakpoint() {
return breakpoints
}
export const bp = breakpoints
import { useClientStore } from "@/components/stores/client"
import { useLayoutStore } from "@/components/stores/layout"
export default function Effects(props: { children?: ReactNode }) {
const { setNavbar } = useLayout()
const md = useClientStore(state => state.breakpoint.md)
const setNavbar = useLayoutStore(state => state.setNavbar)
useEffect(() => {
const sm = window.matchMedia("(width >= 40rem)")
const md = window.matchMedia("(width >= 48rem)")
const lg = window.matchMedia("(width >= 64rem)")
const xl = window.matchMedia("(width >= 80rem)")
breakpoints.sm = sm.matches
breakpoints.md = md.matches
breakpoints.lg = lg.matches
breakpoints.xl = xl.matches
setNavbar(md.matches)
sm.addEventListener("change", e => {
breakpoints.sm = e.matches
})
md.addEventListener("change", e => {
breakpoints.md = e.matches
setNavbar(e.matches)
})
lg.addEventListener("change", e => {
breakpoints.lg = e.matches
})
xl.addEventListener("change", e => {
breakpoints.xl = e.matches
})
// 断点变化时同步侧边栏默认状态:桌面端展开、移动端收起
setNavbar(md)
}, [md, setNavbar])
useEffect(() => {
const html = document.documentElement
const originalFontSize = html.style.fontSize
html.style.fontSize = "16px"
return () => {
html.style.fontSize = originalFontSize
}
}, [setNavbar])
}, [])
return <>{props.children}</>
}

View File

@@ -1,27 +0,0 @@
import { createContext, type ReactNode, useContext, useState } from "react"
type LayoutState = {
navbar: boolean
setNavbar: (navbar: boolean) => void
toggleNavbar: () => void
}
const LayoutContext = createContext<LayoutState | null>(null)
export function LayoutProvider(props: { children: ReactNode }) {
const [navbar, setNavbar] = useState(false)
const toggleNavbar = () => setNavbar(!navbar)
return (
<LayoutContext value={{ navbar, setNavbar, toggleNavbar }}>
{props.children}
</LayoutContext>
)
}
export function useLayout() {
const ctx = useContext(LayoutContext)
if (!ctx) throw new Error("useLayout must be used within LayoutProvider")
return ctx
}

View File

@@ -1,11 +1,10 @@
import { Outlet } from "react-router-dom"
import { Content, Header, Mask, Navbar, Shell } from "./clients"
import Effects from "./effects"
import { LayoutProvider } from "./layout-context"
export default function AdminLayout() {
return (
<LayoutProvider>
<>
<Effects />
<div className="relative h-dvh overflow-hidden">
<Shell>
@@ -45,6 +44,6 @@ export default function AdminLayout() {
<Outlet />
</Content>
</div>
</LayoutProvider>
</>
)
}

View File

@@ -163,7 +163,7 @@ export default function RefundOrdersPage() {
</div>
<div className="bg-white rounded-lg p-4 flex flex-col gap-4">
<h3 className="font-semibold text-lg">退款订单管理</h3>
<h3 className="font-semibold text-lg">退货订单管理</h3>
<DataTable
data={paged}
status="done"

View File

@@ -1,41 +1,17 @@
import type { ApiResponse } from "@/lib/api"
import { callByUser } from "./base"
import { fetchHttpBalance } from "./http"
import type { ApiIndexItem } from "@/lib/models/dashboard"
import { callPublic } from "./base"
// ==================== 仪表盘 ====================
// 余额走 php-api,订单/消费统计走 .NET;账号信息与 IP 统计接口待后端确认。
export async function fetchDashboardBalance(): Promise<ApiResponse<number>> {
return fetchHttpBalance()
}
export async function fetchDashboardConsumption(
params: Record<string, unknown>,
): Promise<ApiResponse<Record<string, unknown>>> {
return await callByUser<Record<string, unknown>>(
"/api/course/v1/order/UserConsumeStatistics",
params,
"GET",
)
}
// TODO: 账号信息/IP 统计接口路径待后端确认
export async function fetchDashboardAccountInfo(): Promise<
ApiResponse<Record<string, unknown>>
export async function fetchApiIndex(): Promise<
ApiResponse<ApiIndexItem | null>
> {
return await callByUser<Record<string, unknown>>(
"/api/baseinfo/v1/user/Info",
undefined,
"GET",
)
}
export async function fetchDashboardIpStats(): Promise<
ApiResponse<Record<string, unknown>>
> {
return await callByUser<Record<string, unknown>>(
"/api/course/v1/order/IpAccountStatistics",
const res = await callPublic<ApiIndexItem | ApiIndexItem[]>(
"/user/ApiIndex",
undefined,
"GET",
)
if (!res.success) return res
// 兼容后端返回单对象或数组两种格式
const item = Array.isArray(res.data) ? res.data[0] : res.data
return { success: true, data: item ?? null }
}

View File

@@ -3,6 +3,8 @@ export const AUTH_EVENT = "auth-change"
const TOKEN_KEY = "auth_token"
const USER_KEY = "auth_user"
export type UserInfoRecord = Record<string, unknown>
export function readCookie(name: string): string | null {
const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`))
return match ? decodeURIComponent(match[1]) : null

View File

@@ -1,6 +1,6 @@
import type { ApiResponse } from "@/lib/api"
import type { UserItem, UserQueryParams } from "@/lib/models/user"
import { callByUser } from "./base"
import { callByUser, callPublic } from "./base"
// ==================== 用户管理(.NET /api/baseinfo/v1/user/*) ====================
@@ -42,3 +42,24 @@ export async function updateUserProfile(
data,
)
}
// ==================== 个人中心资料/密码(.NET /user/*,cookie 会话) ====================
// 编辑资料:老项目 /user/UpdateInfo(QQ/Wx/TaoBao/Email)
export async function updateUserInfo(data: {
QQ: string
Wx: string
TaoBao: string
Email: string
}): Promise<ApiResponse<undefined>> {
return await callPublic<undefined>("/user/UpdateInfo", data)
}
// 修改密码:老项目 /user/UpdatePwd(OldPwd/NewPwd/ConfirmPwd)
export async function updateUserPwd(data: {
OldPwd: string
NewPwd: string
ConfirmPwd: string
}): Promise<ApiResponse<undefined>> {
return await callPublic<undefined>("/user/UpdatePwd", data)
}

View File

@@ -1,16 +1,9 @@
import { useEffect, useState } from "react"
import { Navigate, useLocation } from "react-router-dom"
import { AUTH_EVENT, isAuthed } from "@/api/token"
import { useProfileStore } from "@/components/stores/profile"
export default function AuthGuard({ children }: { children: React.ReactNode }) {
const location = useLocation()
const [isValid, setIsValid] = useState(isAuthed)
useEffect(() => {
const update = () => setIsValid(isAuthed())
window.addEventListener(AUTH_EVENT, update)
return () => window.removeEventListener(AUTH_EVENT, update)
}, [])
const isValid = useProfileStore(state => state.token !== null)
if (!isValid) {
return (

View File

@@ -0,0 +1,170 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { Eye, EyeOff } from "lucide-react"
import { useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { updateUserPwd } from "@/api/user"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { FieldError } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
type ChangePwdValues = {
oldPwd: string
newPwd: string
confirmPwd: string
}
const changePwdSchema = z
.object({
oldPwd: z.string().min(1, "请输入原密码"),
newPwd: z.string().min(1, "请输入新密码"),
confirmPwd: z.string().min(1, "请再次输入新密码"),
})
.refine(v => v.newPwd === v.confirmPwd, {
message: "两次输入的密码不一致",
path: ["confirmPwd"],
})
function PasswordInput(props: {
value: string
onChange: (value: string) => void
placeholder?: string
}) {
const [show, setShow] = useState(false)
return (
<div className="relative">
<Input
value={props.value}
onChange={e => props.onChange(e.target.value)}
type={show ? "text" : "password"}
placeholder={props.placeholder}
className="h-11 bg-gray-50 border-gray-200 pr-10"
/>
<button
type="button"
onClick={() => setShow(!show)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
>
{show ? <Eye className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
</button>
</div>
)
}
export function ChangePwdDialog({
open,
onOpenChange,
}: {
open: boolean
onOpenChange: (open: boolean) => void
}) {
const [submitting, setSubmitting] = useState(false)
const form = useForm<ChangePwdValues>({
resolver: zodResolver(changePwdSchema),
defaultValues: { oldPwd: "", newPwd: "", confirmPwd: "" },
})
const handleOpenChange = (next: boolean) => {
onOpenChange(next)
if (!next) form.reset()
}
const onSubmit = async (data: ChangePwdValues) => {
setSubmitting(true)
const res = await updateUserPwd({
OldPwd: data.oldPwd,
NewPwd: data.newPwd,
ConfirmPwd: data.confirmPwd,
})
setSubmitting(false)
if (!res.success) {
toast.error(res.message)
return
}
toast.success("密码修改成功")
handleOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-h-[85dvh] overflow-y-auto sm:max-w-120 p-6">
<DialogHeader>
<DialogTitle className="text-xl font-semibold text-center">
修改密码
</DialogTitle>
</DialogHeader>
<form className="space-y-4 mt-2" onSubmit={form.handleSubmit(onSubmit)}>
<div className="space-y-1.5">
<Label className="text-sm text-gray-600">原密码</Label>
<Controller
name="oldPwd"
control={form.control}
render={({ field, fieldState }) => (
<>
<PasswordInput
value={field.value}
onChange={field.onChange}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</>
)}
/>
</div>
<div className="space-y-1.5">
<Label className="text-sm text-gray-600">新密码</Label>
<Controller
name="newPwd"
control={form.control}
render={({ field, fieldState }) => (
<>
<PasswordInput
value={field.value}
onChange={field.onChange}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</>
)}
/>
</div>
<div className="space-y-1.5">
<Label className="text-sm text-gray-600">确认新密码</Label>
<Controller
name="confirmPwd"
control={form.control}
render={({ field, fieldState }) => (
<>
<PasswordInput
value={field.value}
onChange={field.onChange}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</>
)}
/>
</div>
<Button
type="submit"
disabled={submitting}
className="w-full h-11 mt-2 bg-blue-600 hover:bg-blue-700 text-white font-medium"
>
{submitting ? "提交中..." : "提交"}
</Button>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -1,8 +1,9 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { Eye, EyeOff } from "lucide-react"
import { useEffect, useState } from "react"
import { Controller, useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { updateUserInfo } from "@/api/user"
import { Button } from "@/components/ui/button"
import {
Dialog,
@@ -15,51 +16,45 @@ import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
export type EditInfoValues = {
username: string
taobao: string
password: string
email: string
wechat: string
qq: string
wechat: string
taobao: string
email: string
}
const editInfoSchema = z.object({
username: z.string().trim().min(1, "请输入用户名"),
qq: z.string(),
wechat: z.string(),
taobao: z.string(),
password: z.string().min(1, "请输入密码"),
email: z
.string()
.refine(
v => !v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
"请输入正确的邮箱",
),
wechat: z.string(),
qq: z.string(),
})
interface EditInfoDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
initialData?: EditInfoValues
onSave?: (data: EditInfoValues) => void
onSaved?: () => void
}
const DEFAULT_INITIAL_DATA: EditInfoValues = {
username: "191****1234",
taobao: "191****1234",
password: "********",
email: "123456123@qq.com",
wechat: "",
qq: "",
wechat: "",
taobao: "",
email: "",
}
export function EditInfoDialog({
open,
onOpenChange,
initialData = DEFAULT_INITIAL_DATA,
onSave,
onSaved,
}: EditInfoDialogProps) {
const [showPassword, setShowPassword] = useState(false)
const [submitting, setSubmitting] = useState(false)
const form = useForm<EditInfoValues>({
resolver: zodResolver(editInfoSchema),
@@ -72,9 +67,23 @@ export function EditInfoDialog({
}
}, [open, initialData, form])
const onSubmit = (data: EditInfoValues) => {
onSave?.(data)
const onSubmit = async (data: EditInfoValues) => {
setSubmitting(true)
const res = await updateUserInfo({
QQ: data.qq,
Wx: data.wechat,
TaoBao: data.taobao,
Email: data.email,
})
setSubmitting(false)
if (!res.success) {
toast.error(res.message)
return
}
toast.success("保存成功")
onOpenChange(false)
onSaved?.()
}
return (
@@ -88,18 +97,23 @@ export function EditInfoDialog({
<form className="space-y-4 mt-2" onSubmit={form.handleSubmit(onSubmit)}>
<div className="space-y-1.5">
<Label className="text-sm text-gray-600">用户名</Label>
<Label className="text-sm text-gray-600">QQ号</Label>
<Controller
name="username"
name="qq"
control={form.control}
render={({ field, fieldState }) => (
<>
<Input
{...field}
className="h-11 bg-gray-50 border-gray-200"
render={({ field }) => (
<Input {...field} className="h-11 bg-gray-50 border-gray-200" />
)}
/>
<FieldError>{fieldState.error?.message}</FieldError>
</>
</div>
<div className="space-y-1.5">
<Label className="text-sm text-gray-600">微信号</Label>
<Controller
name="wechat"
control={form.control}
render={({ field }) => (
<Input {...field} className="h-11 bg-gray-50 border-gray-200" />
)}
/>
</div>
@@ -115,37 +129,6 @@ export function EditInfoDialog({
/>
</div>
<div className="space-y-1.5">
<Label className="text-sm text-gray-600">密码</Label>
<Controller
name="password"
control={form.control}
render={({ field, fieldState }) => (
<>
<div className="relative">
<Input
{...field}
type={showPassword ? "text" : "password"}
className="h-11 bg-gray-50 border-gray-200 pr-10"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
</div>
<FieldError>{fieldState.error?.message}</FieldError>
</>
)}
/>
</div>
<div className="space-y-1.5">
<Label className="text-sm text-gray-600">邮箱</Label>
<Controller
@@ -163,41 +146,12 @@ export function EditInfoDialog({
/>
</div>
<div className="space-y-1.5">
<Label className="text-sm text-gray-600">微信</Label>
<Controller
name="wechat"
control={form.control}
render={({ field }) => (
<Input
{...field}
placeholder="请输入"
className="h-11 bg-gray-50 border-gray-200"
/>
)}
/>
</div>
<div className="space-y-1.5">
<Label className="text-sm text-gray-600">QQ</Label>
<Controller
name="qq"
control={form.control}
render={({ field }) => (
<Input
{...field}
placeholder="请输入"
className="h-11 bg-gray-50 border-gray-200"
/>
)}
/>
</div>
<Button
type="submit"
disabled={submitting}
className="w-full h-11 mt-2 bg-blue-600 hover:bg-blue-700 text-white font-medium"
>
保存
{submitting ? "保存中..." : "保存"}
</Button>
</form>
</DialogContent>

View File

@@ -1,22 +1,11 @@
import { useEffect, useState } from "react"
import { NavLink, useNavigate } from "react-router-dom"
import { logout } from "@/api/auth"
import { AUTH_EVENT, isAuthed } from "@/api/token"
import { useProfileStore } from "@/components/stores/profile"
export default function ProfileOrLogin() {
const [authed, setAuthed] = useState(isAuthed)
const authed = useProfileStore(state => state.token !== null)
const navigate = useNavigate()
useEffect(() => {
const update = () => setAuthed(isAuthed())
window.addEventListener("focus", update)
window.addEventListener(AUTH_EVENT, update)
return () => {
window.removeEventListener("focus", update)
window.removeEventListener(AUTH_EVENT, update)
}
}, [])
const handleLogout = async () => {
await logout()
}

View File

@@ -0,0 +1,11 @@
import { create } from "zustand"
import { API_BASE_URL } from "@/lib/api"
// ==================== 应用配置 ====================
// 后端地址等运行时配置统一从 store 读取,初始值来自 import.meta.env(见 lib/api.ts)
type AppState = {
apiUrl: string
}
export const useAppStore = create<AppState>()(() => ({ apiUrl: API_BASE_URL }))

View File

@@ -0,0 +1,54 @@
import { create } from "zustand"
type ClientState = {
breakpoint: {
sm: boolean
md: boolean
lg: boolean
xl: boolean
}
}
type ClientActions = {
setBreakpoints: (breakpoints: Partial<ClientState["breakpoint"]>) => void
}
export type ClientStore = ClientState & ClientActions
export const useClientStore = create<ClientStore>()(set => ({
breakpoint: { sm: false, md: false, lg: false, xl: false },
setBreakpoints: breakpoints =>
set(state => ({
breakpoint: { ...state.breakpoint, ...breakpoints },
})),
}))
let initialized = false
// 应用入口调用一次,开始监听窗口断点变化
export function initClientStore() {
if (initialized) return
initialized = true
const queries = {
sm: window.matchMedia("(width >= 40rem)"),
md: window.matchMedia("(width >= 48rem)"),
lg: window.matchMedia("(width >= 64rem)"),
xl: window.matchMedia("(width >= 80rem)"),
}
const setBreakpoints = useClientStore.getState().setBreakpoints
setBreakpoints({
sm: queries.sm.matches,
md: queries.md.matches,
lg: queries.lg.matches,
xl: queries.xl.matches,
})
for (const key of Object.keys(queries) as (keyof typeof queries)[]) {
queries[key].addEventListener("change", e => {
setBreakpoints({ [key]: e.matches })
})
}
}

View File

@@ -0,0 +1,41 @@
import { create } from "zustand"
import { fetchAgreementStatus } from "@/api/agreement"
import { fetchApiIndex } from "@/api/dashboard"
import type { ApiIndexItem } from "@/lib/models/dashboard"
// ==================== 个人中心账户总览 ====================
// 数据源:.NET /user/ApiIndex;协议签署状态:php-api /tencent/index/get_is_upload
export type DashboardState = {
data: ApiIndexItem | null
agreementSigned: boolean | null
loading: boolean
error: string | null
}
type DashboardActions = {
refresh: () => Promise<void>
refreshAgreement: () => Promise<void>
}
export type DashboardStore = DashboardState & DashboardActions
export const useDashboardStore = create<DashboardStore>()(set => ({
data: null,
agreementSigned: null,
loading: false,
error: null,
refresh: async () => {
set({ loading: true })
const res = await fetchApiIndex()
if (res.success) {
set({ data: res.data, error: null, loading: false })
} else {
set({ error: res.message, loading: false })
}
},
refreshAgreement: async () => {
const res = await fetchAgreementStatus()
if (res.success) set({ agreementSigned: res.data })
},
}))

View File

@@ -0,0 +1,20 @@
import { create } from "zustand"
type LayoutState = {
navbar: boolean
}
type LayoutActions = {
setNavbar: (navbar: boolean) => void
toggleNavbar: () => void
}
export type LayoutStore = LayoutState & LayoutActions
export const useLayoutStore = create<LayoutStore>()(set => ({
navbar: false,
setNavbar: navbar => set({ navbar }),
toggleNavbar: () => set(state => ({ navbar: !state.navbar })),
}))

View File

@@ -0,0 +1,34 @@
import { create } from "zustand"
import {
AUTH_EVENT,
getUserInfo,
getUserToken,
type UserInfoRecord,
} from "@/api/token"
export type ProfileState = {
token: string | null
userInfo: UserInfoRecord | null
}
type ProfileActions = {
refreshFromStorage: () => void
}
export type ProfileStore = ProfileState & ProfileActions
export const useProfileStore = create<ProfileStore>()(set => ({
token: getUserToken(),
userInfo: getUserInfo<UserInfoRecord>(),
refreshFromStorage: () => {
set({ token: getUserToken(), userInfo: getUserInfo<UserInfoRecord>() })
},
}))
// 应用入口调用一次,监听登录态变化(含跨标签页 focus 同步)
export function initProfileStore() {
const sync = () => useProfileStore.getState().refreshFromStorage()
window.addEventListener(AUTH_EVENT, sync)
window.addEventListener("focus", sync)
}

View File

@@ -1,17 +1,18 @@
import { Menu, User } from "lucide-react"
import { useEffect, useRef, useState, useSyncExternalStore } from "react"
import { useRef, useState, useSyncExternalStore } from "react"
import { NavLink, useNavigate } from "react-router-dom"
import { AUTH_EVENT, isAuthed } from "@/api/token"
import ProductDropdown from "@/components/productDropdown"
import ProfileOrLogin from "@/components/profileOrLogin"
import { useClientStore } from "@/components/stores/client"
import { useProfileStore } from "@/components/stores/profile"
import Wrap from "@/components/wrap"
import { useMediaQuery } from "@/lib/hooks/useMediaQuery"
import { cn } from "@/lib/utils"
import MobileMenu from "./_components/header/menu-mobile"
export default function Header() {
const navigate = useNavigate()
const isWideDesktop = useMediaQuery("(min-width: 80rem)")
const authed = useProfileStore(state => state.token !== null)
const isWideDesktop = useClientStore(state => state.breakpoint.xl)
const scroll = useSyncExternalStore(
callback => {
window.addEventListener("scroll", callback)
@@ -30,17 +31,6 @@ export default function Header() {
// 移动端状态
const [mobileMenu, setMobileMenu] = useState(false)
const [authed, setAuthed] = useState(isAuthed)
useEffect(() => {
const update = () => setAuthed(isAuthed())
window.addEventListener("focus", update)
window.addEventListener(AUTH_EVENT, update)
return () => {
window.removeEventListener("focus", update)
window.removeEventListener(AUTH_EVENT, update)
}
}, [])
return (
<header className={cn("fixed top-0 left-0 w-screen z-50 flex flex-col")}>

View File

@@ -2,8 +2,8 @@ import { ChevronLeft, ChevronRight } from "lucide-react"
import type { ReactNode } from "react"
import { useRef, useState } from "react"
import { useNavigate } from "react-router-dom"
import { useClientStore } from "@/components/stores/client"
import Wrap from "@/components/wrap"
import { useIsMobile } from "@/lib/hooks/useMediaQuery"
import banner from "./_assets/banner.webp"
import s1 from "./_assets/s1.webp"
import s2 from "./_assets/s2.webp"
@@ -22,14 +22,15 @@ import Common from "./_components/header/common"
export default function HomePage() {
const navigate = useNavigate()
// 免费试用:无论是否登录都进入产品购买页(下单时才校验登录)
const handleFreeTrial = () => {
navigate("/login")
navigate("/product")
}
const scrollContainerRef = useRef<HTMLUListElement>(null)
const [showLeftArrow, setShowLeftArrow] = useState(false)
const [showRightArrow, setShowRightArrow] = useState(true)
const isMobile = useIsMobile()
const isMobile = useClientStore(state => !state.breakpoint.md)
const scroll = (direction: "left" | "right") => {
if (!scrollContainerRef.current) return

View File

@@ -1,4 +1,5 @@
import { useNavigate } from "react-router-dom"
import { useProfileStore } from "@/components/stores/profile"
import { Button } from "@/components/ui/button"
import type { Product } from "@/lib/models/product"
import vector from "../_assets/vector.webp"
@@ -9,6 +10,16 @@ type ProductGridProps = {
export default function ProductGrid({ products }: ProductGridProps) {
const navigate = useNavigate()
const authed = useProfileStore(state => state.token !== null)
const handleBuy = (product: Product) => {
// 未登录先登录,已登录进入购买确认页
if (!authed) {
navigate("/login")
return
}
navigate("/product/buy", { state: { product } })
}
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 mt-6 gap-6">
@@ -75,7 +86,7 @@ export default function ProductGrid({ products }: ProductGridProps) {
<Button
variant="outline"
className="w-full text-blue-500 border-blue-400 hover:bg-blue-50"
onClick={() => navigate("/product/buy", { state: { product } })}
onClick={() => handleBuy(product)}
>
立即购买
</Button>

View File

@@ -1,36 +0,0 @@
import { useSyncExternalStore } from "react"
const subscribeMediaQuery = (query: string) => (callback: () => void) => {
if (typeof window === "undefined") return () => {}
const mql = window.matchMedia(query)
mql.addEventListener("change", callback)
return () => mql.removeEventListener("change", callback)
}
const getMediaQuerySnapshot = (query: string) => () => {
if (typeof window === "undefined") return false
return window.matchMedia(query).matches
}
export function useMediaQuery(query: string): boolean {
return useSyncExternalStore(
subscribeMediaQuery(query),
getMediaQuerySnapshot(query),
() => false,
)
}
// 移动端:< 768px(对应 Tailwind md 断点以下)
export function useIsMobile(): boolean {
return useMediaQuery("(max-width: 47.999rem)")
}
// 桌面端:>= 768px
export function useIsDesktop(): boolean {
return useMediaQuery("(min-width: 48rem)")
}
// 窄桌面/平板横屏:< 1280px(对应 Tailwind xl 断点以下)
export function useIsNarrowDesktop(): boolean {
return useMediaQuery("(max-width: 79.999rem)")
}

View File

@@ -1,3 +1,61 @@
// ==================== /user/ApiIndex 账户总览接口返回结构 ====================
export type ApiIndexUserModel = {
apikey: string
TenantId: number
agent_id: number
jgday: number
LoginCode: string
Password: string
Name: string
Phone: string
Enabled: number
LastLoginDate: string
Sex: number
CreateType: number
ProductAccountCount: number
ExpiredProductAccountCount: number
RestAmount: number
ju_money: number
ConsumeAmount: number
Wx: string
QQ: string
Email: string
TestCountLimit: number
UseTestCount: number
ManagerId: number
ManagerName: string
id_code: string
is_verify: number
is_agent: number
parent_id: number
CreateTime: string
UpdateTime: string
DeleteTag: number
Id: number
}
export type ApiIndexAccountModel = {
TotalCount: number
ExpriedCount: number
}
export type ApiIndexStatistic = {
TodayExpend: number
TodayRefund: number
TodayCharege: number
MonthExpend: number
MonthRefund: number
MonthCharege: number
YearExpend: number
}
export type ApiIndexItem = {
UserModel: ApiIndexUserModel
AccountModel: ApiIndexAccountModel
Statistic: ApiIndexStatistic
}
export type DashboardBalance = {
balance: number
hCoin: number

View File

@@ -2,6 +2,11 @@ import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import "./index.css"
import App from "./App.tsx"
import { initClientStore } from "./components/stores/client"
import { initProfileStore } from "./components/stores/profile"
initClientStore()
initProfileStore()
const rootElement = document.getElementById("root")
if (!rootElement) throw new Error("Failed to find root element")