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:
1 parent
1c2f3ba234
commit
df62c960f0
17 files changed
+1617
-2
No files matched your search
@@ -0,0 +1,196 @@
|
||||
# lite-demo design (chg_0007)
|
||||
|
||||
> 补回 ssw-jnpf-lite-react skill 自带的 book / shop demo 模块。
|
||||
> 适配 dth workspace 的 TypeORM-free 后端栈,与 chg_0006 LMS 同形。
|
||||
|
||||
## 1. 背景
|
||||
|
||||
`chg_0001` 起骨架时容器内 `~/.claude/skills/` 软链断裂(见
|
||||
`docs/superpowers/learnings/2026-09-28-dispatch-session.md` §A-1),骨架 agent
|
||||
没找到 `ssw-jnpf-lite-react` skill,改为手写最小 NestJS,**丢了 book / shop /
|
||||
dashboard demo 模块**。chg_0006 LMS、chg_0002 experiment 落地后,业务特定形态
|
||||
有了,但"通用业务模块参考实现"仍然是缺的——
|
||||
|
||||
- 新人 `git clone` 跟进本仓库,看不到一个完整的"实体 CRUD + 鉴权 + 软删"
|
||||
端到端参考实现。
|
||||
- `HOWTO_MODULE.md` 引用的 demo 用例是 `book` + `shop`,缺失让文档与现实脱节。
|
||||
- 后续 chg(如 SP-3 课程内容、SP-4 LMS 高级特性)很可能需要"通用业务模块"
|
||||
形态作为参照。
|
||||
|
||||
`chg_0007` 的目标就是把 `book` + `shop` 这两个 MVP 演示模块补回来。
|
||||
|
||||
## 3. TypeORM-free 选型理由
|
||||
|
||||
skill 自带 backend 用 TypeORM(`@nestjs/typeorm` + `Repository<Book>` +
|
||||
装饰器实体)。**直接复制粘贴会与 dth 后端栈冲突**:
|
||||
|
||||
| 维度 | dth 后端(现状) | skill 原生 |
|
||||
|---|---|---|
|
||||
| ORM | pglite + `getDb()` 直查(chg_0006 LMS 模式) | TypeORM + Repository |
|
||||
| 实体定义 | interface + 静态类型 | `@Entity()` + `@Column()` |
|
||||
| 鉴权 | `JwtAuthGuard` + `RequireAdmin()`(admin-only CRUD) | 同上 |
|
||||
| 表名前缀 | `lms_` / `dth_` / `book_shop_` 三套并存 | 单一 `{app_code}_` 前缀 |
|
||||
| 响应壳 | `{code, msg, data}` ActionResultFilter | 同 |
|
||||
|
||||
本仓库 `package.json` 没有 `typeorm` / `@nestjs/typeorm` 依赖,复制装饰器
|
||||
后会在 `tsc --noEmit` 阶段就挂掉(找不到 `typeorm` 模块)。因此采用与 chg_0006
|
||||
完全对齐的"getDb() 直查"模式:
|
||||
|
||||
```typescript
|
||||
// src/backend/src/books/book.service.ts
|
||||
import { getDb } from '../common/pglite/init';
|
||||
@Injectable()
|
||||
export class BooksService {
|
||||
async list(): Promise<BookRow[]> {
|
||||
const db = getDb();
|
||||
const { rows } = await db.query<BookRow>(
|
||||
`SELECT * FROM book_shop_book WHERE f_delete_mark = 0 ORDER BY f_creator_time DESC`,
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**不引入**:`typeorm`, `@nestjs/typeorm`, `@nestjsx/crud`, `class-transformer`
|
||||
之外的运行时依赖。
|
||||
|
||||
## 4. 模块命名(与 HOWTO_MODULE.md §零 一字不差)
|
||||
|
||||
```
|
||||
业务名:图书超市
|
||||
→ appCode = books
|
||||
→ 文件夹 = src/backend/src/books/
|
||||
→ 表名 = book_shop_book # JNPF 表名规则 {appCode}_{Entity_lower}
|
||||
→ 端点 Entity = Book
|
||||
→ urlAddress = books/Book
|
||||
→ 前端 Route = /books/Book
|
||||
→ 前端视图文件 = Book.tsx
|
||||
→ 前端 api 文件 = api/book.ts
|
||||
|
||||
业务名:超市
|
||||
→ appCode = books (复用 books appCode,表名前缀仍为 book_shop_)
|
||||
→ Entity = Product
|
||||
→ urlAddress = books/Product
|
||||
→ 前端视图文件 = Product.tsx
|
||||
→ 前端 api 文件 = api/product.ts
|
||||
```
|
||||
|
||||
注:dth 后端鉴权简化(仅 admin/non-admin 二值,无 RBAC),所有 CRUD 用 admin
|
||||
token 调通即可;前端菜单按 urlAddress 注册。
|
||||
|
||||
## 5. 表设计(`f_*` 前缀 + `f_id varchar(50)` + `f_delete_mark` 软删)
|
||||
|
||||
```sql
|
||||
CREATE TABLE 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 DEFAULT 0,
|
||||
f_creator_user_id TEXT,
|
||||
f_creator_time TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
f_delete_mark INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE 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 DEFAULT 0,
|
||||
f_creator_user_id TEXT,
|
||||
f_creator_time TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
f_delete_mark INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
```
|
||||
|
||||
`f_delete_mark = 0` 表示未删除;list 查询固定 `WHERE f_delete_mark = 0`;
|
||||
remove 接口固定 `UPDATE ... SET f_delete_mark = 1`,**不真删**(保留审计
|
||||
痕迹,符合 JNPF `f_delete_mark` 约定)。
|
||||
|
||||
## 6. 端点形态(JNPF 风格,5 个动词 × 2 个 Entity)
|
||||
|
||||
```
|
||||
POST /api/ssw/dth/books/Book/List # 列表
|
||||
POST /api/ssw/dth/books/Book/Create # 新建
|
||||
POST /api/ssw/dth/books/Book/Update # 更新
|
||||
POST /api/ssw/dth/books/Book/Remove # 软删
|
||||
POST /api/ssw/dth/books/Book/getInfo # 详情(按 body.id)
|
||||
|
||||
POST /api/ssw/dth/books/Product/List # 同上五件套
|
||||
POST /api/ssw/dth/books/Product/Create
|
||||
POST /api/ssw/dth/books/Product/Update
|
||||
POST /api/ssw/dth/books/Product/Remove
|
||||
POST /api/ssw/dth/books/Product/getInfo
|
||||
```
|
||||
|
||||
与 chg_0006 LMS(RESTful 风格 `GET /api/ssw/dth/lms/students`)的差异:
|
||||
lite-demo 严格遵循 JNPF "动词放 URL" 风格,便于 skill 模板对照;guard 与
|
||||
envelope 完全一致。
|
||||
|
||||
## 7. 与 chg_0006 LMS 一致性说明
|
||||
|
||||
| 维度 | chg_0006 LMS | chg_0007 lite-demo |
|
||||
|---|---|---|
|
||||
| 后端栈 | NestJS + pglite + `getDb()` | 完全相同 |
|
||||
| 鉴权 | `JwtAuthGuard` + `@RequireAdmin()` | 完全相同 |
|
||||
| 响应壳 | `{code, msg, data}` via ActionResultFilter | 完全相同 |
|
||||
| 软删约定 | `DELETE FROM ...` 真删 | `f_delete_mark = 1` 软删(JNPF 约定) |
|
||||
| 表前缀 | `lms_*` | `book_shop_*` |
|
||||
| 端点动词 | RESTful(GET/POST/PUT/DELETE) | JNPF 风格(POST + 动词 URL) |
|
||||
| 实体形态 | interface(无装饰器) | interface(无装饰器) |
|
||||
| 种子数据 | 2 students + 2 courses(chg_0006 spec) | 3 books + 3 products(chg_0007 spec) |
|
||||
|
||||
唯一的差别是"硬删 vs 软删"——这是 chg_0007 spec §S4 明确要求的 JNPF
|
||||
约定;spec 已写死,本文档不重新决策。
|
||||
|
||||
## 8. 改动文件清单
|
||||
|
||||
```
|
||||
docs/dth/lite-demo/design.md # 本文件
|
||||
src/backend/src/books/
|
||||
book.entity.ts interface BookRow + 静态类型
|
||||
book.service.ts list/create/update/getInfo/remove
|
||||
book.controller.ts POST 5 个端点 + JwtAuthGuard + RequireAdmin
|
||||
books.module.ts Module({ providers, controllers })
|
||||
src/backend/src/shop/
|
||||
product.entity.ts interface ProductRow
|
||||
product.service.ts list/create/update/getInfo/remove
|
||||
product.controller.ts POST 5 个端点
|
||||
shop.module.ts
|
||||
src/backend/src/common/pglite/init.ts
|
||||
# 追加 book_shop_book + book_shop_product 两张表 + 6 行 seed
|
||||
src/backend/src/app.module.ts
|
||||
# 追加 imports + modules: [BooksModule, ShopModule]
|
||||
src/frontend/src/api/book.ts # axios 调用封装
|
||||
src/frontend/src/api/product.ts
|
||||
src/frontend/src/views/Book.tsx # 列表 + 新建/编辑表单
|
||||
src/frontend/src/views/Product.tsx
|
||||
src/frontend/src/App.tsx # 加 2 条 Route
|
||||
tests/e2e/dth_lite_demo.test.sh # C1-C8
|
||||
```
|
||||
|
||||
## 9. 不做的清单(与 chg_0007 proposal.md 一致)
|
||||
|
||||
- 不复制 skill 的 sys/UserManage/RoleManage/MenuManage(dth 已有简化 auth)
|
||||
- 不复制 skill 的 typeorm 依赖
|
||||
- 不动 experiment / LMS / auth(契约红线)
|
||||
- 不做前端 Dashboard 实时数据
|
||||
- 不引 typeorm / @nestjs/typeorm / jnpf-* / ssw-* 共享模块
|
||||
|
||||
## 10. 风险与回退
|
||||
|
||||
- **mount 不可用 / tsc 不通 / pglite init seed 失败** → 立即回退给 host,
|
||||
不硬改 `tsconfig` 或绕过 gate(openspec §实施步骤约定 3)。
|
||||
- **pglite 表名冲突** → 已确认 `book_shop_book` / `book_shop_product` 与
|
||||
LMS(`lms_*`)/ experiment(`dth_*`)不冲突。
|
||||
- **admin token 鉴权重定向** → JwtAuthGuard + RequireAdmin() 与 chg_0006
|
||||
完全相同,e2e 已验证。
|
||||
|
||||
---
|
||||
|
||||
变更锚点:`openspec/changes/chg_0007_lite_demo_restore/{proposal.md,spec.md,tasks.md,testcases.md}`
|
||||
相关:chg_0006 LMS(TypeORM-free 参考实现)、chg_0005 experiment extend
|
||||
@@ -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 {}
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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 />} />
|
||||
|
||||
@@ -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 }),
|
||||
);
|
||||
}
|
||||
@@ -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 }),
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
Executable
+234
@@ -0,0 +1,234 @@
|
||||
#!/usr/bin/env bash
|
||||
# dth_lite_demo.test.sh — e2e verification for S1..S5 of chg_0007 (lite-demo restore).
|
||||
# Exit 0 only if all 5 scenarios pass (8 cases total). Each assertion is a hard-fail.
|
||||
#
|
||||
# Usage:
|
||||
# DTH_BASE=http://127.0.0.1:30000 bash tests/e2e/dth_lite_demo.test.sh
|
||||
#
|
||||
# Pre-req: backend is running and admin + 3 books + 3 products seeded.
|
||||
# (3 books/products come from src/backend/src/common/pglite/init.ts)
|
||||
|
||||
set -uo pipefail
|
||||
|
||||
BASE="${DTH_BASE:-http://127.0.0.1:${PORT:-30000}}"
|
||||
LOGIN_URL="$BASE/api/ssw/dth/auth/login"
|
||||
BOOK_LIST_URL="$BASE/api/ssw/dth/books/Book/List"
|
||||
BOOK_CREATE_URL="$BASE/api/ssw/dth/books/Book/Create"
|
||||
PRODUCT_LIST_URL="$BASE/api/ssw/dth/books/Product/List"
|
||||
PRODUCT_UPDATE_URL="$BASE/api/ssw/dth/books/Product/Update"
|
||||
PRODUCT_REMOVE_URL="$BASE/api/ssw/dth/books/Product/Remove"
|
||||
|
||||
# Fixed seed UUIDs (from pglite/init.ts chg_0007 lite-demo seed)
|
||||
SEED_BOOK_1="b0000001-0000-0000-0000-000000000001"
|
||||
SEED_BOOK_2="b0000002-0000-0000-0000-000000000002"
|
||||
SEED_BOOK_3="b0000003-0000-0000-0000-000000000003"
|
||||
SEED_PRODUCT_1="p0000001-0000-0000-0000-000000000001"
|
||||
SEED_PRODUCT_2="p0000002-0000-0000-0000-000000000002"
|
||||
SEED_PRODUCT_3="p0000003-0000-0000-0000-000000000003"
|
||||
|
||||
pass=0; fail=0; fails=()
|
||||
|
||||
json_get() {
|
||||
local field="$1"; local body="$2"
|
||||
python3 -c "import json,sys; d=json.loads(sys.argv[1]); print(d${field})" "$body" 2>/dev/null
|
||||
}
|
||||
|
||||
login() {
|
||||
curl -s -X POST "$LOGIN_URL" -H 'Content-Type: application/json' \
|
||||
-d "{\"username\":\"$1\",\"password\":\"$2\"}"
|
||||
}
|
||||
|
||||
assert() {
|
||||
local id="$1"; local cond="$2"; local detail="$3"
|
||||
if eval "$cond"; then
|
||||
pass=$((pass+1))
|
||||
printf " ✓ %s\n" "$id"
|
||||
else
|
||||
fail=$((fail+1))
|
||||
fails+=("$id: $detail")
|
||||
printf " ✗ %s — %s\n" "$id" "$detail"
|
||||
fi
|
||||
}
|
||||
|
||||
# ============================================================
|
||||
# pre: login admin
|
||||
# ============================================================
|
||||
ADMIN_BODY="$(login admin 123456)"
|
||||
ADMIN_TOKEN="$(json_get "['data']['token']" "$ADMIN_BODY")"
|
||||
assert "pre_admin_login" "[ -n '$ADMIN_TOKEN' ]" "admin token empty; login body=$ADMIN_BODY"
|
||||
|
||||
# ============================================================
|
||||
# S1 / C1: books list with admin token returns ≥3 rows + correct schema
|
||||
# ============================================================
|
||||
LIST_BOOKS_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" \
|
||||
-H 'Content-Type: application/json' -d '{}' "$BOOK_LIST_URL")"
|
||||
LIST_BOOKS_CODE="$(json_get "['code']" "$LIST_BOOKS_BODY")"
|
||||
LIST_BOOKS_LEN="$(python3 -c "import json,sys; print(len(json.loads(sys.argv[1])['data']))" "$LIST_BOOKS_BODY" 2>/dev/null)"
|
||||
BOOK_HAS_FIELDS="$(python3 -c "
|
||||
import json,sys
|
||||
d=json.loads(sys.argv[1])
|
||||
need={'f_id','f_title','f_author','f_isbn','f_price','f_stock','f_creator_user_id'}
|
||||
print(all(need.issubset(set(b.keys())) for b in d['data']))
|
||||
" "$LIST_BOOKS_BODY")"
|
||||
HAS_SEED_BOOK="$(python3 -c "
|
||||
import json,sys
|
||||
d=json.loads(sys.argv[1])
|
||||
ids={b['f_id'] for b in d['data']}
|
||||
print('$SEED_BOOK_1' in ids)
|
||||
" "$LIST_BOOKS_BODY")"
|
||||
assert "C1_books_list_admin_code_200" "[ '$LIST_BOOKS_CODE' = '200' ]" "code=$LIST_BOOKS_CODE"
|
||||
assert "C1_books_list_len_ge_3" "[ '$LIST_BOOKS_LEN' -ge 3 ]" "got $LIST_BOOKS_LEN"
|
||||
assert "C1_books_list_schema_ok" "[ '$BOOK_HAS_FIELDS' = 'True' ]" "schema missing fields"
|
||||
assert "C1_books_list_has_seed" "[ '$HAS_SEED_BOOK' = 'True' ]" "seed book id missing"
|
||||
|
||||
# ============================================================
|
||||
# S1 / C2: no token returns code=600 (not logged in)
|
||||
# ============================================================
|
||||
NO_AUTH_BODY="$(curl -s -H 'Content-Type: application/json' -d '{}' "$BOOK_LIST_URL")"
|
||||
NO_AUTH_CODE="$(json_get "['code']" "$NO_AUTH_BODY")"
|
||||
assert "C2_books_list_nonadmin_600" "[ '$NO_AUTH_CODE' = '600' ]" "code=$NO_AUTH_CODE"
|
||||
|
||||
# ============================================================
|
||||
# S2 / C3: create book with admin token succeeds
|
||||
# ============================================================
|
||||
CREATE_BOOK_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
|
||||
-d '{"f_title":"测试书","f_author":"测试","f_isbn":"9787123456789","f_category":"计算机","f_price":"99.00","f_stock":10}' \
|
||||
"$BOOK_CREATE_URL")"
|
||||
CREATE_BOOK_CODE="$(json_get "['code']" "$CREATE_BOOK_BODY")"
|
||||
NEW_BOOK_ID="$(json_get "['data']['f_id']" "$CREATE_BOOK_BODY")"
|
||||
NEW_BOOK_TITLE="$(json_get "['data']['f_title']" "$CREATE_BOOK_BODY")"
|
||||
assert "C3_books_create_code_200" "[ '$CREATE_BOOK_CODE' = '200' ]" "code=$CREATE_BOOK_CODE"
|
||||
assert "C3_books_create_id_uuid" "echo '$NEW_BOOK_ID' | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'" "f_id=$NEW_BOOK_ID"
|
||||
assert "C3_books_create_title" "[ '$NEW_BOOK_TITLE' = '测试书' ]" "title=$NEW_BOOK_TITLE"
|
||||
|
||||
# verify it shows up in list now
|
||||
LIST_BOOKS_BODY_2="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" \
|
||||
-H 'Content-Type: application/json' -d '{}' "$BOOK_LIST_URL")"
|
||||
LIST_BOOKS_LEN_2="$(python3 -c "import json,sys; print(len(json.loads(sys.argv[1])['data']))" "$LIST_BOOKS_BODY_2" 2>/dev/null)"
|
||||
LIST_BOOKS_HAS_NEW="$(python3 -c "
|
||||
import json,sys
|
||||
d=json.loads(sys.argv[1])
|
||||
ids={b['f_id'] for b in d['data']}
|
||||
print('$NEW_BOOK_ID' in ids)
|
||||
" "$LIST_BOOKS_BODY_2")"
|
||||
assert "C3_books_create_in_list" "[ '$LIST_BOOKS_HAS_NEW' = 'True' ]" "new book not in list"
|
||||
assert "C3_books_list_len_increased" "[ '$LIST_BOOKS_LEN_2' -gt '$LIST_BOOKS_LEN' ]" "before=$LIST_BOOKS_LEN after=$LIST_BOOKS_LEN_2"
|
||||
|
||||
# ============================================================
|
||||
# S2 / C4: create without auth returns 600
|
||||
# ============================================================
|
||||
NO_AUTH_CREATE_BODY="$(curl -s -H 'Content-Type: application/json' \
|
||||
-d '{"f_title":"x"}' "$BOOK_CREATE_URL")"
|
||||
NO_AUTH_CREATE_CODE="$(json_get "['code']" "$NO_AUTH_CREATE_BODY")"
|
||||
assert "C4_books_create_nonadmin_600" "[ '$NO_AUTH_CREATE_CODE' = '600' ]" "code=$NO_AUTH_CREATE_CODE"
|
||||
|
||||
# ============================================================
|
||||
# S3 / C5: products list returns ≥3 + correct schema
|
||||
# ============================================================
|
||||
LIST_PRODUCTS_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" \
|
||||
-H 'Content-Type: application/json' -d '{}' "$PRODUCT_LIST_URL")"
|
||||
LIST_PRODUCTS_CODE="$(json_get "['code']" "$LIST_PRODUCTS_BODY")"
|
||||
LIST_PRODUCTS_LEN="$(python3 -c "import json,sys; print(len(json.loads(sys.argv[1])['data']))" "$LIST_PRODUCTS_BODY" 2>/dev/null)"
|
||||
PRODUCT_HAS_FIELDS="$(python3 -c "
|
||||
import json,sys
|
||||
d=json.loads(sys.argv[1])
|
||||
need={'f_id','f_name','f_sku','f_category','f_price','f_stock'}
|
||||
print(all(need.issubset(set(p.keys())) for p in d['data']))
|
||||
" "$LIST_PRODUCTS_BODY")"
|
||||
HAS_SEED_PRODUCT="$(python3 -c "
|
||||
import json,sys
|
||||
d=json.loads(sys.argv[1])
|
||||
ids={p['f_id'] for p in d['data']}
|
||||
print('$SEED_PRODUCT_1' in ids)
|
||||
" "$LIST_PRODUCTS_BODY")"
|
||||
assert "C5_shop_list_admin_code_200" "[ '$LIST_PRODUCTS_CODE' = '200' ]" "code=$LIST_PRODUCTS_CODE"
|
||||
assert "C5_shop_list_len_ge_3" "[ '$LIST_PRODUCTS_LEN' -ge 3 ]" "got $LIST_PRODUCTS_LEN"
|
||||
assert "C5_shop_list_schema_ok" "[ '$PRODUCT_HAS_FIELDS' = 'True' ]" "schema missing fields"
|
||||
assert "C5_shop_list_has_seed" "[ '$HAS_SEED_PRODUCT' = 'True' ]" "seed product id missing"
|
||||
|
||||
# ============================================================
|
||||
# S4 / C6: update product price → 99.99 + remove → soft-delete + list excludes
|
||||
# (create a fresh product first so the test is idempotent across reruns)
|
||||
# ============================================================
|
||||
CREATE_PRODUCT_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
|
||||
-d '{"f_name":"E2E 测试商品","f_sku":"SKU-E2E-C6","f_category":"e2e","f_price":"50.00","f_stock":5}' \
|
||||
"$BASE/api/ssw/dth/books/Product/Create")"
|
||||
C6_PRODUCT_ID="$(json_get "['data']['f_id']" "$CREATE_PRODUCT_BODY")"
|
||||
assert "C6_setup_create_product" "echo '$C6_PRODUCT_ID' | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'" "f_id=$C6_PRODUCT_ID"
|
||||
|
||||
UPDATE_PRODUCT_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
|
||||
-d "{\"id\":\"$C6_PRODUCT_ID\",\"f_price\":\"99.99\"}" "$PRODUCT_UPDATE_URL")"
|
||||
UPDATE_PRODUCT_CODE="$(json_get "['code']" "$UPDATE_PRODUCT_BODY")"
|
||||
UPDATE_PRODUCT_PRICE="$(json_get "['data']['f_price']" "$UPDATE_PRODUCT_BODY")"
|
||||
assert "C6_shop_update_code_200" "[ '$UPDATE_PRODUCT_CODE' = '200' ]" "code=$UPDATE_PRODUCT_CODE"
|
||||
assert "C6_shop_update_price" "[ '$UPDATE_PRODUCT_PRICE' = '99.99' ]" "f_price=$UPDATE_PRODUCT_PRICE"
|
||||
|
||||
REMOVE_PRODUCT_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
|
||||
-d "{\"id\":\"$C6_PRODUCT_ID\"}" "$PRODUCT_REMOVE_URL")"
|
||||
REMOVE_PRODUCT_CODE="$(json_get "['code']" "$REMOVE_PRODUCT_BODY")"
|
||||
REMOVE_PRODUCT_ID="$(json_get "['data']['id']" "$REMOVE_PRODUCT_BODY")"
|
||||
assert "C6_shop_remove_code_200" "[ '$REMOVE_PRODUCT_CODE' = '200' ]" "code=$REMOVE_PRODUCT_CODE"
|
||||
assert "C6_shop_remove_returns_id" "[ '$REMOVE_PRODUCT_ID' = '$C6_PRODUCT_ID' ]" "id=$REMOVE_PRODUCT_ID"
|
||||
|
||||
LIST_PRODUCTS_BODY_2="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" \
|
||||
-H 'Content-Type: application/json' -d '{}' "$PRODUCT_LIST_URL")"
|
||||
LIST_PRODUCTS_HAS_REMOVED="$(python3 -c "
|
||||
import json,sys
|
||||
d=json.loads(sys.argv[1])
|
||||
ids={p['f_id'] for p in d['data']}
|
||||
print('$C6_PRODUCT_ID' in ids)
|
||||
" "$LIST_PRODUCTS_BODY_2")"
|
||||
assert "C6_shop_softdelete_excludes" "[ '$LIST_PRODUCTS_HAS_REMOVED' = 'False' ]" "soft-deleted product still in list"
|
||||
|
||||
# ============================================================
|
||||
# S4 / C7: remove an existing product (also fresh-create for idempotency)
|
||||
# ============================================================
|
||||
CREATE_PRODUCT_2_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
|
||||
-d '{"f_name":"E2E 测试商品 C7","f_sku":"SKU-E2E-C7","f_category":"e2e","f_price":"60.00","f_stock":6}' \
|
||||
"$BASE/api/ssw/dth/books/Product/Create")"
|
||||
C7_PRODUCT_ID="$(json_get "['data']['f_id']" "$CREATE_PRODUCT_2_BODY")"
|
||||
assert "C7_setup_create_product" "echo '$C7_PRODUCT_ID' | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'" "f_id=$C7_PRODUCT_ID"
|
||||
|
||||
REMOVE_PRODUCT_2_BODY="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
|
||||
-d "{\"id\":\"$C7_PRODUCT_ID\"}" "$PRODUCT_REMOVE_URL")"
|
||||
REMOVE_PRODUCT_2_CODE="$(json_get "['code']" "$REMOVE_PRODUCT_2_BODY")"
|
||||
assert "C7_shop_remove_code_200" "[ '$REMOVE_PRODUCT_2_CODE' = '200' ]" "code=$REMOVE_PRODUCT_2_CODE"
|
||||
|
||||
# verify the row still exists in DB but with f_delete_mark=1
|
||||
# (we cannot query directly via HTTP; instead verify subsequent list excludes it)
|
||||
LIST_PRODUCTS_BODY_3="$(curl -s -H "Authorization: Bearer $ADMIN_TOKEN" \
|
||||
-H 'Content-Type: application/json' -d '{}' "$PRODUCT_LIST_URL")"
|
||||
LIST_PRODUCTS_HAS_P2="$(python3 -c "
|
||||
import json,sys
|
||||
d=json.loads(sys.argv[1])
|
||||
ids={p['f_id'] for p in d['data']}
|
||||
print('$C7_PRODUCT_ID' in ids)
|
||||
" "$LIST_PRODUCTS_BODY_3")"
|
||||
assert "C7_shop_softdelete_excludes" "[ '$LIST_PRODUCTS_HAS_P2' = 'False' ]" "soft-deleted product still in list"
|
||||
|
||||
# ============================================================
|
||||
# S5 / C8: menu + route wiring (files exist + App.tsx has the routes)
|
||||
# ============================================================
|
||||
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
BOOK_VIEW="$ROOT/src/frontend/src/views/Book.tsx"
|
||||
PRODUCT_VIEW="$ROOT/src/frontend/src/views/Product.tsx"
|
||||
APP_TSX="$ROOT/src/frontend/src/App.tsx"
|
||||
SEED_INIT_TS="$ROOT/src/backend/src/common/pglite/init.ts"
|
||||
APP_MODULE="$ROOT/src/backend/src/app.module.ts"
|
||||
|
||||
assert "C8_book_view_exists" "[ -f '$BOOK_VIEW' ]" "Book.tsx missing"
|
||||
assert "C8_product_view_exists" "[ -f '$PRODUCT_VIEW' ]" "Product.tsx missing"
|
||||
assert "C8_route_book_exists" "grep -q 'path=\"/books/Book\"' '$APP_TSX'" "App.tsx missing /books/Book route"
|
||||
assert "C8_route_product_exists" "grep -q 'path=\"/books/Product\"' '$APP_TSX'" "App.tsx missing /books/Product route"
|
||||
assert "C8_seed_has_book_table" "grep -q 'book_shop_book' '$SEED_INIT_TS'" "init.ts missing book_shop_book"
|
||||
assert "C8_seed_has_product_table" "grep -q 'book_shop_product' '$SEED_INIT_TS'" "init.ts missing book_shop_product"
|
||||
assert "C8_appmodule_books_registered" "grep -q 'BooksModule' '$APP_MODULE'" "app.module.ts missing BooksModule"
|
||||
assert "C8_appmodule_shop_registered" "grep -q 'ShopModule' '$APP_MODULE'" "app.module.ts missing ShopModule"
|
||||
|
||||
echo "---"
|
||||
echo "e2e dth_lite_demo: pass=$pass fail=$fail"
|
||||
if [ $fail -gt 0 ]; then
|
||||
printf 'FAILED:\n'; printf ' - %s\n' "${fails[@]}"
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
||||
Reference in new issue
Block a user