来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
308 lines
10 KiB
JavaScript
308 lines
10 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* 生产回填:今日完成单按 picked_weight 对齐结算量 + 同步客户结算单
|
|
* 设计:docs/design/20260813-backfill-delivery-weigh-settlement-today.md
|
|
*
|
|
* node scripts/prod-backfill-delivery-weigh-settlement.mjs # dry-run
|
|
* node scripts/prod-backfill-delivery-weigh-settlement.mjs --execute
|
|
* node scripts/prod-backfill-delivery-weigh-settlement.mjs --day=2026-08-13 --execute
|
|
*/
|
|
import pg from 'pg';
|
|
import { readFileSync, existsSync } from 'fs';
|
|
import { resolve, dirname } from 'path';
|
|
import { fileURLToPath } from 'url';
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
const EXECUTE = process.argv.includes('--execute');
|
|
const dayArg = process.argv.find((a) => a.startsWith('--day='));
|
|
const branchArg = process.argv.find((a) => a.startsWith('--branch='));
|
|
|
|
function loadDatabaseUrl() {
|
|
for (const p of [
|
|
resolve(__dirname, '../.env'),
|
|
'/opt/ai-fresh-delivery/server/.env',
|
|
]) {
|
|
if (!existsSync(p)) continue;
|
|
const m = readFileSync(p, 'utf8').match(/^DATABASE_URL=(.+)$/m);
|
|
if (m) return m[1].trim().replace(/^["']|["']$/g, '');
|
|
}
|
|
throw new Error('DATABASE_URL not found');
|
|
}
|
|
|
|
function chinaTodayYmd() {
|
|
return new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' }).format(new Date());
|
|
}
|
|
|
|
async function listTenantSchemas(client) {
|
|
try {
|
|
const r = await client.query(
|
|
`SELECT schema_name
|
|
FROM public.tenant_schema_registry
|
|
WHERE COALESCE(is_active, true) = true
|
|
AND schema_name LIKE 'tenant_%'
|
|
AND schema_name <> 'tenant_template'
|
|
ORDER BY schema_name`
|
|
);
|
|
if (r.rows.length) return r.rows.map((x) => String(x.schema_name));
|
|
} catch {
|
|
/* registry may not exist */
|
|
}
|
|
const r2 = await client.query(
|
|
`SELECT nspname AS schema_name
|
|
FROM pg_namespace
|
|
WHERE nspname LIKE 'tenant_%'
|
|
AND nspname <> 'tenant_template'
|
|
ORDER BY nspname`
|
|
);
|
|
return r2.rows.map((x) => String(x.schema_name));
|
|
}
|
|
|
|
async function listCandidates(client, day, orderCode) {
|
|
const params = [day];
|
|
let orderSql = '';
|
|
if (orderCode) {
|
|
params.push(orderCode);
|
|
orderSql = ` AND o.order_code = $${params.length}`;
|
|
}
|
|
const result = await client.query(
|
|
`WITH weigh AS (
|
|
SELECT DISTINCT ON (pi.order_item_id)
|
|
pi.order_item_id,
|
|
pi.unit,
|
|
pi.item_name,
|
|
pi.picked_weight::float8 AS picked_weight
|
|
FROM picking_items pi
|
|
WHERE pi.order_item_id IS NOT NULL
|
|
AND COALESCE(pi.picked_weight, 0) > 0
|
|
ORDER BY pi.order_item_id, pi.picked_weight DESC NULLS LAST
|
|
)
|
|
SELECT o.order_code,
|
|
o.branch_code,
|
|
oi.id::text AS order_item_id,
|
|
oi.sku_code,
|
|
COALESCE(NULLIF(TRIM(oi.item_name), ''), w.item_name) AS item_name,
|
|
COALESCE(NULLIF(TRIM(w.unit), ''), oi.unit) AS unit,
|
|
COALESCE(oi.quantity, 0)::float8 AS old_qty,
|
|
COALESCE(oi.locked_price, 0)::float8 AS locked_price,
|
|
COALESCE(oi.price, 0)::float8 AS price,
|
|
w.picked_weight
|
|
FROM weigh w
|
|
JOIN order_items oi ON oi.id = w.order_item_id
|
|
JOIN orders o ON o.order_code = oi.order_code
|
|
WHERE o.deleted_at IS NULL
|
|
AND o.order_status >= 90
|
|
AND o.delivery_date = $1::date
|
|
AND ABS(COALESCE(oi.quantity, 0) - w.picked_weight) > 0.0001
|
|
${orderSql}
|
|
ORDER BY o.order_code, oi.id`,
|
|
params
|
|
);
|
|
return result.rows;
|
|
}
|
|
|
|
async function syncItem(client, row) {
|
|
const settlementQty = Number(row.picked_weight) || 0;
|
|
const salePrice =
|
|
Number(row.locked_price) > 0
|
|
? Number(row.locked_price)
|
|
: Number(row.price) > 0
|
|
? Number(row.price)
|
|
: 0;
|
|
const nextAmount = Math.round(settlementQty * salePrice * 100) / 100;
|
|
const unit = row.unit ? String(row.unit).trim() : null;
|
|
|
|
await client.query(
|
|
`UPDATE order_items
|
|
SET ordered_quantity = CASE
|
|
WHEN ordered_quantity IS NULL OR ordered_quantity <= 0 THEN quantity
|
|
ELSE ordered_quantity
|
|
END,
|
|
ordered_unit = CASE
|
|
WHEN ordered_unit IS NULL OR TRIM(ordered_unit) = '' THEN unit
|
|
ELSE ordered_unit
|
|
END,
|
|
quantity = $2::numeric,
|
|
unit = COALESCE($3::varchar, unit),
|
|
price = $4::numeric,
|
|
locked_price = $4::numeric,
|
|
amount = $5::numeric,
|
|
price_locked_at = COALESCE(price_locked_at, NOW())
|
|
WHERE id = $1::uuid`,
|
|
[row.order_item_id, settlementQty, unit, salePrice, nextAmount]
|
|
);
|
|
|
|
await client.query(
|
|
`UPDATE orders o
|
|
SET total_amount = COALESCE((
|
|
SELECT ROUND(SUM(COALESCE(oi.amount, 0))::numeric, 2)
|
|
FROM order_items oi
|
|
WHERE oi.order_code = o.order_code
|
|
), 0),
|
|
updated_at = NOW()
|
|
WHERE o.order_code = $1`,
|
|
[row.order_code]
|
|
);
|
|
}
|
|
|
|
/** 仅重建已存在且订单≥90 的客户结算单明细(与 upsert 一致的最小路径) */
|
|
async function refreshCustomerStatement(client, orderCode) {
|
|
const orderRow = await client.query(
|
|
`SELECT o.order_code, o.customer_code, o.branch_code,
|
|
to_char(COALESCE(o.delivery_date, (o.updated_at AT TIME ZONE 'Asia/Shanghai')::date), 'YYYY-MM-DD') AS day
|
|
FROM orders o
|
|
WHERE o.order_code = $1 AND o.order_status >= 90 AND o.deleted_at IS NULL
|
|
LIMIT 1`,
|
|
[orderCode]
|
|
);
|
|
if (!orderRow.rows.length || !orderRow.rows[0].customer_code) return 'empty';
|
|
|
|
const existing = await client.query(
|
|
`SELECT statement_no, statement_status, COALESCE(paid_amount,0)::numeric AS paid_amount
|
|
FROM customer_statements WHERE statement_no = $1 LIMIT 1`,
|
|
[orderCode]
|
|
);
|
|
if (!existing.rows.length) return 'no_statement';
|
|
|
|
const items = await client.query(
|
|
`SELECT sku_code, quantity, amount, locked_price, price, price_source, quote_version_code
|
|
FROM order_items WHERE order_code = $1`,
|
|
[orderCode]
|
|
);
|
|
let total = 0;
|
|
const lines = [];
|
|
for (const item of items.rows) {
|
|
const qty = Number(item.quantity) || 0;
|
|
const locked = Number(item.locked_price) || 0;
|
|
const basePrice = Number(item.price) || 0;
|
|
const avgPrice = qty > 0 ? (Number(item.amount) || 0) / qty : 0;
|
|
const unitPrice = locked > 0 ? locked : basePrice > 0 ? basePrice : avgPrice;
|
|
const lineAmount = Math.round(unitPrice * qty * 100) / 100;
|
|
total += lineAmount;
|
|
lines.push({
|
|
sku_code: item.sku_code,
|
|
quantity: qty,
|
|
unit_price: unitPrice,
|
|
line_amount: lineAmount,
|
|
price_source: item.price_source,
|
|
quote_version_code: item.quote_version_code,
|
|
});
|
|
}
|
|
total = Math.round(total * 100) / 100;
|
|
if (total <= 0 || !lines.length) return 'empty';
|
|
|
|
const paid = Math.max(0, Number(existing.rows[0].paid_amount) || 0);
|
|
await client.query(`DELETE FROM statement_lines WHERE statement_no = $1 AND statement_type = 'customer'`, [
|
|
orderCode,
|
|
]);
|
|
await client.query(
|
|
`UPDATE customer_statements
|
|
SET total_amount = $2,
|
|
unpaid_amount = GREATEST(0, $2::numeric - $3::numeric),
|
|
updated_at = NOW()
|
|
WHERE statement_no = $1`,
|
|
[orderCode, total, paid]
|
|
);
|
|
for (const line of lines) {
|
|
await client.query(
|
|
`INSERT INTO statement_lines (
|
|
statement_no, statement_type, order_code, sku_code, quantity, unit_price, line_amount,
|
|
price_source, quote_version_code, branch_code
|
|
) VALUES ($1, 'customer', $1, $2, $3, $4, $5, $6, $7, $8)`,
|
|
[
|
|
orderCode,
|
|
line.sku_code,
|
|
line.quantity,
|
|
line.unit_price,
|
|
line.line_amount,
|
|
line.price_source,
|
|
line.quote_version_code,
|
|
orderRow.rows[0].branch_code,
|
|
]
|
|
);
|
|
}
|
|
return 'updated';
|
|
}
|
|
|
|
async function main() {
|
|
const day = dayArg ? dayArg.slice('--day='.length).trim() : chinaTodayYmd();
|
|
const onlyBranch = branchArg ? branchArg.slice('--branch='.length).trim() : '';
|
|
const orderArg = process.argv.find((a) => a.startsWith('--order='));
|
|
const onlyOrder = orderArg ? orderArg.slice('--order='.length).trim() : '';
|
|
|
|
console.log(JSON.stringify({ mode: EXECUTE ? 'execute' : 'dry-run', day, branch: onlyBranch || null }, null, 2));
|
|
|
|
const pool = new pg.Pool({ connectionString: loadDatabaseUrl() });
|
|
const client = await pool.connect();
|
|
try {
|
|
const schemas = await listTenantSchemas(client);
|
|
let targets = onlyBranch
|
|
? schemas.filter(
|
|
(s) =>
|
|
s === `tenant_${onlyBranch.toLowerCase()}` ||
|
|
s.toLowerCase().includes(onlyBranch.toLowerCase())
|
|
)
|
|
: schemas.slice();
|
|
if (!targets.length) {
|
|
console.log('无可用 tenant schema,退出');
|
|
return;
|
|
}
|
|
|
|
const all = [];
|
|
for (const schema of targets) {
|
|
await client.query(`SELECT set_config('search_path', $1, false)`, [`${schema}, public`]);
|
|
try {
|
|
const rows = await listCandidates(client, day, onlyOrder || undefined);
|
|
for (const row of rows) all.push({ schema, ...row });
|
|
} catch (err) {
|
|
console.warn(`skip ${schema}:`, err.message || err);
|
|
}
|
|
}
|
|
|
|
console.log(`\n待对齐明细: ${all.length}`);
|
|
for (const row of all) {
|
|
console.log(
|
|
[row.schema, row.order_code, row.item_name || row.sku_code, `${row.old_qty} → ${row.picked_weight}`, row.unit || ''].join(
|
|
'\t'
|
|
)
|
|
);
|
|
}
|
|
|
|
if (!EXECUTE) {
|
|
console.log('\n(dry-run) 未写库。加 --execute 执行。');
|
|
return;
|
|
}
|
|
|
|
let ok = 0;
|
|
let failed = 0;
|
|
const touchedOrders = new Set();
|
|
for (const row of all) {
|
|
try {
|
|
await client.query('BEGIN');
|
|
if (row.schema !== 'public') {
|
|
await client.query(`SELECT set_config('search_path', $1, true)`, [`${row.schema}, public`]);
|
|
}
|
|
await syncItem(client, row);
|
|
const st = await refreshCustomerStatement(client, row.order_code);
|
|
await client.query('COMMIT');
|
|
ok += 1;
|
|
touchedOrders.add(`${row.schema}:${row.order_code}`);
|
|
console.log(`OK ${row.schema} ${row.order_code} ${row.old_qty}→${row.picked_weight} statement=${st}`);
|
|
} catch (err) {
|
|
await client.query('ROLLBACK').catch(() => undefined);
|
|
failed += 1;
|
|
console.error(`FAIL ${row.schema} ${row.order_code}:`, err.message || err);
|
|
}
|
|
}
|
|
console.log('\n汇总:', { ok, failed, orders: touchedOrders.size });
|
|
if (failed) process.exitCode = 1;
|
|
} finally {
|
|
client.release();
|
|
await pool.end();
|
|
}
|
|
}
|
|
|
|
main().catch((err) => {
|
|
console.error(err);
|
|
process.exit(1);
|
|
});
|