feat: add report material workflows and gateway safeguards

This commit is contained in:
hectorzhao
2026-07-15 18:23:48 +08:00
parent cf9f4ce4cd
commit 7091a8bed4
41 changed files with 3606 additions and 71 deletions
+7
View File
@@ -13,6 +13,7 @@ import {
CreateReportFieldDto,
CreateReportMaterialDto,
CreateReportTaskDto,
ReplaceReportFieldsDto,
ChangeReportTaskStatusesDto,
CreateRouteRuleDto,
TestChannelDto,
@@ -147,6 +148,12 @@ export class ChannelsController {
return this.channels.createReportField(body);
}
@Put('channels/:channelId/report-fields/:reportType')
@RequireRecentAuthentication()
replaceReportFields(@Param('channelId') channelId: string, @Param('reportType') reportType: 'signature' | 'drainage', @Body() body: ReplaceReportFieldsDto) {
return this.channels.replaceReportFields(channelId, reportType, body);
}
@Get('signature-report-materials')
listReportMaterials(@Query('signatureId') signatureId?: string, @Query('channelId') channelId?: string) {
return this.channels.listReportMaterials(signatureId, channelId);
+25
View File
@@ -96,6 +96,7 @@ function createPrismaMock() {
},
drainageField: {
findUnique: jest.fn().mockResolvedValue({ id: 'library-1', code: 'license', name: '营业执照', fieldType: 'file', required: true, status: 'active', description: '执照文件' }),
findMany: jest.fn().mockResolvedValue([{ id: 'library-1', code: 'license', name: '营业执照', fieldType: 'file', required: true, status: 'active', description: '执照文件' }]),
},
signatureReportMaterial: {
findMany: jest.fn().mockResolvedValue([{ signatureId: 'sig-1', fieldCode: 'license', fieldValue: '营业执照', fileObjectId: 'file-1' }]),
@@ -178,6 +179,26 @@ describe('ChannelsService', () => {
});
});
it('replaces one report type while preserving legacy both fields for the opposite type', async () => {
const prisma = createPrismaMock();
const legacyBoth = { id: 'legacy-1', channelId: 'channel-1', drainageFieldId: 'library-1', reportType: 'both', code: 'license', name: '营业执照', exportName: '旧表头', fieldType: 'file', required: true, description: null, sortOrder: 10, columnWidth: 18, imageWidth: 120, imageHeight: 80, defaultValue: null, transform: null, status: 'active', createdAt: new Date(), updatedAt: new Date() };
const tx = {
channelReportField: {
findMany: jest.fn().mockResolvedValueOnce([legacyBoth]).mockResolvedValueOnce([]).mockResolvedValueOnce([{ id: 'signature-field' }]),
deleteMany: jest.fn(),
create: jest.fn().mockImplementation(({ data }) => Promise.resolve({ id: `created-${data.reportType}`, ...data })),
},
};
prisma.$transaction.mockImplementation((callback) => callback(tx));
const service = new ChannelsService(prisma as never);
await service.replaceReportFields('channel-1', 'signature', { fields: [{ drainageFieldId: 'library-1', exportName: '新签名表头', required: true }] });
expect(tx.channelReportField.deleteMany).toHaveBeenCalledWith({ where: { channelId: 'channel-1', reportType: { in: ['signature', 'both'] } } });
expect(tx.channelReportField.create).toHaveBeenCalledWith({ data: expect.objectContaining({ channelId: 'channel-1', code: 'license', reportType: 'drainage', exportName: '旧表头' }) });
expect(tx.channelReportField.create).toHaveBeenCalledWith({ data: expect.objectContaining({ channelId: 'channel-1', code: 'license', reportType: 'signature', exportName: '新签名表头' }) });
});
it('lists report tasks for one real channel', async () => {
const prisma = createPrismaMock();
prisma.channelSignatureReportTask.findMany.mockResolvedValue([]);
@@ -460,6 +481,7 @@ describe('ChannelsService', () => {
expect(prisma.smsChannelGroupItem.create).toHaveBeenCalledWith({
data: expect.objectContaining({ groupId: 'group-1', channelId: 'channel-1', carrier: 'mobile', province: '山东' }),
});
expect(prisma.smsChannelGroupItem.create.mock.calls[0][0].data).not.toHaveProperty('rateLimitPerSecond');
await expect(service.addGroupItem({ groupId: 'group-1', channelId: 'channel-1', carrier: 'unicom' }))
.rejects.toThrow('Channel group items must use the same carrier');
@@ -545,6 +567,9 @@ describe('ChannelsService', () => {
where: { id: 'group-1' },
data: expect.objectContaining({ retryTimeLimitHours: 13, retryTimeLimitMinutes: 750 }),
});
for (const item of tx.smsChannelGroupItem.createMany.mock.calls[0][0].data) {
expect(item).not.toHaveProperty('rateLimitPerSecond');
}
await expect(service.updateGroup('group-1', {
carrier: 'mobile',
+69 -3
View File
@@ -47,7 +47,6 @@ export interface CreateChannelGroupItemDto {
priority?: number;
weight?: number;
isBackup?: boolean;
rateLimitPerSecond?: number;
}
export interface UpdateChannelGroupDto {
@@ -83,9 +82,19 @@ export interface CreateReportFieldDto {
required?: boolean;
description?: string;
sortOrder?: number;
exportName?: string;
columnWidth?: number;
imageWidth?: number;
imageHeight?: number;
defaultValue?: string;
transform?: string;
status?: string;
}
export interface ReplaceReportFieldsDto {
fields: Array<Omit<CreateReportFieldDto, 'channelId' | 'reportType'>>;
}
export interface CreateReportMaterialDto {
signatureId: string;
channelId: string;
@@ -787,7 +796,6 @@ export class ChannelsService implements OnModuleInit, OnModuleDestroy {
priority: data.priority ?? 100,
weight: data.weight ?? 1,
isBackup: data.isBackup ?? false,
rateLimitPerSecond: data.rateLimitPerSecond,
},
});
}
@@ -834,7 +842,6 @@ export class ChannelsService implements OnModuleInit, OnModuleDestroy {
priority: item.priority ?? 100,
weight: item.weight ?? 1,
isBackup: item.isBackup ?? false,
rateLimitPerSecond: item.rateLimitPerSecond,
})),
});
}
@@ -928,15 +935,69 @@ export class ChannelsService implements OnModuleInit, OnModuleDestroy {
reportType,
code: field.code,
name: field.name,
exportName: data.exportName?.trim() || field.name,
fieldType: field.fieldType,
required: data.required ?? field.required,
description: data.description ?? field.description,
sortOrder: data.sortOrder ?? 100,
columnWidth: normalizeSpreadsheetSize(data.columnWidth, 18, 6, 80),
imageWidth: normalizeSpreadsheetSize(data.imageWidth, 120, 24, 600),
imageHeight: normalizeSpreadsheetSize(data.imageHeight, 80, 24, 600),
defaultValue: data.defaultValue,
transform: data.transform,
status: data.status ?? 'active',
},
});
}
async replaceReportFields(channelId: string, reportType: 'signature' | 'drainage', data: ReplaceReportFieldsDto) {
const channel = await this.prisma.smsChannel.findUnique({ where: { id: channelId } });
if (!channel) throw new NotFoundException('Channel not found');
const ids = data.fields.map((field) => field.drainageFieldId);
if (new Set(ids).size !== ids.length) throw new BadRequestException('同一通道报备类型不能重复配置字段');
const libraryFields = await this.prisma.drainageField.findMany({ where: { id: { in: ids }, status: 'active' } });
if (libraryFields.length !== ids.length) throw new BadRequestException('报备字段库字段不存在或已停用');
const fieldById = new Map(libraryFields.map((field) => [field.id, field]));
return this.prisma.$transaction(async (tx) => {
const oppositeType = reportType === 'signature' ? 'drainage' : 'signature';
const [legacyBoth, oppositeFields] = await Promise.all([
tx.channelReportField.findMany({ where: { channelId, reportType: 'both' } }),
tx.channelReportField.findMany({ where: { channelId, reportType: oppositeType } }),
]);
const oppositeCodes = new Set(oppositeFields.map((field) => field.code));
await tx.channelReportField.deleteMany({ where: { channelId, reportType: { in: [reportType, 'both'] } } });
for (const legacy of legacyBoth) {
if (oppositeCodes.has(legacy.code)) continue;
const { id: _id, createdAt: _createdAt, updatedAt: _updatedAt, ...legacyData } = legacy;
await tx.channelReportField.create({ data: { ...legacyData, reportType: oppositeType } });
}
for (const [index, configured] of data.fields.entries()) {
const field = fieldById.get(configured.drainageFieldId)!;
await tx.channelReportField.create({
data: {
channelId,
drainageFieldId: field.id,
reportType,
code: field.code,
name: field.name,
exportName: configured.exportName?.trim() || field.name,
fieldType: field.fieldType,
required: configured.required ?? field.required,
description: configured.description ?? field.description,
sortOrder: configured.sortOrder ?? (index + 1) * 10,
columnWidth: normalizeSpreadsheetSize(configured.columnWidth, 18, 6, 80),
imageWidth: normalizeSpreadsheetSize(configured.imageWidth, 120, 24, 600),
imageHeight: normalizeSpreadsheetSize(configured.imageHeight, 80, 24, 600),
defaultValue: configured.defaultValue,
transform: configured.transform,
status: configured.status ?? 'active',
},
});
}
return tx.channelReportField.findMany({ where: { channelId, reportType }, include: { drainageField: true }, orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }] });
});
}
listReportMaterials(signatureId?: string, channelId?: string) {
return this.prisma.signatureReportMaterial.findMany({
where: {
@@ -1652,6 +1713,11 @@ function normalizeRetryTimeLimitMinutes(minutes: number | undefined, hours: numb
return value;
}
function normalizeSpreadsheetSize(value: number | undefined, fallback: number, minimum: number, maximum: number) {
if (value === undefined || !Number.isFinite(value)) return fallback;
return Math.min(maximum, Math.max(minimum, Math.round(value)));
}
function normalizeBusinessCarrier(carrier?: string | null) {
const normalized = normalizeChannelCarrier(carrier);
if (!['mobile', 'unicom', 'telecom'].includes(normalized)) {