Files
SupplierSystem/server/src/services/printJobService.ts
T
Ubuntu 6f2ab60249
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(分拣/标签): 商品名取档案当前名(skus→订单行→分拣行),快照另存 item_name_snapshot 留档;取值链抽成单一实现并与核货共用
2026-10-21 14:31:02 +08:00

576 lines
18 KiB
TypeScript

import { itemDisplayNameSql } from './itemDisplayNameSql';
/**
* Web 分拣远程打印任务。设计:docs/design/20260829-web-picking-remote-print.md
* 回执超时 / 人工标记已打印:docs/design/20260920-print-job-ack-timeout.md
* 小程序行上补打:docs/design/20260922-mp-print-reprint.md
* 只读写 weigh_devices / print_jobs;组装 payload 只读 picking_items / orders / customers。
* last_user_id 仅心跳在传入 JWT 时更新;Web 待打印列表禁止写该列。
* 禁止写 orders、禁止调用分拣完成接口 / 推进订单状态。
*/
import { pool } from '../db';
import { formatChinaDate } from '../utils/chinaDate';
import { ORDER_ITEM_LABEL_BARCODE_SQL } from './orderItemLabelBarcodeSql';
const DEVICE_ID_RE = /^[a-zA-Z0-9_-]{8,64}$/;
const CLAIM_STALE_INTERVAL = "INTERVAL '2 minutes'";
export type PrintJobStatus = 'pending' | 'claimed' | 'done' | 'failed' | 'cancelled';
export type PrintJobPayload = {
company_name: string;
order_code: string;
item_name: string;
weight: number;
unit: string;
date: string;
barcode: string;
job_code: string;
copies?: number;
};
const ACTIVE_STATUS = ['pending', 'claimed'] as const;
function biz(message: string, status = 400) {
return Object.assign(new Error(message), { status });
}
export function normalizeDeviceId(raw: unknown): string {
const id = String(raw || '').trim();
if (!DEVICE_ID_RE.test(id)) {
throw biz('设备标识无效');
}
return id;
}
function jobCodeFromId(id: string): string {
return String(id).replace(/-/g, '').slice(0, 8).toUpperCase();
}
function num(v: unknown): number {
const n = Number(v);
return Number.isFinite(n) ? n : 0;
}
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** 导出仅为测试/校验:分拣标签打印 payload SQL(商品名档案优先) */
export const ITEM_PAYLOAD_SQL = `
SELECT DISTINCT ON (pi.id)
pi.id,
pi.pick_code,
${itemDisplayNameSql({
skuName: 's.sku_name',
orderItemName: 'oi.item_name',
pickingItemName: 'pi.item_name',
})} AS item_name,
pi.item_name AS item_name_snapshot,
pi.picked_qty,
pi.picked_weight,
pi.required_qty,
pi.unit,
pi.order_code,
COALESCE(c.company_name, '') AS company_name,
to_char(o.delivery_date, 'YYYY-MM-DD') AS delivery_date,
-- 与分拣界面同一口径(2026-10-13 方案 A):有主系统来源 ⇒ 标签二维码印**主系统 SKU**
-- (主系统扫码核货/入库可识别);无来源 ⇒ 回退我方条码/SKU。旧秤端打印通道(已停用但保留)同步对齐。
-- 取值链的唯一来源见 services/orderItemLabelBarcodeSql.ts(打印与扫码解析共用,避免口径漂移)。
${ORDER_ITEM_LABEL_BARCODE_SQL} AS barcode
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN public.main_system_order_import_items msi ON msi.our_order_item_id = pi.order_item_id
LEFT JOIN product_catalog catalog ON catalog.item_type = 'product' AND (
catalog.code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
)
LEFT JOIN skus s ON s.sku_code = COALESCE(
NULLIF(TRIM(pi.sku_code), ''),
NULLIF(TRIM(oi.sku_code), ''),
catalog.code
)
LEFT JOIN orders o ON o.order_code = pi.order_code
LEFT JOIN customers c ON c.customer_code = o.customer_code
WHERE pi.pick_code = $1
AND pi.id = ANY($2::uuid[])
ORDER BY pi.id
`;
export type WeighDeviceRow = {
device_id: string;
display_name: string;
branch_code: string;
last_heartbeat: string | Date | null;
last_user_id: string | null;
online: boolean;
};
function mapWeighDeviceRow(row: {
device_id: string;
display_name?: string | null;
branch_code: string;
last_heartbeat?: string | Date | null;
last_user_id?: string | null;
}): WeighDeviceRow {
const hb = row.last_heartbeat ? new Date(row.last_heartbeat).getTime() : 0;
const online = hb > 0 && Date.now() - hb < 90_000;
const lastUserId = row.last_user_id != null ? String(row.last_user_id) : null;
return {
device_id: row.device_id,
display_name: row.display_name || row.device_id,
branch_code: row.branch_code,
last_heartbeat: row.last_heartbeat ?? null,
last_user_id: lastUserId,
online,
};
}
export async function listWeighDevices(branchCode: string): Promise<WeighDeviceRow[]> {
const result = await pool.query(
`SELECT device_id, display_name, branch_code, last_heartbeat, last_user_id
FROM weigh_devices
WHERE branch_code = $1
ORDER BY last_heartbeat DESC NULLS LAST
LIMIT 50`,
[branchCode]
);
return result.rows.map(mapWeighDeviceRow);
}
export function listMyOnlineWeighDevices(
devices: WeighDeviceRow[],
userId: string | null | undefined
): WeighDeviceRow[] {
const uid = String(userId || '').trim();
if (!uid || !UUID_RE.test(uid)) return [];
return devices.filter((row) => row.online && row.last_user_id === uid);
}
export function listOnlineWeighDevices(devices: WeighDeviceRow[]): WeighDeviceRow[] {
return devices.filter((row) => row.online);
}
export async function heartbeatWeighDevice(input: {
deviceId: string;
branchCode: string;
displayName?: string;
userId?: string | null;
}) {
const deviceId = normalizeDeviceId(input.deviceId);
const name = String(input.displayName || '').trim().slice(0, 100);
const rawUser = String(input.userId || '').trim();
const userId = UUID_RE.test(rawUser) ? rawUser : null;
await pool.query(
`INSERT INTO weigh_devices (device_id, display_name, branch_code, last_heartbeat, last_user_id)
VALUES ($1, $2, $3, NOW(), $4)
ON CONFLICT (device_id) DO UPDATE SET
display_name = CASE
WHEN EXCLUDED.display_name <> '' THEN EXCLUDED.display_name
ELSE weigh_devices.display_name
END,
last_heartbeat = NOW(),
last_user_id = CASE
WHEN EXCLUDED.last_user_id IS NOT NULL THEN EXCLUDED.last_user_id
ELSE weigh_devices.last_user_id
END
WHERE weigh_devices.branch_code = EXCLUDED.branch_code`,
[deviceId, name, input.branchCode, userId]
);
const check = await pool.query(
`SELECT branch_code FROM weigh_devices WHERE device_id = $1`,
[deviceId]
);
if (!check.rows[0]) {
throw biz('秤注册失败,请稍后重试');
}
if (check.rows[0].branch_code !== input.branchCode) {
throw biz('该秤已绑定其他分公司', 403);
}
return deviceId;
}
export async function createPrintJobs(input: {
pickCode: string;
pickingItemIds: string[];
deviceId: string;
branchCode: string;
userId?: string | null;
copies?: number;
force?: boolean;
}) {
const pickCode = String(input.pickCode || '').trim();
if (!pickCode) throw biz('缺少拣货单号');
const deviceId = normalizeDeviceId(input.deviceId);
const copies = Math.min(20, Math.max(1, Math.floor(Number(input.copies) || 1)));
const force = input.force === true;
const ids = Array.from(
new Set(
(input.pickingItemIds || []).map((id) => String(id || '').trim()).filter(Boolean)
)
);
if (!ids.length) throw biz('请选择要打印的商品行');
const device = await pool.query(
`SELECT device_id, branch_code FROM weigh_devices WHERE device_id = $1`,
[deviceId]
);
if (!device.rows[0]) throw biz('秤未注册,请先在称上打开分拣或称重工作台');
if (device.rows[0].branch_code !== input.branchCode) {
throw biz('不能向其他分公司的秤发送打印任务', 403);
}
const task = await pool.query(
`SELECT pick_code, branch_code FROM picking_tasks WHERE pick_code = $1`,
[pickCode]
);
if (!task.rows[0]) throw biz('拣货单不存在', 404);
if (task.rows[0].branch_code && task.rows[0].branch_code !== input.branchCode) {
throw biz('拣货单不属于当前分公司', 403);
}
const items = await pool.query(ITEM_PAYLOAD_SQL, [pickCode, ids]);
if (items.rows.length !== ids.length) {
throw biz('部分商品行不在该拣货单中');
}
const today = formatChinaDate();
const createdBy =
input.userId && UUID_RE.test(String(input.userId)) ? input.userId : null;
const created: Array<{ id: string; picking_item_id: string; status: PrintJobStatus }> = [];
const skipped: Array<{ picking_item_id: string; reason: string }> = [];
for (const row of items.rows) {
const weight = num(row.picked_weight) > 0
? num(row.picked_weight)
: num(row.picked_qty) > 0
? num(row.picked_qty)
: num(row.required_qty);
const exists = await pool.query(
`SELECT 1 FROM print_jobs
WHERE branch_code = $1 AND picking_item_id = $2 AND status = ANY($3::text[])
LIMIT 1`,
[input.branchCode, row.id, ACTIVE_STATUS]
);
if (exists.rows[0]) {
if (!force) {
skipped.push({ picking_item_id: row.id, reason: '已存在待打印任务' });
continue;
}
await pool.query(
`UPDATE print_jobs
SET status = 'cancelled', finished_at = NOW(), error = '补打取消'
WHERE branch_code = $1
AND picking_item_id = $2
AND status = ANY($3::text[])`,
[input.branchCode, row.id, ACTIVE_STATUS]
);
}
const job = await insertOnePrintJob({
branchCode: input.branchCode,
pickCode,
itemId: row.id,
deviceId,
createdBy,
copies,
companyName: String(row.company_name || '').trim() || '客户',
orderCode: String(row.order_code || ''),
itemName: String(row.item_name || '商品'),
weight,
unit: String(row.unit || 'kg'),
date: String(row.delivery_date || today),
barcode: String(row.barcode || ''),
});
created.push(job);
}
return { jobs: created, skipped };
}
async function insertOnePrintJob(row: {
branchCode: string;
pickCode: string;
itemId: string;
deviceId: string;
createdBy: string | null;
copies: number;
companyName: string;
orderCode: string;
itemName: string;
weight: number;
unit: string;
date: string;
barcode: string;
}): Promise<{ id: string; picking_item_id: string; status: PrintJobStatus }> {
const ins = await pool.query(
`INSERT INTO print_jobs (
branch_code, pick_code, picking_item_id, device_id, status, payload, created_by, copies
) VALUES ($1, $2, $3, $4, 'pending', $5::jsonb, $6, $7)
RETURNING id`,
[
row.branchCode,
row.pickCode,
row.itemId,
row.deviceId,
JSON.stringify({
company_name: row.companyName,
order_code: row.orderCode,
item_name: row.itemName,
weight: row.weight,
unit: row.unit,
date: row.date,
barcode: row.barcode,
job_code: '',
}),
row.createdBy,
row.copies,
]
);
const id = String(ins.rows[0].id);
const payload: PrintJobPayload & { copies: number } = {
company_name: row.companyName,
order_code: row.orderCode,
item_name: row.itemName,
weight: row.weight,
unit: row.unit,
date: row.date,
barcode: row.barcode || jobCodeFromId(id),
job_code: jobCodeFromId(id),
copies: row.copies,
};
await pool.query(`UPDATE print_jobs SET payload = $2::jsonb WHERE id = $1`, [
id,
JSON.stringify(payload),
]);
return { id, picking_item_id: String(row.itemId), status: 'pending' };
}
export async function listPrintJobs(pickCode: string, branchCode: string) {
const code = String(pickCode || '').trim();
if (!code) throw biz('缺少拣货单号');
const result = await pool.query(
`SELECT pj.id, pj.pick_code, pj.picking_item_id, pj.device_id, pj.status,
pj.payload, pj.error, pj.claimed_at, pj.finished_at, pj.created_at,
pj.copies, pj.attempt_count, pj.max_attempts,
wd.display_name AS device_name, wd.last_heartbeat
FROM print_jobs pj
LEFT JOIN weigh_devices wd ON wd.device_id = pj.device_id
WHERE pj.pick_code = $1 AND pj.branch_code = $2
ORDER BY pj.created_at DESC
LIMIT 200`,
[code, branchCode]
);
return result.rows;
}
export async function listPendingPrintJobs(
branchCode: string,
filters: { pickCode?: string; deviceId?: string; status?: string }
) {
const params: unknown[] = [branchCode];
let where = `pj.branch_code = $1 AND pj.status = ANY($2::text[])`;
params.push(ACTIVE_STATUS);
if (filters.pickCode) {
params.push(String(filters.pickCode).trim());
where += ` AND pj.pick_code = $${params.length}`;
}
if (filters.deviceId) {
params.push(String(filters.deviceId).trim());
where += ` AND pj.device_id = $${params.length}`;
}
if (filters.status === 'pending' || filters.status === 'claimed') {
params.push(filters.status);
where += ` AND pj.status = $${params.length}`;
}
const result = await pool.query(
`SELECT pj.id, pj.pick_code, pj.picking_item_id, pj.device_id, pj.status,
pj.payload, pj.error, pj.claimed_at, pj.finished_at, pj.created_at,
pj.copies, pj.attempt_count, pj.max_attempts,
wd.display_name AS device_name, wd.last_heartbeat
FROM print_jobs pj
LEFT JOIN weigh_devices wd ON wd.device_id = pj.device_id
WHERE ${where}
ORDER BY pj.created_at ASC
LIMIT 200`,
params
);
return result.rows;
}
export async function updatePrintJob(input: {
jobId: string;
branchCode: string;
copies?: number;
weight?: number;
}) {
const jobId = String(input.jobId || '').trim();
if (!jobId) throw biz('缺少任务 id');
const copies =
input.copies !== undefined
? Math.min(20, Math.max(1, Math.floor(Number(input.copies) || 1)))
: undefined;
const weight = input.weight !== undefined ? num(input.weight) : undefined;
if (copies === undefined && weight === undefined) {
throw biz('没有可修改的字段');
}
if (weight !== undefined && weight <= 0) {
throw biz('重量必须大于 0');
}
const result = await pool.query(
`UPDATE print_jobs
SET copies = COALESCE($3, copies),
payload = CASE
WHEN $4::numeric IS NOT NULL THEN jsonb_set(payload, '{weight}', to_jsonb($4::numeric))
ELSE payload
END
WHERE id = $1
AND branch_code = $2
AND status = 'pending'
RETURNING id, status, copies, payload`,
[jobId, input.branchCode, copies ?? null, weight ?? null]
);
if (!result.rows[0]) {
throw biz('任务不存在、已被领取或已结束', 404);
}
return result.rows[0];
}
export async function cancelPrintJob(jobId: string, branchCode: string) {
const id = String(jobId || '').trim();
if (!id) throw biz('缺少任务 id');
const result = await pool.query(
`UPDATE print_jobs
SET status = 'cancelled', finished_at = NOW(), error = '手动取消'
WHERE id = $1
AND branch_code = $2
AND status IN ('pending', 'claimed')
RETURNING id, status`,
[id, branchCode]
);
if (!result.rows[0]) {
throw biz('任务不存在或已结束', 404);
}
return result.rows[0];
}
export async function claimPendingPrintJob(input: {
deviceId: string;
branchCode: string;
displayName?: string;
userId?: string | null;
}) {
const deviceId = await heartbeatWeighDevice(input);
await pool.query(
`UPDATE print_jobs
SET status = 'failed', finished_at = NOW(), error = '打印回执超时'
WHERE device_id = $1
AND branch_code = $2
AND status = 'claimed'
AND claimed_at < NOW() - ${CLAIM_STALE_INTERVAL}`,
[deviceId, input.branchCode]
);
const result = await pool.query(
`WITH next AS (
SELECT id FROM print_jobs
WHERE device_id = $1
AND branch_code = $2
AND status = 'pending'
ORDER BY created_at ASC
LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE print_jobs pj
SET status = 'claimed',
claimed_at = NOW(),
attempt_count = pj.attempt_count + 1
FROM next
WHERE pj.id = next.id
AND pj.status = 'pending'
RETURNING pj.id, pj.pick_code, pj.picking_item_id, pj.device_id, pj.status,
pj.payload, pj.copies, pj.attempt_count, pj.max_attempts`,
[deviceId, input.branchCode]
);
const job = result.rows[0];
if (job && job.attempt_count > job.max_attempts) {
await pool.query(
`UPDATE print_jobs
SET status = 'failed', finished_at = NOW(), error = '打印超时,已停止重试'
WHERE id = $1`,
[job.id]
);
return null;
}
if (!job) return null;
const payload =
job.payload && typeof job.payload === 'object' ? { ...job.payload } : {};
payload.copies = Number(job.copies) || 1;
return { ...job, payload };
}
export async function ackPrintJob(input: {
jobId: string;
deviceId: string;
branchCode: string;
status: 'done' | 'failed';
error?: string;
}) {
const deviceId = normalizeDeviceId(input.deviceId);
const jobId = String(input.jobId || '').trim();
if (!jobId) throw biz('缺少任务 id');
const status = input.status;
if (status !== 'done' && status !== 'failed') throw biz('回执状态无效');
const result = await pool.query(
`UPDATE print_jobs
SET status = $3,
finished_at = NOW(),
error = CASE WHEN $3 = 'failed' THEN NULLIF(TRIM($4), '') ELSE NULL END
WHERE id = $1
AND device_id = $2
AND branch_code = $5
AND status = 'claimed'
RETURNING id, status, error`,
[jobId, deviceId, status, String(input.error || '').slice(0, 500), input.branchCode]
);
if (!result.rows[0]) {
throw biz('任务不存在或已结束', 404);
}
return result.rows[0];
}
export async function markPrintJobDone(jobId: string, branchCode: string) {
const id = String(jobId || '').trim();
if (!id) throw biz('缺少任务 id');
const result = await pool.query(
`UPDATE print_jobs
SET status = 'done', finished_at = NOW(), error = '人工标记已打印'
WHERE id = $1
AND branch_code = $2
AND status = 'claimed'
RETURNING id, status, error`,
[id, branchCode]
);
if (!result.rows[0]) {
throw biz('任务不存在或不是打印中', 404);
}
return result.rows[0];
}
export async function markClaimedPrintJobsDone(input: {
branchCode: string;
pickCode?: string;
}) {
const params: unknown[] = [input.branchCode];
let pickSql = '';
const pickCode = String(input.pickCode || '').trim();
if (pickCode) {
params.push(pickCode);
pickSql = ` AND pick_code = $2`;
}
const result = await pool.query(
`UPDATE print_jobs
SET status = 'done', finished_at = NOW(), error = '人工标记已打印'
WHERE branch_code = $1
AND status = 'claimed'
${pickSql}
RETURNING id, status`,
params
);
return { count: result.rowCount || 0, jobs: result.rows };
}