feat(ops): kb doc edit, validation auto-tickets, support batch ops

Add knowledge document GET/PUT and admin edit UI; auto-create support tickets on client 400 validation errors across user/shop/partner apps; batch create tasks and publish from support tickets; restore mini-user store env single-column layout.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-05 00:08:40 +08:00
parent 16c386f165
commit 02d89e6385
18 changed files with 677 additions and 24 deletions
@@ -96,6 +96,7 @@ export const HqOperationAction = {
KNOWLEDGE_BASE_UPDATE: 'KNOWLEDGE_BASE_UPDATE',
KNOWLEDGE_BASE_DELETE: 'KNOWLEDGE_BASE_DELETE',
KNOWLEDGE_DOC_CREATE: 'KNOWLEDGE_DOC_CREATE',
KNOWLEDGE_DOC_UPDATE: 'KNOWLEDGE_DOC_UPDATE',
KNOWLEDGE_DOC_DELETE: 'KNOWLEDGE_DOC_DELETE',
REDEEM_PENDING_COMPLETE: 'REDEEM_PENDING_COMPLETE',
REDEEM_PENDING_REJECT: 'REDEEM_PENDING_REJECT',
@@ -218,6 +219,7 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
[HqOperationAction.KNOWLEDGE_BASE_UPDATE]: '更新知识库',
[HqOperationAction.KNOWLEDGE_BASE_DELETE]: '删除知识库',
[HqOperationAction.KNOWLEDGE_DOC_CREATE]: '上传知识库文档',
[HqOperationAction.KNOWLEDGE_DOC_UPDATE]: '编辑知识库文档',
[HqOperationAction.KNOWLEDGE_DOC_DELETE]: '删除知识库文档',
[HqOperationAction.REDEEM_PENDING_COMPLETE]: '弱网待处理单-补核销',
[HqOperationAction.REDEEM_PENDING_REJECT]: '弱网待处理单-驳回',
@@ -5,6 +5,7 @@ import { AlertService } from '../../common/alert/alert.service';
import type { AlertLevel } from '../../common/alert/alert.constants';
import type { AuthUser } from '../../common/guards/jwt-auth.guard';
import type { ReportClientErrorDto } from './dto/client-error.dto';
import { SupportTicketService } from './support-ticket.service';
const WECOM_LEVELS = new Set(['fatal', 'error']);
@@ -15,6 +16,7 @@ export class ClientErrorService {
constructor(
private readonly prisma: PrismaService,
private readonly alert: AlertService,
private readonly supportTicket: SupportTicketService,
) {}
async report(dto: ReportClientErrorDto, user?: AuthUser, headerClientApp?: string) {
@@ -107,6 +109,25 @@ export class ClientErrorService {
);
}
if (dto.category === 'validation_error') {
const apiPath =
dto.extra && typeof dto.extra.url === 'string' ? dto.extra.url.slice(0, 256) : undefined;
void this.supportTicket
.createFromClientValidation({
clientApp,
message,
pagePath,
apiPath,
actorLabel:
user?.actorId != null ? `${user.actorType}:${String(user.actorId)}` : undefined,
})
.catch((e) => {
this.logger.warn(
`auto support ticket failed: ${e instanceof Error ? e.message : String(e)}`,
);
});
}
return { ok: true };
}
}
@@ -9,6 +9,7 @@ export const CLIENT_ERROR_CATEGORIES = [
'js_error',
'unhandled_rejection',
'api_error',
'validation_error',
'network',
'render',
'bridge',
@@ -95,6 +95,32 @@ export class BatchUpdateSupportTicketStatusDto {
note?: string;
}
export class BatchCreateSupportTicketTasksDto {
@IsArray()
@ArrayMinSize(1)
@IsString({ each: true })
ticketIds!: string[];
}
export class BatchPublishSupportTicketsDto {
@IsArray()
@ArrayMinSize(1)
@IsString({ each: true })
ticketIds!: string[];
@IsString()
@IsNotEmpty()
versionId!: string;
@IsOptional()
@IsBoolean()
dispatchToWecom?: boolean;
@IsOptional()
@IsString()
dispatchSupplement?: string;
}
export class RejectSupportTicketDto {
@IsString()
@IsNotEmpty()
@@ -6,6 +6,7 @@ import {
import type { SupportTicketStatus, SupportTicketType } from '@prisma/client';
import { Prisma } from '@prisma/client';
import type { CreateDevPlanTaskFromTicketInput } from '@dukang/shared-types';
import { mapSupportTicketTypeToDevPlanTask } from '@dukang/shared-types';
import { validateSupportTicketStatusTransition } from '@dukang/domain';
import { PrismaService } from '../../common/prisma/prisma.module';
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
@@ -37,8 +38,17 @@ function generateSupportTicketNo() {
return `ST${Date.now()}${Math.floor(Math.random() * 900 + 100)}`;
}
const AUTO_VALIDATION_TICKET_APPS = new Set([
'USER_H5',
'USER_MINI',
'SHOP_H5',
'PARTNER_H5',
]);
@Injectable()
export class SupportTicketService {
private systemCreatorCache: { id: bigint; name: string } | null = null;
constructor(
private readonly prisma: PrismaService,
private readonly alert: AlertService,
@@ -94,6 +104,66 @@ export class SupportTicketService {
return serializeBigInt(mapSupportTicketRow(ticket));
}
/** 客户端 400 验证错误自动建单(1 小时内同标题去重) */
async createFromClientValidation(input: {
clientApp: string;
message: string;
pagePath?: string;
apiPath?: string;
actorLabel?: string;
}) {
if (!AUTO_VALIDATION_TICKET_APPS.has(input.clientApp)) {
return { skipped: true as const, reason: 'unsupported_app' as const };
}
const title = `[客户端验证] ${input.clientApp}${input.pagePath ? ` · ${input.pagePath}` : ''} · ${input.message.slice(0, 60)}`;
const oneHourAgo = new Date(Date.now() - 3600_000);
const existing = await this.prisma.commonSupportTicket.findFirst({
where: { title, createdAt: { gte: oneHourAgo } },
select: { id: true },
});
if (existing) {
return { skipped: true as const, ticketId: existing.id.toString() };
}
const creator = await this.resolveSystemCreator();
const content = [
`端:${input.clientApp}`,
input.pagePath ? `页面:${input.pagePath}` : null,
input.apiPath ? `接口:${input.apiPath}` : null,
input.actorLabel ? `用户:${input.actorLabel}` : null,
'',
input.message,
]
.filter(Boolean)
.join('\n');
const ticket = await this.create(
{
ticketType: 'BUG',
title,
content,
remark: '客户端验证错误自动上报',
},
creator,
);
return { skipped: false as const, ticketId: String(ticket.id) };
}
private async resolveSystemCreator() {
if (this.systemCreatorCache) return this.systemCreatorCache;
const account = await this.prisma.hqAccount.findFirst({
where: { adminRole: 'SUPER_ADMIN', status: 'ACTIVE' },
orderBy: { id: 'asc' },
select: { id: true },
});
if (!account) {
throw new BadRequestException('未找到系统管理员账号,无法自动创建工单');
}
this.systemCreatorCache = { id: account.id, name: '系统自动' };
return this.systemCreatorCache;
}
async update(id: bigint, dto: UpdateSupportTicketDto) {
const ticket = await this.getOrThrow(id);
if (ticket.status !== 'PENDING_REVIEW') {
@@ -360,6 +430,134 @@ export class SupportTicketService {
return { items: results };
}
/** 批量一键创建开发任务(每工单 1 条,内容取自标题/说明) */
async batchCreateTasks(
ticketIds: bigint[],
operator: { id: bigint; name: string },
) {
const results: Array<{
ticketId: string;
ok: boolean;
message?: string;
taskIds?: string[];
}> = [];
for (const id of ticketIds) {
try {
const ticket = await this.getOrThrow(id);
const linkedMap = await this.devPlan.listLinkedTasksByTicketIds([id]);
const existing = linkedMap.get(String(id)) ?? [];
if (existing.length > 0) {
results.push({ ticketId: String(id), ok: false, message: '已有开发任务,已跳过' });
continue;
}
const summary = [ticket.title, ticket.content].filter(Boolean).join('\n').slice(0, 500);
const createdTasks = await this.devPlan.createTasksFromTicket(
id,
[
{
content: summary || ticket.title,
type: mapSupportTicketTypeToDevPlanTask(ticket.ticketType as 'BUG' | 'SUGGESTION' | 'OTHER'),
},
],
operator.id,
);
if (ticket.status === 'PENDING_REVIEW') {
await this.prisma.commonSupportTicket.update({
where: { id },
data: {
status: 'DEVELOPING',
reviewerId: operator.id,
reviewerName: operator.name,
reviewedAt: new Date(),
},
});
}
results.push({
ticketId: String(id),
ok: true,
taskIds: createdTasks.map((t) => t.id),
});
} catch (err) {
results.push({
ticketId: String(id),
ok: false,
message: err instanceof Error ? err.message : '创建失败',
});
}
}
const successCount = results.filter((r) => r.ok).length;
return { results, successCount, failCount: results.length - successCount };
}
/** 批量一键发布:关联开发版本,可选企微派发 */
async batchPublish(
ticketIds: bigint[],
input: {
versionId: string;
dispatchToWecom?: boolean;
dispatchSupplement?: string;
},
operator: { id: bigint; name: string },
) {
const perTicket: Array<{ ticketId: string; ok: boolean; message?: string }> = [];
const taskIdSet = new Set<string>();
for (const id of ticketIds) {
const linkedMap = await this.devPlan.listLinkedTasksByTicketIds([id]);
const linked = linkedMap.get(String(id)) ?? [];
if (!linked.length) {
perTicket.push({ ticketId: String(id), ok: false, message: '无关联开发任务' });
continue;
}
linked.forEach((t) => taskIdSet.add(t.id));
perTicket.push({ ticketId: String(id), ok: true });
}
const taskIds = [...taskIdSet];
if (!taskIds.length) {
return {
results: perTicket,
successCount: 0,
failCount: perTicket.length,
linkedTaskCount: 0,
};
}
await this.devPlan.batchUpdateTasks({ taskIds, versionId: input.versionId });
if (input.dispatchToWecom) {
try {
await this.devPlan.dispatchTasks(
{ taskIds, supplement: input.dispatchSupplement },
operator.id,
);
} catch (err) {
this.alert.notify({
level: 'P2',
category: 'ops',
title: '批量发布企微派发失败',
detail: err instanceof Error ? err.message : String(err),
dedupeKey: `support_batch_publish_dispatch_fail|${Date.now()}`,
dedupeTtlSec: 120,
});
}
}
const successCount = perTicket.filter((r) => r.ok).length;
return {
results: perTicket,
successCount,
failCount: perTicket.length - successCount,
linkedTaskCount: taskIds.length,
versionId: input.versionId,
};
}
/** 开发完成 → 测试 */
async startTesting(id: bigint, dto?: SupportTicketRemarkDto) {
const ticket = await this.getOrThrow(id);
@@ -13,6 +13,7 @@ import type {
CreateKnowledgeBaseRequest,
CreateKnowledgeDocumentRequest,
UpdateKnowledgeBaseRequest,
UpdateKnowledgeDocumentRequest,
} from '@dukang/shared-types';
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
import {
@@ -119,6 +120,33 @@ export class AdminKnowledgeBasesController {
return this.service.addDocument(actor, BigInt(id), body);
}
@Get(':id/documents/:docId')
async getDocument(
@CurrentUser() user: AuthUser,
@Param('id') id: string,
@Param('docId') docId: string,
) {
const actor = await this.service.resolveActor(user.actorId);
return this.service.getDocument(actor, BigInt(id), BigInt(docId));
}
@Put(':id/documents/:docId')
@HqOperation({
action: HqOperationAction.KNOWLEDGE_DOC_UPDATE,
refType: 'KNOWLEDGE_DOCUMENT',
refIdField: 'docId',
includeBody: true,
})
async updateDocument(
@CurrentUser() user: AuthUser,
@Param('id') id: string,
@Param('docId') docId: string,
@Body() body: UpdateKnowledgeDocumentRequest,
) {
const actor = await this.service.resolveActor(user.actorId);
return this.service.updateDocument(actor, BigInt(id), BigInt(docId), body);
}
@Delete(':id/documents/:docId')
@HqOperation({
action: HqOperationAction.KNOWLEDGE_DOC_DELETE,
@@ -9,8 +9,10 @@ import type {
CreateKnowledgeDocumentRequest,
KnowledgeBaseDto,
KnowledgeBaseOptionDto,
KnowledgeDocumentDetailDto,
KnowledgeDocumentDto,
UpdateKnowledgeBaseRequest,
UpdateKnowledgeDocumentRequest,
} from '@dukang/shared-types';
import { PrismaService } from '../../common/prisma/prisma.module';
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
@@ -228,6 +230,113 @@ export class AdminKnowledgeBasesService {
return this.toDocDto(row);
}
async getDocument(actor: ActorCtx, kbId: bigint, docId: bigint): Promise<KnowledgeDocumentDetailDto> {
await this.requireKb(actor, kbId);
const doc = await this.prisma.knowledgeDocument.findFirst({
where: { id: docId, knowledgeBaseId: kbId },
});
if (!doc) throw new NotFoundException('文档不存在');
return {
...this.toDocDto(doc),
contentText: doc.contentText,
};
}
async updateDocument(
actor: ActorCtx,
kbId: bigint,
docId: bigint,
dto: UpdateKnowledgeDocumentRequest,
) {
const kb = await this.requireKb(actor, kbId);
this.requireWrite(actor, kb);
const doc = await this.prisma.knowledgeDocument.findFirst({
where: { id: docId, knowledgeBaseId: kbId },
});
if (!doc) throw new NotFoundException('文档不存在');
const data: {
title?: string;
fileName?: string | null;
fileUrl?: string | null;
mimeType?: string | null;
sizeBytes?: number | null;
contentText?: string | null;
status?: 'READY' | 'EMPTY' | 'FAILED';
errorMessage?: string | null;
} = {};
if (dto.title !== undefined) {
const title = dto.title.trim();
if (!title) throw new BadRequestException('请填写标题');
data.title = title;
}
const hasContentInput =
dto.contentText !== undefined ||
dto.fileUrl !== undefined ||
dto.fileName !== undefined ||
dto.mimeType !== undefined;
if (hasContentInput) {
let contentText = dto.contentText !== undefined ? dto.contentText?.trim() || '' : doc.contentText?.trim() || '';
let status: 'READY' | 'EMPTY' | 'FAILED' = doc.status as 'READY' | 'EMPTY' | 'FAILED';
let errorMessage: string | null = doc.errorMessage;
if (dto.contentText !== undefined) {
if (contentText) {
status = 'READY';
errorMessage = null;
} else if (!dto.fileUrl?.trim() && !doc.fileUrl) {
status = 'EMPTY';
errorMessage = null;
}
data.contentText = contentText || null;
}
if (dto.fileUrl !== undefined) data.fileUrl = dto.fileUrl?.trim() || null;
if (dto.fileName !== undefined) data.fileName = dto.fileName?.trim() || null;
if (dto.mimeType !== undefined) data.mimeType = dto.mimeType?.trim() || null;
if (dto.sizeBytes !== undefined) data.sizeBytes = dto.sizeBytes ?? null;
const fileUrl = dto.fileUrl?.trim() || doc.fileUrl;
const fileName = dto.fileName?.trim() || doc.fileName || '';
const mimeType = dto.mimeType?.trim() || doc.mimeType;
if (dto.fileUrl?.trim() && dto.contentText === undefined) {
if (TEXT_EXT.test(fileName) || isLikelyTextMime(mimeType)) {
try {
contentText = await fetchText(dto.fileUrl.trim());
data.contentText = contentText || null;
status = contentText.trim() ? 'READY' : 'EMPTY';
errorMessage = contentText.trim() ? null : '文件内容为空';
} catch (e) {
status = 'FAILED';
errorMessage = e instanceof Error ? e.message : String(e);
}
} else {
status = 'EMPTY';
errorMessage = '非文本文件未抽取正文,请粘贴文本或上传 .txt/.md';
}
} else if (dto.contentText !== undefined && contentText) {
status = 'READY';
errorMessage = null;
} else if (dto.contentText !== undefined && !contentText && !fileUrl) {
status = 'EMPTY';
errorMessage = null;
}
data.status = status;
data.errorMessage = errorMessage;
}
const updated = await this.prisma.knowledgeDocument.update({
where: { id: docId },
data,
});
return this.toDocDto(updated);
}
async removeDocument(actor: ActorCtx, kbId: bigint, docId: bigint) {
const kb = await this.requireKb(actor, kbId);
this.requireWrite(actor, kb);
@@ -25,6 +25,8 @@ import {
SupportTicketRemarkDto,
UpdateSupportTicketDto,
BatchUpdateSupportTicketStatusDto,
BatchCreateSupportTicketTasksDto,
BatchPublishSupportTicketsDto,
} from '../common/dto/support-ticket.dto';
import {
BatchReviewConfirmDto,
@@ -109,6 +111,26 @@ export class AdminSupportTicketsController {
);
}
@Post('batch-create-tasks')
@UseGuards(SuperAdminGuard)
async batchCreateTasks(
@CurrentUser() user: AuthUser,
@Body() body: BatchCreateSupportTicketTasksDto,
) {
const account = await this.resolveHqAccount(user);
return this.service.batchCreateTasks(body.ticketIds.map(BigInt), account);
}
@Post('batch-publish')
@UseGuards(SuperAdminGuard)
async batchPublish(
@CurrentUser() user: AuthUser,
@Body() body: BatchPublishSupportTicketsDto,
) {
const account = await this.resolveHqAccount(user);
return this.service.batchPublish(body.ticketIds.map(BigInt), body, account);
}
@Get(':id')
detail(@Param('id') id: string) {
return this.service.detail(BigInt(id));