Files
SupplierSystem/server/scripts/prod-backfill-dahongjiao-resv-gap.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

163 lines
5.2 KiB
JavaScript

#!/usr/bin/env node
/**
* 富顺大红椒:他单预留占池后本单可领用仅 1,再补 9 斤(备注:补录)
* 订单 ORD_MP_20260802_1785661058786SWR4
*/
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 ORDER = 'ORD_MP_20260802_1785661058786SWR4';
const SKU = 'SKU78661300611';
const ITEM = '大红椒';
const BRANCH = 'BR002';
const SCHEMA = 'tenant_br002';
const GAP = 9;
const REMARK = '补录';
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 newBatchNo() {
const d = new Date();
const ymd = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
return `IN${ymd}${Math.random().toString(36).slice(2, 8).toUpperCase()}`;
}
async function main() {
const pool = new pg.Pool({ connectionString: loadDatabaseUrl() });
const client = await pool.connect();
try {
await client.query(`SET search_path TO ${SCHEMA}, public`);
const avail = await client.query(
`SELECT COALESCE(SUM(available_qty),0)::float AS a
FROM inventory WHERE sku_code=$1 AND branch_code=$2 AND available_qty>0`,
[SKU, BRANCH]
);
const other = await client.query(
`SELECT COALESCE(SUM(qty),0)::float AS r
FROM inventory_reservations
WHERE sku_code=$1 AND status=10 AND order_code IS DISTINCT FROM $2`,
[SKU, ORDER]
);
const a = Number(avail.rows[0].a) || 0;
const r = Number(other.rows[0].r) || 0;
const claimable = Math.max(0, a - r);
const short = Math.max(0, Math.round((10 - claimable) * 1000) / 1000);
console.log({ avail: a, other_resv: r, claimable, short, plan_gap: GAP, execute: EXECUTE });
if (!EXECUTE) {
console.log('dry-run: 将补', short || GAP, '斤');
return;
}
const gap = short > 0 ? short : GAP;
const costR = await client.query(
`SELECT COALESCE(actual_price, purchase_price, 0)::float AS p
FROM purchase_orders WHERE order_code=$1 AND sku_code=$2
ORDER BY created_at DESC LIMIT 1`,
[ORDER, SKU]
);
const cost =
Number(costR.rows[0]?.p) ||
Number(
(
await client.query(
`SELECT cost_price::float AS p FROM inventory
WHERE sku_code=$1 AND cost_price IS NOT NULL ORDER BY created_at DESC LIMIT 1`,
[SKU]
)
).rows[0]?.p
) ||
4;
const batchNo = newBatchNo();
const bt = `BT${Date.now().toString(36).toUpperCase()}`;
await client.query('BEGIN');
const insp = await client.query(
`INSERT INTO inspections (
order_code, sku_code, supplier_code, prepare_qty, actual_qty, purchase_price,
batch_no, branch_code, source_type, item_name, unit,
quality_rating, loss_qty, compliance_status, inspection_time, inbound_batch_no,
processing_details
) VALUES (
$1,$2,NULL,$3,$3,$4,$5,$6,'purchase',$7,'斤','A',0,40,NOW(),$8,$9::jsonb
) RETURNING id`,
[
ORDER,
SKU,
gap,
cost,
bt,
BRANCH,
ITEM,
batchNo,
JSON.stringify({
repair: 'dahongjiao_resv_gap_20260803',
remark: REMARK,
gap,
avail_before: a,
other_resv: r,
}),
]
);
await client.query(
`INSERT INTO inventory (
batch_no, sku_code, quantity, available_qty, supplier_code, cost_price, status, branch_code, production_date
) VALUES ($1,$2,$3,$3,NULL,$4,10,$5,(NOW() AT TIME ZONE 'Asia/Shanghai')::date)`,
[batchNo, SKU, gap, cost, BRANCH]
);
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,'inspection_in',$3,0,$3,$4,$5)`,
[batchNo, SKU, gap, ORDER, REMARK]
);
await client.query('COMMIT');
const afterAvail = await client.query(
`SELECT COALESCE(SUM(available_qty),0)::float AS a
FROM inventory WHERE sku_code=$1 AND branch_code=$2 AND available_qty>0`,
[SKU, BRANCH]
);
const afterOther = await client.query(
`SELECT COALESCE(SUM(qty),0)::float AS r
FROM inventory_reservations
WHERE sku_code=$1 AND status=10 AND order_code IS DISTINCT FROM $2`,
[SKU, ORDER]
);
const aa = Number(afterAvail.rows[0].a) || 0;
const rr = Number(afterOther.rows[0].r) || 0;
console.log('FILLED', {
gap,
batchNo,
insp: insp.rows[0].id,
avail: aa,
other_resv: rr,
claimable: aa - rr,
});
} catch (err) {
await client.query('ROLLBACK').catch(() => undefined);
throw err;
} finally {
client.release();
await pool.end();
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});