feat(v2.2): 完成高频读取热路径
This commit is contained in:
@@ -6,9 +6,10 @@ import { AiModule } from './modules/ai/ai.module';
|
||||
import { ConfigModule } from './modules/config/config.module';
|
||||
import { DataModule } from './modules/data/data.module';
|
||||
import { MigrationModule } from './modules/migration/migration.module';
|
||||
import { V22QueryModule } from './modules/v22-query/v22-query.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, ProductModule, RequirementModule, ConfigModule, DataModule, MigrationModule, AiModule],
|
||||
imports: [PrismaModule, ProductModule, RequirementModule, ConfigModule, DataModule, MigrationModule, V22QueryModule, AiModule],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
})
|
||||
|
||||
@@ -55,6 +55,31 @@ function buildAppData(): Record<string, any> {
|
||||
},
|
||||
],
|
||||
},
|
||||
members: {
|
||||
members: [
|
||||
{
|
||||
id: 'member-pm',
|
||||
name: 'Product manager',
|
||||
username: 'pm',
|
||||
email: '',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'member-dev',
|
||||
name: 'Developer',
|
||||
username: 'dev',
|
||||
email: 'dev@example.com',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'member-test',
|
||||
name: 'Tester',
|
||||
username: 'test',
|
||||
email: '',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
},
|
||||
'task-categories': [
|
||||
{
|
||||
id: 'cat-fe',
|
||||
@@ -261,6 +286,11 @@ describe('mapAppDataToV22Rows', () => {
|
||||
releaseDate: '2026-02-01',
|
||||
}),
|
||||
]);
|
||||
expect(result.users).toEqual([
|
||||
expect.objectContaining({ id: 'member-pm', email: 'pm@local.ftb', name: 'Product manager' }),
|
||||
expect.objectContaining({ id: 'member-dev', email: 'dev@example.com', name: 'Developer' }),
|
||||
expect.objectContaining({ id: 'member-test', email: 'test@local.ftb', name: 'Tester' }),
|
||||
]);
|
||||
|
||||
expect(result.requirements).toEqual([
|
||||
expect.objectContaining({
|
||||
|
||||
@@ -34,6 +34,15 @@ interface VersionRow {
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
interface UserRow {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
avatar?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
interface RequirementRow {
|
||||
id: string;
|
||||
productId: string;
|
||||
@@ -256,6 +265,7 @@ export interface V22MappedRows {
|
||||
products: ProductRow[];
|
||||
projects: ProjectRow[];
|
||||
versions: VersionRow[];
|
||||
users: UserRow[];
|
||||
requirements: RequirementRow[];
|
||||
taskCategories: TaskCategoryRow[];
|
||||
versionPlans: VersionPlanRow[];
|
||||
@@ -277,6 +287,7 @@ export function mapAppDataToV22Rows(appData: Record<string, unknown>): V22Mapped
|
||||
const products: ProductRow[] = [];
|
||||
const projects: ProjectRow[] = [];
|
||||
const versions: VersionRow[] = [];
|
||||
const users: UserRow[] = [];
|
||||
const requirements: RequirementRow[] = [];
|
||||
const taskCategories: TaskCategoryRow[] = [];
|
||||
const versionPlans: VersionPlanRow[] = [];
|
||||
@@ -346,6 +357,21 @@ export function mapAppDataToV22Rows(appData: Record<string, unknown>): V22Mapped
|
||||
}
|
||||
}
|
||||
|
||||
const nextEmail = uniqueEmailFactory();
|
||||
for (const [index, member] of readNestedArray(appData.members, 'members').entries()) {
|
||||
const id = stringField(member, 'id') ?? `member-${index + 1}`;
|
||||
const username = stringField(member, 'username') ?? id;
|
||||
const email = normalizeMemberEmail(stringField(member, 'email'), username, id);
|
||||
users.push({
|
||||
id,
|
||||
email: nextEmail(email),
|
||||
name: stringField(member, 'name') ?? username,
|
||||
avatar: stringField(member, 'avatar'),
|
||||
createdAt: stringField(member, 'createdAt'),
|
||||
updatedAt: stringField(member, 'updatedAt') ?? stringField(member, 'createdAt'),
|
||||
});
|
||||
}
|
||||
|
||||
const defaultProductId = products[0]?.id;
|
||||
const requirementCode = scopedCodeFactory('REQ');
|
||||
for (const [index, requirement] of readNestedArray(appData.requirements, 'requirements').entries()) {
|
||||
@@ -705,6 +731,7 @@ export function mapAppDataToV22Rows(appData: Record<string, unknown>): V22Mapped
|
||||
products,
|
||||
projects,
|
||||
versions,
|
||||
users,
|
||||
requirements,
|
||||
taskCategories,
|
||||
versionPlans,
|
||||
@@ -809,6 +836,34 @@ function scopedCodeFactory(prefix: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function uniqueEmailFactory() {
|
||||
const used = new Set<string>();
|
||||
return (email: string): string => {
|
||||
const normalized = email.trim().toLowerCase();
|
||||
if (!used.has(normalized)) {
|
||||
used.add(normalized);
|
||||
return normalized;
|
||||
}
|
||||
const atIndex = normalized.indexOf('@');
|
||||
const name = atIndex >= 0 ? normalized.slice(0, atIndex) : normalized;
|
||||
const domain = atIndex >= 0 ? normalized.slice(atIndex + 1) : 'local.ftb';
|
||||
let suffix = 2;
|
||||
let next = `${name}+${suffix}@${domain}`;
|
||||
while (used.has(next)) {
|
||||
suffix++;
|
||||
next = `${name}+${suffix}@${domain}`;
|
||||
}
|
||||
used.add(next);
|
||||
return next;
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeMemberEmail(email: string | undefined, username: string, id: string): string {
|
||||
if (email?.includes('@')) return email;
|
||||
const base = email || username || id;
|
||||
return `${base.trim().toLowerCase()}@local.ftb`;
|
||||
}
|
||||
|
||||
function inferProjectIdForVersion(version: AppDataRecord, projects: AppDataRecord[]): string | undefined {
|
||||
const explicitProjectId = stringField(version, 'projectId');
|
||||
if (explicitProjectId) return explicitProjectId;
|
||||
|
||||
@@ -15,6 +15,20 @@ describe('AppDataV22MigrationService', () => {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'members',
|
||||
value: {
|
||||
members: [
|
||||
{
|
||||
id: 'member-pm',
|
||||
name: 'Product manager',
|
||||
username: 'pm',
|
||||
email: '',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'requirements',
|
||||
value: {
|
||||
@@ -26,6 +40,7 @@ describe('AppDataV22MigrationService', () => {
|
||||
projectId: 'project-1',
|
||||
versionId: 'version-1',
|
||||
title: 'Customer import',
|
||||
creator: 'member-pm',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
@@ -64,10 +79,98 @@ describe('AppDataV22MigrationService', () => {
|
||||
products: 1,
|
||||
projects: 1,
|
||||
versions: 1,
|
||||
users: 1,
|
||||
requirements: 1,
|
||||
devTasks: 1,
|
||||
}),
|
||||
);
|
||||
expect(preview.skipped).toEqual([]);
|
||||
});
|
||||
|
||||
it('imports mapped rows in foreign-key-safe order with duplicate protection', async () => {
|
||||
const calls: string[] = [];
|
||||
const delegate = (name: string) => ({
|
||||
createMany: jest.fn().mockImplementation(async () => {
|
||||
calls.push(name);
|
||||
return { count: 1 };
|
||||
}),
|
||||
});
|
||||
const tx = {
|
||||
user: delegate('user'),
|
||||
product: delegate('product'),
|
||||
project: delegate('project'),
|
||||
version: delegate('version'),
|
||||
taskCategory: delegate('taskCategory'),
|
||||
requirement: delegate('requirement'),
|
||||
versionPlan: delegate('versionPlan'),
|
||||
devTask: delegate('devTask'),
|
||||
testCase: delegate('testCase'),
|
||||
bug: delegate('bug'),
|
||||
workActivity: delegate('workActivity'),
|
||||
taskWorklog: delegate('taskWorklog'),
|
||||
overtimeRecord: delegate('overtimeRecord'),
|
||||
xiaobaoRiskSnapshot: delegate('xiaobaoRiskSnapshot'),
|
||||
xiaobaoRiskInsight: delegate('xiaobaoRiskInsight'),
|
||||
xiaobaoRiskSummary: delegate('xiaobaoRiskSummary'),
|
||||
};
|
||||
const prisma = {
|
||||
$transaction: jest.fn().mockImplementation(async (callback: (client: typeof tx) => Promise<unknown>) => callback(tx)),
|
||||
appData: { findMany: jest.fn() },
|
||||
};
|
||||
const service = new AppDataV22MigrationService(prisma as any);
|
||||
const mapped = service.mapSnapshot({
|
||||
'products-overview': [
|
||||
{
|
||||
id: 'product-1',
|
||||
name: 'FTB',
|
||||
projects: [{ id: 'project-1', name: 'CRM', description: '', createdAt: '2026-01-01T00:00:00.000Z' }],
|
||||
versions: [{ id: 'version-1', name: 'CRM V1.0', createdAt: '2026-01-01T00:00:00.000Z' }],
|
||||
},
|
||||
],
|
||||
members: {
|
||||
members: [{ id: 'member-pm', name: 'Product manager', username: 'pm', email: '', createdAt: '2026-01-01' }],
|
||||
},
|
||||
'task-categories': [
|
||||
{
|
||||
id: 'cat-fe',
|
||||
code: 'frontend_development',
|
||||
name: 'Frontend development',
|
||||
group: 'development',
|
||||
isSystem: true,
|
||||
},
|
||||
],
|
||||
requirements: {
|
||||
requirements: [
|
||||
{
|
||||
id: 'req-1',
|
||||
code: 'REQ-001',
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
versionId: 'version-1',
|
||||
title: 'Customer import',
|
||||
creator: 'member-pm',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.importMappedRows(mapped);
|
||||
|
||||
expect(result.readyToImport).toBe(true);
|
||||
expect(result.inserted).toEqual(expect.objectContaining({ users: 1, products: 1, requirements: 1 }));
|
||||
expect(calls.slice(0, 6)).toEqual(['user', 'product', 'project', 'version', 'taskCategory', 'requirement']);
|
||||
expect(tx.user.createMany).toHaveBeenCalledWith({
|
||||
data: [expect.objectContaining({
|
||||
id: 'member-pm',
|
||||
email: 'pm@local.ftb',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
})],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
expect(tx.requirement.createMany).toHaveBeenCalledWith({
|
||||
data: [expect.objectContaining({ creatorId: 'member-pm' })],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { APP_DATA_KEYS } from '../data/data-keys';
|
||||
import { mapAppDataToV22Rows, type V22MappedRows } from './app-data-v22.mapper';
|
||||
|
||||
const COUNT_KEYS = [
|
||||
'users',
|
||||
'products',
|
||||
'projects',
|
||||
'versions',
|
||||
'requirements',
|
||||
'taskCategories',
|
||||
'requirements',
|
||||
'versionPlans',
|
||||
'devTasks',
|
||||
'testCases',
|
||||
@@ -23,6 +24,72 @@ const COUNT_KEYS = [
|
||||
] as const;
|
||||
|
||||
type CountKey = (typeof COUNT_KEYS)[number];
|
||||
type DelegateName =
|
||||
| 'user'
|
||||
| 'product'
|
||||
| 'project'
|
||||
| 'version'
|
||||
| 'taskCategory'
|
||||
| 'requirement'
|
||||
| 'versionPlan'
|
||||
| 'devTask'
|
||||
| 'testCase'
|
||||
| 'bug'
|
||||
| 'workActivity'
|
||||
| 'taskWorklog'
|
||||
| 'overtimeRecord'
|
||||
| 'xiaobaoRiskSnapshot'
|
||||
| 'xiaobaoRiskInsight'
|
||||
| 'xiaobaoRiskSummary';
|
||||
|
||||
type CreateManyDelegate = {
|
||||
createMany(args: { data: unknown[]; skipDuplicates: boolean }): Promise<{ count: number }>;
|
||||
};
|
||||
|
||||
type MigrationTransaction = Record<DelegateName, CreateManyDelegate>;
|
||||
|
||||
const DELEGATE_BY_COUNT_KEY: Record<CountKey, DelegateName> = {
|
||||
users: 'user',
|
||||
products: 'product',
|
||||
projects: 'project',
|
||||
versions: 'version',
|
||||
taskCategories: 'taskCategory',
|
||||
requirements: 'requirement',
|
||||
versionPlans: 'versionPlan',
|
||||
devTasks: 'devTask',
|
||||
testCases: 'testCase',
|
||||
bugs: 'bug',
|
||||
workActivities: 'workActivity',
|
||||
taskWorklogs: 'taskWorklog',
|
||||
overtimeRecords: 'overtimeRecord',
|
||||
xiaobaoRiskSnapshots: 'xiaobaoRiskSnapshot',
|
||||
xiaobaoRiskInsights: 'xiaobaoRiskInsight',
|
||||
xiaobaoRiskSummaries: 'xiaobaoRiskSummary',
|
||||
aiLogs: 'user',
|
||||
};
|
||||
|
||||
const DATE_TIME_KEYS = new Set([
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'releaseDate',
|
||||
'expectedStartAt',
|
||||
'expectedEndAt',
|
||||
'actualStartAt',
|
||||
'completedAt',
|
||||
'startDate',
|
||||
'plannedTestAt',
|
||||
'plannedEndAt',
|
||||
'startedAt',
|
||||
'plannedFixAt',
|
||||
'resolvedAt',
|
||||
'closedAt',
|
||||
'startAt',
|
||||
'endAt',
|
||||
'occurredAt',
|
||||
'aiDraftAt',
|
||||
'recomputedAt',
|
||||
'forecastReleaseDate',
|
||||
]);
|
||||
|
||||
export interface AppDataV22MigrationPreview {
|
||||
readyToImport: boolean;
|
||||
@@ -30,6 +97,10 @@ export interface AppDataV22MigrationPreview {
|
||||
skipped: V22MappedRows['skipped'];
|
||||
}
|
||||
|
||||
export interface AppDataV22MigrationImportResult extends AppDataV22MigrationPreview {
|
||||
inserted: Record<CountKey, number>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AppDataV22MigrationService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@@ -54,8 +125,65 @@ export class AppDataV22MigrationService {
|
||||
skipped: mapped.skipped,
|
||||
};
|
||||
}
|
||||
|
||||
async importCurrentAppData(): Promise<AppDataV22MigrationImportResult> {
|
||||
return this.importMappedRows(this.mapSnapshot(await this.loadSnapshot()));
|
||||
}
|
||||
|
||||
async importMappedRows(mapped: V22MappedRows): Promise<AppDataV22MigrationImportResult> {
|
||||
if (mapped.skipped.length > 0) {
|
||||
throw new BadRequestException({
|
||||
code: 'APP_DATA_V22_MIGRATION_HAS_SKIPPED_ROWS',
|
||||
message: 'Resolve skipped AppData rows before importing V2.2 relation tables.',
|
||||
skipped: mapped.skipped,
|
||||
});
|
||||
}
|
||||
|
||||
const inserted = await this.prisma.$transaction(async (tx) => {
|
||||
const client = tx as unknown as MigrationTransaction;
|
||||
const result = emptyCounts();
|
||||
for (const key of COUNT_KEYS) {
|
||||
if (key === 'aiLogs') continue;
|
||||
result[key] = await createMany(client[DELEGATE_BY_COUNT_KEY[key]], mapped[key]);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
return {
|
||||
readyToImport: true,
|
||||
counts: countRows(mapped),
|
||||
skipped: [],
|
||||
inserted,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function countRows(mapped: V22MappedRows): Record<CountKey, number> {
|
||||
return Object.fromEntries(COUNT_KEYS.map((key) => [key, mapped[key].length])) as Record<CountKey, number>;
|
||||
}
|
||||
|
||||
function emptyCounts(): Record<CountKey, number> {
|
||||
return Object.fromEntries(COUNT_KEYS.map((key) => [key, 0])) as Record<CountKey, number>;
|
||||
}
|
||||
|
||||
async function createMany(delegate: CreateManyDelegate, data: unknown[]): Promise<number> {
|
||||
if (data.length === 0) return 0;
|
||||
const result = await delegate.createMany({ data: data.map(normalizeDateTimeFields), skipDuplicates: true });
|
||||
return result.count;
|
||||
}
|
||||
|
||||
function normalizeDateTimeFields(row: unknown): unknown {
|
||||
if (typeof row !== 'object' || row === null || Array.isArray(row)) return row;
|
||||
return Object.fromEntries(
|
||||
Object.entries(row).map(([key, value]) => [
|
||||
key,
|
||||
DATE_TIME_KEYS.has(key) ? normalizeDateTimeValue(value) : value,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeDateTimeValue(value: unknown): unknown {
|
||||
if (typeof value !== 'string') return value;
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return `${value}T00:00:00.000Z`;
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { V22QueryController } from './v22-query.controller';
|
||||
|
||||
describe('V22QueryController', () => {
|
||||
it('forwards V2.2 hot-path requests to the query service', async () => {
|
||||
const service = {
|
||||
getVersionDetailData: jest.fn().mockResolvedValue({ version: { id: 'version-1' } }),
|
||||
listRequirements: jest.fn().mockResolvedValue({ items: [], nextCursor: undefined }),
|
||||
getWorkspaceData: jest.fn().mockResolvedValue({ devTasks: [] }),
|
||||
getXiaobaoWarnings: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
const controller = new V22QueryController(service as any);
|
||||
|
||||
await controller.getVersionDetailData('version-1');
|
||||
await controller.listRequirements(
|
||||
'product-1',
|
||||
'project-1',
|
||||
undefined,
|
||||
'adopted',
|
||||
'P1',
|
||||
'feature',
|
||||
'login',
|
||||
'created_at_asc',
|
||||
'req-2',
|
||||
'50',
|
||||
);
|
||||
await controller.getWorkspaceData('member-1');
|
||||
await controller.getXiaobaoWarnings('member-1', 'false');
|
||||
|
||||
expect(service.getVersionDetailData).toHaveBeenCalledWith('version-1');
|
||||
expect(service.listRequirements).toHaveBeenCalledWith({
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
versionId: undefined,
|
||||
status: 'adopted',
|
||||
priority: 'P1',
|
||||
type: 'feature',
|
||||
q: 'login',
|
||||
sort: 'created_at_asc',
|
||||
cursor: 'req-2',
|
||||
limit: '50',
|
||||
});
|
||||
expect(service.getWorkspaceData).toHaveBeenCalledWith('member-1');
|
||||
expect(service.getXiaobaoWarnings).toHaveBeenCalledWith({ userId: 'member-1', manager: 'false' });
|
||||
});
|
||||
});
|
||||
52
apps/server/src/modules/v22-query/v22-query.controller.ts
Normal file
52
apps/server/src/modules/v22-query/v22-query.controller.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { Controller, Get, Param, Query } from '@nestjs/common';
|
||||
import { V22QueryService } from './v22-query.service';
|
||||
|
||||
@Controller('v2.2')
|
||||
export class V22QueryController {
|
||||
constructor(private readonly v22QueryService: V22QueryService) {}
|
||||
|
||||
@Get('versions/:versionId/detail-data')
|
||||
getVersionDetailData(@Param('versionId') versionId: string) {
|
||||
return this.v22QueryService.getVersionDetailData(versionId);
|
||||
}
|
||||
|
||||
@Get('requirements')
|
||||
listRequirements(
|
||||
@Query('productId') productId?: string,
|
||||
@Query('projectId') projectId?: string,
|
||||
@Query('versionId') versionId?: string,
|
||||
@Query('status') status?: string,
|
||||
@Query('priority') priority?: string,
|
||||
@Query('type') type?: string,
|
||||
@Query('q') q?: string,
|
||||
@Query('sort') sort?: string,
|
||||
@Query('cursor') cursor?: string,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
return this.v22QueryService.listRequirements({
|
||||
productId,
|
||||
projectId,
|
||||
versionId,
|
||||
status,
|
||||
priority,
|
||||
type,
|
||||
q,
|
||||
sort,
|
||||
cursor,
|
||||
limit,
|
||||
});
|
||||
}
|
||||
|
||||
@Get('workspace')
|
||||
getWorkspaceData(@Query('userId') userId: string) {
|
||||
return this.v22QueryService.getWorkspaceData(userId);
|
||||
}
|
||||
|
||||
@Get('xiaobao-warning')
|
||||
getXiaobaoWarnings(
|
||||
@Query('userId') userId?: string,
|
||||
@Query('manager') manager?: string,
|
||||
) {
|
||||
return this.v22QueryService.getXiaobaoWarnings({ userId, manager });
|
||||
}
|
||||
}
|
||||
9
apps/server/src/modules/v22-query/v22-query.module.ts
Normal file
9
apps/server/src/modules/v22-query/v22-query.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { V22QueryController } from './v22-query.controller';
|
||||
import { V22QueryService } from './v22-query.service';
|
||||
|
||||
@Module({
|
||||
controllers: [V22QueryController],
|
||||
providers: [V22QueryService],
|
||||
})
|
||||
export class V22QueryModule {}
|
||||
157
apps/server/src/modules/v22-query/v22-query.service.spec.ts
Normal file
157
apps/server/src/modules/v22-query/v22-query.service.spec.ts
Normal file
@@ -0,0 +1,157 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { V22QueryService } from './v22-query.service';
|
||||
|
||||
function buildPrismaMock() {
|
||||
return {
|
||||
version: {
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
requirement: {
|
||||
findMany: jest.fn(),
|
||||
},
|
||||
versionPlan: {
|
||||
findMany: jest.fn(),
|
||||
},
|
||||
devTask: {
|
||||
findMany: jest.fn(),
|
||||
},
|
||||
testCase: {
|
||||
findMany: jest.fn(),
|
||||
},
|
||||
bug: {
|
||||
findMany: jest.fn(),
|
||||
},
|
||||
xiaobaoRiskSummary: {
|
||||
findMany: jest.fn(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('V22QueryService', () => {
|
||||
it('loads version detail data through version-scoped relation queries', async () => {
|
||||
const prisma = buildPrismaMock();
|
||||
prisma.version.findUnique.mockResolvedValue({ id: 'version-1', productId: 'product-1', projectId: 'project-1' });
|
||||
prisma.requirement.findMany.mockResolvedValue([{ id: 'req-1' }]);
|
||||
prisma.versionPlan.findMany.mockResolvedValue([{ id: 'plan-1' }]);
|
||||
prisma.devTask.findMany.mockResolvedValue([{ id: 'dev-1' }]);
|
||||
prisma.testCase.findMany.mockResolvedValue([{ id: 'tc-1' }]);
|
||||
prisma.bug.findMany.mockResolvedValue([{ id: 'bug-1' }]);
|
||||
const service = new V22QueryService(prisma as any);
|
||||
|
||||
const result = await service.getVersionDetailData('version-1');
|
||||
|
||||
expect(result.requirements).toEqual([{ id: 'req-1' }]);
|
||||
expect(result.devTasks).toEqual([{ id: 'dev-1' }]);
|
||||
expect(prisma.requirement.findMany).toHaveBeenCalledWith({
|
||||
where: { versionId: 'version-1' },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
expect(prisma.devTask.findMany).toHaveBeenCalledWith({
|
||||
where: { versionId: 'version-1' },
|
||||
orderBy: [{ status: 'asc' }, { updatedAt: 'desc' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects missing productId for requirement pool queries to avoid full-table scans', async () => {
|
||||
const service = new V22QueryService(buildPrismaMock() as any);
|
||||
|
||||
await expect(service.listRequirements({})).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('paginates requirement pool queries by product partition key and composite cursor', async () => {
|
||||
const prisma = buildPrismaMock();
|
||||
prisma.requirement.findMany.mockResolvedValue([{ id: 'req-2' }, { id: 'req-1' }]);
|
||||
const service = new V22QueryService(prisma as any);
|
||||
|
||||
const result = await service.listRequirements({
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
status: 'adopted',
|
||||
priority: 'P1',
|
||||
type: 'feature',
|
||||
q: 'login',
|
||||
sort: 'created_at_asc',
|
||||
cursor: 'req-3',
|
||||
limit: '1',
|
||||
});
|
||||
|
||||
expect(result).toEqual({ items: [{ id: 'req-2' }], nextCursor: 'req-1' });
|
||||
expect(prisma.requirement.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
status: 'adopted',
|
||||
priority: 1,
|
||||
type: 'feature',
|
||||
OR: [
|
||||
{ code: { contains: 'login', mode: 'insensitive' } },
|
||||
{ title: { contains: 'login', mode: 'insensitive' } },
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: 2,
|
||||
cursor: { id_productId: { id: 'req-3', productId: 'product-1' } },
|
||||
skip: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('aggregates workspace rows by current user without scanning unrelated assignees', async () => {
|
||||
const prisma = buildPrismaMock();
|
||||
prisma.versionPlan.findMany.mockResolvedValue([{ id: 'plan-1' }]);
|
||||
prisma.devTask.findMany.mockResolvedValue([{ id: 'dev-1' }]);
|
||||
prisma.testCase.findMany.mockResolvedValue([{ id: 'tc-1' }]);
|
||||
prisma.bug.findMany.mockResolvedValue([{ id: 'bug-1' }]);
|
||||
const service = new V22QueryService(prisma as any);
|
||||
|
||||
const result = await service.getWorkspaceData('member-1');
|
||||
|
||||
expect(result).toEqual({
|
||||
versionPlans: [{ id: 'plan-1' }],
|
||||
devTasks: [{ id: 'dev-1' }],
|
||||
testCases: [{ id: 'tc-1' }],
|
||||
bugs: [{ id: 'bug-1' }],
|
||||
});
|
||||
expect(prisma.devTask.findMany).toHaveBeenCalledWith({
|
||||
where: { assigneeId: 'member-1', status: { not: 'submitted' } },
|
||||
orderBy: [{ priority: 'asc' }, { updatedAt: 'desc' }],
|
||||
});
|
||||
expect(prisma.bug.findMany).toHaveBeenCalledWith({
|
||||
where: { assigneeId: 'member-1', status: { in: ['open', 'fixing', 'fixed', 'verifying'] } },
|
||||
orderBy: [{ priority: 'asc' }, { updatedAt: 'desc' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('loads Xiaobao warning summaries either globally for managers or by user-owned version ids', async () => {
|
||||
const prisma = buildPrismaMock();
|
||||
prisma.versionPlan.findMany.mockResolvedValue([{ versionId: 'version-1' }]);
|
||||
prisma.devTask.findMany.mockResolvedValue([{ versionId: 'version-2' }]);
|
||||
prisma.testCase.findMany.mockResolvedValue([{ versionId: 'version-2' }]);
|
||||
prisma.bug.findMany.mockResolvedValue([{ versionId: 'version-3' }]);
|
||||
prisma.xiaobaoRiskSummary.findMany.mockResolvedValue([{ versionId: 'version-2', riskScore: 70 }]);
|
||||
const service = new V22QueryService(prisma as any);
|
||||
|
||||
const userResult = await service.getXiaobaoWarnings({ userId: 'member-1' });
|
||||
await service.getXiaobaoWarnings({ manager: 'true' });
|
||||
|
||||
expect(userResult).toEqual([{ versionId: 'version-2', riskScore: 70 }]);
|
||||
expect(prisma.xiaobaoRiskSummary.findMany).toHaveBeenNthCalledWith(1, {
|
||||
where: {
|
||||
versionId: { in: ['version-1', 'version-2', 'version-3'] },
|
||||
riskLevel: { not: 'on_track' },
|
||||
},
|
||||
orderBy: [{ riskScore: 'desc' }, { updatedAt: 'desc' }],
|
||||
});
|
||||
expect(prisma.xiaobaoRiskSummary.findMany).toHaveBeenNthCalledWith(2, {
|
||||
where: { riskLevel: { not: 'on_track' } },
|
||||
orderBy: [{ riskScore: 'desc' }, { updatedAt: 'desc' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when a version detail query targets a missing version', async () => {
|
||||
const prisma = buildPrismaMock();
|
||||
prisma.version.findUnique.mockResolvedValue(null);
|
||||
const service = new V22QueryService(prisma as any);
|
||||
|
||||
await expect(service.getVersionDetailData('missing-version')).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
});
|
||||
185
apps/server/src/modules/v22-query/v22-query.service.ts
Normal file
185
apps/server/src/modules/v22-query/v22-query.service.ts
Normal file
@@ -0,0 +1,185 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
|
||||
interface RequirementQuery {
|
||||
productId?: string;
|
||||
projectId?: string;
|
||||
versionId?: string;
|
||||
status?: string;
|
||||
priority?: string;
|
||||
type?: string;
|
||||
q?: string;
|
||||
sort?: string;
|
||||
cursor?: string;
|
||||
limit?: string;
|
||||
}
|
||||
|
||||
interface XiaobaoWarningQuery {
|
||||
userId?: string;
|
||||
manager?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class V22QueryService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getVersionDetailData(versionId: string) {
|
||||
const version = await this.prisma.version.findUnique({ where: { id: versionId } });
|
||||
if (!version) throw new NotFoundException('Version not found');
|
||||
|
||||
const [requirements, versionPlans, devTasks, testCases, bugs] = await Promise.all([
|
||||
this.prisma.requirement.findMany({
|
||||
where: { versionId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
}),
|
||||
this.prisma.versionPlan.findMany({
|
||||
where: { versionId },
|
||||
orderBy: [{ type: 'asc' }, { createdAt: 'desc' }],
|
||||
}),
|
||||
this.prisma.devTask.findMany({
|
||||
where: { versionId },
|
||||
orderBy: [{ status: 'asc' }, { updatedAt: 'desc' }],
|
||||
}),
|
||||
this.prisma.testCase.findMany({
|
||||
where: { versionId },
|
||||
orderBy: [{ roundNo: 'desc' }, { status: 'asc' }, { updatedAt: 'desc' }],
|
||||
}),
|
||||
this.prisma.bug.findMany({
|
||||
where: { versionId },
|
||||
orderBy: [{ status: 'asc' }, { priority: 'asc' }, { updatedAt: 'desc' }],
|
||||
}),
|
||||
]);
|
||||
|
||||
return { version, requirements, versionPlans, devTasks, testCases, bugs };
|
||||
}
|
||||
|
||||
async listRequirements(query: RequirementQuery) {
|
||||
const productId = query.productId?.trim();
|
||||
if (!productId) {
|
||||
throw new BadRequestException('productId is required for requirement pool queries');
|
||||
}
|
||||
|
||||
const limit = parseLimit(query.limit);
|
||||
const priority = parsePriority(query.priority);
|
||||
const search = query.q?.trim();
|
||||
const sortDirection = query.sort === 'created_at_asc' ? 'asc' : 'desc';
|
||||
const rows = await this.prisma.requirement.findMany({
|
||||
where: {
|
||||
productId,
|
||||
...(query.projectId?.trim() ? { projectId: query.projectId.trim() } : {}),
|
||||
...(query.versionId?.trim() ? { versionId: query.versionId.trim() } : {}),
|
||||
...(query.status?.trim() ? { status: query.status.trim() } : {}),
|
||||
...(priority !== undefined ? { priority } : {}),
|
||||
...(query.type?.trim() ? { type: query.type.trim() } : {}),
|
||||
...(search
|
||||
? {
|
||||
OR: [
|
||||
{ code: { contains: search, mode: 'insensitive' as const } },
|
||||
{ title: { contains: search, mode: 'insensitive' as const } },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
orderBy: { createdAt: sortDirection },
|
||||
take: limit + 1,
|
||||
...(query.cursor
|
||||
? {
|
||||
cursor: { id_productId: { id: query.cursor, productId } },
|
||||
skip: 1,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
const hasNext = rows.length > limit;
|
||||
return {
|
||||
items: hasNext ? rows.slice(0, limit) : rows,
|
||||
nextCursor: hasNext ? rows[limit]?.id : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async getWorkspaceData(userId: string) {
|
||||
const normalizedUserId = userId.trim();
|
||||
if (!normalizedUserId) throw new BadRequestException('userId is required');
|
||||
|
||||
const [versionPlans, devTasks, testCases, bugs] = await Promise.all([
|
||||
this.prisma.versionPlan.findMany({
|
||||
where: { ownerId: normalizedUserId, status: { not: 'completed' } },
|
||||
orderBy: [{ expectedEndAt: 'asc' }, { updatedAt: 'desc' }],
|
||||
}),
|
||||
this.prisma.devTask.findMany({
|
||||
where: { assigneeId: normalizedUserId, status: { not: 'submitted' } },
|
||||
orderBy: [{ priority: 'asc' }, { updatedAt: 'desc' }],
|
||||
}),
|
||||
this.prisma.testCase.findMany({
|
||||
where: { assigneeId: normalizedUserId, status: { notIn: ['passed', 'failed', 'blocked'] } },
|
||||
orderBy: [{ priority: 'asc' }, { updatedAt: 'desc' }],
|
||||
}),
|
||||
this.prisma.bug.findMany({
|
||||
where: { assigneeId: normalizedUserId, status: { in: ['open', 'fixing', 'fixed', 'verifying'] } },
|
||||
orderBy: [{ priority: 'asc' }, { updatedAt: 'desc' }],
|
||||
}),
|
||||
]);
|
||||
|
||||
return { versionPlans, devTasks, testCases, bugs };
|
||||
}
|
||||
|
||||
async getXiaobaoWarnings(query: XiaobaoWarningQuery) {
|
||||
if (query.manager === 'true') {
|
||||
return this.prisma.xiaobaoRiskSummary.findMany({
|
||||
where: { riskLevel: { not: 'on_track' } },
|
||||
orderBy: [{ riskScore: 'desc' }, { updatedAt: 'desc' }],
|
||||
});
|
||||
}
|
||||
|
||||
const userId = query.userId?.trim();
|
||||
if (!userId) throw new BadRequestException('userId is required');
|
||||
const versionIds = await this.getUserOwnedVersionIds(userId);
|
||||
if (versionIds.length === 0) return [];
|
||||
|
||||
return this.prisma.xiaobaoRiskSummary.findMany({
|
||||
where: {
|
||||
versionId: { in: versionIds },
|
||||
riskLevel: { not: 'on_track' },
|
||||
},
|
||||
orderBy: [{ riskScore: 'desc' }, { updatedAt: 'desc' }],
|
||||
});
|
||||
}
|
||||
|
||||
private async getUserOwnedVersionIds(userId: string): Promise<string[]> {
|
||||
const [plans, devTasks, testCases, bugs] = await Promise.all([
|
||||
this.prisma.versionPlan.findMany({
|
||||
where: { ownerId: userId, status: { not: 'completed' } },
|
||||
select: { versionId: true },
|
||||
}),
|
||||
this.prisma.devTask.findMany({
|
||||
where: { assigneeId: userId, status: { not: 'submitted' } },
|
||||
select: { versionId: true },
|
||||
}),
|
||||
this.prisma.testCase.findMany({
|
||||
where: { assigneeId: userId, status: { notIn: ['passed', 'failed', 'blocked'] } },
|
||||
select: { versionId: true },
|
||||
}),
|
||||
this.prisma.bug.findMany({
|
||||
where: { assigneeId: userId, status: { in: ['open', 'fixing', 'fixed', 'verifying'] } },
|
||||
select: { versionId: true },
|
||||
}),
|
||||
]);
|
||||
return Array.from(new Set([...plans, ...devTasks, ...testCases, ...bugs].map((item) => item.versionId)));
|
||||
}
|
||||
}
|
||||
|
||||
function parseLimit(raw?: string): number {
|
||||
const parsed = raw ? Number(raw) : 50;
|
||||
if (!Number.isFinite(parsed)) return 50;
|
||||
return Math.max(1, Math.min(200, Math.floor(parsed)));
|
||||
}
|
||||
|
||||
function parsePriority(raw?: string): number | undefined {
|
||||
const normalized = raw?.trim().toUpperCase();
|
||||
if (!normalized) return undefined;
|
||||
const prefixed = /^P([0-4])$/.exec(normalized);
|
||||
if (prefixed) return Number(prefixed[1]);
|
||||
const parsed = Number(normalized);
|
||||
if (!Number.isFinite(parsed)) return undefined;
|
||||
return Math.max(0, Math.min(4, Math.floor(parsed)));
|
||||
}
|
||||
Reference in New Issue
Block a user