门店账号管理修改

This commit is contained in:
2026-07-07 00:01:16 +08:00
parent e85c4b9bcb
commit 7ca9fc8a35
25 changed files with 599 additions and 134 deletions
@@ -0,0 +1,76 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
import {
clearAuth,
ensureSession,
saveAuth,
type ShopSessionPayload,
type StoreSessionStore,
} from '../lib/api';
type StoreSessionContextValue = {
ready: boolean;
authenticated: boolean;
store: StoreSessionStore | null;
applySession: (session: ShopSessionPayload) => void;
resetSession: () => void;
};
const StoreSessionContext = createContext<StoreSessionContextValue | null>(null);
export function StoreSessionProvider({ children }: { children: ReactNode }) {
const [ready, setReady] = useState(false);
const [authenticated, setAuthenticated] = useState(false);
const [store, setStore] = useState<StoreSessionStore | null>(null);
const applySession = useCallback((session: ShopSessionPayload) => {
saveAuth(session);
setAuthenticated(true);
if (session.store) setStore(session.store);
}, []);
const resetSession = useCallback(() => {
clearAuth();
setAuthenticated(false);
setStore(null);
}, []);
useEffect(() => {
let cancelled = false;
(async () => {
try {
const result = await ensureSession();
if (cancelled) return;
setAuthenticated(result.authenticated);
setStore(result.store);
} catch {
if (!cancelled) resetSession();
} finally {
if (!cancelled) setReady(true);
}
})();
return () => {
cancelled = true;
};
}, [resetSession]);
const value = useMemo(
() => ({ ready, authenticated, store, applySession, resetSession }),
[ready, authenticated, store, applySession, resetSession],
);
return <StoreSessionContext.Provider value={value}>{children}</StoreSessionContext.Provider>;
}
export function useStoreSession() {
const ctx = useContext(StoreSessionContext);
if (!ctx) throw new Error('useStoreSession must be used within StoreSessionProvider');
return ctx;
}