feat(chat): 完善附件预览与订单提取交互
- 优化聊天附件上传、预览及 PDF.js 加载 - 完善订单文档画布与审核预览体验 - 优化订单提取运行状态及发送流程 - 增强会话附件接口与相关测试覆盖 - 更新 Nginx 配置、技术文档及四语言文案
This commit is contained in:
1 parent
104afa3844
commit
9d2fa522fa
29 files changed
+584
-140
No files matched your search
+15
-4
@@ -613,6 +613,14 @@ const coordinateCanvasActions = computed<OrderProfileCanvasActions>(() => ({
|
||||
page: (nextPageNo) => { void selectPage(nextPageNo); },
|
||||
draw: (kind) => startDrawing(kind),
|
||||
}));
|
||||
/** 页图 token 失效时自动重签;客户端渲染失败(如 worker MIME)不得超过预算。 */
|
||||
let previewReauthInFlight = false;
|
||||
let previewAutoReauthCount = 0;
|
||||
const PREVIEW_AUTO_REAUTH_LIMIT = 2;
|
||||
const resetPreviewAutoReauthBudget = () => {
|
||||
previewAutoReauthCount = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* 共享视觉画布模型:模板差异在此处一次性被 adapter 吸收,之后所有画布事件和 props
|
||||
* 均只消费 visualCanvas。datasets path、集合与拆分规则不属于视觉模型,继续留在 XFA
|
||||
@@ -659,7 +667,10 @@ const visualCanvas = computed<OrderProfileVisualCanvasAdapter>(() => {
|
||||
warningVisible: adapterWarningVisible || canvasUnavailable.value,
|
||||
warningText: adapterWarningText
|
||||
|| (canvasUnavailable.value ? t('admin.shippingOrderProfiles.workbench.canvasUnavailable') : null),
|
||||
retryCanvas: () => { void loadPages(); },
|
||||
retryCanvas: () => {
|
||||
resetPreviewAutoReauthBudget();
|
||||
void loadPages();
|
||||
},
|
||||
reportCanvasLoadFailed: () => { canvasUnavailable.value = true; },
|
||||
applyAutomarkCandidates: () => false,
|
||||
canRender: true,
|
||||
@@ -814,13 +825,13 @@ const deskCanvasReadonly = computed(() => visualCanvas.value.canvasReadonly);
|
||||
const deskCanvasWarningVisible = computed(() => visualCanvas.value.warningVisible);
|
||||
const deskCanvasWarningText = computed(() => visualCanvas.value.warningText || '');
|
||||
const onDeskCanvasRetry = () => visualCanvas.value.retryCanvas();
|
||||
/** 页图 token 失效时自动重签一批预览令牌,避免翻页后只能手动点「重试画布」。 */
|
||||
let previewReauthInFlight = false;
|
||||
/** 页图/原 PDF 令牌 HTTP 失效时自动重签;客户端渲染失败不得走此路径(见 DocumentCanvas)。 */
|
||||
const onDeskCanvasLoadFailed = async () => {
|
||||
if (previewReauthInFlight) {
|
||||
if (previewReauthInFlight || previewAutoReauthCount >= PREVIEW_AUTO_REAUTH_LIMIT) {
|
||||
visualCanvas.value.reportCanvasLoadFailed();
|
||||
return;
|
||||
}
|
||||
previewAutoReauthCount += 1;
|
||||
previewReauthInFlight = true;
|
||||
try {
|
||||
await loadPages();
|
||||
|
||||
+90
-4
@@ -14,11 +14,12 @@ const { getDocumentMock, getPageMock, renderMock } = vi.hoisted(() => ({
|
||||
renderMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('pdfjs-dist', () => ({
|
||||
GlobalWorkerOptions: {},
|
||||
getDocument: (...args: unknown[]) => getDocumentMock(...args),
|
||||
vi.mock('@/shared/utils/pdfjs', () => ({
|
||||
loadPdfJs: async () => ({
|
||||
GlobalWorkerOptions: {},
|
||||
getDocument: (...args: unknown[]) => getDocumentMock(...args),
|
||||
}),
|
||||
}));
|
||||
vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '/pdf.worker.min.mjs' }));
|
||||
vi.mock('@/shared/utils/auth', () => ({ getAuthHeaders: () => ({ Authorization: 'Bearer test' }) }));
|
||||
|
||||
describe('OrderProfileDocumentCanvas PDF preview', () => {
|
||||
@@ -274,4 +275,89 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
|
||||
// 使用 PDF.js 原始像素而不是 CSS 缩放后的大小,保证回读与用户框选区域一致。
|
||||
expect(drawImage).toHaveBeenCalledWith(source, 60, 160, 181, 240, 0, 0, 181, 240);
|
||||
});
|
||||
|
||||
it('keeps pdfCanvas mounted under pdfPreview error overlay and does not reauth on render failure', async () => {
|
||||
getDocumentMock.mockReturnValue({
|
||||
promise: Promise.resolve({
|
||||
numPages: 1,
|
||||
getPage: vi.fn(async () => {
|
||||
throw new Error('PDF canvas is unavailable');
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 71,
|
||||
pdfPreview: { preview_token: 'single-use-token' },
|
||||
regions: [], pageNo: 1, pageCount: 1,
|
||||
},
|
||||
global: {
|
||||
plugins: [createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: { shippingOrderProfiles: { workbench: { canvasUnavailable: '受控 PDF 画布暂不可用', retryCanvas: '重试' } } },
|
||||
},
|
||||
},
|
||||
})],
|
||||
},
|
||||
});
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
|
||||
// 关键断言:原 PDF 路径失败不得卸掉 canvas,否则重试/reauth 后 render 仍读到 null。
|
||||
expect(wrapper.find('canvas.pdf-page').exists()).toBe(true);
|
||||
expect(wrapper.find('.canvas-error-overlay').exists()).toBe(true);
|
||||
expect(wrapper.emitted('loadFailed')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reuses in-memory PDF bytes for the same single-use preview token', async () => {
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 71,
|
||||
pdfPreview: { preview_token: 'single-use-token' },
|
||||
regions: [], pageNo: 1, pageCount: 1,
|
||||
},
|
||||
global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] },
|
||||
});
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
// 改 grant 依赖重入 watch,但 pdfPreview token 不变;必须走内存缓存,否则 getdel 二次 GET=404。
|
||||
await wrapper.setProps({
|
||||
grant: { page_no: 1, preview_token: 'png-ignored' },
|
||||
pdfPreview: { preview_token: 'single-use-token' },
|
||||
});
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('emits loadFailed only for preview-token HTTP failures', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 404 })));
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 71,
|
||||
pdfPreview: { preview_token: 'dead-token' },
|
||||
regions: [], pageNo: 1, pageCount: 1,
|
||||
},
|
||||
global: {
|
||||
plugins: [createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: { shippingOrderProfiles: { workbench: { canvasUnavailable: '受控 PDF 画布暂不可用', retryCanvas: '重试' } } },
|
||||
},
|
||||
},
|
||||
})],
|
||||
},
|
||||
});
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
expect(wrapper.emitted('loadFailed')).toHaveLength(1);
|
||||
expect(wrapper.find('canvas.pdf-page').exists()).toBe(true);
|
||||
});
|
||||
});
|
||||
+93
-35
@@ -4,6 +4,9 @@
|
||||
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion、isUnboundOrderFieldCanvasRegion。
|
||||
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
|
||||
PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token;
|
||||
原 PDF(pdf-preview)令牌亦为 Redis getdel 单次消费:同 token 字节必须缓存,且仅 HTTP 401/403/404
|
||||
才 emit loadFailed 触发父级 reauth;画布/渲染失败不得重签,否则会空转授权风暴;
|
||||
pdfPreview 错误态用 overlay,禁止 v-if 卸掉 pdfCanvas(否则 renderPdfPage 必失败);
|
||||
未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除;
|
||||
选中框用 top/right/bottom/left 定位(避免 height% 在内容撑高容器上失效);
|
||||
拖拽/缩放进行中忽略滚轮缩放,避免触控板纵向手势把高度调整抢走;
|
||||
@@ -16,28 +19,11 @@ import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, MessageSquareText, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { loadPdfJs } from '@/shared/utils/pdfjs';
|
||||
import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { isUnboundOrderFieldCanvasRegion } from '../orderProfileForm.utils';
|
||||
import type { PDFDocumentProxy } from 'pdfjs-dist';
|
||||
|
||||
type PdfJsModule = typeof import('pdfjs-dist');
|
||||
let pdfjsLoader: Promise<PdfJsModule> | null = null;
|
||||
|
||||
/** 动态加载 PDF.js 与 worker;坐标 PDF 与 XFA 在受控管理员画布按需共用。 */
|
||||
async function loadPdfJs(): Promise<PdfJsModule> {
|
||||
if (!pdfjsLoader) {
|
||||
pdfjsLoader = (async () => {
|
||||
const [pdfjs, workerMod] = await Promise.all([
|
||||
import('pdfjs-dist'),
|
||||
import('pdfjs-dist/build/pdf.worker.min.mjs?url'),
|
||||
]);
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default;
|
||||
return pdfjs;
|
||||
})();
|
||||
}
|
||||
return pdfjsLoader;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
profileId: number | null;
|
||||
grant?: OrderProfilePreviewPageGrant | null;
|
||||
@@ -107,6 +93,12 @@ const viewport = ref<HTMLElement | null>(null);
|
||||
const zoom = ref(1);
|
||||
/** 按页缓存已消费 token 拉取的 PNG,翻页回访不再触发一次性 token 失效。 */
|
||||
const pageImageCache = new Map<string, string>();
|
||||
/**
|
||||
* 原 PDF 字节缓存:pdf-preview 令牌是 Redis getdel 单次消费。
|
||||
* 同 token 的并发/重入 loadPage 若再次 GET 会 404,并误触发父级 reauth 风暴。
|
||||
*/
|
||||
let cachedPdfBytes: Uint8Array | null = null;
|
||||
let cachedPdfToken: string | null = null;
|
||||
let loadGeneration = 0;
|
||||
let cachedProfileId: number | null = null;
|
||||
const zoomPercent = computed(() => Math.round(zoom.value * 100));
|
||||
@@ -123,17 +115,34 @@ const emptyStateText = computed(() => (
|
||||
props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf')
|
||||
));
|
||||
|
||||
/**
|
||||
* 等待 pdfCanvas 进入 DOM。
|
||||
* 错误态曾用 v-if 卸掉 canvas;清错后仅一次 nextTick 仍可能读到 null,
|
||||
* 进而抛 "PDF canvas is unavailable",被空 catch 吃掉且 0 console error。
|
||||
*/
|
||||
const ensurePdfCanvas = async (): Promise<{ canvas: HTMLCanvasElement; context: CanvasRenderingContext2D }> => {
|
||||
for (let attempt = 0; attempt < 10; attempt += 1) {
|
||||
await nextTick();
|
||||
const el = pdfCanvas.value;
|
||||
const context = el?.getContext('2d');
|
||||
if (el && context) return { canvas: el, context };
|
||||
await new Promise<void>((resolve) => {
|
||||
if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => resolve());
|
||||
else window.setTimeout(() => resolve(), 16);
|
||||
});
|
||||
}
|
||||
throw new Error('PDF canvas is unavailable');
|
||||
};
|
||||
|
||||
/**
|
||||
* 将内存中的原 PDF 按真实页面外观流绘制到 Canvas。
|
||||
* 核心逻辑:坐标 PDF 与 hybrid XFA 都用 page.render(),不生成可下载 URL。
|
||||
*/
|
||||
const renderPdfPage = async (pdf: PDFDocumentProxy) => {
|
||||
await nextTick();
|
||||
const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages);
|
||||
const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages || 1);
|
||||
if (pdf.numPages < 1) throw new Error('PDF has no pages');
|
||||
const page = await pdf.getPage(targetPage);
|
||||
const canvas = pdfCanvas.value;
|
||||
const context = canvas?.getContext('2d');
|
||||
if (!canvas || !context) throw new Error('PDF canvas is unavailable');
|
||||
const { canvas, context } = await ensurePdfCanvas();
|
||||
const viewport = page.getViewport({ scale: zoom.value });
|
||||
pdfPageSize.value = { width: viewport.width, height: viewport.height };
|
||||
canvas.width = Math.ceil(viewport.width);
|
||||
@@ -142,6 +151,12 @@ const renderPdfPage = async (pdf: PDFDocumentProxy) => {
|
||||
pdfRendered.value = true;
|
||||
};
|
||||
|
||||
/** 令牌失效类 HTTP 才值得父级 reauth;画布未挂载/渲染失败重签只会空转。 */
|
||||
const isPreviewTokenHttpError = (error: unknown): boolean => {
|
||||
if (!(error instanceof Error)) return false;
|
||||
return /^HTTP (401|403|404)\b/.test(error.message);
|
||||
};
|
||||
|
||||
/**
|
||||
* 回收某次会话内全部页图 blob;切换样本 Profile 或卸载时调用。
|
||||
*/
|
||||
@@ -149,6 +164,8 @@ const clearPageImageCache = () => {
|
||||
for (const url of pageImageCache.values()) URL.revokeObjectURL(url);
|
||||
pageImageCache.clear();
|
||||
inflightPageLoads.clear();
|
||||
cachedPdfBytes = null;
|
||||
cachedPdfToken = null;
|
||||
};
|
||||
|
||||
/** 同一页的并发拉取共用一个 Promise,成功后必入缓存(即使请求已过期)。 */
|
||||
@@ -206,13 +223,21 @@ const loadPage = async () => {
|
||||
|| `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`;
|
||||
if (props.pdfPreview) {
|
||||
imageUrl.value = '';
|
||||
const response = await fetch(
|
||||
`${previewPath}?preview_token=${encodeURIComponent(props.pdfPreview.preview_token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const token = props.pdfPreview.preview_token;
|
||||
let bytes: Uint8Array;
|
||||
if (cachedPdfToken === token && cachedPdfBytes) {
|
||||
bytes = cachedPdfBytes;
|
||||
} else {
|
||||
const response = await fetch(
|
||||
`${previewPath}?preview_token=${encodeURIComponent(token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
bytes = new Uint8Array(await response.arrayBuffer());
|
||||
cachedPdfBytes = bytes;
|
||||
cachedPdfToken = token;
|
||||
}
|
||||
const pdfjs = await loadPdfJs();
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
pdfDocument = await pdfjs.getDocument({ data: bytes, enableXfa: true }).promise;
|
||||
if (generation !== loadGeneration) return;
|
||||
emit('pageCount', pdfDocument.numPages);
|
||||
@@ -224,7 +249,7 @@ const loadPage = async () => {
|
||||
const blobUrl = await fetchPageImage(previewPath, grant);
|
||||
if (generation !== loadGeneration) return;
|
||||
imageUrl.value = blobUrl;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (generation !== loadGeneration) return;
|
||||
const fallback = props.grant ? pageImageCache.get(String(props.grant.page_no)) : null;
|
||||
if (fallback) {
|
||||
@@ -234,7 +259,10 @@ const loadPage = async () => {
|
||||
}
|
||||
imageUrl.value = '';
|
||||
internalLoadError.value = t('admin.shippingOrderProfiles.workbench.canvasUnavailable');
|
||||
emit('loadFailed');
|
||||
// 仅令牌 HTTP 失效才通知父级重签;画布未挂载/PDF.js 渲染失败重签只会烧掉单次 token。
|
||||
if (isPreviewTokenHttpError(error) || (props.grant && error instanceof Error && /^HTTP \d+/.test(error.message))) {
|
||||
emit('loadFailed');
|
||||
}
|
||||
} finally {
|
||||
if (generation === loadGeneration) loading.value = false;
|
||||
}
|
||||
@@ -442,10 +470,20 @@ defineExpose({
|
||||
watch(() => [props.grant?.page_no, props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true });
|
||||
watch(() => props.pageNo, async (value) => {
|
||||
pageInput.value = value;
|
||||
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
|
||||
if (!(props.pdfPreview && pdfDocument)) return;
|
||||
try {
|
||||
await renderPdfPage(pdfDocument);
|
||||
} catch {
|
||||
/* 翻页时画布可能短暂卸载;下一次 load/retry 会恢复 */
|
||||
}
|
||||
});
|
||||
watch(zoom, async () => {
|
||||
if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument);
|
||||
if (!(props.pdfPreview && pdfDocument)) return;
|
||||
try {
|
||||
await renderPdfPage(pdfDocument);
|
||||
} catch {
|
||||
/* 缩放同翻页:避免未捕获 Promise 干扰控制台 */
|
||||
}
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
endMove();
|
||||
@@ -494,7 +532,8 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
</header>
|
||||
<div v-if="loading && !pdfPreview" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
|
||||
<div v-else-if="displayLoadError" class="canvas-state canvas-state--error" role="alert">
|
||||
<!-- PNG 路径仍可用整页错误态;原 PDF 路径必须保留 canvas 挂载,否则 renderPdfPage 必抛 canvas unavailable。 -->
|
||||
<div v-else-if="displayLoadError && !pdfPreview" class="canvas-state canvas-state--error" role="alert">
|
||||
<p>{{ displayLoadError }}</p>
|
||||
<button type="button" class="canvas-retry" @click="onRetryClick">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
|
||||
@@ -592,6 +631,12 @@ onBeforeUnmount(() => {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="displayLoadError && pdfPreview" class="canvas-error-overlay" role="alert">
|
||||
<p>{{ displayLoadError }}</p>
|
||||
<button type="button" class="canvas-retry" @click="onRetryClick">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -635,7 +680,20 @@ onBeforeUnmount(() => {
|
||||
cursor: pointer;
|
||||
}
|
||||
.canvas-retry:hover { border-color: #60a5fa; background: #26364f; }
|
||||
.canvas-work-area { display: flex; min-height: 0; flex: 1; gap: .6rem; }
|
||||
.canvas-work-area { position: relative; display: flex; min-height: 0; flex: 1; gap: .6rem; }
|
||||
.canvas-error-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 8;
|
||||
display: grid;
|
||||
place-content: center;
|
||||
gap: .75rem;
|
||||
background: rgb(15 23 42 / .82);
|
||||
color: #fecaca;
|
||||
font-size: .875rem;
|
||||
text-align: center;
|
||||
padding: 1rem;
|
||||
}
|
||||
.canvas-work-area.readonly { gap: 0; }
|
||||
.canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; }
|
||||
.canvas-viewport.panning { cursor: grab; }
|
||||
|
||||
Reference in new issue
Block a user