merge sandbox/edd39ac: chg_0007 lite_demo_restore — 补回 lite-react book/shop demo (TypeORM-free, 33+17+16=66 e2e PASS)

Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
xstudio agentandClaude Code committed 2026-09-28 17:03:01 +08:00
1 parent 1c2f3ba234
commit df62c960f0
17 files changed
+1617 -2

No files matched your search

+4 -2
View File
@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';
import { BooksModule } from './books/books.module';
import { DthExperimentModule } from './dth/experiment/experiment.module';
import { LmsModule } from './lms/lms.module';
import { ShopModule } from './shop/shop.module';
@Module({
imports: [AuthModule, DthExperimentModule, LmsModule],
imports: [AuthModule, BooksModule, DthExperimentModule, LmsModule, ShopModule],
})
export class AppModule {}
export class AppModule {}
+64
View File
@@ -0,0 +1,64 @@
import { Body, Controller, Post, Req, UseGuards } from '@nestjs/common';
import { JwtAuthGuard, RequireAdmin } from '../auth/jwt.guard';
import {
BooksService,
} from './book.service';
import {
CreateBookDto,
GetInfoDto,
RemoveDto,
UpdateBookDto,
} from './book.entity';
/**
* BooksController — chg_0007 lite-demo books module.
* 端点风格遵循 JNPF "动词放 URL":`POST /api/ssw/dth/books/Book/{动词}`。
* 所有动作 @RequireAdmin(),与 chg_0006 LMS 同形。
*/
@Controller('api/ssw/dth/books/Book')
@UseGuards(JwtAuthGuard)
export class BooksController {
constructor(private readonly books: BooksService) {}
@Post('List')
@RequireAdmin()
async list() {
return { code: 200, msg: 'ok', data: await this.books.list() };
}
@Post('Create')
@RequireAdmin()
async create(@Body() dto: CreateBookDto, @Req() req: any) {
return {
code: 200,
msg: 'ok',
data: await this.books.create(dto, req?.user?.username ?? null),
};
}
@Post('getInfo')
@RequireAdmin()
async getInfo(@Body() dto: GetInfoDto) {
return { code: 200, msg: 'ok', data: await this.books.getInfo(dto) };
}
@Post('Update')
@RequireAdmin()
async update(@Body() dto: UpdateBookDto & { id: string }, @Req() req: any) {
return {
code: 200,
msg: 'ok',
data: await this.books.update(dto, req?.user?.username ?? null),
};
}
@Post('Remove')
@RequireAdmin()
async remove(@Body() dto: RemoveDto, @Req() req: any) {
return {
code: 200,
msg: 'ok',
data: await this.books.remove(dto, req?.user?.username ?? null),
};
}
}
+43
View File
@@ -0,0 +1,43 @@
// chg_0007 lite-demo — book entity (TypeORM-free)
// 字段严格遵循 JNPF `f_*` 前缀约定 + `f_id` varchar(50) + `f_delete_mark` 软删。
// 没有装饰器、没有 typeorm import —— 与 chg_0006 LMS 的 students.students.service.ts 同形。
export interface BookRow {
f_id: string;
f_title: string;
f_author: string | null;
f_isbn: string | null;
f_category: string | null;
f_price: string | null; // NUMERIC → string(pglite 不返回 JS number)
f_stock: number;
f_creator_user_id: string | null;
f_creator_time: string;
f_modify_time: string;
f_delete_mark: number;
}
export interface CreateBookDto {
f_title: string;
f_author?: string;
f_isbn?: string;
f_category?: string;
f_price?: string | number;
f_stock?: number;
}
export interface UpdateBookDto {
f_title?: string;
f_author?: string;
f_isbn?: string;
f_category?: string;
f_price?: string | number;
f_stock?: number;
}
export interface GetInfoDto {
id: string; // 即 f_id
}
export interface RemoveDto {
id: string;
}
+120
View File
@@ -0,0 +1,120 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { v4 as uuidv4 } from 'uuid';
import { getDb } from '../common/pglite/init';
import {
BookRow,
CreateBookDto,
GetInfoDto,
RemoveDto,
UpdateBookDto,
} from './book.entity';
/**
* BooksService — chg_0007 lite-demo books module.
* 直查 pglite,不引 typeorm。表名 = `book_shop_book`(JNPF `{appCode}_{Entity_lower}`)。
*/
@Injectable()
export class BooksService {
async list(): Promise<BookRow[]> {
const db = getDb();
const r = await db.query<BookRow>(
`SELECT f_id, f_title, f_author, f_isbn, f_category,
f_price::text AS f_price, f_stock,
f_creator_user_id, f_creator_time::text AS f_creator_time,
f_modify_time::text AS f_modify_time, f_delete_mark
FROM book_shop_book
WHERE f_delete_mark = 0
ORDER BY f_creator_time DESC`,
);
return r.rows;
}
async create(dto: CreateBookDto, userId?: string): Promise<BookRow> {
if (!dto?.f_title) {
throw new BadRequestException('f_title is required');
}
const db = getDb();
const f_id = uuidv4();
const f_author = dto.f_author ?? null;
const f_isbn = dto.f_isbn ?? null;
const f_category = dto.f_category ?? null;
const f_price = dto.f_price != null ? String(dto.f_price) : null;
const f_stock = dto.f_stock ?? 0;
await db.query(
`INSERT INTO book_shop_book
(f_id, f_title, f_author, f_isbn, f_category, f_price, f_stock, f_creator_user_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
[f_id, dto.f_title, f_author, f_isbn, f_category, f_price, f_stock, userId ?? null],
);
return (await this.getById(f_id))!;
}
async getInfo(dto: GetInfoDto): Promise<BookRow> {
const row = await this.getById(dto?.id);
if (!row) throw new NotFoundException(`book ${dto?.id} not found`);
return row;
}
async update(dto: UpdateBookDto & { id: string }, userId?: string): Promise<BookRow> {
if (!dto?.id) throw new BadRequestException('id is required');
const exist = await this.getById(dto.id);
if (!exist) throw new NotFoundException(`book ${dto.id} not found`);
const sets: string[] = [];
const params: any[] = [];
const add = (col: string, v: any) => {
params.push(v);
sets.push(`${col} = $${params.length}`);
};
if (dto.f_title !== undefined) add('f_title', dto.f_title);
if (dto.f_author !== undefined) add('f_author', dto.f_author);
if (dto.f_isbn !== undefined) add('f_isbn', dto.f_isbn);
if (dto.f_category !== undefined) add('f_category', dto.f_category);
if (dto.f_price !== undefined) add('f_price', String(dto.f_price));
if (dto.f_stock !== undefined) add('f_stock', dto.f_stock);
if (sets.length === 0) return exist;
sets.push('f_modify_time = NOW()');
if (userId) {
params.push(userId);
sets.push(`f_modify_user_id = $${params.length}`);
}
params.push(dto.id);
const db = getDb();
await db.query(
`UPDATE book_shop_book SET ${sets.join(', ')} WHERE f_id = $${params.length} AND f_delete_mark = 0`,
params,
);
return (await this.getById(dto.id))!;
}
async remove(dto: RemoveDto, userId?: string): Promise<{ id: string }> {
if (!dto?.id) throw new BadRequestException('id is required');
const exist = await this.getById(dto.id);
if (!exist) throw new NotFoundException(`book ${dto.id} not found`);
const db = getDb();
await db.query(
`UPDATE book_shop_book SET f_delete_mark = 1, f_modify_time = NOW() WHERE f_id = $1`,
[dto.id],
);
void userId;
return { id: dto.id };
}
// ---- internal ----
private async getById(id: string): Promise<BookRow | null> {
if (!id) return null;
const db = getDb();
const r = await db.query<BookRow>(
`SELECT f_id, f_title, f_author, f_isbn, f_category,
f_price::text AS f_price, f_stock,
f_creator_user_id, f_creator_time::text AS f_creator_time,
f_modify_time::text AS f_modify_time, f_delete_mark
FROM book_shop_book WHERE f_id = $1 LIMIT 1`,
[id],
);
return r.rows[0] ?? null;
}
}
+11
View File
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { BooksController } from './book.controller';
import { BooksService } from './book.service';
@Module({
imports: [AuthModule],
controllers: [BooksController],
providers: [BooksService],
})
export class BooksModule {}
+55
View File
@@ -64,6 +64,41 @@ export async function initPglite(): Promise<PGlite> {
);
CREATE INDEX IF NOT EXISTS idx_lms_enroll_student ON lms_enrollment(student_id);
CREATE INDEX IF NOT EXISTS idx_lms_enroll_course ON lms_enrollment(course_id);
-- chg_0007 lite-demo schema: book_shop_book / book_shop_product
-- JNPF f_ 前缀 + f_id varchar(50) + f_delete_mark 软删
CREATE TABLE IF NOT EXISTS book_shop_book (
f_id VARCHAR(50) PRIMARY KEY,
f_title TEXT NOT NULL,
f_author TEXT,
f_isbn TEXT,
f_category TEXT,
f_price NUMERIC(10,2),
f_stock INTEGER NOT NULL DEFAULT 0,
f_creator_user_id TEXT,
f_creator_time TIMESTAMP NOT NULL DEFAULT NOW(),
f_modify_user_id TEXT,
f_modify_time TIMESTAMP NOT NULL DEFAULT NOW(),
f_delete_mark INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_book_shop_book_title ON book_shop_book(f_title);
CREATE INDEX IF NOT EXISTS idx_book_shop_book_active ON book_shop_book(f_delete_mark);
CREATE TABLE IF NOT EXISTS book_shop_product (
f_id VARCHAR(50) PRIMARY KEY,
f_name TEXT NOT NULL,
f_sku TEXT,
f_category TEXT,
f_price NUMERIC(10,2),
f_stock INTEGER NOT NULL DEFAULT 0,
f_creator_user_id TEXT,
f_creator_time TIMESTAMP NOT NULL DEFAULT NOW(),
f_modify_user_id TEXT,
f_modify_time TIMESTAMP NOT NULL DEFAULT NOW(),
f_delete_mark INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_book_shop_product_name ON book_shop_product(f_name);
CREATE INDEX IF NOT EXISTS idx_book_shop_product_active ON book_shop_product(f_delete_mark);
`);
// Seed admin if not present
@@ -98,6 +133,26 @@ export async function initPglite(): Promise<PGlite> {
ON CONFLICT (id) DO NOTHING;`,
);
// chg_0007 lite-demo seed: 3 books + 3 products (fixed UUIDs for e2e stability)
await db.exec(
`INSERT INTO book_shop_book
(f_id, f_title, f_author, f_isbn, f_category, f_price, f_stock, f_creator_user_id)
VALUES
('b0000001-0000-0000-0000-000000000001', '数据安全导论', '王老师', '9787111000001', '计算机', 49.00, 100, '${adminUser}'),
('b0000002-0000-0000-0000-000000000002', '隐私计算实战', '陈老师', '9787111000002', '计算机', 69.00, 80, '${adminUser}'),
('b0000003-0000-0000-0000-000000000003', '联邦学习入门', '李老师', '9787111000003', '人工智能', 39.50, 60, '${adminUser}')
ON CONFLICT (f_id) DO NOTHING;`,
);
await db.exec(
`INSERT INTO book_shop_product
(f_id, f_name, f_sku, f_category, f_price, f_stock, f_creator_user_id)
VALUES
('p0000001-0000-0000-0000-000000000001', 'JNPF 入门手册', 'SKU-JNPF-001', '文档', 9.90, 500, '${adminUser}'),
('p0000002-0000-0000-0000-000000000002', 'MPC 工具链', 'SKU-MPC-002', '软件', 199.00, 30, '${adminUser}'),
('p0000003-0000-0000-0000-000000000003', 'PIR SDK', 'SKU-PIR-003', 'SDK', 299.00, 20, '${adminUser}')
ON CONFLICT (f_id) DO NOTHING;`,
);
return db;
}
@@ -0,0 +1,64 @@
import { Body, Controller, Post, Req, UseGuards } from '@nestjs/common';
import { JwtAuthGuard, RequireAdmin } from '../auth/jwt.guard';
import { ProductsService } from './product.service';
import {
CreateProductDto,
GetInfoDto,
RemoveDto,
UpdateProductDto,
} from './product.entity';
/**
* ProductsController — chg_0007 lite-demo shop module.
* 端点风格遵循 JNPF "动词放 URL":`POST /api/ssw/dth/books/Product/{动词}`。
*/
@Controller('api/ssw/dth/books/Product')
@UseGuards(JwtAuthGuard)
export class ProductsController {
constructor(private readonly products: ProductsService) {}
@Post('List')
@RequireAdmin()
async list() {
return { code: 200, msg: 'ok', data: await this.products.list() };
}
@Post('Create')
@RequireAdmin()
async create(@Body() dto: CreateProductDto, @Req() req: any) {
return {
code: 200,
msg: 'ok',
data: await this.products.create(dto, req?.user?.username ?? null),
};
}
@Post('getInfo')
@RequireAdmin()
async getInfo(@Body() dto: GetInfoDto) {
return { code: 200, msg: 'ok', data: await this.products.getInfo(dto) };
}
@Post('Update')
@RequireAdmin()
async update(
@Body() dto: UpdateProductDto & { id: string },
@Req() req: any,
) {
return {
code: 200,
msg: 'ok',
data: await this.products.update(dto, req?.user?.username ?? null),
};
}
@Post('Remove')
@RequireAdmin()
async remove(@Body() dto: RemoveDto, @Req() req: any) {
return {
code: 200,
msg: 'ok',
data: await this.products.remove(dto, req?.user?.username ?? null),
};
}
}
+40
View File
@@ -0,0 +1,40 @@
// chg_0007 lite-demo — product entity (TypeORM-free)
// 复用 books appCode,但表前缀仍为 `book_shop_`(JNPF `{appCode}_{Entity_lower}`)。
// urlAddress = `books/Product`,前端路由 `/books/Product`。
export interface ProductRow {
f_id: string;
f_name: string;
f_sku: string | null;
f_category: string | null;
f_price: string | null;
f_stock: number;
f_creator_user_id: string | null;
f_creator_time: string;
f_modify_time: string;
f_delete_mark: number;
}
export interface CreateProductDto {
f_name: string;
f_sku?: string;
f_category?: string;
f_price?: string | number;
f_stock?: number;
}
export interface UpdateProductDto {
f_name?: string;
f_sku?: string;
f_category?: string;
f_price?: string | number;
f_stock?: number;
}
export interface GetInfoDto {
id: string;
}
export interface RemoveDto {
id: string;
}
+122
View File
@@ -0,0 +1,122 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { v4 as uuidv4 } from 'uuid';
import { getDb } from '../common/pglite/init';
import {
CreateProductDto,
GetInfoDto,
ProductRow,
RemoveDto,
UpdateProductDto,
} from './product.entity';
/**
* ProductsService — chg_0007 lite-demo shop module.
* 直查 pglite,不引 typeorm。表名 = `book_shop_product`。
* 软删约定:`f_delete_mark = 1`。
*/
@Injectable()
export class ProductsService {
async list(): Promise<ProductRow[]> {
const db = getDb();
const r = await db.query<ProductRow>(
`SELECT f_id, f_name, f_sku, f_category,
f_price::text AS f_price, f_stock,
f_creator_user_id, f_creator_time::text AS f_creator_time,
f_modify_time::text AS f_modify_time, f_delete_mark
FROM book_shop_product
WHERE f_delete_mark = 0
ORDER BY f_creator_time DESC`,
);
return r.rows;
}
async create(dto: CreateProductDto, userId?: string): Promise<ProductRow> {
if (!dto?.f_name) {
throw new BadRequestException('f_name is required');
}
const db = getDb();
const f_id = uuidv4();
const f_sku = dto.f_sku ?? null;
const f_category = dto.f_category ?? null;
const f_price = dto.f_price != null ? String(dto.f_price) : null;
const f_stock = dto.f_stock ?? 0;
await db.query(
`INSERT INTO book_shop_product
(f_id, f_name, f_sku, f_category, f_price, f_stock, f_creator_user_id)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
[f_id, dto.f_name, f_sku, f_category, f_price, f_stock, userId ?? null],
);
return (await this.getById(f_id))!;
}
async getInfo(dto: GetInfoDto): Promise<ProductRow> {
const row = await this.getById(dto?.id);
if (!row) throw new NotFoundException(`product ${dto?.id} not found`);
return row;
}
async update(
dto: UpdateProductDto & { id: string },
userId?: string,
): Promise<ProductRow> {
if (!dto?.id) throw new BadRequestException('id is required');
const exist = await this.getById(dto.id);
if (!exist) throw new NotFoundException(`product ${dto.id} not found`);
const sets: string[] = [];
const params: any[] = [];
const add = (col: string, v: any) => {
params.push(v);
sets.push(`${col} = $${params.length}`);
};
if (dto.f_name !== undefined) add('f_name', dto.f_name);
if (dto.f_sku !== undefined) add('f_sku', dto.f_sku);
if (dto.f_category !== undefined) add('f_category', dto.f_category);
if (dto.f_price !== undefined) add('f_price', String(dto.f_price));
if (dto.f_stock !== undefined) add('f_stock', dto.f_stock);
if (sets.length === 0) return exist;
sets.push('f_modify_time = NOW()');
if (userId) {
params.push(userId);
sets.push(`f_modify_user_id = $${params.length}`);
}
params.push(dto.id);
const db = getDb();
await db.query(
`UPDATE book_shop_product SET ${sets.join(', ')} WHERE f_id = $${params.length} AND f_delete_mark = 0`,
params,
);
return (await this.getById(dto.id))!;
}
async remove(dto: RemoveDto, userId?: string): Promise<{ id: string }> {
if (!dto?.id) throw new BadRequestException('id is required');
const exist = await this.getById(dto.id);
if (!exist) throw new NotFoundException(`product ${dto.id} not found`);
const db = getDb();
await db.query(
`UPDATE book_shop_product SET f_delete_mark = 1, f_modify_time = NOW() WHERE f_id = $1`,
[dto.id],
);
void userId;
return { id: dto.id };
}
// ---- internal ----
private async getById(id: string): Promise<ProductRow | null> {
if (!id) return null;
const db = getDb();
const r = await db.query<ProductRow>(
`SELECT f_id, f_name, f_sku, f_category,
f_price::text AS f_price, f_stock,
f_creator_user_id, f_creator_time::text AS f_creator_time,
f_modify_time::text AS f_modify_time, f_delete_mark
FROM book_shop_product WHERE f_id = $1 LIMIT 1`,
[id],
);
return r.rows[0] ?? null;
}
}
+11
View File
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { ProductsController } from './product.controller';
import { ProductsService } from './product.service';
@Module({
imports: [AuthModule],
controllers: [ProductsController],
providers: [ProductsService],
})
export class ShopModule {}
+5
View File
@@ -4,6 +4,9 @@ import Login from './views/Login';
import Dashboard from './views/Dashboard';
import OperatorList from './views/OperatorList';
import Run from './views/Run';
// chg_0007 lite-demo: book + product 通用 CRUD 参考实现
import Book from './views/Book';
import Product from './views/Product';
export default function App() {
return (
@@ -13,6 +16,8 @@ export default function App() {
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/operators" element={<OperatorList />} />
<Route path="/operators/:code/run" element={<Run />} />
<Route path="/books/Book" element={<Book />} />
<Route path="/books/Product" element={<Product />} />
</Route>
<Route path="/" element={<Navigate to="/login" replace />} />
<Route path="*" element={<Navigate to="/login" replace />} />
+76
View File
@@ -0,0 +1,76 @@
import { AxiosResponse } from 'axios';
import { client } from './client';
/**
* chg_0007 lite-demo books API.
* 端点形态:POST /api/ssw/dth/books/Book/{List|Create|Update|Remove|getInfo}
* 响应壳:{code, msg, data} — 见 src/backend/src/common/action-result.filter.ts
*/
export interface BookRow {
f_id: string;
f_title: string;
f_author: string | null;
f_isbn: string | null;
f_category: string | null;
f_price: string | null;
f_stock: number;
f_creator_user_id: string | null;
f_creator_time: string;
f_modify_time: string;
f_delete_mark: number;
}
interface Envelope<T> {
code: number;
msg: string;
data: T;
}
async function unwrap<T>(p: Promise<AxiosResponse<Envelope<T>>>): Promise<T> {
const r = await p;
return r.data.data;
}
export function listBooks(): Promise<BookRow[]> {
return unwrap(client.post<Envelope<BookRow[]>>('/ssw/dth/books/Book/List'));
}
export function createBook(input: {
f_title: string;
f_author?: string;
f_isbn?: string;
f_category?: string;
f_price?: string | number;
f_stock?: number;
}): Promise<BookRow> {
return unwrap(
client.post<Envelope<BookRow>>('/ssw/dth/books/Book/Create', input),
);
}
export function updateBook(input: {
id: string;
f_title?: string;
f_author?: string;
f_isbn?: string;
f_category?: string;
f_price?: string | number;
f_stock?: number;
}): Promise<BookRow> {
return unwrap(
client.post<Envelope<BookRow>>('/ssw/dth/books/Book/Update', input),
);
}
export function removeBook(id: string): Promise<{ id: string }> {
return unwrap(
client.post<Envelope<{ id: string }>>('/ssw/dth/books/Book/Remove', { id }),
);
}
export function getBookInfo(id: string): Promise<BookRow> {
return unwrap(
client.post<Envelope<BookRow>>('/ssw/dth/books/Book/getInfo', { id }),
);
}
+73
View File
@@ -0,0 +1,73 @@
import { AxiosResponse } from 'axios';
import { client } from './client';
/**
* chg_0007 lite-demo shop (products) API.
* 端点形态:POST /api/ssw/dth/books/Product/{List|Create|Update|Remove|getInfo}
* 响应壳:{code, msg, data} — 见 src/backend/src/common/action-result.filter.ts
*/
export interface ProductRow {
f_id: string;
f_name: string;
f_sku: string | null;
f_category: string | null;
f_price: string | null;
f_stock: number;
f_creator_user_id: string | null;
f_creator_time: string;
f_modify_time: string;
f_delete_mark: number;
}
interface Envelope<T> {
code: number;
msg: string;
data: T;
}
async function unwrap<T>(p: Promise<AxiosResponse<Envelope<T>>>): Promise<T> {
const r = await p;
return r.data.data;
}
export function listProducts(): Promise<ProductRow[]> {
return unwrap(client.post<Envelope<ProductRow[]>>('/ssw/dth/books/Product/List'));
}
export function createProduct(input: {
f_name: string;
f_sku?: string;
f_category?: string;
f_price?: string | number;
f_stock?: number;
}): Promise<ProductRow> {
return unwrap(
client.post<Envelope<ProductRow>>('/ssw/dth/books/Product/Create', input),
);
}
export function updateProduct(input: {
id: string;
f_name?: string;
f_sku?: string;
f_category?: string;
f_price?: string | number;
f_stock?: number;
}): Promise<ProductRow> {
return unwrap(
client.post<Envelope<ProductRow>>('/ssw/dth/books/Product/Update', input),
);
}
export function removeProduct(id: string): Promise<{ id: string }> {
return unwrap(
client.post<Envelope<{ id: string }>>('/ssw/dth/books/Product/Remove', { id }),
);
}
export function getProductInfo(id: string): Promise<ProductRow> {
return unwrap(
client.post<Envelope<ProductRow>>('/ssw/dth/books/Product/getInfo', { id }),
);
}
+253
View File
@@ -0,0 +1,253 @@
import { FormEvent, useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { BookRow, createBook, listBooks, removeBook, updateBook } from '../api/book';
import { useAuth } from '../components/AuthContext';
import type { ApiError } from '../api/client';
interface FormState {
f_title: string;
f_author: string;
f_isbn: string;
f_category: string;
f_price: string;
f_stock: string;
}
const EMPTY_FORM: FormState = {
f_title: '',
f_author: '',
f_isbn: '',
f_category: '',
f_price: '',
f_stock: '0',
};
export default function Book() {
const { user, clearAuth } = useAuth();
const [books, setBooks] = useState<BookRow[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [editing, setEditing] = useState<BookRow | null>(null);
const [showForm, setShowForm] = useState(false);
const [form, setForm] = useState<FormState>(EMPTY_FORM);
const [submitting, setSubmitting] = useState(false);
async function refresh() {
setError(null);
try {
const rows = await listBooks();
setBooks(rows);
} catch (e) {
const apiErr = e as ApiError;
setError(apiErr.kind === 'envelope' ? apiErr.msg : '加载失败');
}
}
useEffect(() => {
refresh();
}, []);
function openCreate() {
setEditing(null);
setForm(EMPTY_FORM);
setShowForm(true);
}
function openEdit(row: BookRow) {
setEditing(row);
setForm({
f_title: row.f_title,
f_author: row.f_author ?? '',
f_isbn: row.f_isbn ?? '',
f_category: row.f_category ?? '',
f_price: row.f_price ?? '',
f_stock: String(row.f_stock ?? 0),
});
setShowForm(true);
}
async function onSubmit(e: FormEvent) {
e.preventDefault();
setSubmitting(true);
setError(null);
try {
const payload = {
f_title: form.f_title.trim(),
f_author: form.f_author.trim() || undefined,
f_isbn: form.f_isbn.trim() || undefined,
f_category: form.f_category.trim() || undefined,
f_price: form.f_price.trim() || undefined,
f_stock: form.f_stock ? Number(form.f_stock) : 0,
};
if (editing) {
await updateBook({ id: editing.f_id, ...payload });
} else {
await createBook(payload);
}
setShowForm(false);
await refresh();
} catch (e) {
const apiErr = e as ApiError;
setError(apiErr.kind === 'envelope' ? apiErr.msg : '保存失败');
} finally {
setSubmitting(false);
}
}
async function onRemove(id: string) {
if (!confirm('确认软删除这本书?')) return;
setError(null);
try {
await removeBook(id);
await refresh();
} catch (e) {
const apiErr = e as ApiError;
setError(apiErr.kind === 'envelope' ? apiErr.msg : '删除失败');
}
}
return (
<div className="book-list">
<header className="book-list__header">
<Link className="book-list__back" to="/dashboard">
← 返回 Dashboard
</Link>
<h1>图书管理</h1>
<div className="book-list__user">
<span>
{user?.username ?? '匿名'}
{user?.isAdmin ? ' · 管理员' : ''}
</span>
<button
className="book-list__logout"
onClick={() => {
clearAuth();
window.location.assign('/login');
}}
>
退出
</button>
</div>
</header>
<section className="book-list__actions">
<button
className="book-list__create"
onClick={openCreate}
data-testid="book-create-btn"
>
+ 新建图书
</button>
</section>
{error && (
<div className="book-list__error" role="alert">
{error}
</div>
)}
{!books && !error && <div className="book-list__loading">加载中…</div>}
{books && books.length === 0 && (
<div className="book-list__empty">暂无图书</div>
)}
{books && books.length > 0 && (
<table className="book-list__table" data-testid="book-table">
<thead>
<tr>
<th>书名</th>
<th>作者</th>
<th>ISBN</th>
<th>分类</th>
<th>价格</th>
<th>库存</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{books.map((b) => (
<tr key={b.f_id} data-testid={`book-row-${b.f_id}`}>
<td>{b.f_title}</td>
<td>{b.f_author ?? '-'}</td>
<td>{b.f_isbn ?? '-'}</td>
<td>{b.f_category ?? '-'}</td>
<td>{b.f_price ?? '-'}</td>
<td>{b.f_stock}</td>
<td>
<button onClick={() => openEdit(b)}>编辑</button>{' '}
<button onClick={() => onRemove(b.f_id)}>删除</button>
</td>
</tr>
))}
</tbody>
</table>
)}
{showForm && (
<div className="book-list__modal">
<form className="book-list__modal-card" onSubmit={onSubmit}>
<h2>{editing ? '编辑图书' : '新建图书'}</h2>
<label>
书名 <em>*</em>
<input
required
value={form.f_title}
onChange={(e) => setForm({ ...form, f_title: e.target.value })}
data-testid="book-form-title"
/>
</label>
<label>
作者
<input
value={form.f_author}
onChange={(e) => setForm({ ...form, f_author: e.target.value })}
/>
</label>
<label>
ISBN
<input
value={form.f_isbn}
onChange={(e) => setForm({ ...form, f_isbn: e.target.value })}
/>
</label>
<label>
分类
<input
value={form.f_category}
onChange={(e) => setForm({ ...form, f_category: e.target.value })}
/>
</label>
<label>
价格
<input
value={form.f_price}
onChange={(e) => setForm({ ...form, f_price: e.target.value })}
/>
</label>
<label>
库存
<input
type="number"
min={0}
value={form.f_stock}
onChange={(e) => setForm({ ...form, f_stock: e.target.value })}
/>
</label>
<div className="book-list__modal-actions">
<button type="submit" disabled={submitting} data-testid="book-form-submit">
{submitting ? '保存中…' : '保存'}
</button>
<button
type="button"
onClick={() => setShowForm(false)}
disabled={submitting}
>
取消
</button>
</div>
</form>
</div>
)}
</div>
);
}
+246
View File
@@ -0,0 +1,246 @@
import { FormEvent, useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import {
ProductRow,
createProduct,
listProducts,
removeProduct,
updateProduct,
} from '../api/product';
import { useAuth } from '../components/AuthContext';
import type { ApiError } from '../api/client';
interface FormState {
f_name: string;
f_sku: string;
f_category: string;
f_price: string;
f_stock: string;
}
const EMPTY_FORM: FormState = {
f_name: '',
f_sku: '',
f_category: '',
f_price: '',
f_stock: '0',
};
export default function Product() {
const { user, clearAuth } = useAuth();
const [products, setProducts] = useState<ProductRow[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [editing, setEditing] = useState<ProductRow | null>(null);
const [showForm, setShowForm] = useState(false);
const [form, setForm] = useState<FormState>(EMPTY_FORM);
const [submitting, setSubmitting] = useState(false);
async function refresh() {
setError(null);
try {
const rows = await listProducts();
setProducts(rows);
} catch (e) {
const apiErr = e as ApiError;
setError(apiErr.kind === 'envelope' ? apiErr.msg : '加载失败');
}
}
useEffect(() => {
refresh();
}, []);
function openCreate() {
setEditing(null);
setForm(EMPTY_FORM);
setShowForm(true);
}
function openEdit(row: ProductRow) {
setEditing(row);
setForm({
f_name: row.f_name,
f_sku: row.f_sku ?? '',
f_category: row.f_category ?? '',
f_price: row.f_price ?? '',
f_stock: String(row.f_stock ?? 0),
});
setShowForm(true);
}
async function onSubmit(e: FormEvent) {
e.preventDefault();
setSubmitting(true);
setError(null);
try {
const payload = {
f_name: form.f_name.trim(),
f_sku: form.f_sku.trim() || undefined,
f_category: form.f_category.trim() || undefined,
f_price: form.f_price.trim() || undefined,
f_stock: form.f_stock ? Number(form.f_stock) : 0,
};
if (editing) {
await updateProduct({ id: editing.f_id, ...payload });
} else {
await createProduct(payload);
}
setShowForm(false);
await refresh();
} catch (e) {
const apiErr = e as ApiError;
setError(apiErr.kind === 'envelope' ? apiErr.msg : '保存失败');
} finally {
setSubmitting(false);
}
}
async function onRemove(id: string) {
if (!confirm('确认软删除该商品?')) return;
setError(null);
try {
await removeProduct(id);
await refresh();
} catch (e) {
const apiErr = e as ApiError;
setError(apiErr.kind === 'envelope' ? apiErr.msg : '删除失败');
}
}
return (
<div className="product-list">
<header className="product-list__header">
<Link className="product-list__back" to="/dashboard">
← 返回 Dashboard
</Link>
<h1>商品管理</h1>
<div className="product-list__user">
<span>
{user?.username ?? '匿名'}
{user?.isAdmin ? ' · 管理员' : ''}
</span>
<button
className="product-list__logout"
onClick={() => {
clearAuth();
window.location.assign('/login');
}}
>
退出
</button>
</div>
</header>
<section className="product-list__actions">
<button
className="product-list__create"
onClick={openCreate}
data-testid="product-create-btn"
>
+ 新建商品
</button>
</section>
{error && (
<div className="product-list__error" role="alert">
{error}
</div>
)}
{!products && !error && <div className="product-list__loading">加载中…</div>}
{products && products.length === 0 && (
<div className="product-list__empty">暂无商品</div>
)}
{products && products.length > 0 && (
<table className="product-list__table" data-testid="product-table">
<thead>
<tr>
<th>商品名</th>
<th>SKU</th>
<th>分类</th>
<th>价格</th>
<th>库存</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{products.map((p) => (
<tr key={p.f_id} data-testid={`product-row-${p.f_id}`}>
<td>{p.f_name}</td>
<td>{p.f_sku ?? '-'}</td>
<td>{p.f_category ?? '-'}</td>
<td>{p.f_price ?? '-'}</td>
<td>{p.f_stock}</td>
<td>
<button onClick={() => openEdit(p)}>编辑</button>{' '}
<button onClick={() => onRemove(p.f_id)}>删除</button>
</td>
</tr>
))}
</tbody>
</table>
)}
{showForm && (
<div className="product-list__modal">
<form className="product-list__modal-card" onSubmit={onSubmit}>
<h2>{editing ? '编辑商品' : '新建商品'}</h2>
<label>
商品名 <em>*</em>
<input
required
value={form.f_name}
onChange={(e) => setForm({ ...form, f_name: e.target.value })}
data-testid="product-form-name"
/>
</label>
<label>
SKU
<input
value={form.f_sku}
onChange={(e) => setForm({ ...form, f_sku: e.target.value })}
/>
</label>
<label>
分类
<input
value={form.f_category}
onChange={(e) => setForm({ ...form, f_category: e.target.value })}
/>
</label>
<label>
价格
<input
value={form.f_price}
onChange={(e) => setForm({ ...form, f_price: e.target.value })}
/>
</label>
<label>
库存
<input
type="number"
min={0}
value={form.f_stock}
onChange={(e) => setForm({ ...form, f_stock: e.target.value })}
/>
</label>
<div className="product-list__modal-actions">
<button type="submit" disabled={submitting} data-testid="product-form-submit">
{submitting ? '保存中…' : '保存'}
</button>
<button
type="button"
onClick={() => setShowForm(false)}
disabled={submitting}
>
取消
</button>
</div>
</form>
</div>
)}
</div>
);
}