feat(auth): 用户登录+云端豆仓——JWT认证+库存同步+三语言
后端: - schema/users + bead_inventories 表(SQLite+PG 双DDL) - auth 模块:注册/登录/me(bcrypt+JWT,双SQL实现) - beads 模块:云端库存CRUD(增/查/扣/补/清,requireAuth 保护) - 188 测试全过(含新增 auth 17 + beads 12) 前端: - auth.ts + useAuth hook + AuthModal 登录/注册弹窗 - bead-api.ts 云端桥接 + useBeadInventory 云感知改造 - MyBeadsPage/App 登录态 + 云端同步 - 三语言 auth 文案(zh-CN/en/zh-TW) - 220 测试全过 + typecheck 0 错误 + build 成功
This commit is contained in:
1 parent
33e7b38271
commit
3bb67ebf30
25 files changed
+2069
-14
No files matched your search
@@ -45,6 +45,7 @@ import { COLOR_CHART_BRANDS } from './lib/color-chart-data';
|
||||
import type { ProcessResult, ProcessedCell, ProcessedPaletteEntry } from './lib/image-processor';
|
||||
import type { BeadUsage } from './lib/bead-inventory';
|
||||
import { useBeadInventory } from './lib/useBeadInventory';
|
||||
import { useAuth } from './lib/auth';
|
||||
import { readDeductMode } from './lib/bead-deduct-mode';
|
||||
import './pages/beads.css';
|
||||
import ShareButton from './components/ShareButton';
|
||||
@@ -195,7 +196,8 @@ function HomePage() {
|
||||
// 换色成功提示。
|
||||
const [replaceToast, setReplaceToast] = useState<string | null>(null);
|
||||
// 豆仓库存(consume / ensure 供结算确认与补货使用)。
|
||||
const beadInventory = useBeadInventory();
|
||||
const { token: authToken } = useAuth();
|
||||
const beadInventory = useBeadInventory(authToken);
|
||||
|
||||
// T-067 分享:?share= 分享码解码出的图纸(绕过上传直接渲染)。
|
||||
const [sharedPattern, setSharedPattern] = useState<SharedPattern | null>(null);
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* AuthModal — 登录/注册弹窗,切换登录/注册模式。
|
||||
*
|
||||
* 用例:
|
||||
* <AuthModal open={open} onClose={() => setOpen(false)} />
|
||||
*
|
||||
* 登录成功后自动关闭弹窗,auth user 自动更新到 useAuth()。
|
||||
*/
|
||||
|
||||
import { useCallback, useState, type FormEvent } from 'react';
|
||||
import { useT } from '../i18n';
|
||||
import { useAuth } from '../lib/auth';
|
||||
|
||||
interface AuthModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function AuthModal({ open, onClose }: AuthModalProps) {
|
||||
const { t } = useT();
|
||||
const { login, register } = useAuth();
|
||||
|
||||
const [mode, setMode] = useState<'login' | 'register'>('login');
|
||||
const [phone, setPhone] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [nickname, setNickname] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const switchMode = useCallback(() => {
|
||||
setMode((m) => (m === 'login' ? 'register' : 'login'));
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
if (!phone.trim() || !password) {
|
||||
setError('请输入手机号和密码');
|
||||
return;
|
||||
}
|
||||
if (mode === 'register' && password.length < 6) {
|
||||
setError('密码至少需要 6 位');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
if (mode === 'login') {
|
||||
await login(phone.trim(), password);
|
||||
} else {
|
||||
await register(phone.trim(), password, nickname.trim() || undefined);
|
||||
}
|
||||
// 成功后由 useAuth 更新状态,关闭弹窗
|
||||
onClose();
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : '操作失败,请稍后重试');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[mode, phone, password, nickname, login, register, onClose],
|
||||
);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div className="bd-modal-overlay" onClick={onClose}>
|
||||
<div
|
||||
className="bd-modal bd-add-modal"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t(mode === 'login' ? 'auth.loginTitle' : 'auth.registerTitle')}
|
||||
>
|
||||
{/* 标题 */}
|
||||
<div className="bd-modal-header">
|
||||
<span className="bd-modal-title">
|
||||
{t(mode === 'login' ? 'auth.loginTitle' : 'auth.registerTitle')}
|
||||
</span>
|
||||
<button type="button" className="bd-modal-close" onClick={onClose} aria-label={t('auth.close')}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 提示 */}
|
||||
<p style={{ fontSize: '0.85rem', color: 'var(--text-secondary)', margin: '0 0 1rem' }}>
|
||||
{t('auth.syncHint')}
|
||||
</p>
|
||||
|
||||
{/* 表单 */}
|
||||
<form onSubmit={handleSubmit} className="bd-add-form">
|
||||
{/* 手机号 */}
|
||||
<div className="bd-add-field">
|
||||
<label className="bd-add-label">{t('auth.phone')}</label>
|
||||
<input
|
||||
className="bd-add-input"
|
||||
type="tel"
|
||||
inputMode="numeric"
|
||||
value={phone}
|
||||
onChange={(e) => setPhone(e.target.value)}
|
||||
placeholder={t('auth.phonePlaceholder')}
|
||||
autoComplete="tel"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 密码 */}
|
||||
<div className="bd-add-field">
|
||||
<label className="bd-add-label">{t('auth.password')}</label>
|
||||
<input
|
||||
className="bd-add-input"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={t('auth.passwordPlaceholder')}
|
||||
autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 昵称(注册时) */}
|
||||
{mode === 'register' && (
|
||||
<div className="bd-add-field">
|
||||
<label className="bd-add-label">{t('auth.nickname')}</label>
|
||||
<input
|
||||
className="bd-add-input"
|
||||
type="text"
|
||||
value={nickname}
|
||||
onChange={(e) => setNickname(e.target.value)}
|
||||
placeholder="可选"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 错误提示 */}
|
||||
{error && (
|
||||
<p style={{ color: 'var(--error, #e74c3c)', fontSize: '0.85rem', margin: '0 0 0.5rem' }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* 提交 */}
|
||||
<button
|
||||
type="submit"
|
||||
className="bd-empty-btn bd-empty-btn--primary"
|
||||
style={{ alignSelf: 'flex-end', marginTop: 0 }}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? '...' : t(mode === 'login' ? 'auth.submitLogin' : 'auth.submitRegister')}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{/* 切换模式 */}
|
||||
<div style={{ textAlign: 'center', marginTop: '1rem' }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={switchMode}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
color: 'var(--accent, #6c5ce7)',
|
||||
cursor: 'pointer',
|
||||
fontSize: '0.875rem',
|
||||
textDecoration: 'underline',
|
||||
}}
|
||||
>
|
||||
{t(mode === 'login' ? 'auth.switchToRegister' : 'auth.switchToLogin')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -532,4 +532,24 @@ export const en: Messages = {
|
||||
'beads.add.code': 'Code',
|
||||
'beads.add.count': 'Count',
|
||||
'beads.add.submit': 'Add',
|
||||
|
||||
/* ── Auth ── */
|
||||
'auth.login': 'Sign In',
|
||||
'auth.register': 'Sign Up',
|
||||
'auth.logout': 'Sign Out',
|
||||
'auth.phone': 'Phone',
|
||||
'auth.password': 'Password',
|
||||
'auth.nickname': 'Nickname (optional)',
|
||||
'auth.loginTitle': 'Sign In to Bead Storage',
|
||||
'auth.registerTitle': 'Create Account',
|
||||
'auth.switchToRegister': 'No account? Sign up',
|
||||
'auth.switchToLogin': 'Have account? Sign in',
|
||||
'auth.submitLogin': 'Sign In',
|
||||
'auth.submitRegister': 'Sign Up',
|
||||
'auth.close': 'Close',
|
||||
'auth.syncHint': 'Sign in to sync your bead inventory to the cloud — keep it on any device.',
|
||||
'auth.loggedInAs': 'Signed in: {phone}',
|
||||
'auth.notLoggedIn': 'Not signed in — inventory is stored on this device only',
|
||||
'auth.phonePlaceholder': 'Enter your phone number',
|
||||
'auth.passwordPlaceholder': 'Enter password (6+ characters)',
|
||||
};
|
||||
@@ -520,6 +520,26 @@ export const zhCN = {
|
||||
'beads.add.code': '色号',
|
||||
'beads.add.count': '数量',
|
||||
'beads.add.submit': '添加',
|
||||
|
||||
/* ── Auth(登录/注册) ── */
|
||||
'auth.login': '登录',
|
||||
'auth.register': '注册',
|
||||
'auth.logout': '退出登录',
|
||||
'auth.phone': '手机号',
|
||||
'auth.password': '密码',
|
||||
'auth.nickname': '昵称(可选)',
|
||||
'auth.loginTitle': '登录豆仓',
|
||||
'auth.registerTitle': '注册账号',
|
||||
'auth.switchToRegister': '没有账号?去注册',
|
||||
'auth.switchToLogin': '已有账号?去登录',
|
||||
'auth.submitLogin': '登录',
|
||||
'auth.submitRegister': '注册',
|
||||
'auth.close': '关闭',
|
||||
'auth.syncHint': '登录后豆仓数据云端同步,换设备也不丢',
|
||||
'auth.loggedInAs': '已登录:{phone}',
|
||||
'auth.notLoggedIn': '未登录,豆仓仅保存在本机',
|
||||
'auth.phonePlaceholder': '请输入手机号',
|
||||
'auth.passwordPlaceholder': '请输入密码(至少 6 位)',
|
||||
} as const;
|
||||
|
||||
export type Messages = { [K in keyof typeof zhCN]: string };
|
||||
|
||||
@@ -520,4 +520,24 @@ export const zhTW: Messages = {
|
||||
'beads.add.code': '色號',
|
||||
'beads.add.count': '數量',
|
||||
'beads.add.submit': '添加',
|
||||
|
||||
/* ── Auth(登入/註冊) ── */
|
||||
'auth.login': '登入',
|
||||
'auth.register': '註冊',
|
||||
'auth.logout': '退出登入',
|
||||
'auth.phone': '手機號',
|
||||
'auth.password': '密碼',
|
||||
'auth.nickname': '暱稱(選填)',
|
||||
'auth.loginTitle': '登入豆倉',
|
||||
'auth.registerTitle': '註冊帳號',
|
||||
'auth.switchToRegister': '沒有帳號?去註冊',
|
||||
'auth.switchToLogin': '已有帳號?去登入',
|
||||
'auth.submitLogin': '登入',
|
||||
'auth.submitRegister': '註冊',
|
||||
'auth.close': '關閉',
|
||||
'auth.syncHint': '登入後豆倉資料雲端同步,換裝置也不怕',
|
||||
'auth.loggedInAs': '已登入:{phone}',
|
||||
'auth.notLoggedIn': '未登入,豆倉僅保存在本機',
|
||||
'auth.phonePlaceholder': '請輸入手機號',
|
||||
'auth.passwordPlaceholder': '請輸入密碼(至少 6 位)',
|
||||
};
|
||||
@@ -84,14 +84,14 @@ export interface GenerateChibiResponse {
|
||||
}
|
||||
|
||||
/** Base URL: override with VITE_API_BASE, default to the local dev server. */
|
||||
const API_BASE: string = import.meta.env.VITE_API_BASE ?? 'http://localhost:8788';
|
||||
export const API_BASE: string = import.meta.env.VITE_API_BASE ?? 'http://localhost:8788';
|
||||
|
||||
/**
|
||||
* Shared JSON helper: normalizes headers, then parses the body.
|
||||
* On a non-2xx response it reads { error } and throws Error(error) so the
|
||||
* UI can surface the server's Chinese message directly.
|
||||
*/
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (!headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* 前端认证 —— token 管理 + 登录/注册 API + useAuth hook。
|
||||
*
|
||||
* token 存 localStorage(key: perler-auth-token),提供模块级
|
||||
* 读取/写入/清除;useAuth() 订阅登录状态供组件使用。
|
||||
*/
|
||||
|
||||
import { useCallback, useState } from 'react';
|
||||
import { request } from './api';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 类型
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
phone: string;
|
||||
nickname: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
token: string;
|
||||
user: AuthUser;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Token 管理
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const TOKEN_KEY = 'perler-auth-token';
|
||||
const USER_KEY = 'perler-auth-user';
|
||||
|
||||
/** 读取 token(无则 null)。 */
|
||||
export function getToken(): string | null {
|
||||
try {
|
||||
return globalThis.localStorage?.getItem(TOKEN_KEY) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取缓存的用户信息(无则 null)。 */
|
||||
export function getCachedUser(): AuthUser | null {
|
||||
try {
|
||||
const raw = globalThis.localStorage?.getItem(USER_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (typeof parsed === 'object' && parsed !== null) {
|
||||
const u = parsed as Record<string, unknown>;
|
||||
if (typeof u['id'] === 'string' && typeof u['phone'] === 'string') {
|
||||
return { id: u['id'], phone: u['phone'], nickname: u['nickname'] as string | null, createdAt: u['createdAt'] as string };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 持久化登录态。 */
|
||||
export function persistAuth(token: string, user: AuthUser): void {
|
||||
try {
|
||||
globalThis.localStorage?.setItem(TOKEN_KEY, token);
|
||||
globalThis.localStorage?.setItem(USER_KEY, JSON.stringify(user));
|
||||
} catch {
|
||||
// 隐私模式等写入失败时静默忽略
|
||||
}
|
||||
}
|
||||
|
||||
/** 清除登录态。 */
|
||||
export function clearAuth(): void {
|
||||
try {
|
||||
globalThis.localStorage?.removeItem(TOKEN_KEY);
|
||||
globalThis.localStorage?.removeItem(USER_KEY);
|
||||
} catch {
|
||||
// 静默忽略
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 注册。 */
|
||||
export async function register(
|
||||
phone: string,
|
||||
password: string,
|
||||
nickname?: string,
|
||||
): Promise<AuthResponse> {
|
||||
return request<AuthResponse>('/api/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phone, password, nickname }),
|
||||
});
|
||||
}
|
||||
|
||||
/** 登录。 */
|
||||
export async function login(phone: string, password: string): Promise<AuthResponse> {
|
||||
return request<AuthResponse>('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phone, password }),
|
||||
});
|
||||
}
|
||||
|
||||
/** 校验 token 有效性,返回当前用户。 */
|
||||
export async function fetchMe(token: string): Promise<{ user: AuthUser }> {
|
||||
return request<{ user: AuthUser }>('/api/auth/me', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// useAuth hook
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface UseAuth {
|
||||
user: AuthUser | null;
|
||||
token: string | null;
|
||||
login: (phone: string, password: string) => Promise<AuthUser>;
|
||||
register: (phone: string, password: string, nickname?: string) => Promise<AuthUser>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录状态 hook:初始从 localStorage 恢复,提供 login/logout。
|
||||
* 登录成功后持久化;token 失效时(fetchMe 401)自动登出。
|
||||
*/
|
||||
export function useAuth(): UseAuth {
|
||||
const [user, setUser] = useState<AuthUser | null>(() => getCachedUser());
|
||||
const [token, setToken] = useState<string | null>(() => getToken());
|
||||
|
||||
const doLogin = useCallback(async (phone: string, password: string): Promise<AuthUser> => {
|
||||
const res = await login(phone, password);
|
||||
persistAuth(res.token, res.user);
|
||||
setToken(res.token);
|
||||
setUser(res.user);
|
||||
return res.user;
|
||||
}, []);
|
||||
|
||||
const doRegister = useCallback(
|
||||
async (phone: string, password: string, nickname?: string): Promise<AuthUser> => {
|
||||
const res = await register(phone, password, nickname);
|
||||
persistAuth(res.token, res.user);
|
||||
setToken(res.token);
|
||||
setUser(res.user);
|
||||
return res.user;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const doLogout = useCallback(() => {
|
||||
clearAuth();
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
return { user, token, login: doLogin, register: doRegister, logout: doLogout };
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* 云端豆仓桥接 —— 登录后与后端同步库存。
|
||||
*
|
||||
* 策略:
|
||||
* - 未登录 → 纯 localStorage(现有逻辑,不变)
|
||||
* - 登录后 → 后端 API 操作,同时缓存到 localStorage
|
||||
* - 首次登录 → 合并本地库存到云端(上传)
|
||||
*
|
||||
* 所有操作需传入 token(来自 useAuth())。
|
||||
*/
|
||||
|
||||
import { request } from './api';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 类型
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface CloudInventory {
|
||||
brandId: string;
|
||||
bottles: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface CloudShortage {
|
||||
code: string;
|
||||
count: number;
|
||||
missing: number;
|
||||
}
|
||||
|
||||
export interface BeadEntry {
|
||||
code: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 获取云端库存。 */
|
||||
export async function fetchInventory(token: string): Promise<CloudInventory> {
|
||||
return request<CloudInventory>('/api/beads/inventory', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
}
|
||||
|
||||
/** 添加豆子(增量)。 */
|
||||
export async function addBeads(token: string, code: string, count: number): Promise<void> {
|
||||
await request<{ ok: boolean }>('/api/beads/add', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, count }),
|
||||
});
|
||||
}
|
||||
|
||||
/** 扣豆,返回缺口列表。 */
|
||||
export async function consumeBeads(
|
||||
token: string,
|
||||
entries: BeadEntry[],
|
||||
): Promise<CloudShortage[]> {
|
||||
const res = await request<{ shortages: CloudShortage[] }>('/api/beads/consume', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ entries }),
|
||||
});
|
||||
return res.shortages;
|
||||
}
|
||||
|
||||
/** 一键补货。 */
|
||||
export async function ensureStock(
|
||||
token: string,
|
||||
entries: BeadEntry[],
|
||||
brandId = 'MARD',
|
||||
): Promise<void> {
|
||||
await request<{ ok: boolean }>('/api/beads/ensure', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ entries, brandId }),
|
||||
});
|
||||
}
|
||||
|
||||
/** 清空库存。 */
|
||||
export async function clearInventory(token: string): Promise<void> {
|
||||
await request<{ ok: boolean }>('/api/beads/clear', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
/**
|
||||
* 豆仓 React hook —— 订阅 localStorage + 跨组件同步。
|
||||
* 豆仓 React hook —— 本地 localStorage 读写 + 登录后云端同步。
|
||||
*
|
||||
* `useBeadInventory` 以 `useState` 初始化 `loadInventory()`,
|
||||
* 通过 `useEffect` 监听 `window` 上的 `bead-inventory-changed` 与 `storage` 事件
|
||||
* 实现多组件 / 多标签页间的库存状态同步。
|
||||
* 双模式:
|
||||
* - 未登录(token 为空):纯本地,跨组件通过 `bead-inventory-changed` /
|
||||
* `storage` 事件同步(现有行为不变)。
|
||||
* - 已登录(token 非空):首次拉取云端库存并「本地 ∪ 云端」合并
|
||||
* (逐色号取较大值,不丢数据),合并结果回写云端;此后每次
|
||||
* add/consume/ensure 立即更新本地并异步同步云端(失败静默降级为本地)。
|
||||
*
|
||||
* 内部维护 `inventoryRef` 确保 `add`/`consume`/`ensure` 在同步调用序列中
|
||||
* 始终基于最新库存计算,避免 React 批次更新导致的闭包过期。
|
||||
* 维持同步 API:调用方无需 await。云端失败不影响本地操作。
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
@@ -20,6 +22,7 @@ import {
|
||||
type BeadUsage,
|
||||
type Shortage,
|
||||
} from './bead-inventory.js';
|
||||
import * as cloud from './bead-api.js';
|
||||
|
||||
export interface UseBeadInventory {
|
||||
inventory: BeadInventory;
|
||||
@@ -29,7 +32,34 @@ export interface UseBeadInventory {
|
||||
refresh(): void;
|
||||
}
|
||||
|
||||
export function useBeadInventory(): UseBeadInventory {
|
||||
/**
|
||||
* 合并本地+云端库存:逐色号取较大值(任一方的数据都不丢)。
|
||||
*/
|
||||
function mergeBottles(
|
||||
local: BeadInventory,
|
||||
cloudBottles: Record<string, number>,
|
||||
cloudBrandId: string,
|
||||
): BeadInventory {
|
||||
const merged: Record<string, number> = { ...cloudBottles };
|
||||
for (const [code, count] of Object.entries(local.bottles)) {
|
||||
merged[code] = Math.max(merged[code] ?? 0, count);
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
brandId: cloudBrandId && cloudBrandId.length > 0 ? cloudBrandId : local.brandId,
|
||||
bottles: merged,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
/** 把整仓库存上传为云端绝对状态(合并后调用)。 */
|
||||
async function pushFullInventory(token: string, inv: BeadInventory): Promise<void> {
|
||||
const entries = Object.entries(inv.bottles).map(([code, count]) => ({ code, count }));
|
||||
if (entries.length === 0) return;
|
||||
await cloud.ensureStock(token, entries, inv.brandId);
|
||||
}
|
||||
|
||||
export function useBeadInventory(token?: string | null): UseBeadInventory {
|
||||
const [inventory, setInventory] = useState<BeadInventory>(() => loadInventory());
|
||||
const inventoryRef = useRef<BeadInventory>(inventory);
|
||||
|
||||
@@ -50,13 +80,40 @@ export function useBeadInventory(): UseBeadInventory {
|
||||
};
|
||||
}, [applyInventory]);
|
||||
|
||||
// 登录后:拉取云端 → 合并 → 回写(避免丢任何一方数据)
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
const cloudInv = await cloud.fetchInventory(token);
|
||||
if (cancelled) return;
|
||||
const local = loadInventory();
|
||||
const merged = mergeBottles(local, cloudInv.bottles, cloudInv.brandId);
|
||||
saveInventory(merged);
|
||||
applyInventory(merged);
|
||||
await pushFullInventory(token, merged);
|
||||
} catch {
|
||||
// 云端不可达:保持本地数据,不影响使用
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [token, applyInventory]);
|
||||
|
||||
const add = useCallback(
|
||||
(code: string, count: number): void => {
|
||||
const next = addBeads(inventoryRef.current, code, count);
|
||||
saveInventory(next);
|
||||
applyInventory(next);
|
||||
if (token) {
|
||||
void cloud.addBeads(token, code, count).catch(() => {
|
||||
/* 云端失败静默降级本地 */
|
||||
});
|
||||
}
|
||||
},
|
||||
[applyInventory],
|
||||
[token, applyInventory],
|
||||
);
|
||||
|
||||
const consume = useCallback(
|
||||
@@ -64,9 +121,14 @@ export function useBeadInventory(): UseBeadInventory {
|
||||
const result = consumeBeads(inventoryRef.current, entries);
|
||||
saveInventory(result.inv);
|
||||
applyInventory(result.inv);
|
||||
if (token && entries.length > 0) {
|
||||
void cloud.consumeBeads(token, entries as cloud.BeadEntry[]).catch(() => {
|
||||
/* 云端失败静默降级本地 */
|
||||
});
|
||||
}
|
||||
return result.shortages;
|
||||
},
|
||||
[applyInventory],
|
||||
[token, applyInventory],
|
||||
);
|
||||
|
||||
const ensure = useCallback(
|
||||
@@ -74,8 +136,13 @@ export function useBeadInventory(): UseBeadInventory {
|
||||
const next = ensureStock(inventoryRef.current, entries);
|
||||
saveInventory(next);
|
||||
applyInventory(next);
|
||||
if (token && entries.length > 0) {
|
||||
void cloud.ensureStock(token, entries as cloud.BeadEntry[], next.brandId).catch(() => {
|
||||
/* 云端失败静默降级本地 */
|
||||
});
|
||||
}
|
||||
},
|
||||
[applyInventory],
|
||||
[token, applyInventory],
|
||||
);
|
||||
|
||||
const refresh = useCallback((): void => {
|
||||
|
||||
@@ -11,6 +11,8 @@ import './beads.css';
|
||||
import SubNav from '../components/SubNav';
|
||||
import { useT } from '../i18n';
|
||||
import { useBeadInventory } from '../lib/useBeadInventory';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import AuthModal from '../components/AuthModal';
|
||||
import { getBrandPalette, BRANDS } from '../lib/brand-palettes';
|
||||
import { readDeductMode, writeDeductMode, type BeadDeductMode } from '../lib/bead-deduct-mode';
|
||||
|
||||
@@ -415,9 +417,11 @@ function AddBeadsModal({ open, onClose, onAdd }: AddBeadsModalProps) {
|
||||
|
||||
export default function MyBeadsPage() {
|
||||
const { t } = useT();
|
||||
const { inventory, add } = useBeadInventory();
|
||||
const { user, token, logout } = useAuth();
|
||||
const { inventory, add } = useBeadInventory(token);
|
||||
const [deductMode, setDeductMode] = useState<BeadDeductMode>(readDeductMode);
|
||||
const [addModalOpen, setAddModalOpen] = useState(false);
|
||||
const [authModalOpen, setAuthModalOpen] = useState(false);
|
||||
|
||||
const bottles = inventory?.bottles ?? {};
|
||||
const bottleEntries = Object.entries(bottles);
|
||||
@@ -453,6 +457,33 @@ export default function MyBeadsPage() {
|
||||
<p className="pl-sub">{t('beads.pageDesc')}</p>
|
||||
</header>
|
||||
|
||||
{/* 登录状态栏 */}
|
||||
<div className="bd-auth-bar">
|
||||
{user ? (
|
||||
<>
|
||||
<span className="bd-auth-text">{t('auth.loggedInAs', { phone: user.phone })}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="bd-empty-btn bd-empty-btn--outline"
|
||||
onClick={() => logout()}
|
||||
>
|
||||
{t('auth.logout')}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="bd-auth-text">{t('auth.notLoggedIn')}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="bd-empty-btn bd-empty-btn--primary"
|
||||
onClick={() => setAuthModalOpen(true)}
|
||||
>
|
||||
{t('auth.login')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 扣豆模式开关 */}
|
||||
<div className="bd-settings">
|
||||
<span className="bd-settings-label">{t('beads.settings.title')}</span>
|
||||
@@ -546,6 +577,9 @@ export default function MyBeadsPage() {
|
||||
onClose={() => setAddModalOpen(false)}
|
||||
onAdd={handleAdd}
|
||||
/>
|
||||
|
||||
{/* 登录/注册弹窗 */}
|
||||
<AuthModal open={authModalOpen} onClose={() => setAuthModalOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -42,6 +42,26 @@
|
||||
|
||||
/* ═══════════════════════ 扣豆模式开关 ═══════════════════════ */
|
||||
|
||||
/* 登录状态栏 */
|
||||
.bd-auth-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
margin-bottom: var(--space-5);
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
.bd-auth-text {
|
||||
font-size: var(--text-sm, 0.875rem);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.bd-settings {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
Reference in new issue
Block a user