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
Generated
+144
@@ -9,13 +9,17 @@
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@types/pg": "^8.23.1",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^11.7.0",
|
||||
"express": "^4.21.0",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"pg": "^8.23.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/better-sqlite3": "^7.6.12",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/supertest": "^7.2.1",
|
||||
"supertest": "^7.2.2",
|
||||
"tsx": "^4.19.0",
|
||||
@@ -904,6 +908,13 @@
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@types/bcryptjs": {
|
||||
"version": "2.4.6",
|
||||
"resolved": "https://registry.npmmirror.com/@types/bcryptjs/-/bcryptjs-2.4.6.tgz",
|
||||
"integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/better-sqlite3": {
|
||||
"version": "7.6.13",
|
||||
"resolved": "https://registry.npmmirror.com/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz",
|
||||
@@ -981,6 +992,17 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/jsonwebtoken": {
|
||||
"version": "9.0.10",
|
||||
"resolved": "https://registry.npmmirror.com/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",
|
||||
"integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/ms": "*",
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/methods": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmmirror.com/@types/methods/-/methods-1.1.4.tgz",
|
||||
@@ -988,6 +1010,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/ms": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmmirror.com/@types/ms/-/ms-2.1.0.tgz",
|
||||
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "26.2.0",
|
||||
"resolved": "https://registry.npmmirror.com/@types/node/-/node-26.2.0.tgz",
|
||||
@@ -1243,6 +1272,15 @@
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/bcryptjs": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/bcryptjs/-/bcryptjs-3.0.3.tgz",
|
||||
"integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==",
|
||||
"license": "BSD-3-Clause",
|
||||
"bin": {
|
||||
"bcrypt": "bin/bcrypt"
|
||||
}
|
||||
},
|
||||
"node_modules/better-sqlite3": {
|
||||
"version": "11.10.0",
|
||||
"resolved": "https://registry.npmmirror.com/better-sqlite3/-/better-sqlite3-11.10.0.tgz",
|
||||
@@ -1322,6 +1360,12 @@
|
||||
"ieee754": "^1.1.13"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-equal-constant-time": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
|
||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmmirror.com/bytes/-/bytes-3.1.2.tgz",
|
||||
@@ -1575,6 +1619,15 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/ecdsa-sig-formatter": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmmirror.com/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
||||
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/ee-first": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/ee-first/-/ee-first-1.1.1.tgz",
|
||||
@@ -2066,6 +2119,97 @@
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonwebtoken": {
|
||||
"version": "9.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
|
||||
"integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jws": "^4.0.1",
|
||||
"lodash.includes": "^4.3.0",
|
||||
"lodash.isboolean": "^3.0.3",
|
||||
"lodash.isinteger": "^4.0.4",
|
||||
"lodash.isnumber": "^3.0.3",
|
||||
"lodash.isplainobject": "^4.0.6",
|
||||
"lodash.isstring": "^4.0.1",
|
||||
"lodash.once": "^4.0.0",
|
||||
"ms": "^2.1.1",
|
||||
"semver": "^7.5.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12",
|
||||
"npm": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonwebtoken/node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jwa": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/jwa/-/jwa-2.0.1.tgz",
|
||||
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer-equal-constant-time": "^1.0.1",
|
||||
"ecdsa-sig-formatter": "1.0.11",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/jws": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/jws/-/jws-4.0.1.tgz",
|
||||
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jwa": "^2.0.1",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash.includes": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmmirror.com/lodash.includes/-/lodash.includes-4.3.0.tgz",
|
||||
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isboolean": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
|
||||
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isinteger": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmmirror.com/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
|
||||
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isnumber": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmmirror.com/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
|
||||
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isplainobject": {
|
||||
"version": "4.0.6",
|
||||
"resolved": "https://registry.npmmirror.com/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
|
||||
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isstring": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
|
||||
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.once": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/lodash.once/-/lodash.once-4.1.1.tgz",
|
||||
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/loupe": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmmirror.com/loupe/-/loupe-3.2.1.tgz",
|
||||
|
||||
@@ -13,13 +13,17 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/pg": "^8.23.1",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"better-sqlite3": "^11.7.0",
|
||||
"express": "^4.21.0",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"pg": "^8.23.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/better-sqlite3": "^7.6.12",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.10",
|
||||
"@types/supertest": "^7.2.1",
|
||||
"supertest": "^7.2.2",
|
||||
"tsx": "^4.19.0",
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* JWT 工具 —— 签发与校验用户令牌。
|
||||
*
|
||||
* HS256 + 对称密钥:密钥来自 JWT_SECRET 环境变量(生产必须设置),
|
||||
* 缺省回退到开发默认值并打印警告(避免本地启动失败)。
|
||||
*/
|
||||
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
/** 开发默认密钥(仅本地/测试使用,生产必须用 JWT_SECRET 覆盖)。 */
|
||||
const DEV_SECRET = "perler-lab-dev-secret-do-not-use-in-prod";
|
||||
|
||||
function resolveSecret(): string {
|
||||
const secret = process.env["JWT_SECRET"];
|
||||
if (!secret || secret === "") {
|
||||
if (process.env["NODE_ENV"] !== "test") {
|
||||
console.warn(
|
||||
"[auth] JWT_SECRET 未设置,使用开发默认密钥 —— 生产环境必须通过环境变量配置!",
|
||||
);
|
||||
}
|
||||
return DEV_SECRET;
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
|
||||
const SECRET = resolveSecret();
|
||||
|
||||
/** JWT 载荷(sub = 用户 ID)。 */
|
||||
export interface JwtPayload {
|
||||
sub: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
/** 签发访问令牌(默认 30 天,供移动端持续登录)。 */
|
||||
export function signToken(payload: JwtPayload): string {
|
||||
return jwt.sign(payload, SECRET, { expiresIn: "30d" });
|
||||
}
|
||||
|
||||
/** 校验令牌:成功返回载荷,失败返回 undefined。 */
|
||||
export function verifyToken(token: string): JwtPayload | undefined {
|
||||
try {
|
||||
const decoded = jwt.verify(token, SECRET);
|
||||
if (typeof decoded !== "object" || decoded === null) return undefined;
|
||||
const d = decoded as Record<string, unknown>;
|
||||
if (typeof d["sub"] !== "string" || typeof d["phone"] !== "string") return undefined;
|
||||
return { sub: d["sub"], phone: d["phone"] };
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 认证中间件 —— 从 Authorization: Bearer <token> 解析用户。
|
||||
*
|
||||
* 用例:
|
||||
* router.use(requireAuth); // 整组路由需要登录
|
||||
* router.get("/x", requireAuth, handler); // 单路由需要登录
|
||||
*
|
||||
* 成功:挂 req.userId / req.userPhone,进入下一个中间件。
|
||||
* 失败:401 { error: "请先登录" },不进入后续处理。
|
||||
*/
|
||||
|
||||
import type { NextFunction, Request, RequestHandler, Response } from "express";
|
||||
import { verifyToken } from "./jwt.js";
|
||||
|
||||
declare global {
|
||||
// eslint-disable-next-line @typescript-eslint/no-namespace
|
||||
namespace Express {
|
||||
interface Request {
|
||||
userId?: string;
|
||||
userPhone?: string;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const AUTH_REQUIRED_MESSAGE = "请先登录";
|
||||
|
||||
/**
|
||||
* 要求登录的中间件工厂。挂载到需要用户上下文的路由上。
|
||||
*/
|
||||
export function requireAuth(req: Request, res: Response, next: NextFunction): void {
|
||||
const header = req.headers.authorization;
|
||||
if (typeof header !== "string" || !header.startsWith("Bearer ")) {
|
||||
res.status(401).json({ error: AUTH_REQUIRED_MESSAGE });
|
||||
return;
|
||||
}
|
||||
const token = header.slice("Bearer ".length).trim();
|
||||
const payload = verifyToken(token);
|
||||
if (payload === undefined) {
|
||||
res.status(401).json({ error: AUTH_REQUIRED_MESSAGE });
|
||||
return;
|
||||
}
|
||||
req.userId = payload.sub;
|
||||
req.userPhone = payload.phone;
|
||||
next();
|
||||
}
|
||||
|
||||
/** 短路用;路由测试可直接引用该中间件类型。 */
|
||||
export type { RequestHandler };
|
||||
export const requireAuthHandler: RequestHandler = requireAuth;
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* 认证路由 —— 注册 / 登录 / 当前用户。
|
||||
*
|
||||
* POST /api/auth/register { phone, password, nickname? } → 201 { token, user }
|
||||
* POST /api/auth/login { phone, password } → 200 { token, user }
|
||||
* GET /api/auth/me (Bearer) → 200 { user }
|
||||
*/
|
||||
|
||||
import { Router } from "express";
|
||||
import type { Request, Response } from "express";
|
||||
import type { Db } from "../db/index.js";
|
||||
import { getDb } from "../db/index.js";
|
||||
import { AuthError, AUTH_ERRORS, findUserById, loginUser, registerUser } from "./service.js";
|
||||
import { signToken } from "./jwt.js";
|
||||
import { requireAuth } from "./middleware.js";
|
||||
import { createRateLimiter } from "../security/rate-limit.js";
|
||||
|
||||
/** 解析 DB:测试注入优先,否则回退全局单例。 */
|
||||
function resolveDb(injected?: Db): Db {
|
||||
return injected ?? getDb();
|
||||
}
|
||||
|
||||
/** 把 AuthError 格式化为 Express 响应。 */
|
||||
function handleAuthError(res: Response, err: AuthError): void {
|
||||
res.status(err.status).json({ error: err.message });
|
||||
}
|
||||
|
||||
/** 解析手机号/密码请求体(非法时抛 400)。 */
|
||||
function parseCredentials(body: unknown): { phone: string; password: string } {
|
||||
const b = (body ?? {}) as { phone?: unknown; password?: unknown };
|
||||
const phone = typeof b.phone === "string" ? b.phone.trim() : "";
|
||||
const password = typeof b.password === "string" ? b.password : "";
|
||||
if (phone === "" || password === "") {
|
||||
throw new AuthError("请输入手机号和密码", 400, "MISSING_CREDENTIALS");
|
||||
}
|
||||
return { phone, password };
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建认证路由。可注入 DB 便于测试。
|
||||
*/
|
||||
export function createAuthRouter(injectedDb?: Db): Router {
|
||||
const router = Router();
|
||||
|
||||
// 防刷限流:注册 5/lh、登录 10/lh(按 IP)
|
||||
const registerLimiter = createRateLimiter({ windowMs: 60 * 60 * 1000, max: 5 })("auth-register");
|
||||
const loginLimiter = createRateLimiter({ windowMs: 60 * 60 * 1000, max: 10 })("auth-login");
|
||||
|
||||
/** POST /api/auth/register */
|
||||
router.post("/register", registerLimiter, async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { phone, password } = parseCredentials(req.body);
|
||||
const b = (req.body ?? {}) as { nickname?: unknown };
|
||||
const nickname =
|
||||
typeof b.nickname === "string" && b.nickname.trim() !== "" ? b.nickname.trim() : null;
|
||||
const db = resolveDb(injectedDb);
|
||||
const user = await registerUser(db, phone, password);
|
||||
const token = signToken({ sub: user.id, phone: user.phone });
|
||||
res.status(201).json({ token, user: { ...user, nickname: user.nickname ?? nickname } });
|
||||
} catch (err) {
|
||||
if (err instanceof AuthError) {
|
||||
handleAuthError(res, err);
|
||||
} else {
|
||||
console.error("POST /api/auth/register error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/** POST /api/auth/login */
|
||||
router.post("/login", loginLimiter, async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { phone, password } = parseCredentials(req.body);
|
||||
const db = resolveDb(injectedDb);
|
||||
const user = await loginUser(db, phone, password);
|
||||
const token = signToken({ sub: user.id, phone: user.phone });
|
||||
res.status(200).json({ token, user });
|
||||
} catch (err) {
|
||||
if (err instanceof AuthError) {
|
||||
handleAuthError(res, err);
|
||||
} else {
|
||||
console.error("POST /api/auth/login error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/** GET /api/auth/me */
|
||||
router.get("/me", requireAuth, async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const db = resolveDb(injectedDb);
|
||||
const row = await findUserById(db, req.userId!);
|
||||
if (!row) throw AUTH_ERRORS.NOT_FOUND;
|
||||
res.status(200).json({
|
||||
user: {
|
||||
id: row.id,
|
||||
phone: row.phone,
|
||||
nickname: row.nickname,
|
||||
createdAt: row.created_at,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof AuthError) {
|
||||
handleAuthError(res, err);
|
||||
} else {
|
||||
console.error("GET /api/auth/me error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* 用户认证 service —— PostgreSQL 异步实现(生产)。
|
||||
* 与同步的 SQLite 实现(service.ts 内部)一一对应。
|
||||
*/
|
||||
|
||||
import bcrypt from "bcryptjs";
|
||||
import type { PgDb } from "../db/index.js";
|
||||
import {
|
||||
AUTH_ERRORS,
|
||||
genUserId,
|
||||
isValidPassword,
|
||||
isValidPhone,
|
||||
SALT_ROUNDS,
|
||||
toPublicUser,
|
||||
type PublicUser,
|
||||
type UserRow,
|
||||
} from "./service.js";
|
||||
|
||||
/** 按手机号查用户(不存在返回 undefined)。 */
|
||||
export async function findUserByPhonePg(db: PgDb, phone: string): Promise<UserRow | undefined> {
|
||||
const { rows } = await db.query<UserRow>("SELECT * FROM users WHERE phone = $1", [
|
||||
phone.trim(),
|
||||
]);
|
||||
return rows[0] as UserRow | undefined;
|
||||
}
|
||||
|
||||
/** 按 ID 查用户(不存在返回 undefined)。 */
|
||||
export async function findUserByIdPg(db: PgDb, id: string): Promise<UserRow | undefined> {
|
||||
const { rows } = await db.query<UserRow>("SELECT * FROM users WHERE id = $1", [id]);
|
||||
return rows[0] as UserRow | undefined;
|
||||
}
|
||||
|
||||
/** 注册用户;已存在手机号时抛 PHONE_TAKEN。 */
|
||||
export async function registerPg(
|
||||
db: PgDb,
|
||||
phoneInput: string,
|
||||
rawPassword: string,
|
||||
): Promise<PublicUser> {
|
||||
const phone = phoneInput.trim();
|
||||
if (!isValidPhone(phone)) throw AUTH_ERRORS.PHONE_INVALID;
|
||||
if (!isValidPassword(rawPassword)) throw AUTH_ERRORS.PASSWORD_WEAK;
|
||||
const existing = await findUserByPhonePg(db, phone);
|
||||
if (existing) throw AUTH_ERRORS.PHONE_TAKEN;
|
||||
|
||||
const id = genUserId();
|
||||
const hash = await bcrypt.hash(rawPassword, SALT_ROUNDS);
|
||||
await db.query(
|
||||
"INSERT INTO users (id, phone, password_hash) VALUES ($1, $2, $3)",
|
||||
[id, phone, hash],
|
||||
);
|
||||
const row = await findUserByIdPg(db, id);
|
||||
return toPublicUser(row!);
|
||||
}
|
||||
|
||||
/** 登录校验;手机号或密码错误一律抛 WRONG_PASSWORD(避免用户枚举)。 */
|
||||
export async function loginPg(
|
||||
db: PgDb,
|
||||
phoneInput: string,
|
||||
rawPassword: string,
|
||||
): Promise<PublicUser> {
|
||||
const row = await findUserByPhonePg(db, phoneInput.trim());
|
||||
if (!row) throw AUTH_ERRORS.WRONG_PASSWORD;
|
||||
const ok = await bcrypt.compare(rawPassword, row.password_hash);
|
||||
if (!ok) throw AUTH_ERRORS.WRONG_PASSWORD;
|
||||
return toPublicUser(row);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* 用户认证 service —— 注册 / 登录 / 用户查询。
|
||||
*
|
||||
* 双数据库实现(与 codes 模块同构):
|
||||
* - service.ts:同步 SQLite 实现(测试用内存库)+ Dispatcher
|
||||
* - service.pg.ts:异步 PostgreSQL 实现(生产)
|
||||
*
|
||||
* 密码使用 bcrypt 哈希存储;JWT 签发/校验见 jwt.ts 与 middleware.ts。
|
||||
*/
|
||||
|
||||
import { randomBytes } from "node:crypto";
|
||||
import bcrypt from "bcryptjs";
|
||||
import type { Db, PgDb, SqliteDb } from "../db/index.js";
|
||||
import { isPgDb } from "../db/index.js";
|
||||
import {
|
||||
findUserByIdPg,
|
||||
findUserByPhonePg,
|
||||
loginPg,
|
||||
registerPg,
|
||||
} from "./service.pg.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 类型 & 常量
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 用户公开信息(不含密码哈希)。 */
|
||||
export interface PublicUser {
|
||||
id: string;
|
||||
phone: string;
|
||||
nickname: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/** users 表行(含密码哈希,仅内部使用)。 */
|
||||
export interface UserRow {
|
||||
id: string;
|
||||
phone: string;
|
||||
password_hash: string;
|
||||
nickname: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** 业务错误(与 codes 模块 CodeError 同构)。 */
|
||||
export class AuthError extends Error {
|
||||
readonly status: number;
|
||||
readonly code: string;
|
||||
constructor(message: string, status: number, code: string) {
|
||||
super(message);
|
||||
this.name = "AuthError";
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export const AUTH_ERRORS = {
|
||||
PHONE_INVALID: new AuthError("手机号格式不正确", 400, "PHONE_INVALID"),
|
||||
PASSWORD_WEAK: new AuthError("密码至少需要 6 位", 400, "PASSWORD_WEAK"),
|
||||
PHONE_TAKEN: new AuthError("该手机号已注册,请直接登录", 409, "PHONE_TAKEN"),
|
||||
NOT_FOUND: new AuthError("用户不存在", 404, "USER_NOT_FOUND"),
|
||||
WRONG_PASSWORD: new AuthError("手机号或密码错误", 401, "WRONG_PASSWORD"),
|
||||
} as const;
|
||||
|
||||
export const SALT_ROUNDS = 10;
|
||||
|
||||
/** 手机号宽松校验:1 开头 + 10 位数字(支持 11 位中/港/澳号段)。 */
|
||||
export function isValidPhone(phone: string): boolean {
|
||||
return /^1\d{10}$/.test(phone.trim());
|
||||
}
|
||||
|
||||
/** 密码强度:至少 6 位。 */
|
||||
export function isValidPassword(password: string): boolean {
|
||||
return typeof password === "string" && password.length >= 6;
|
||||
}
|
||||
|
||||
/** 行 → 公开信息。 */
|
||||
export function toPublicUser(row: UserRow): PublicUser {
|
||||
return {
|
||||
id: row.id,
|
||||
phone: row.phone,
|
||||
nickname: row.nickname,
|
||||
createdAt: row.created_at,
|
||||
};
|
||||
}
|
||||
|
||||
/** 生成用户 ID(24 位十六进制)。 */
|
||||
export function genUserId(): string {
|
||||
return randomBytes(12).toString("hex");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SQLite 内部实现(同步,测试用)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function findUserByPhoneSqlite(db: SqliteDb, phone: string): UserRow | undefined {
|
||||
return db.prepare("SELECT * FROM users WHERE phone = ?").get(phone.trim()) as UserRow | undefined;
|
||||
}
|
||||
|
||||
function findUserByIdSqlite(db: SqliteDb, id: string): UserRow | undefined {
|
||||
return db.prepare("SELECT * FROM users WHERE id = ?").get(id) as UserRow | undefined;
|
||||
}
|
||||
|
||||
function registerSqlite(db: SqliteDb, phoneInput: string, rawPassword: string): PublicUser {
|
||||
const phone = phoneInput.trim();
|
||||
if (!isValidPhone(phone)) throw AUTH_ERRORS.PHONE_INVALID;
|
||||
if (!isValidPassword(rawPassword)) throw AUTH_ERRORS.PASSWORD_WEAK;
|
||||
if (findUserByPhoneSqlite(db, phone)) throw AUTH_ERRORS.PHONE_TAKEN;
|
||||
|
||||
const id = genUserId();
|
||||
const hash = bcrypt.hashSync(rawPassword, SALT_ROUNDS);
|
||||
db.prepare("INSERT INTO users (id, phone, password_hash) VALUES (?, ?, ?)").run(
|
||||
id,
|
||||
phone,
|
||||
hash,
|
||||
);
|
||||
const row = findUserByIdSqlite(db, id)!;
|
||||
return toPublicUser(row);
|
||||
}
|
||||
|
||||
function loginSqlite(db: SqliteDb, phoneInput: string, rawPassword: string): PublicUser {
|
||||
const row = findUserByPhoneSqlite(db, phoneInput.trim());
|
||||
if (!row) throw AUTH_ERRORS.WRONG_PASSWORD;
|
||||
if (!bcrypt.compareSync(rawPassword, row.password_hash)) throw AUTH_ERRORS.WRONG_PASSWORD;
|
||||
return toPublicUser(row);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dispatcher(根据 db 类型路由到 SQLite 或 PostgreSQL)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type MaybePromise<T> = T | Promise<T>;
|
||||
|
||||
export function registerUser(db: SqliteDb, phone: string, password: string): PublicUser;
|
||||
export function registerUser(db: PgDb, phone: string, password: string): Promise<PublicUser>;
|
||||
export function registerUser(
|
||||
db: Db,
|
||||
phone: string,
|
||||
password: string,
|
||||
): MaybePromise<PublicUser>;
|
||||
export function registerUser(
|
||||
db: Db,
|
||||
phone: string,
|
||||
password: string,
|
||||
): MaybePromise<PublicUser> {
|
||||
return isPgDb(db) ? registerPg(db, phone, password) : registerSqlite(db, phone, password);
|
||||
}
|
||||
|
||||
export function findUserByPhone(db: SqliteDb, phone: string): UserRow | undefined;
|
||||
export function findUserByPhone(db: PgDb, phone: string): Promise<UserRow | undefined>;
|
||||
export function findUserByPhone(
|
||||
db: Db,
|
||||
phone: string,
|
||||
): MaybePromise<UserRow | undefined>;
|
||||
export function findUserByPhone(db: Db, phone: string): MaybePromise<UserRow | undefined> {
|
||||
return isPgDb(db) ? findUserByPhonePg(db, phone) : findUserByPhoneSqlite(db, phone);
|
||||
}
|
||||
|
||||
export function findUserById(db: SqliteDb, id: string): UserRow | undefined;
|
||||
export function findUserById(db: PgDb, id: string): Promise<UserRow | undefined>;
|
||||
export function findUserById(db: Db, id: string): MaybePromise<UserRow | undefined>;
|
||||
export function findUserById(db: Db, id: string): MaybePromise<UserRow | undefined> {
|
||||
return isPgDb(db) ? findUserByIdPg(db, id) : findUserByIdSqlite(db, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录校验(不含 JWT 签发,签发在路由层)。返回公开用户信息;
|
||||
* 手机号不存在或密码错误时一律抛 WRONG_PASSWORD(避免用户枚举)。
|
||||
*/
|
||||
export function loginUser(db: SqliteDb, phone: string, password: string): PublicUser;
|
||||
export function loginUser(db: PgDb, phone: string, password: string): Promise<PublicUser>;
|
||||
export function loginUser(
|
||||
db: Db,
|
||||
phone: string,
|
||||
password: string,
|
||||
): MaybePromise<PublicUser>;
|
||||
export function loginUser(
|
||||
db: Db,
|
||||
phone: string,
|
||||
password: string,
|
||||
): MaybePromise<PublicUser> {
|
||||
return isPgDb(db) ? loginPg(db, phone, password) : loginSqlite(db, phone, password);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* 云端豆仓路由 —— 按用户隔离的库存 CRUD(JWT 保护)。
|
||||
*
|
||||
* GET /api/beads/inventory → 200 { brandId, bottles: { code: count } }
|
||||
* POST /api/beads/add { code, count } → 200
|
||||
* POST /api/beads/consume { entries: [{code,count}] } → 200 { shortages }
|
||||
* POST /api/beads/ensure { entries: [{code,count}] } → 200
|
||||
* POST /api/beads/clear → 200
|
||||
*/
|
||||
|
||||
import { Router } from "express";
|
||||
import type { Request, Response } from "express";
|
||||
import type { Db } from "../db/index.js";
|
||||
import { getDb } from "../db/index.js";
|
||||
import { requireAuth } from "../auth/middleware.js";
|
||||
import {
|
||||
getInventory,
|
||||
addBeads as addBeadsService,
|
||||
consumeBeads as consumeBeadsService,
|
||||
ensureStock as ensureStockService,
|
||||
clearInventory,
|
||||
} from "./service.js";
|
||||
|
||||
function resolveDb(injected?: Db): Db {
|
||||
return injected ?? getDb();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建云端豆仓路由。所有路由均需登录(requireAuth)。
|
||||
*/
|
||||
export function createBeadsRouter(injectedDb?: Db): Router {
|
||||
const router = Router();
|
||||
|
||||
// 所有端点需要登录
|
||||
router.use(requireAuth);
|
||||
|
||||
/** GET /api/beads/inventory */
|
||||
router.get("/inventory", async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const db = resolveDb(injectedDb);
|
||||
const rows = await getInventory(db, req.userId!);
|
||||
const brandId = rows.length > 0 ? rows[0]!.brand_id : "MARD";
|
||||
const bottles: Record<string, number> = {};
|
||||
for (const row of rows) {
|
||||
bottles[row.code] = row.count;
|
||||
}
|
||||
res.status(200).json({ brandId, bottles });
|
||||
} catch (err) {
|
||||
console.error("GET /api/beads/inventory error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
/** POST /api/beads/add */
|
||||
router.post("/add", async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { code, count } = req.body as { code?: unknown; count?: unknown };
|
||||
if (typeof code !== "string" || code.trim() === "") {
|
||||
res.status(400).json({ error: "请输入色号" });
|
||||
return;
|
||||
}
|
||||
const n = typeof count === "number" && Number.isFinite(count) ? count : 0;
|
||||
if (n <= 0) {
|
||||
res.status(400).json({ error: "数量必须大于 0" });
|
||||
return;
|
||||
}
|
||||
const db = resolveDb(injectedDb);
|
||||
// 获取当前品牌(从库存第一行推断,没有则默认 MARD)
|
||||
const rows = await getInventory(db, req.userId!);
|
||||
const brandId = rows.length > 0 ? rows[0]!.brand_id : "MARD";
|
||||
await addBeadsService(db, req.userId!, brandId, code.trim().toUpperCase(), n);
|
||||
res.status(200).json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error("POST /api/beads/add error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
/** POST /api/beads/consume */
|
||||
router.post("/consume", async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { entries } = req.body as { entries?: unknown };
|
||||
if (!Array.isArray(entries) || entries.length === 0) {
|
||||
res.status(400).json({ error: "缺少扣豆清单" });
|
||||
return;
|
||||
}
|
||||
const parsed = entries.map((e: unknown) => {
|
||||
const item = (e ?? {}) as { code?: unknown; count?: unknown };
|
||||
return {
|
||||
code: typeof item.code === "string" ? item.code.trim().toUpperCase() : "",
|
||||
count: typeof item.count === "number" && Number.isFinite(item.count) ? item.count : 0,
|
||||
};
|
||||
});
|
||||
const db = resolveDb(injectedDb);
|
||||
const shortages = await consumeBeadsService(db, req.userId!, parsed);
|
||||
res.status(200).json({ shortages });
|
||||
} catch (err) {
|
||||
console.error("POST /api/beads/consume error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
/** POST /api/beads/ensure */
|
||||
router.post("/ensure", async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { entries, brandId } = req.body as { entries?: unknown; brandId?: unknown };
|
||||
if (!Array.isArray(entries) || entries.length === 0) {
|
||||
res.status(400).json({ error: "缺少补货清单" });
|
||||
return;
|
||||
}
|
||||
const parsed = entries.map((e: unknown) => {
|
||||
const item = (e ?? {}) as { code?: unknown; count?: unknown };
|
||||
return {
|
||||
code: typeof item.code === "string" ? item.code.trim().toUpperCase() : "",
|
||||
count: typeof item.count === "number" && Number.isFinite(item.count) ? item.count : 0,
|
||||
};
|
||||
});
|
||||
const brand = typeof brandId === "string" && brandId.trim() !== "" ? brandId.trim() : "MARD";
|
||||
const db = resolveDb(injectedDb);
|
||||
await ensureStockService(db, req.userId!, brand, parsed);
|
||||
res.status(200).json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error("POST /api/beads/ensure error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
/** POST /api/beads/clear */
|
||||
router.post("/clear", async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const db = resolveDb(injectedDb);
|
||||
await clearInventory(db, req.userId!);
|
||||
res.status(200).json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error("POST /api/beads/clear error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* 云端豆仓 service —— PostgreSQL 异步实现。
|
||||
* 与同步的 SQLite 实现(service.ts 内部)一一对应。
|
||||
*/
|
||||
|
||||
import type { PgDb } from "../db/index.js";
|
||||
import type { BeadInventoryRow } from "./service.js";
|
||||
|
||||
/** 按用户查询全部库存(返回 {code, count} 记录)。 */
|
||||
export async function findAllByUserPg(
|
||||
db: PgDb,
|
||||
userId: string,
|
||||
): Promise<BeadInventoryRow[]> {
|
||||
const { rows } = await db.query<BeadInventoryRow>(
|
||||
"SELECT code, count, brand_id FROM bead_inventories WHERE user_id = $1",
|
||||
[userId],
|
||||
);
|
||||
return rows as BeadInventoryRow[];
|
||||
}
|
||||
|
||||
/** 按用户 + 色号查询单条记录。 */
|
||||
export async function findByUserAndCodePg(
|
||||
db: PgDb,
|
||||
userId: string,
|
||||
code: string,
|
||||
): Promise<BeadInventoryRow | undefined> {
|
||||
const { rows } = await db.query<BeadInventoryRow>(
|
||||
"SELECT code, count, brand_id FROM bead_inventories WHERE user_id = $1 AND code = $2",
|
||||
[userId, code],
|
||||
);
|
||||
return rows[0] as BeadInventoryRow | undefined;
|
||||
}
|
||||
|
||||
/** 批量 upsert 库存(无事务,由路由层的事务/批量保证一致性)。 */
|
||||
export async function upsertBatchPg(
|
||||
db: PgDb,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
entries: { code: string; count: number }[],
|
||||
): Promise<void> {
|
||||
for (const { code, count } of entries) {
|
||||
await db.query(
|
||||
`INSERT INTO bead_inventories (user_id, brand_id, code, count, updated_at)
|
||||
VALUES ($1, $2, $3, $4, now())
|
||||
ON CONFLICT (user_id, code)
|
||||
DO UPDATE SET count = EXCLUDED.count, brand_id = EXCLUDED.brand_id, updated_at = now()`,
|
||||
[userId, brandId, code, count],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** 删除用户所有库存(清仓换品牌时用)。 */
|
||||
export async function deleteAllByUserPg(db: PgDb, userId: string): Promise<void> {
|
||||
await db.query("DELETE FROM bead_inventories WHERE user_id = $1", [userId]);
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
/**
|
||||
* 云端豆仓 service —— 按用户隔离的库存 CRUD。
|
||||
*
|
||||
* 双数据库实现(与 auth 模块同构):
|
||||
* - service.ts:同步 SQLite 实现 + Dispatcher
|
||||
* - service.pg.ts:异步 PostgreSQL 实现
|
||||
*
|
||||
* 语义与前端 `bead-inventory.ts` 的纯函数一致:
|
||||
* - 加豆:addBeads 合并已有库存
|
||||
* - 扣豆:consumeBeads 扣到 0 为止,返回缺口
|
||||
* - 补货:ensureStock 补齐到满足用量
|
||||
*/
|
||||
|
||||
import type { Db, PgDb, SqliteDb } from "../db/index.js";
|
||||
import { isPgDb } from "../db/index.js";
|
||||
import {
|
||||
findAllByUserPg,
|
||||
findByUserAndCodePg,
|
||||
upsertBatchPg,
|
||||
deleteAllByUserPg,
|
||||
} from "./service.pg.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 类型
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface BeadInventoryRow {
|
||||
code: string;
|
||||
count: number;
|
||||
brand_id: string;
|
||||
}
|
||||
|
||||
/** 单条库存编辑操作。 */
|
||||
export interface BeadEntry {
|
||||
code: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/** 扣豆结果(缺口列表)。 */
|
||||
export interface Shortage {
|
||||
code: string;
|
||||
count: number;
|
||||
missing: number;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SQLite 内部实现(同步,测试用)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function findAllByUserSqlite(db: SqliteDb, userId: string): BeadInventoryRow[] {
|
||||
return db.prepare("SELECT code, count, brand_id FROM bead_inventories WHERE user_id = ?").all(userId) as BeadInventoryRow[];
|
||||
}
|
||||
|
||||
function findByUserAndCodeSqlite(db: SqliteDb, userId: string, code: string): BeadInventoryRow | undefined {
|
||||
return db.prepare("SELECT code, count, brand_id FROM bead_inventories WHERE user_id = ? AND code = ?").get(userId, code) as BeadInventoryRow | undefined;
|
||||
}
|
||||
|
||||
function upsertBatchSqlite(
|
||||
db: SqliteDb,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
entries: BeadEntry[],
|
||||
): void {
|
||||
const upsert = db.prepare(
|
||||
`INSERT INTO bead_inventories (user_id, brand_id, code, count, updated_at)
|
||||
VALUES (?, ?, ?, ?, datetime('now'))
|
||||
ON CONFLICT(user_id, code)
|
||||
DO UPDATE SET count = excluded.count, brand_id = excluded.brand_id, updated_at = datetime('now')`,
|
||||
);
|
||||
const run = db.transaction(() => {
|
||||
for (const { code, count } of entries) {
|
||||
upsert.run(userId, brandId, code, count);
|
||||
}
|
||||
});
|
||||
run();
|
||||
}
|
||||
|
||||
function deleteAllByUserSqlite(db: SqliteDb, userId: string): void {
|
||||
db.prepare("DELETE FROM bead_inventories WHERE user_id = ?").run(userId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dispatcher
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type MaybePromise<T> = T | Promise<T>;
|
||||
|
||||
export function getInventory(db: SqliteDb, userId: string): BeadInventoryRow[];
|
||||
export function getInventory(db: PgDb, userId: string): Promise<BeadInventoryRow[]>;
|
||||
export function getInventory(db: Db, userId: string): MaybePromise<BeadInventoryRow[]>;
|
||||
export function getInventory(db: Db, userId: string): MaybePromise<BeadInventoryRow[]> {
|
||||
return isPgDb(db) ? findAllByUserPg(db, userId) : findAllByUserSqlite(db, userId);
|
||||
}
|
||||
|
||||
/** 加豆:合并增量到已有库存(count 为加量,非绝对值)。 */
|
||||
/** 加豆:合并增量到已有库存(count 为加量,非绝对值)。count ≤ 0 时静默忽略。 */
|
||||
export function addBeads(
|
||||
db: SqliteDb,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
code: string,
|
||||
count: number,
|
||||
): void;
|
||||
export function addBeads(
|
||||
db: PgDb,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
code: string,
|
||||
count: number,
|
||||
): Promise<void>;
|
||||
export function addBeads(
|
||||
db: Db,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
code: string,
|
||||
count: number,
|
||||
): MaybePromise<void>;
|
||||
export function addBeads(
|
||||
db: Db,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
code: string,
|
||||
count: number,
|
||||
): MaybePromise<void> {
|
||||
if (count <= 0 || !Number.isFinite(count)) {
|
||||
return (isPgDb(db) ? Promise.resolve() : undefined) as MaybePromise<void>;
|
||||
}
|
||||
return isPgDb(db)
|
||||
? upsertBatchPg(db, userId, brandId, [{ code, count }])
|
||||
: upsertSingleSqlite(db, userId, brandId, code, count);
|
||||
}
|
||||
|
||||
/** SQLite 单条 upsert(加豆专用,合并数量)。 */
|
||||
function upsertSingleSqlite(
|
||||
db: SqliteDb,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
code: string,
|
||||
count: number,
|
||||
): void {
|
||||
const existing = findByUserAndCodeSqlite(db, userId, code);
|
||||
const newCount = (existing?.count ?? 0) + count;
|
||||
db.prepare(
|
||||
`INSERT INTO bead_inventories (user_id, brand_id, code, count, updated_at)
|
||||
VALUES (?, ?, ?, ?, datetime('now'))
|
||||
ON CONFLICT(user_id, code)
|
||||
DO UPDATE SET count = excluded.count, brand_id = excluded.brand_id, updated_at = datetime('now')`,
|
||||
).run(userId, brandId, code, newCount);
|
||||
}
|
||||
|
||||
/** 扣豆:按 entries 扣减,每色号扣到 0 为止,返回缺口。 */
|
||||
export function consumeBeads(
|
||||
db: SqliteDb,
|
||||
userId: string,
|
||||
entries: BeadEntry[],
|
||||
): Shortage[];
|
||||
export function consumeBeads(
|
||||
db: PgDb,
|
||||
userId: string,
|
||||
entries: BeadEntry[],
|
||||
): Promise<Shortage[]>;
|
||||
export function consumeBeads(
|
||||
db: Db,
|
||||
userId: string,
|
||||
entries: BeadEntry[],
|
||||
): MaybePromise<Shortage[]>;
|
||||
export function consumeBeads(
|
||||
db: Db,
|
||||
userId: string,
|
||||
entries: BeadEntry[],
|
||||
): MaybePromise<Shortage[]> {
|
||||
return isPgDb(db) ? consumeBeadsPg(db, userId, entries) : consumeBeadsSqlite(db, userId, entries);
|
||||
}
|
||||
|
||||
function consumeBeadsSqlite(db: SqliteDb, userId: string, entries: BeadEntry[]): Shortage[] {
|
||||
const shortages: Shortage[] = [];
|
||||
const setCount = db.prepare(
|
||||
"UPDATE bead_inventories SET count = ?, updated_at = datetime('now') WHERE user_id = ? AND code = ?",
|
||||
);
|
||||
const run = db.transaction(() => {
|
||||
for (const { code, count } of entries) {
|
||||
if (count <= 0 || !Number.isFinite(count)) continue;
|
||||
const row = findByUserAndCodeSqlite(db, userId, code);
|
||||
const have = row?.count ?? 0;
|
||||
const actual = Math.min(have, count);
|
||||
const missing = count - actual;
|
||||
if (missing > 0) {
|
||||
shortages.push({ code, count, missing });
|
||||
}
|
||||
if (actual > 0) {
|
||||
setCount.run(have - actual, userId, code);
|
||||
}
|
||||
}
|
||||
});
|
||||
run();
|
||||
return shortages;
|
||||
}
|
||||
|
||||
async function consumeBeadsPg(
|
||||
db: PgDb,
|
||||
userId: string,
|
||||
entries: BeadEntry[],
|
||||
): Promise<Shortage[]> {
|
||||
const shortages: Shortage[] = [];
|
||||
for (const { code, count } of entries) {
|
||||
if (count <= 0 || !Number.isFinite(count)) continue;
|
||||
const row = await findByUserAndCodePg(db, userId, code);
|
||||
const have = row?.count ?? 0;
|
||||
const actual = Math.min(have, count);
|
||||
const missing = count - actual;
|
||||
if (missing > 0) {
|
||||
shortages.push({ code, count, missing });
|
||||
}
|
||||
if (actual > 0) {
|
||||
await db.query(
|
||||
"UPDATE bead_inventories SET count = $1, updated_at = now() WHERE user_id = $2 AND code = $3",
|
||||
[have - actual, userId, code],
|
||||
);
|
||||
}
|
||||
}
|
||||
return shortages;
|
||||
}
|
||||
|
||||
/** 补货:补齐缺口到恰好满足用量(已有库存 ≥ 用量时不动)。 */
|
||||
export function ensureStock(
|
||||
db: SqliteDb,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
entries: BeadEntry[],
|
||||
): void;
|
||||
export function ensureStock(
|
||||
db: PgDb,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
entries: BeadEntry[],
|
||||
): Promise<void>;
|
||||
export function ensureStock(
|
||||
db: Db,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
entries: BeadEntry[],
|
||||
): MaybePromise<void>;
|
||||
export function ensureStock(
|
||||
db: Db,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
entries: BeadEntry[],
|
||||
): MaybePromise<void> {
|
||||
return isPgDb(db) ? ensureStockPg(db, userId, brandId, entries) : ensureStockSqlite(db, userId, brandId, entries);
|
||||
}
|
||||
|
||||
function ensureStockSqlite(
|
||||
db: SqliteDb,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
entries: BeadEntry[],
|
||||
): void {
|
||||
const toUpsert: BeadEntry[] = [];
|
||||
for (const { code, count } of entries) {
|
||||
if (count <= 0 || !Number.isFinite(count)) continue;
|
||||
const row = findByUserAndCodeSqlite(db, userId, code);
|
||||
if (!row || row.count < count) {
|
||||
toUpsert.push({ code, count });
|
||||
}
|
||||
}
|
||||
if (toUpsert.length > 0) {
|
||||
upsertBatchSqlite(db, userId, brandId, toUpsert);
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureStockPg(
|
||||
db: PgDb,
|
||||
userId: string,
|
||||
brandId: string,
|
||||
entries: BeadEntry[],
|
||||
): Promise<void> {
|
||||
const toUpsert: { code: string; count: number }[] = [];
|
||||
for (const { code, count } of entries) {
|
||||
if (count <= 0 || !Number.isFinite(count)) continue;
|
||||
const row = await findByUserAndCodePg(db, userId, code);
|
||||
if (!row || row.count < count) {
|
||||
toUpsert.push({ code, count });
|
||||
}
|
||||
}
|
||||
if (toUpsert.length > 0) {
|
||||
await upsertBatchPg(db, userId, brandId, toUpsert);
|
||||
}
|
||||
}
|
||||
|
||||
/** 清空用户所有库存(换品牌时调用)。 */
|
||||
export function clearInventory(db: SqliteDb, userId: string): void;
|
||||
export function clearInventory(db: PgDb, userId: string): Promise<void>;
|
||||
export function clearInventory(db: Db, userId: string): MaybePromise<void>;
|
||||
export function clearInventory(db: Db, userId: string): MaybePromise<void> {
|
||||
return isPgDb(db) ? deleteAllByUserPg(db, userId) : deleteAllByUserSqlite(db, userId);
|
||||
}
|
||||
@@ -121,6 +121,29 @@ CREATE TABLE IF NOT EXISTS showcase_works (
|
||||
|
||||
-- 索引:按创建时间倒序查询作品列表(Showcase 展示页主路径)
|
||||
CREATE INDEX IF NOT EXISTS idx_showcase_works_created_at ON showcase_works(created_at DESC, id DESC);
|
||||
|
||||
-- 用户表(账号体系:手机号 + bcrypt 密码哈希)
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY,
|
||||
phone TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
nickname TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
-- 云端豆仓表(按用户隔离,色号 → 数量)
|
||||
CREATE TABLE IF NOT EXISTS bead_inventories (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL REFERENCES users(id),
|
||||
brand_id TEXT NOT NULL DEFAULT 'MARD',
|
||||
code TEXT NOT NULL,
|
||||
count INTEGER NOT NULL DEFAULT 0 CHECK(count >= 0),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
UNIQUE(user_id, code)
|
||||
);
|
||||
|
||||
-- 索引:按用户查询库存(豆仓主路径)
|
||||
CREATE INDEX IF NOT EXISTS idx_bead_inventories_user ON bead_inventories(user_id);
|
||||
`;
|
||||
|
||||
/** All DDL statements for creating tables on PostgreSQL. */
|
||||
@@ -233,6 +256,29 @@ CREATE TABLE IF NOT EXISTS showcase_works (
|
||||
|
||||
-- 索引:按创建时间倒序查询作品列表
|
||||
CREATE INDEX IF NOT EXISTS idx_showcase_works_created_at ON showcase_works(created_at DESC, id DESC);
|
||||
|
||||
-- 用户表(账号体系:手机号 + bcrypt 密码哈希)
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY,
|
||||
phone TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
nickname TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- 云端豆仓表(按用户隔离,色号 → 数量)
|
||||
CREATE TABLE IF NOT EXISTS bead_inventories (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id),
|
||||
brand_id TEXT NOT NULL DEFAULT 'MARD',
|
||||
code TEXT NOT NULL,
|
||||
count INTEGER NOT NULL DEFAULT 0 CHECK(count >= 0),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE(user_id, code)
|
||||
);
|
||||
|
||||
-- 索引:按用户查询库存
|
||||
CREATE INDEX IF NOT EXISTS idx_bead_inventories_user ON bead_inventories(user_id);
|
||||
`;
|
||||
|
||||
/** 保留旧名以便渐进切换(SQLite DDL,用于 createTestDatabase)。 */
|
||||
|
||||
@@ -10,6 +10,8 @@ import { createPalettesRouter } from "./palettes/routes.js";
|
||||
import { createExportRouter } from "./export/routes.js";
|
||||
import { createColorChartRouter } from "./color-chart/routes.js";
|
||||
import { createShowcaseRouter } from "./showcase/routes.js";
|
||||
import { createAuthRouter } from "./auth/routes.js";
|
||||
import { createBeadsRouter } from "./beads/routes.js";
|
||||
|
||||
const PORT = parseInt(process.env["PORT"] ?? "8788", 10);
|
||||
|
||||
@@ -62,6 +64,8 @@ export function createApp(db?: Db): Express {
|
||||
app.use("/api/export", createExportRouter());
|
||||
app.use("/api/color-chart", createColorChartRouter());
|
||||
app.use("/api/showcase", createShowcaseRouter(db));
|
||||
app.use("/api/auth", createAuthRouter(db));
|
||||
app.use("/api/beads", createBeadsRouter(db));
|
||||
|
||||
// ---- 404 handler ----
|
||||
app.use((_req, res) => {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* 认证模块测试 —— 注册 / 登录 / 当前用户。
|
||||
*
|
||||
* 使用内存 SQLite 数据库 + supertest 模拟 HTTP 请求。
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import request from "supertest";
|
||||
import { createApp } from "../server.js";
|
||||
import { createTestDatabase } from "../db/index.js";
|
||||
|
||||
describe("POST /api/auth/register", () => {
|
||||
const app = createApp(createTestDatabase());
|
||||
|
||||
it("注册成功返回 201 及 token + user", async () => {
|
||||
const res = await request(app)
|
||||
.post("/api/auth/register")
|
||||
.send({ phone: "13800138000", password: "123456" });
|
||||
expect(res.status).toBe(201);
|
||||
expect(typeof res.body.token).toBe("string");
|
||||
expect(res.body.token.length).toBeGreaterThan(0);
|
||||
expect(res.body.user.phone).toBe("13800138000");
|
||||
expect(res.body.user.id).toBeDefined();
|
||||
});
|
||||
|
||||
it("重复手机号返回 409", async () => {
|
||||
await request(app)
|
||||
.post("/api/auth/register")
|
||||
.send({ phone: "13800138001", password: "123456" });
|
||||
const res = await request(app)
|
||||
.post("/api/auth/register")
|
||||
.send({ phone: "13800138001", password: "123456" });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toContain("已注册");
|
||||
});
|
||||
|
||||
it("手机号格式错误返回 400", async () => {
|
||||
const res = await request(app)
|
||||
.post("/api/auth/register")
|
||||
.send({ phone: "1234", password: "123456" });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toContain("手机号");
|
||||
});
|
||||
|
||||
it("密码少于 6 位返回 400", async () => {
|
||||
const res = await request(app)
|
||||
.post("/api/auth/register")
|
||||
.send({ phone: "13800138002", password: "123" });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toContain("密码");
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/auth/login", () => {
|
||||
const app = createApp(createTestDatabase());
|
||||
|
||||
// 先注册一个用户
|
||||
const phone = "13900139000";
|
||||
const password = "654321";
|
||||
let token = "";
|
||||
|
||||
it("注册后登录成功返回 200 + token", async () => {
|
||||
await request(app).post("/api/auth/register").send({ phone, password });
|
||||
const res = await request(app).post("/api/auth/login").send({ phone, password });
|
||||
expect(res.status).toBe(200);
|
||||
expect(typeof res.body.token).toBe("string");
|
||||
expect(res.body.user.phone).toBe(phone);
|
||||
token = res.body.token;
|
||||
});
|
||||
|
||||
it("错误密码返回 401", async () => {
|
||||
const res = await request(app).post("/api/auth/login").send({ phone, password: "wrong" });
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.error).toContain("手机号或密码错误");
|
||||
});
|
||||
|
||||
it("不存在的手机号返回 401", async () => {
|
||||
const res = await request(app)
|
||||
.post("/api/auth/login")
|
||||
.send({ phone: "19900000000", password: "123456" });
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.error).toContain("手机号或密码错误");
|
||||
});
|
||||
|
||||
it("缺少手机号或密码返回 400", async () => {
|
||||
const res = await request(app).post("/api/auth/login").send({});
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/auth/me", () => {
|
||||
const app = createApp(createTestDatabase());
|
||||
|
||||
it("未登录(无 token)返回 401", async () => {
|
||||
const res = await request(app).get("/api/auth/me");
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.error).toContain("请先登录");
|
||||
});
|
||||
|
||||
it("登录后获取当前用户信息", async () => {
|
||||
const registerRes = await request(app)
|
||||
.post("/api/auth/register")
|
||||
.send({ phone: "13700137000", password: "pass123" });
|
||||
const token = registerRes.body.token;
|
||||
|
||||
const res = await request(app)
|
||||
.get("/api/auth/me")
|
||||
.set("Authorization", `Bearer ${token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.user.phone).toBe("13700137000");
|
||||
expect(res.body.user.id).toBeDefined();
|
||||
});
|
||||
|
||||
it("无效 token 返回 401", async () => {
|
||||
const res = await request(app)
|
||||
.get("/api/auth/me")
|
||||
.set("Authorization", "Bearer invalidtoken123");
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* 云端豆仓路由测试 —— 增/查/扣/补/清(JWT 保护)。
|
||||
*
|
||||
* 流程:
|
||||
* 1. 注册用户获取 token
|
||||
* 2. 用 token 操作豆仓 API
|
||||
* 3. 验证返回结果
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import request from "supertest";
|
||||
import { createApp } from "../server.js";
|
||||
import { createTestDatabase } from "../db/index.js";
|
||||
|
||||
/** 递增计数器,每个测试唯一手机号 */
|
||||
let phoneCounter = 0;
|
||||
const uniquePhone = () => `1360000${String(10000 + phoneCounter++).slice(1)}`;
|
||||
|
||||
/** 注册用户并返回 token。 */
|
||||
async function registerAndGetToken(app: ReturnType<typeof createApp>): Promise<string> {
|
||||
const phone = uniquePhone();
|
||||
const res = await request(app)
|
||||
.post("/api/auth/register")
|
||||
.send({ phone, password: "test123456" });
|
||||
return res.body.token as string;
|
||||
}
|
||||
|
||||
describe("POST /api/beads/add", () => {
|
||||
const app = createApp(createTestDatabase());
|
||||
|
||||
it("未登录返回 401", async () => {
|
||||
const res = await request(app)
|
||||
.post("/api/beads/add")
|
||||
.send({ code: "M001", count: 100 });
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("登录后添加豆子成功", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
const res = await request(app)
|
||||
.post("/api/beads/add")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.send({ code: "M001", count: 100 });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("缺少色号返回 400", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
const res = await request(app)
|
||||
.post("/api/beads/add")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.send({ count: 100 });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toContain("色号");
|
||||
});
|
||||
|
||||
it("数量为 0 返回 400", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
const res = await request(app)
|
||||
.post("/api/beads/add")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.send({ code: "M001", count: 0 });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/beads/inventory", () => {
|
||||
const app = createApp(createTestDatabase());
|
||||
|
||||
it("新用户库存为空", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
const res = await request(app)
|
||||
.get("/api/beads/inventory")
|
||||
.set("Authorization", `Bearer ${token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.bottles).toEqual({});
|
||||
});
|
||||
|
||||
it("添加后库存包含该色号", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
await request(app)
|
||||
.post("/api/beads/add")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.send({ code: "M001", count: 100 });
|
||||
|
||||
const res = await request(app)
|
||||
.get("/api/beads/inventory")
|
||||
.set("Authorization", `Bearer ${token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.bottles["M001"]).toBe(100);
|
||||
});
|
||||
|
||||
it("多次添加同一色号累计数量", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 50 });
|
||||
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 30 });
|
||||
|
||||
const res = await request(app).get("/api/beads/inventory").set("Authorization", `Bearer ${token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.bottles["M001"]).toBe(80);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/beads/consume", () => {
|
||||
const app = createApp(createTestDatabase());
|
||||
|
||||
it("扣豆成功返回缺口列表", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
// 先加 100 颗 M001
|
||||
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 100 });
|
||||
|
||||
// 扣 30 颗 M001 + 10 颗 M002(缺口)
|
||||
const res = await request(app)
|
||||
.post("/api/beads/consume")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.send({ entries: [{ code: "M001", count: 30 }, { code: "M002", count: 10 }] });
|
||||
expect(res.status).toBe(200);
|
||||
// M001 有货,缺口 0;M002 无货,缺口 10
|
||||
const shortages = res.body.shortages as { code: string; missing: number }[];
|
||||
const m002 = shortages.find((s) => s.code === "M002");
|
||||
expect(m002?.missing).toBe(10);
|
||||
expect(shortages.find((s) => s.code === "M001")).toBeUndefined();
|
||||
|
||||
// 验证库存:M001 剩 70
|
||||
const inv = await request(app).get("/api/beads/inventory").set("Authorization", `Bearer ${token}`);
|
||||
expect(inv.body.bottles["M001"]).toBe(70);
|
||||
});
|
||||
|
||||
it("扣豆超过库存时扣到 0 并报缺口", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 10 });
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/beads/consume")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.send({ entries: [{ code: "M001", count: 100 }] });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.shortages[0]?.missing).toBe(90);
|
||||
|
||||
// 库存扣到 0
|
||||
const inv = await request(app).get("/api/beads/inventory").set("Authorization", `Bearer ${token}`);
|
||||
expect(inv.body.bottles["M001"]).toBe(0);
|
||||
});
|
||||
|
||||
it("缺少 entries 返回 400", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
const res = await request(app).post("/api/beads/consume").set("Authorization", `Bearer ${token}`).send({});
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/beads/ensure", () => {
|
||||
const app = createApp(createTestDatabase());
|
||||
|
||||
it("补货补齐缺口", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
// 有 10 颗 M001,需要 100 颗
|
||||
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 10 });
|
||||
|
||||
await request(app)
|
||||
.post("/api/beads/ensure")
|
||||
.set("Authorization", `Bearer ${token}`)
|
||||
.send({ entries: [{ code: "M001", count: 100 }], brandId: "MARD" });
|
||||
expect(200);
|
||||
|
||||
// 库存补齐到 100
|
||||
const inv = await request(app).get("/api/beads/inventory").set("Authorization", `Bearer ${token}`);
|
||||
expect(inv.body.bottles["M001"]).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/beads/clear", () => {
|
||||
const app = createApp(createTestDatabase());
|
||||
|
||||
it("清空后库存为空", async () => {
|
||||
const token = await registerAndGetToken(app);
|
||||
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M001", count: 100 });
|
||||
await request(app).post("/api/beads/add").set("Authorization", `Bearer ${token}`).send({ code: "M002", count: 50 });
|
||||
|
||||
await request(app).post("/api/beads/clear").set("Authorization", `Bearer ${token}`);
|
||||
expect(200);
|
||||
|
||||
const inv = await request(app).get("/api/beads/inventory").set("Authorization", `Bearer ${token}`);
|
||||
expect(inv.body.bottles).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -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