Files
SupplierSystem/scripts/prod-diagnose-stuck-skus.cjs
Ubuntu deb3e72750
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
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

323 lines
11 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* 排查指定商品名今日卡流程原因(验收/加工/分拣/配送)
* 用法(生产机):
* cd /opt/ai-fresh-delivery/server && node ../scripts/prod-diagnose-stuck-skus.cjs
* 或本地设 DATABASE_URL 后执行
*/
const path = require('path');
const fs = require('fs');
function loadEnv() {
if (process.env.DATABASE_URL) return;
for (const p of [
path.join(process.cwd(), '.env'),
path.join(process.cwd(), 'server', '.env'),
'/opt/ai-fresh-delivery/server/.env',
]) {
if (!fs.existsSync(p)) continue;
for (const line of fs.readFileSync(p, 'utf8').split(/\r?\n/)) {
const m = line.match(/^DATABASE_URL=(.*)$/);
if (m) {
process.env.DATABASE_URL = m[1].trim().replace(/^['"]|['"]$/g, '');
return;
}
}
}
}
loadEnv();
const { Pool } = require('pg');
const NAMES = (process.env.SKU_NAMES || '瓢尔菜,细面,鸡蛋,花菜')
.split(/[,,]/)
.map((s) => s.trim())
.filter(Boolean);
const TODAY =
process.env.CHINA_DATE ||
new Date(Date.now() + 8 * 3600 * 1000).toISOString().slice(0, 10);
const ORDER_STATUS = {
10: '待分配',
20: '采购/备货',
30: '验收中',
40: '待加工/分拣',
45: '分拣中',
50: '待配送',
60: '配送中',
90: '已完成',
};
const PROC = {
10: '待加工',
20: '加工中',
30: '待加工验收',
40: '加工完成',
50: '加工拒收',
};
async function main() {
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL missing');
}
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
console.log(`\n=== 卡流程排查 ${TODAY} · ${NAMES.join(' / ')} ===\n`);
for (const name of NAMES) {
console.log(`\n########## ${name} ##########`);
const items = await pool.query(
`
SELECT
o.order_code,
o.order_status,
o.branch_code,
o.customer_code,
c.company_name,
o.delivery_date::text AS delivery_date,
oi.id AS order_item_id,
oi.item_name,
oi.sku_code,
s.sku_name,
oi.quantity,
oi.unit,
oi.processing_method,
oi.processing_owner,
oi.supplier_code
FROM order_items oi
JOIN orders o ON o.order_code = oi.order_code
LEFT JOIN customers c ON c.customer_code = o.customer_code
LEFT JOIN skus s ON s.sku_code = oi.sku_code
WHERE o.delivery_date::date = $1::date
AND o.order_status < 90
AND (
oi.item_name ILIKE '%' || $2 || '%'
OR s.sku_name ILIKE '%' || $2 || '%'
)
ORDER BY o.order_status, o.order_code
LIMIT 40
`,
[TODAY, name]
);
if (!items.rowCount) {
console.log(' 今日未完成订单中无此商品(可能已完成或无单)');
const done = await pool.query(
`
SELECT COUNT(*)::int AS cnt
FROM order_items oi
JOIN orders o ON o.order_code = oi.order_code
LEFT JOIN skus s ON s.sku_code = oi.sku_code
WHERE o.delivery_date::date = $1::date
AND o.order_status >= 90
AND (oi.item_name ILIKE '%' || $2 || '%' OR s.sku_name ILIKE '%' || $2 || '%')
`,
[TODAY, name]
);
console.log(` 已完成订单命中行数: ${done.rows[0].cnt}`);
continue;
}
for (const it of items.rows) {
const st = ORDER_STATUS[it.order_status] || String(it.order_status);
console.log(
`\n 订单 ${it.order_code} | status=${it.order_status}(${st}) | ${it.company_name || it.customer_code} | branch=${it.branch_code}`
);
console.log(
` 明细「${it.item_name}」 sku=${it.sku_code || '-'}(${it.sku_name || '-'}) qty=${it.quantity}${it.unit || ''} method=${it.processing_method || '-'} owner=${it.processing_owner || '-'} supplier=${it.supplier_code || '-'}`
);
const blockers = [];
const insp = await pool.query(
`
SELECT id, quality_rating, actual_qty, inspection_time, sku_code, item_name,
COALESCE(array_length(inspection_photos, 1), 0) AS photo_count
FROM inspections
WHERE order_code = $1
AND (
($2::text IS NOT NULL AND sku_code = $2)
OR item_name ILIKE '%' || $3 || '%'
)
ORDER BY COALESCE(inspection_time, created_at) DESC NULLS LAST
LIMIT 5
`,
[it.order_code, it.sku_code, name]
);
if (!insp.rowCount) {
blockers.push('无验收单 / 验收未生成');
} else {
for (const i of insp.rows) {
const pending = i.actual_qty == null && !i.quality_rating;
const failed = String(i.quality_rating || '').toLowerCase() === 'fail' || i.quality_rating === '不合格';
console.log(
` 验收 ${i.id.slice(0, 8)}… rating=${i.quality_rating ?? '空'} qty=${i.actual_qty ?? '空'} photos=${i.photo_count} time=${i.inspection_time || '-'}`
);
if (pending) blockers.push('验收未填数量/结果(待验收)');
if (failed) blockers.push('验收不合格未闭环');
}
}
const unresolved = await pool.query(
`
SELECT COUNT(*)::int AS cnt
FROM inspections
WHERE order_code = $1
AND (
quality_rating IN ('fail', '不合格', 'Fail', 'FAIL')
OR (actual_qty IS NULL AND quality_rating IS NULL)
)
`,
[it.order_code]
);
// only note order-level pending inspections if blocking
const pendingInspOrder = await pool.query(
`SELECT COUNT(*)::int AS cnt FROM inspections
WHERE order_code = $1 AND actual_qty IS NULL AND quality_rating IS NULL`,
[it.order_code]
);
if (Number(pendingInspOrder.rows[0].cnt) > 0) {
blockers.push(`本单仍有 ${pendingInspOrder.rows[0].cnt} 条待验收`);
}
const pt = await pool.query(
`
SELECT id, process_status, process_fee, net_weight, quality_rating,
processing_inspection_time, processing_method
FROM processing_tasks
WHERE order_code = $1
AND (sku_code = $2 OR sku_code IS NOT DISTINCT FROM $2)
ORDER BY updated_at DESC NULLS LAST
LIMIT 5
`,
[it.order_code, it.sku_code]
);
if (pt.rowCount) {
for (const t of pt.rows) {
const pLabel = PROC[t.process_status] || t.process_status;
console.log(
` 加工任务 status=${t.process_status}(${pLabel}) method=${t.processing_method || '-'} fee=${t.process_fee ?? '-'} net=${t.net_weight ?? '-'} rating=${t.quality_rating ?? '-'}`
);
if (Number(t.process_status) < 40) {
blockers.push(`加工未完成: ${pLabel}`);
}
if (Number(t.process_status) === 50) {
blockers.push('加工验收拒收');
}
}
} else if (it.processing_method && String(it.processing_owner || '').includes('warehouse')) {
blockers.push('需要仓内加工但尚未生成加工任务');
}
try {
const pick = await pool.query(
`SELECT pick_code, pick_status FROM picking_tasks
WHERE order_code = $1
ORDER BY created_at DESC NULLS LAST LIMIT 8`,
[it.order_code]
);
const pendingPick = pick.rows.filter((p) => Number(p.pick_status || 10) < 40);
console.log(` 分拣任务 ${pick.rowCount} 条,未完成 ${pendingPick.length}`);
if (pendingPick.length) blockers.push(`分拣未出库 ${pendingPick.length} 条`);
} catch (e) {
console.log(` 分拣查询跳过: ${e.message}`);
}
try {
const prep = await pool.query(
`SELECT prepare_code, prepare_status, sku_code
FROM supplier_preparations
WHERE order_code = $1 AND ($2::text IS NULL OR sku_code = $2)
ORDER BY created_at DESC NULLS LAST LIMIT 5`,
[it.order_code, it.sku_code]
);
for (const p of prep.rows) {
console.log(` 备货 ${p.prepare_code || '-'} status=${p.prepare_status}`);
if (Number(p.prepare_status || 10) < 30) blockers.push(`供应商备货未完成 status=${p.prepare_status}`);
}
} catch (e) {
console.log(` 备货查询跳过: ${e.message}`);
}
try {
const po = await pool.query(
`SELECT purchase_code, purchase_status, sku_code
FROM purchase_orders
WHERE order_code = $1 AND ($2::text IS NULL OR sku_code = $2)
ORDER BY created_at DESC NULLS LAST LIMIT 5`,
[it.order_code, it.sku_code]
);
for (const p of po.rows) {
console.log(` 采购 ${p.purchase_code || '-'} status=${p.purchase_status}`);
if (Number(p.purchase_status || 10) < 20) blockers.push(`采购未完成 status=${p.purchase_status}`);
}
} catch (e) {
console.log(` 采购查询跳过: ${e.message}`);
}
if (Number(it.order_status) >= 50) {
try {
const dt = await pool.query(
`SELECT task_code, task_status, person_code, start_time
FROM delivery_tasks WHERE order_code = $1 LIMIT 3`,
[it.order_code]
);
for (const d of dt.rows) {
console.log(
` 配送 ${d.task_code} status=${d.task_status} person=${d.person_code || '-'} start=${d.start_time || '-'}`
);
if (Number(d.task_status || 10) < 30) blockers.push(`配送未签收/未完成 status=${d.task_status}`);
}
if (!dt.rowCount) blockers.push('订单已到配送态但无配送任务');
} catch (e) {
console.log(` 配送查询跳过: ${e.message}`);
}
}
if (blockers.length) {
console.log(` >> 卡点: ${[...new Set(blockers)].join(';')}`);
} else {
console.log(' >> 本行未见明确未完成作业(或卡在整单其它商品)');
}
}
}
// 汇总:今日这些商品所在订单里「任一未完成作业」
console.log('\n\n=== 汇总:今日含上述商品且订单未完成 ===');
const summary = await pool.query(
`
WITH target AS (
SELECT DISTINCT o.order_code, o.order_status, o.branch_code, o.delivery_date::text AS delivery_date,
c.company_name,
string_agg(DISTINCT oi.item_name, '、') AS items
FROM order_items oi
JOIN orders o ON o.order_code = oi.order_code
LEFT JOIN customers c ON c.customer_code = o.customer_code
LEFT JOIN skus s ON s.sku_code = oi.sku_code
WHERE o.delivery_date::date = $1::date
AND o.order_status < 90
AND (
oi.item_name ILIKE ANY(ARRAY[${NAMES.map((_, i) => `$${i + 2}`).join(',')}])
OR s.sku_name ILIKE ANY(ARRAY[${NAMES.map((_, i) => `$${i + 2}`).join(',')}])
)
GROUP BY o.order_code, o.order_status, o.branch_code, o.delivery_date, c.company_name
)
SELECT * FROM target ORDER BY order_status, order_code
`,
[TODAY, ...NAMES.map((n) => `%${n}%`)]
);
for (const r of summary.rows) {
console.log(
`${r.order_code} | ${ORDER_STATUS[r.order_status] || r.order_status} | ${r.company_name || '-'} | ${r.items}`
);
}
console.log(`合计订单 ${summary.rowCount} 单\n`);
await pool.end();
}
main().catch((e) => {
console.error(e);
process.exit(1);
});