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 {}