122 lines
3.3 KiB
JavaScript
122 lines
3.3 KiB
JavaScript
const normalizePrinterName = (printerName) => String(printerName ?? '').trim()
|
|
|
|
const parsePayload = (job) => {
|
|
if (job?.payload && typeof job.payload === 'object') {
|
|
return job.payload
|
|
}
|
|
|
|
if (typeof job?.payload_json === 'string') {
|
|
try {
|
|
return JSON.parse(job.payload_json)
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
if (job?.payload_json && typeof job.payload_json === 'object') {
|
|
return job.payload_json
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
const getAssetLabelItems = (job) => {
|
|
const payload = parsePayload(job)
|
|
if (!payload || !Array.isArray(payload.items)) {
|
|
return null
|
|
}
|
|
return payload.items
|
|
}
|
|
|
|
export function createTestPrintSuccessMessage(printerName) {
|
|
const resolvedPrinterName = normalizePrinterName(printerName) || '已选打印机'
|
|
return `测试标签已发送到 ${resolvedPrinterName},请确认是否按 60x40mm 正常出纸。`
|
|
}
|
|
|
|
export function createJobProcessor({
|
|
printAssetLabels = async () => {
|
|
throw new Error('尚未注入真实资产标签打印执行器')
|
|
},
|
|
printTestLabel = async () => {
|
|
throw new Error('尚未注入真实测试标签打印执行器')
|
|
}
|
|
} = {}) {
|
|
return {
|
|
async process(job, { selectedPrinterName } = {}) {
|
|
if (job?.job_type === 'asset_label') {
|
|
const printerName = normalizePrinterName(selectedPrinterName)
|
|
if (!printerName) {
|
|
return {
|
|
ok: false,
|
|
nextStatus: 'failed',
|
|
errorMessage: '尚未选择标签打印机,请先在打印助手里完成打印机配置。'
|
|
}
|
|
}
|
|
|
|
const items = getAssetLabelItems(job)
|
|
if (!items?.length) {
|
|
return {
|
|
ok: false,
|
|
nextStatus: 'failed',
|
|
errorMessage: '当前打印任务缺少可用的资产标签数据,已阻止实际出纸。'
|
|
}
|
|
}
|
|
|
|
try {
|
|
const printResult = await printAssetLabels({
|
|
job,
|
|
items,
|
|
printerName
|
|
})
|
|
|
|
const printedCount =
|
|
typeof printResult?.printed_count === 'number' ? printResult.printed_count : items.length
|
|
|
|
return {
|
|
ok: true,
|
|
nextStatus: 'completed',
|
|
message: `已发送到 ${printerName} 打印,准备输出 ${printedCount} 张资产标签。`
|
|
}
|
|
} catch (error) {
|
|
return {
|
|
ok: false,
|
|
nextStatus: 'failed',
|
|
errorMessage: error instanceof Error ? error.message : '资产标签打印失败'
|
|
}
|
|
}
|
|
}
|
|
|
|
return {
|
|
ok: true,
|
|
nextStatus: 'completed',
|
|
message: '当前任务类型未实现,已跳过。'
|
|
}
|
|
},
|
|
async runTestPrint({ selectedPrinterName }) {
|
|
const printerName = normalizePrinterName(selectedPrinterName)
|
|
if (!printerName) {
|
|
return {
|
|
ok: false,
|
|
message: '尚未选择标签打印机,请先保存打印机后再做测试打印。'
|
|
}
|
|
}
|
|
|
|
try {
|
|
await printTestLabel({
|
|
printerName
|
|
})
|
|
|
|
return {
|
|
ok: true,
|
|
message: createTestPrintSuccessMessage(printerName)
|
|
}
|
|
} catch (error) {
|
|
return {
|
|
ok: false,
|
|
message: error instanceof Error ? error.message : '测试打印失败'
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|