Files
SupplierSystem/server/scripts/prod-zero-inventory-available.mjs
T
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

124 lines
4.0 KiB
JavaScript
Raw 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
/**
* 生产:将库存 available_qty 全部清零,并写 adjust 流水
*
* 用法(API 机 /opt/ai-fresh-delivery/server):
* node scripts/prod-zero-inventory-available.mjs
* node scripts/prod-zero-inventory-available.mjs --execute
* node scripts/prod-zero-inventory-available.mjs --branch=BR002 --execute
*/
import path from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
import { createRequire } from 'module';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const serverRoot = path.resolve(__dirname, '..');
const require = createRequire(path.join(serverRoot, 'package.json'));
try {
require('dotenv').config({ path: path.join(serverRoot, '.env') });
} catch {
/* ignore */
}
function parseArgs(argv) {
const opts = { execute: false, branch: undefined, help: false };
for (const arg of argv) {
if (arg === '--execute') opts.execute = true;
else if (arg === '--help' || arg === '-h') opts.help = true;
else if (arg.startsWith('--branch=')) opts.branch = arg.slice(9).trim();
}
return opts;
}
const opts = parseArgs(process.argv.slice(2));
if (opts.help) {
console.log('用法: node scripts/prod-zero-inventory-available.mjs [--branch=BR002] [--execute]');
process.exit(0);
}
const tenantUrl = pathToFileURL(
path.join(serverRoot, 'dist', 'services', 'tenantSchemaFallback.js')
).href;
const dbUrl = pathToFileURL(path.join(serverRoot, 'dist', 'db.js')).href;
const { listActiveTenantBranches, runInBranchSchema } = await import(tenantUrl);
const { pool } = await import(dbUrl);
const dryRun = !opts.execute;
console.log(JSON.stringify({ mode: dryRun ? 'dry-run' : 'execute', branch: opts.branch || 'ALL' }, null, 2));
async function zeroInCurrentSchema(label) {
const countResult = await pool.query(
`SELECT COUNT(*)::int AS cnt,
COALESCE(SUM(available_qty), 0)::float AS sum_available
FROM inventory
WHERE available_qty <> 0`
);
const cnt = Number(countResult.rows[0]?.cnt) || 0;
const sumAvailable = Number(countResult.rows[0]?.sum_available) || 0;
console.log(`[${label}] 待清零行=${cnt} 可用合计=${sumAvailable}`);
if (dryRun || cnt === 0) {
return { label, cnt, sumAvailable, updated: 0, logs: 0 };
}
const client = await pool.connect();
try {
await client.query('BEGIN');
const victims = await client.query(
`SELECT id, batch_no, sku_code, available_qty
FROM inventory
WHERE available_qty <> 0
FOR UPDATE`
);
let logs = 0;
for (const row of victims.rows) {
const before = Number(row.available_qty) || 0;
await client.query(`UPDATE inventory SET available_qty = 0 WHERE id = $1`, [row.id]);
await client.query(
`INSERT INTO inventory_logs
(batch_no, sku_code, operation_type, quantity, before_qty, after_qty, related_order_code, remark)
VALUES ($1, $2, 'adjust', $3, $4, 0, NULL, $5)`,
[
row.batch_no,
row.sku_code,
before,
before,
`运维清零可用库存 ${new Date().toISOString().slice(0, 19)}`,
]
);
logs += 1;
}
await client.query('COMMIT');
console.log(`[${label}] 已清零=${victims.rowCount} 流水=${logs}`);
return { label, cnt, sumAvailable, updated: victims.rowCount || 0, logs };
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
const results = [];
if (opts.branch) {
results.push(await runInBranchSchema(opts.branch, () => zeroInCurrentSchema(opts.branch)));
} else {
const tenants = await listActiveTenantBranches();
if (!tenants.length) {
results.push(await zeroInCurrentSchema('public'));
} else {
for (const t of tenants) {
results.push(await runInBranchSchema(t.branch_code, () => zeroInCurrentSchema(t.branch_code)));
}
}
}
console.log('\n汇总:', results);
if (dryRun) console.log('\n[dry-run] 未写库。确认后加 --execute');
await pool.end();
process.exit(0);