feat(print): 新增本机组件(17301)并接入 PDF 打印
- 打印组件新增「本机组件」(ws://127.0.0.1:17301),获取打印机走 printer.getWindowsPrinters - 打印机列表测试弹窗改为读取运行时组件列表,未连接时先直连再查询 - 本机组件打印改用 printer.printPdf(method 协议),其余组件仍走 cmd=print - 从 documents[].contents[].pdf_base64 组装 PDF 打印载荷 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
ebf20f5269
commit
4e18eb4d00
@ -44,7 +44,9 @@ export const DEFAULT_PRINTER_COMPONENTS: PrinterComponentPort[] = [
|
||||
{ name: '菜鸟', port: '13528' },
|
||||
{ name: '视频号', port: '12705' },
|
||||
{ name: '小红书', port: '10818' },
|
||||
{ name: 'LODOP', port: '8000/c_webskt' }
|
||||
{ name: 'LODOP', port: '8000/c_webskt' },
|
||||
// 前端直连测试组件(ws://127.0.0.1:17301),仅用于「打印机列表测试」获取打印机
|
||||
{ name: '本机组件', port: '17301' }
|
||||
]
|
||||
|
||||
const MESSAGE_EVENT_MAP: Record<string, string> = {
|
||||
@ -55,7 +57,8 @@ const MESSAGE_EVENT_MAP: Record<string, string> = {
|
||||
京东: 'jingdongMessage',
|
||||
菜鸟: 'cainiaoMessage',
|
||||
视频号: 'shipinhaoMessage',
|
||||
小红书: 'xiaohongshuMessage'
|
||||
小红书: 'xiaohongshuMessage',
|
||||
本机组件: 'localComponentMessage'
|
||||
}
|
||||
|
||||
/** 打印组件 WebSocket 长连接管理(浏览器版) */
|
||||
|
||||
@ -17,6 +17,7 @@ export class PrinterComponentMessageHandler {
|
||||
this.app.on('cainiaoMessage', this.handleCainiaoMessage.bind(this))
|
||||
this.app.on('shipinhaoMessage', this.handleShipinhaoMessage.bind(this))
|
||||
this.app.on('xiaohongshuMessage', this.handleXiaohongshuMessage.bind(this))
|
||||
this.app.on('localComponentMessage', this.handleLocalComponentMessage.bind(this))
|
||||
this.app.on('printerComponentMessage', this.handleOtherComponentMessage.bind(this))
|
||||
}
|
||||
|
||||
@ -57,6 +58,10 @@ export class PrinterComponentMessageHandler {
|
||||
console.log('[小红书]', msg)
|
||||
}
|
||||
|
||||
private handleLocalComponentMessage(msg: unknown): void {
|
||||
console.log('[本机组件]', msg)
|
||||
}
|
||||
|
||||
private handleOtherComponentMessage(payload: unknown): void {
|
||||
const data = payload as { name?: string; message?: unknown }
|
||||
console.log(`[${data?.name ?? '未知组件'}]`, data?.message)
|
||||
|
||||
@ -124,36 +124,31 @@ const visibleProxy = computed({
|
||||
set: (v: boolean) => emit('update:modelValue', v)
|
||||
})
|
||||
|
||||
/** 打印组件端口映射(与 printerComponentCore DEFAULT_PRINTER_COMPONENTS 一致) */
|
||||
const COMPONENT_PORT_MAP: Record<string, string> = {
|
||||
抖音: '13888',
|
||||
拼多多: '5000',
|
||||
快手: '16888/ks/printer',
|
||||
京东: '9113',
|
||||
菜鸟: '13528',
|
||||
视频号: '12705',
|
||||
小红书: '10818',
|
||||
LODOP: '8000/c_webskt'
|
||||
}
|
||||
/** 打印组件列表与端口:直接取运行时配置,避免与 DEFAULT_PRINTER_COMPONENTS 重复维护 */
|
||||
const componentList = computed(() => printerStore.components)
|
||||
|
||||
/** 所有打印组件名称列表 */
|
||||
const ALL_PRINT_COMPONENTS = ['抖音', '拼多多', '快手', '京东', '菜鸟', '视频号', '小红书', 'LODOP']
|
||||
const componentPortMap = computed<Record<string, string>>(() => {
|
||||
const map: Record<string, string> = {}
|
||||
componentList.value.forEach((item) => {
|
||||
map[item.name] = item.port
|
||||
})
|
||||
return map
|
||||
})
|
||||
|
||||
const componentStatusRows = computed(() => {
|
||||
return ALL_PRINT_COMPONENTS.map((name) => ({
|
||||
name,
|
||||
port: COMPONENT_PORT_MAP[name] || '',
|
||||
connected: printerStore.isConnected(name)
|
||||
return componentList.value.map((item) => ({
|
||||
name: item.name,
|
||||
port: item.port,
|
||||
connected: printerStore.isConnected(item.name)
|
||||
}))
|
||||
})
|
||||
|
||||
const componentSelectOptions = computed(() => {
|
||||
return ALL_PRINT_COMPONENTS.map((name) => {
|
||||
const connected = printerStore.isConnected(name)
|
||||
const port = COMPONENT_PORT_MAP[name] || ''
|
||||
return componentList.value.map((item) => {
|
||||
const connected = printerStore.isConnected(item.name)
|
||||
return {
|
||||
label: `${name}${connected ? ' ✓' : ''} [${port}]`,
|
||||
value: name
|
||||
label: `${item.name}${connected ? ' ✓' : ''} [${item.port}]`,
|
||||
value: item.name
|
||||
}
|
||||
})
|
||||
})
|
||||
@ -174,6 +169,21 @@ function refreshStatus() {
|
||||
printerStore.refreshFromRuntime()
|
||||
}
|
||||
|
||||
/** 未连接时直连尝试一次,并等待连接就绪(默认最多 3s) */
|
||||
async function ensureConnected(componentName: string, timeoutMs = 3000): Promise<boolean> {
|
||||
printerStore.refreshFromRuntime()
|
||||
if (printerStore.isConnected(componentName)) return true
|
||||
|
||||
printerStore.reconnectComponent(componentName)
|
||||
const deadline = Date.now() + timeoutMs
|
||||
while (Date.now() < deadline) {
|
||||
await new Promise((resolve) => globalThis.setTimeout(resolve, 100))
|
||||
printerStore.refreshFromRuntime()
|
||||
if (printerStore.isConnected(componentName)) return true
|
||||
}
|
||||
return printerStore.isConnected(componentName)
|
||||
}
|
||||
|
||||
async function fetchPrinterList() {
|
||||
const componentName = selectedComponent.value
|
||||
if (!componentName) return
|
||||
@ -183,9 +193,8 @@ async function fetchPrinterList() {
|
||||
printerError.value = ''
|
||||
|
||||
try {
|
||||
printerStore.refreshFromRuntime()
|
||||
const connected = printerStore.isConnected(componentName)
|
||||
const port = COMPONENT_PORT_MAP[componentName] || '未知'
|
||||
const port = componentPortMap.value[componentName] || '未知'
|
||||
const connected = await ensureConnected(componentName)
|
||||
|
||||
if (!connected) {
|
||||
printerError.value = `组件「${componentName}」未连接(目标端口 ws://127.0.0.1:${port}),请先在「打印组件连接」面板中确认连接状态,并确保 ${componentName} 打印控件已启动`
|
||||
@ -194,7 +203,7 @@ async function fetchPrinterList() {
|
||||
|
||||
const result = await queryComponentPrinterList(componentName, undefined, 5000)
|
||||
if (!result) {
|
||||
printerError.value = `组件「${componentName}」(端口 ${port})无响应或超时。可能原因:① ${componentName} 打印控件未正常运行;② 控件版本不支持 getPrinters 协议;③ 网络环境限制(公网 HTTP 请改用 HTTPS 打开)`
|
||||
printerError.value = `组件「${componentName}」(端口 ${port})无响应或超时。可能原因:① ${componentName} 打印控件未正常运行;② 控件版本不支持获取打印机协议;③ 网络环境限制(公网 HTTP 请改用 HTTPS 打开)`
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@ -216,6 +216,7 @@ export interface PrintSendRequest {
|
||||
视频号: '12705',
|
||||
小红书: '10818',
|
||||
LODOP: '8000/c_webskt',
|
||||
本机组件: '17301',
|
||||
};
|
||||
|
||||
/** 英文/别名 → 组件注册名 */
|
||||
@ -425,6 +426,58 @@ export interface PrintSendRequest {
|
||||
return lodop.EXPORT_INSTRUCTIONS();
|
||||
}
|
||||
|
||||
/** 本机组件 method 协议的自增调用号 */
|
||||
let localPrintCallSeq = 0;
|
||||
|
||||
/** 取文档内的 pdf_base64(document.pdf_base64 或 documents[].contents[].pdf_base64) */
|
||||
function extractDocumentPdfBase64(document: Record<string, unknown>): string {
|
||||
const direct = String(document.pdf_base64 ?? '').trim();
|
||||
if (direct) return direct;
|
||||
const contents = Array.isArray(document.contents) ? document.contents : [];
|
||||
for (const item of contents) {
|
||||
const base64 = String(asRecord(item)?.pdf_base64 ?? '').trim();
|
||||
if (base64) return base64;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 本机组件(printServer 17301)使用 method 协议:printer.printPdf。
|
||||
* 后端已在 print_data 里给出 method 信封时原样下发,其余组件仍走 cmd=print。
|
||||
*/
|
||||
function buildLocalComponentPrintPayload(task: PrintTaskData): Record<string, unknown> {
|
||||
const data = asRecord(task.data) ?? {};
|
||||
if (typeof data.method === 'string' && data.method.trim()) return data;
|
||||
|
||||
const documentsRaw = asRecord(data.task)?.documents ?? data.documents;
|
||||
const documents = Array.isArray(documentsRaw) ? (documentsRaw as unknown[]) : [];
|
||||
const orders: Array<{ order_id: unknown; pdf_base64: string }> = [];
|
||||
for (const document of documents) {
|
||||
const rec = asRecord(document);
|
||||
if (!rec) continue;
|
||||
const pdfBase64 = extractDocumentPdfBase64(rec);
|
||||
if (!pdfBase64) continue;
|
||||
orders.push({
|
||||
order_id: rec.documentID ?? rec.document_id ?? rec.order_id ?? null,
|
||||
pdf_base64: pdfBase64,
|
||||
});
|
||||
}
|
||||
|
||||
if (!orders.length) {
|
||||
throw new Error('本机组件仅支持 PDF 打印:documents[].contents[].pdf_base64 为空');
|
||||
}
|
||||
|
||||
return {
|
||||
method: 'printer.printPdf',
|
||||
data: {
|
||||
printer: task.printer,
|
||||
printId: task.printId,
|
||||
payload: [{ printer: task.printer, orders }],
|
||||
},
|
||||
_callId: ++localPrintCallSeq,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建发往打印组件的最终载荷(与 printer.js print() 中 component.send 入参一致)
|
||||
*/
|
||||
@ -443,7 +496,9 @@ export interface PrintSendRequest {
|
||||
throw new Error('express 类型缺少有效的 component(如 douyin、菜鸟)');
|
||||
}
|
||||
componentName = resolved;
|
||||
payload = task.data as Record<string, unknown>;
|
||||
payload = isLocalComponent(resolved)
|
||||
? buildLocalComponentPrintPayload(task)
|
||||
: (task.data as Record<string, unknown>);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
@ -1291,6 +1346,7 @@ const COMPONENT_GET_PRINTERS_EVENT: Record<string, string> = {
|
||||
拼多多: 'pinduoduoMessage',
|
||||
视频号: 'shipinhaoMessage',
|
||||
小红书: 'xiaohongshuMessage',
|
||||
本机组件: 'localComponentMessage',
|
||||
};
|
||||
|
||||
function shouldAlignPrinterViaComponent(component: string): boolean {
|
||||
@ -1495,6 +1551,11 @@ function shouldAlignPrinterViaComponent(component: string): boolean {
|
||||
return component === '视频号';
|
||||
}
|
||||
|
||||
/** 本机组件(127.0.0.1:17301)使用 method 协议(printer.getWindowsPrinters),而非 cmd=getPrinters */
|
||||
function isLocalComponent(component: string): boolean {
|
||||
return component === '本机组件';
|
||||
}
|
||||
|
||||
function isJingdongCloudPrintPayload(payload: Record<string, unknown>): boolean {
|
||||
return String(payload.orderType ?? '').trim().length > 0;
|
||||
}
|
||||
@ -1835,6 +1896,7 @@ function parseComponentGetPrintersResponse(
|
||||
response: Record<string, unknown>,
|
||||
useJingdongProtocol: boolean,
|
||||
useShipinhaoProtocol = false,
|
||||
useLocalProtocol = false,
|
||||
): ComponentPrinterListResult {
|
||||
const printerNames = useJingdongProtocol
|
||||
? parseJingdongPrinterNames(response)
|
||||
@ -1852,7 +1914,28 @@ function parseComponentGetPrintersResponse(
|
||||
})
|
||||
.filter(Boolean);
|
||||
})()
|
||||
: (() => {
|
||||
: useLocalProtocol
|
||||
? (() => {
|
||||
// 本机组件协议返回 result: [{ name, workOffline }],兼容 result.printers / result.data
|
||||
const raw = response.result as Record<string, unknown> | unknown[] | undefined;
|
||||
const listRaw = Array.isArray(raw)
|
||||
? raw
|
||||
: Array.isArray((raw as Record<string, unknown> | undefined)?.printers)
|
||||
? ((raw as Record<string, unknown>).printers as unknown[])
|
||||
: Array.isArray((raw as Record<string, unknown> | undefined)?.data)
|
||||
? ((raw as Record<string, unknown>).data as unknown[])
|
||||
: [];
|
||||
return listRaw
|
||||
.map((item) => {
|
||||
if (typeof item === 'string') return item.trim();
|
||||
if (item && typeof item === 'object') {
|
||||
return String((item as Record<string, unknown>).name ?? '').trim();
|
||||
}
|
||||
return '';
|
||||
})
|
||||
.filter(Boolean);
|
||||
})()
|
||||
: (() => {
|
||||
const printersRaw = Array.isArray(response.printers) ? response.printers : [];
|
||||
return printersRaw
|
||||
.map((item) => {
|
||||
@ -1876,6 +1959,9 @@ export type ComponentPrinterListResult = {
|
||||
defaultPrinter: string;
|
||||
};
|
||||
|
||||
/** 本机组件 method 协议的自增调用号(响应按 method + result 匹配,不依赖该值) */
|
||||
let localComponentCallSeq = 0;
|
||||
|
||||
/** 向已连接的本地打印组件查询 getPrinters 列表 */
|
||||
export async function queryComponentPrinterList(
|
||||
componentName: string,
|
||||
@ -1890,6 +1976,8 @@ export async function queryComponentPrinterList(
|
||||
|
||||
const jingdong = isJingdongComponent(componentName);
|
||||
const shipinhao = isShipinhaoComponent(componentName);
|
||||
const localComponent = isLocalComponent(componentName);
|
||||
const callId = localComponent ? ++localComponentCallSeq : 0;
|
||||
|
||||
try {
|
||||
const { printerComponents } = await import('@/core/printerRuntime');
|
||||
@ -1930,6 +2018,12 @@ export async function queryComponentPrinterList(
|
||||
const isMatch = rcmd === 'getPrinterList' && rrid === reqId;
|
||||
console.log(`[queryComponentPrinterList] 组件 "${componentName}" 视频号响应匹配`, { command: rcmd, requestID: rrid, expectedReqId: reqId, isMatch, keys: Object.keys(parsed) })
|
||||
if (!isMatch) return;
|
||||
} else if (localComponent) {
|
||||
// 本机组件协议:先回执 { method, _callId }(无 result),随后广播带 result 的打印机列表
|
||||
const method = String(parsed.method ?? '');
|
||||
const hasResult = Boolean(parsed.result);
|
||||
console.log(`[queryComponentPrinterList] 组件 "${componentName}" 本机组件响应`, { method, hasResult, callId, keys: Object.keys(parsed) })
|
||||
if (method !== 'printer.getWindowsPrinters' || !hasResult) return;
|
||||
} else {
|
||||
const cmd = String(parsed.cmd ?? '');
|
||||
const rid = String(parsed.requestID ?? parsed.requetID ?? parsed.requestId ?? '');
|
||||
@ -1958,6 +2052,16 @@ export async function queryComponentPrinterList(
|
||||
command: 'getPrinterList',
|
||||
}),
|
||||
);
|
||||
} else if (localComponent) {
|
||||
// 本机组件协议:{ method, data, _callId }
|
||||
printerComponents.sendMessage(
|
||||
componentName,
|
||||
JSON.stringify({
|
||||
method: 'printer.getWindowsPrinters',
|
||||
data: {},
|
||||
_callId: callId,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
printerComponents.sendMessage(
|
||||
componentName,
|
||||
@ -1976,7 +2080,7 @@ export async function queryComponentPrinterList(
|
||||
console.log(`[queryComponentPrinterList] 组件 "${componentName}" 无响应,返回 null`)
|
||||
return null;
|
||||
}
|
||||
const parsed = parseComponentGetPrintersResponse(response, jingdong, shipinhao);
|
||||
const parsed = parseComponentGetPrintersResponse(response, jingdong, shipinhao, localComponent);
|
||||
console.log(`[queryComponentPrinterList] 组件 "${componentName}" 解析结果:`, parsed)
|
||||
return parsed;
|
||||
} catch (err) {
|
||||
@ -2002,7 +2106,12 @@ export async function fetchConnectedComponentPrinters(
|
||||
const isOpen = printerComponents.isComponentOpen(componentName)
|
||||
console.log(`[fetchConnectedComponentPrinters] 组件 "${componentName}" WebSocket OPEN: ${isOpen}`)
|
||||
if (!isOpen) continue;
|
||||
const result = await queryComponentPrinterList(componentName);
|
||||
// 本机组件枚举 Windows 打印机较慢(实测首次返回约 1.5s),放宽超时
|
||||
const result = await queryComponentPrinterList(
|
||||
componentName,
|
||||
undefined,
|
||||
isLocalComponent(componentName) ? 5000 : undefined,
|
||||
);
|
||||
console.log(`[fetchConnectedComponentPrinters] 组件 "${componentName}" queryComponentPrinterList 返回:`, result)
|
||||
if (!result) continue;
|
||||
result.printers.forEach((name) => merged.add(name));
|
||||
@ -2043,6 +2152,7 @@ async function alignComponentPrinterName(
|
||||
const result = await queryComponentPrinterList(
|
||||
componentName,
|
||||
requestID || `wave-${componentName}-getPrinters-${Date.now()}`,
|
||||
isLocalComponent(componentName) ? 5000 : undefined,
|
||||
);
|
||||
if (!result) {
|
||||
waveBrowserPrintLog('alignComponentPrinterName: getPrinters 超时,使用原打印机名', {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user