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:
@@ -18,6 +18,7 @@ import type { ColumnsType } from 'antd/es/table';
|
||||
import { UploadOutlined } from '@ant-design/icons';
|
||||
import type {
|
||||
KnowledgeBaseDto,
|
||||
KnowledgeDocumentDetailDto,
|
||||
KnowledgeDocumentDto,
|
||||
} from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
@@ -49,6 +50,10 @@ export default function KnowledgeBasesPage() {
|
||||
const [docsLoading, setDocsLoading] = useState(false);
|
||||
const [docModalOpen, setDocModalOpen] = useState(false);
|
||||
const [docSaving, setDocSaving] = useState(false);
|
||||
const [editingDoc, setEditingDoc] = useState<KnowledgeDocumentDto | null>(null);
|
||||
const [editDocModalOpen, setEditDocModalOpen] = useState(false);
|
||||
const [editDocSaving, setEditDocSaving] = useState(false);
|
||||
const [editDocForm] = Form.useForm<DocForm>();
|
||||
|
||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } =
|
||||
useAdminList<KnowledgeBaseDto>(
|
||||
@@ -195,28 +200,52 @@ export default function KnowledgeBasesPage() {
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 80,
|
||||
width: 140,
|
||||
render: (_, row) =>
|
||||
drawerKb?.canEditFull ? (
|
||||
<Popconfirm
|
||||
title="删除文档?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await request(`/admin/knowledge-bases/${drawerKb.id}/documents/${row.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
message.success('已删除');
|
||||
void loadDocs(drawerKb);
|
||||
reload();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button type="link" size="small" danger>
|
||||
删除
|
||||
<Space>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={async () => {
|
||||
if (!drawerKb) return;
|
||||
try {
|
||||
const detail = await request<KnowledgeDocumentDetailDto>(
|
||||
`/admin/knowledge-bases/${drawerKb.id}/documents/${row.id}`,
|
||||
);
|
||||
setEditingDoc(row);
|
||||
editDocForm.setFieldsValue({
|
||||
title: detail.title,
|
||||
contentText: detail.contentText || '',
|
||||
});
|
||||
setEditDocModalOpen(true);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
<Popconfirm
|
||||
title="删除文档?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await request(`/admin/knowledge-bases/${drawerKb.id}/documents/${row.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
message.success('已删除');
|
||||
void loadDocs(drawerKb);
|
||||
reload();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button type="link" size="small" danger>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
) : null,
|
||||
},
|
||||
];
|
||||
@@ -398,6 +427,50 @@ export default function KnowledgeBasesPage() {
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="编辑知识文档"
|
||||
open={editDocModalOpen}
|
||||
onCancel={() => {
|
||||
setEditDocModalOpen(false);
|
||||
setEditingDoc(null);
|
||||
}}
|
||||
confirmLoading={editDocSaving}
|
||||
onOk={async () => {
|
||||
if (!drawerKb || !editingDoc) return;
|
||||
const values = await editDocForm.validateFields();
|
||||
setEditDocSaving(true);
|
||||
try {
|
||||
await request(`/admin/knowledge-bases/${drawerKb.id}/documents/${editingDoc.id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
title: values.title,
|
||||
contentText: values.contentText || null,
|
||||
}),
|
||||
});
|
||||
message.success('已保存');
|
||||
setEditDocModalOpen(false);
|
||||
setEditingDoc(null);
|
||||
void loadDocs(drawerKb);
|
||||
reload();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setEditDocSaving(false);
|
||||
}
|
||||
}}
|
||||
destroyOnClose
|
||||
width={640}
|
||||
>
|
||||
<Form form={editDocForm} layout="vertical">
|
||||
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="contentText" label="正文(可粘贴)">
|
||||
<Input.TextArea rows={8} placeholder="支持 Markdown / 纯文本" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
type BatchReviewPreviewItem,
|
||||
type BatchReviewPreviewResponse,
|
||||
type DevPlanTaskTypeDto,
|
||||
type DevPlanVersionDto,
|
||||
type SupportTicketDto,
|
||||
type SupportTicketLinkedTaskDto,
|
||||
type SupportTicketStatusDto,
|
||||
@@ -96,6 +97,10 @@ export default function SupportTicketsPage() {
|
||||
const [batchConfirming, setBatchConfirming] = useState(false);
|
||||
const [batchStatusOpen, setBatchStatusOpen] = useState(false);
|
||||
const [batchStatusSaving, setBatchStatusSaving] = useState(false);
|
||||
const [batchCreateSaving, setBatchCreateSaving] = useState(false);
|
||||
const [batchPublishOpen, setBatchPublishOpen] = useState(false);
|
||||
const [batchPublishSaving, setBatchPublishSaving] = useState(false);
|
||||
const [versions, setVersions] = useState<DevPlanVersionDto[]>([]);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [editSaving, setEditSaving] = useState(false);
|
||||
const [reviewDecision, setReviewDecision] = useState<'APPROVE' | 'REJECT'>('APPROVE');
|
||||
@@ -114,9 +119,21 @@ export default function SupportTicketsPage() {
|
||||
rejectReason?: string;
|
||||
note?: string;
|
||||
}>();
|
||||
const [batchPublishForm] = Form.useForm<{
|
||||
versionId: string;
|
||||
dispatchToWecom?: boolean;
|
||||
dispatchSupplement?: string;
|
||||
}>();
|
||||
|
||||
const isSuperAdmin = profile?.adminRole === 'SUPER_ADMIN';
|
||||
|
||||
useEffect(() => {
|
||||
if (!batchPublishOpen) return;
|
||||
request<{ items: DevPlanVersionDto[] }>('/admin/dev-plan/versions?pageSize=100')
|
||||
.then((res) => setVersions(res.items ?? []))
|
||||
.catch(() => setVersions([]));
|
||||
}, [batchPublishOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
request<HqProfile>('/admin/auth/me').then(setProfile).catch(() => {});
|
||||
}, []);
|
||||
@@ -257,6 +274,67 @@ export default function SupportTicketsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function submitBatchCreateTasks() {
|
||||
if (!selectedRowKeys.length) return;
|
||||
setBatchCreateSaving(true);
|
||||
try {
|
||||
const res = await request<{ successCount: number; failCount: number }>(
|
||||
'/admin/support-tickets/batch-create-tasks',
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ticketIds: selectedRowKeys }),
|
||||
},
|
||||
);
|
||||
message.success(`已创建 ${res.successCount} 条任务,跳过/失败 ${res.failCount} 条`);
|
||||
setSelectedRowKeys([]);
|
||||
reload();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '批量创建任务失败');
|
||||
} finally {
|
||||
setBatchCreateSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
function openBatchPublish() {
|
||||
batchPublishForm.setFieldsValue({
|
||||
versionId: undefined,
|
||||
dispatchToWecom: localStorage.getItem(DISPATCH_WECOM_STORAGE_KEY) !== 'false',
|
||||
dispatchSupplement: DEFAULT_DISPATCH_SUPPLEMENT,
|
||||
});
|
||||
setBatchPublishOpen(true);
|
||||
}
|
||||
|
||||
async function submitBatchPublish() {
|
||||
const values = await batchPublishForm.validateFields();
|
||||
localStorage.setItem(DISPATCH_WECOM_STORAGE_KEY, values.dispatchToWecom ? 'true' : 'false');
|
||||
setBatchPublishSaving(true);
|
||||
try {
|
||||
const res = await request<{
|
||||
successCount: number;
|
||||
failCount: number;
|
||||
linkedTaskCount: number;
|
||||
}>('/admin/support-tickets/batch-publish', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
ticketIds: selectedRowKeys,
|
||||
versionId: values.versionId,
|
||||
dispatchToWecom: !!values.dispatchToWecom,
|
||||
dispatchSupplement: values.dispatchSupplement?.trim() || undefined,
|
||||
}),
|
||||
});
|
||||
message.success(
|
||||
`已关联 ${res.linkedTaskCount} 条任务到版本,工单成功 ${res.successCount} 条,失败 ${res.failCount} 条`,
|
||||
);
|
||||
setBatchPublishOpen(false);
|
||||
setSelectedRowKeys([]);
|
||||
reload();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '批量发布失败');
|
||||
} finally {
|
||||
setBatchPublishSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function submitCreateTasks() {
|
||||
const values = await tasksForm.validateFields();
|
||||
const note = reviewForm.getFieldValue('note') as string | undefined;
|
||||
@@ -440,6 +518,16 @@ export default function SupportTicketsPage() {
|
||||
<Space>
|
||||
{isSuperAdmin ? (
|
||||
<>
|
||||
<Button
|
||||
disabled={!selectedRowKeys.length}
|
||||
loading={batchCreateSaving}
|
||||
onClick={() => void submitBatchCreateTasks()}
|
||||
>
|
||||
一键创建任务
|
||||
</Button>
|
||||
<Button disabled={!selectedRowKeys.length} onClick={openBatchPublish}>
|
||||
一键发布
|
||||
</Button>
|
||||
<Button disabled={!selectedRowKeys.length} loading={acting} onClick={() => void startBatchPreview()}>
|
||||
批量审核
|
||||
</Button>
|
||||
@@ -945,6 +1033,33 @@ export default function SupportTicketsPage() {
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="一键发布"
|
||||
open={batchPublishOpen}
|
||||
onCancel={() => setBatchPublishOpen(false)}
|
||||
onOk={() => void submitBatchPublish()}
|
||||
confirmLoading={batchPublishSaving}
|
||||
destroyOnClose
|
||||
>
|
||||
<Typography.Paragraph type="secondary">
|
||||
已选 {selectedRowKeys.length} 条工单。将把各工单关联的开发任务追加到所选版本;无任务的工单将跳过。
|
||||
</Typography.Paragraph>
|
||||
<Form form={batchPublishForm} layout="vertical">
|
||||
<Form.Item name="versionId" label="开发版本" rules={[{ required: true, message: '请选择开发版本' }]}>
|
||||
<Select
|
||||
placeholder="选择版本"
|
||||
options={versions.map((v) => ({ value: v.id, label: v.versionNo }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="dispatchToWecom" valuePropName="checked">
|
||||
<Checkbox>同时发送到企微开发助手</Checkbox>
|
||||
</Form.Item>
|
||||
<Form.Item name="dispatchSupplement" label="派发补充说明">
|
||||
<Input.TextArea rows={2} placeholder={DEFAULT_DISPATCH_SUPPLEMENT} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="批量 AI 审核确认"
|
||||
open={batchPreviewOpen}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { PartnerMe, PartnerStaffRole } from '@dukang/shared-types';
|
||||
import { reportApiError } from '@dukang/client-logging';
|
||||
import { isOnAppPath, toAppPath } from '@dukang/weixin-sdk';
|
||||
import { showPartnerToast } from './toast';
|
||||
|
||||
@@ -159,6 +160,12 @@ async function rawRequest<T>(
|
||||
if (json.code !== 0) {
|
||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||
err.status = json.code === 401 ? 401 : json.code;
|
||||
if (json.code === 400) {
|
||||
reportApiError(
|
||||
{ apiBase, clientApp: CLIENT_APP, getToken: () => localStorage.getItem(ACCESS_TOKEN) },
|
||||
{ message: json.message || '请求失败', status: 400, url: path, category: 'validation_error' },
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return json.data as T;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { reportApiError } from '@dukang/client-logging';
|
||||
|
||||
export const apiBase = '/api/v1';
|
||||
const CLIENT_APP = 'SHOP_H5';
|
||||
|
||||
@@ -213,6 +215,12 @@ async function rawRequest<T>(
|
||||
if (json.code !== 0) {
|
||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||
err.status = res.status >= 500 ? res.status : json.code;
|
||||
if (json.code === 400) {
|
||||
reportApiError(
|
||||
{ apiBase, clientApp: CLIENT_APP, getToken: () => localStorage.getItem(ACCESS_TOKEN) },
|
||||
{ message: json.message || '请求失败', status: 400, url: path, category: 'validation_error' },
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return json.data as T;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { reportApiError } from '@dukang/client-logging';
|
||||
|
||||
export const BRAND = {
|
||||
red: '#A02D30',
|
||||
yellow: '#FFC107',
|
||||
@@ -83,6 +85,12 @@ async function rawRequest<T>(
|
||||
if (json.code !== 0) {
|
||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||
err.status = json.code;
|
||||
if (json.code === 400) {
|
||||
reportApiError(
|
||||
{ apiBase, clientApp: CLIENT_APP, getToken: () => localStorage.getItem(ACCESS_TOKEN) },
|
||||
{ message: json.message || '请求失败', status: 400, url: path, category: 'validation_error' },
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return json.data as T;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ClientApp } from '@dukang/shared-types';
|
||||
import { forceReloadAfterAccountMerge } from './auth-nav';
|
||||
import { resetStoresSessionBootstrap } from './stores-session';
|
||||
import { resetHomeCatalogBootstrap } from './home-catalog-session';
|
||||
import { reportClientValidationError } from './client-error';
|
||||
|
||||
function resolveApiBase(): string {
|
||||
const origin =
|
||||
@@ -113,6 +114,12 @@ export async function request<T = unknown>(path: string, options: ReqOptions = {
|
||||
throw new Error('接口不可达,请确认 API 服务已启动');
|
||||
}
|
||||
if (status >= 400 || body.code !== 0) {
|
||||
if (status === 400 || body?.code === 400) {
|
||||
reportClientValidationError({
|
||||
message: body?.message || `请求失败(${status})`,
|
||||
apiPath: path,
|
||||
});
|
||||
}
|
||||
throw new Error(body?.message || `请求失败(${status})`);
|
||||
}
|
||||
return (res.data as { data: T }).data;
|
||||
|
||||
@@ -6,6 +6,7 @@ export type ClientErrorCategory =
|
||||
| 'js_error'
|
||||
| 'unhandled_rejection'
|
||||
| 'api_error'
|
||||
| 'validation_error'
|
||||
| 'network'
|
||||
| 'render'
|
||||
| 'bridge'
|
||||
@@ -57,6 +58,17 @@ export function reportClientError(payload: ClientErrorPayload): void {
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
/** 上报 API 400 验证错误(失败静默) */
|
||||
export function reportClientValidationError(input: { message: string; apiPath?: string }): void {
|
||||
if (input.apiPath?.includes('/common/client-errors')) return;
|
||||
reportClientError({
|
||||
level: 'warn',
|
||||
category: 'validation_error',
|
||||
message: input.message,
|
||||
extra: { status: 400, url: input.apiPath },
|
||||
});
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
|
||||
/** 安装小程序/H5 全局未捕获错误钩子(幂等) */
|
||||
|
||||
@@ -175,15 +175,14 @@
|
||||
}
|
||||
|
||||
.store-detail-env-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.store-detail-env-item {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 4 / 3;
|
||||
border-radius: var(--radius-md, 8px);
|
||||
overflow: hidden;
|
||||
background: var(--color-surface-container);
|
||||
@@ -192,8 +191,9 @@
|
||||
|
||||
.store-detail-env-img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.store-detail-bar {
|
||||
|
||||
@@ -5,6 +5,7 @@ export type ClientErrorCategory =
|
||||
| 'js_error'
|
||||
| 'unhandled_rejection'
|
||||
| 'api_error'
|
||||
| 'validation_error'
|
||||
| 'network'
|
||||
| 'render'
|
||||
| 'bridge'
|
||||
@@ -73,6 +74,7 @@ export function reportApiError(
|
||||
input: { message: string; status?: number; url?: string; category?: ClientErrorCategory },
|
||||
) {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (input.url?.includes('/common/client-errors')) return;
|
||||
const token = opts.getToken?.() ?? localStorage.getItem('accessToken');
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -85,7 +87,7 @@ export function reportApiError(
|
||||
headers,
|
||||
body: {
|
||||
level: 'warn',
|
||||
category: input.category ?? 'api_error',
|
||||
category: input.category ?? (input.status === 400 ? 'validation_error' : 'api_error'),
|
||||
message: input.message.slice(0, 1000),
|
||||
pagePath: window.location.pathname,
|
||||
clientApp: opts.clientApp,
|
||||
|
||||
@@ -50,6 +50,20 @@ export type CreateKnowledgeDocumentRequest = {
|
||||
sizeBytes?: number | null;
|
||||
};
|
||||
|
||||
export type UpdateKnowledgeDocumentRequest = {
|
||||
title?: string;
|
||||
contentText?: string | null;
|
||||
fileName?: string | null;
|
||||
fileUrl?: string | null;
|
||||
mimeType?: string | null;
|
||||
sizeBytes?: number | null;
|
||||
};
|
||||
|
||||
/** 编辑文档时含正文 */
|
||||
export type KnowledgeDocumentDetailDto = KnowledgeDocumentDto & {
|
||||
contentText: string | null;
|
||||
};
|
||||
|
||||
export type KnowledgeBaseOptionDto = {
|
||||
id: string;
|
||||
name: string;
|
||||
|
||||
@@ -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));
|
||||
|
||||
Reference in New Issue
Block a user