Files
SupplierSystem/server/scripts/prod-kugua-self-purchase-and-zero-inventory.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

290 lines
11 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
/**
* 生产运维:
* 1) 苦瓜取消库存抵扣,自采数量改为订货全量
* 2) 全库库存 available/reserved 清零,并释放活跃预留、清空未完成单 stock_cover
*
* node scripts/prod-kugua-self-purchase-and-zero-inventory.mjs
* node scripts/prod-kugua-self-purchase-and-zero-inventory.mjs --execute
*/
import pg from 'pg';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
dotenv.config({ path: path.join(__dirname, '..', '.env') });
const EXECUTE = process.argv.includes('--execute');
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
async function schemas(client) {
const r = await client.query(
`SELECT schema_name FROM public.tenant_schema_registry
WHERE schema_name LIKE 'tenant_%' AND schema_name <> 'tenant_template'
AND COALESCE(status,'active') IN ('active','ready')
ORDER BY branch_code`
);
return r.rows.map((x) => String(x.schema_name));
}
async function processSchema(client, schema) {
console.log(`\n======== ${schema} ========`);
await client.query(`SELECT set_config('search_path', $1, false)`, [`${schema}, public`]);
const hasOrders = await client.query(`SELECT to_regclass('order_items') IS NOT NULL AS ok`);
if (!hasOrders.rows[0]?.ok) {
console.log('无 order_items,跳过');
return;
}
const kugua = await client.query(`
SELECT oi.id, oi.order_code, oi.sku_code, oi.item_name,
oi.quantity::float8 AS qty,
COALESCE(oi.stock_cover_qty,0)::float8 AS stock_cover,
o.order_status, o.branch_code
FROM order_items oi
JOIN orders o ON o.order_code = oi.order_code AND o.deleted_at IS NULL
WHERE o.order_status < 90
AND (
oi.item_name ILIKE '%苦瓜%'
OR oi.sku_code IN (SELECT sku_code FROM skus WHERE sku_name ILIKE '%苦瓜%')
)
ORDER BY oi.created_at
`);
console.log(`开放订单苦瓜行: ${kugua.rowCount}`);
for (const row of kugua.rows) {
console.log(
` ${row.order_code} ${row.item_name} qty=${row.qty} cover=${row.stock_cover} status=${row.order_status}`
);
const po = await client.query(
`SELECT purchase_code, purchase_status, purchase_qty::float8 AS purchase_qty
FROM purchase_orders
WHERE order_code = $1 AND sku_code = $2 AND purchase_status < 40
ORDER BY created_at DESC LIMIT 1`,
[row.order_code, row.sku_code]
);
const ful = await client.query(
`SELECT purchase_code, inventory_cover_qty::float8 AS cover
FROM order_item_fulfillments WHERE order_item_id = $1::uuid`,
[row.id]
);
console.log(' po', po.rows[0] || null, 'ful', ful.rows[0] || null);
if (!EXECUTE) continue;
// 释放预留 + 清空抵扣
await client.query(
`UPDATE inventory_reservations
SET status = 30, updated_at = NOW()
WHERE order_item_id = $1::uuid AND status = 10`,
[row.id]
);
await client.query(`UPDATE order_items SET stock_cover_qty = 0 WHERE id = $1::uuid`, [row.id]);
const needQty = Number(row.qty) || 0;
let purchaseCode = po.rows[0]?.purchase_code || ful.rows[0]?.purchase_code || null;
if (purchaseCode && Number(po.rows[0]?.purchase_status) < 40) {
await client.query(
`UPDATE purchase_orders
SET purchase_qty = $2,
remark = CASE
WHEN remark IS NULL OR TRIM(remark) = '' THEN '取消库存抵扣改全量自采'
WHEN remark LIKE '%取消库存抵扣%' THEN remark
ELSE remark || ';取消库存抵扣改全量自采'
END
WHERE purchase_code = $1 AND purchase_status < 40`,
[purchaseCode, needQty]
);
} else if (!purchaseCode || Number(po.rows[0]?.purchase_status) >= 40) {
// 新建自采单
purchaseCode = `PUR${Date.now()}${String(row.id).slice(-4)}${Math.floor(Math.random() * 1000)}`;
const priceRow = await client.query(
`SELECT COALESCE(
(SELECT purchase_price FROM purchase_orders WHERE sku_code=$1 AND purchase_price>0 ORDER BY created_at DESC LIMIT 1),
(SELECT cost_price FROM skus WHERE sku_code=$1 LIMIT 1),
0
)::numeric AS price`,
[row.sku_code]
);
await client.query(
`INSERT INTO purchase_orders (
purchase_code, order_code, sku_code, supplier_code, purchaser_code, purchaser_name,
purchase_qty, purchase_price, purchase_status, is_temporary_supplier,
source_type, source_id, remark, branch_code
) VALUES ($1,$2,$3,NULL,'PUR001','采购员',$4,$5,10,false,'order_stock_cover_to_purchase',$6,
'取消库存抵扣改全量自采',$7)`,
[
purchaseCode,
row.order_code,
row.sku_code,
needQty,
Number(priceRow.rows[0]?.price) || 0,
row.id,
row.branch_code || 'BR002',
]
);
}
await client.query(
`INSERT INTO order_item_fulfillments (
order_item_id, order_code, supplier_preparation_id, purchase_code, inventory_cover_qty, updated_at
) VALUES ($1::uuid, $2, NULL, $3, 0, NOW())
ON CONFLICT (order_item_id) DO UPDATE SET
purchase_code = EXCLUDED.purchase_code,
supplier_preparation_id = NULL,
inventory_cover_qty = 0,
updated_at = NOW()`,
[row.id, row.order_code, purchaseCode]
);
console.log(` -> 自采 ${purchaseCode} qty=${needQty}`);
}
const invBefore = await client.query(`
SELECT COUNT(*)::int AS batches,
ROUND(SUM(COALESCE(available_qty,0))::numeric,2) AS sum_available,
ROUND(SUM(COALESCE(quantity,0))::numeric,2) AS sum_quantity
FROM inventory
`);
console.log('库存清零前:', invBefore.rows[0]);
const coverOpen = await client.query(`
SELECT COUNT(*)::int AS n,
ROUND(SUM(COALESCE(stock_cover_qty,0))::numeric,2) AS sum_cover
FROM order_items oi
JOIN orders o ON o.order_code=oi.order_code AND o.deleted_at IS NULL
WHERE o.order_status < 90 AND COALESCE(oi.stock_cover_qty,0) > 1e-9
`);
console.log('其它未完成抵扣(将一并清空预留/抵扣标记):', coverOpen.rows[0]);
if (EXECUTE) {
// 清零库存(quantity + available_qty)
const cleared = await client.query(`
UPDATE inventory
SET available_qty = 0,
quantity = 0
WHERE COALESCE(available_qty,0) <> 0 OR COALESCE(quantity,0) <> 0
`);
console.log(`已清零库存批次: ${cleared.rowCount}`);
// 释放全部活跃预留
const hasRes = await client.query(`SELECT to_regclass('inventory_reservations') IS NOT NULL AS ok`);
if (hasRes.rows[0]?.ok) {
const rel = await client.query(`
UPDATE inventory_reservations
SET status = 30, updated_at = NOW()
WHERE status = 10
`);
console.log(`已释放活跃预留: ${rel.rowCount}`);
}
// 清空未完成订单的库存抵扣标记(库存已无,抵扣无效)
// 注意:苦瓜已单独改自采;其它有抵扣的行仅清标记,若已有自采单则把 purchase_qty 调到全量
const others = await client.query(`
SELECT oi.id, oi.order_code, oi.sku_code, oi.quantity::float8 AS qty,
COALESCE(oi.stock_cover_qty,0)::float8 AS stock_cover
FROM order_items oi
JOIN orders o ON o.order_code=oi.order_code AND o.deleted_at IS NULL
WHERE o.order_status < 90 AND COALESCE(oi.stock_cover_qty,0) > 1e-9
`);
for (const row of others.rows) {
await client.query(`UPDATE order_items SET stock_cover_qty = 0 WHERE id = $1::uuid`, [row.id]);
const po = await client.query(
`SELECT purchase_code FROM purchase_orders
WHERE order_code=$1 AND sku_code=$2 AND purchase_status < 40
ORDER BY created_at DESC LIMIT 1`,
[row.order_code, row.sku_code]
);
let purchaseCode = po.rows[0]?.purchase_code || null;
if (purchaseCode) {
await client.query(
`UPDATE purchase_orders SET purchase_qty = $2
WHERE purchase_code = $1 AND purchase_status < 40`,
[purchaseCode, Number(row.qty) || 0]
);
} else {
purchaseCode = `PUR${Date.now()}${String(row.id).slice(-4)}${Math.floor(Math.random() * 1000)}`;
const priceRow = await client.query(
`SELECT COALESCE(
(SELECT purchase_price FROM purchase_orders WHERE sku_code=$1 AND purchase_price>0 ORDER BY created_at DESC LIMIT 1),
(SELECT cost_price FROM skus WHERE sku_code=$1 LIMIT 1),
0
)::numeric AS price`,
[row.sku_code]
);
const branch = await client.query(
`SELECT branch_code FROM orders WHERE order_code=$1`,
[row.order_code]
);
await client.query(
`INSERT INTO purchase_orders (
purchase_code, order_code, sku_code, supplier_code, purchaser_code, purchaser_name,
purchase_qty, purchase_price, purchase_status, is_temporary_supplier,
source_type, source_id, remark, branch_code
) VALUES ($1,$2,$3,NULL,'PUR001','采购员',$4,$5,10,false,'order_stock_cover_to_purchase',$6,
'库存清零后改全量自采',$7)`,
[
purchaseCode,
row.order_code,
row.sku_code,
Number(row.qty) || 0,
Number(priceRow.rows[0]?.price) || 0,
row.id,
branch.rows[0]?.branch_code || null,
]
);
}
await client.query(
`INSERT INTO order_item_fulfillments (
order_item_id, order_code, supplier_preparation_id, purchase_code, inventory_cover_qty, updated_at
) VALUES ($1::uuid, $2, NULL, $3, 0, NOW())
ON CONFLICT (order_item_id) DO UPDATE SET
purchase_code = EXCLUDED.purchase_code,
supplier_preparation_id = NULL,
inventory_cover_qty = 0,
updated_at = NOW()`,
[row.id, row.order_code, purchaseCode]
);
}
console.log(`已清空其它抵扣并改为自采: ${others.rowCount} 行`);
}
const invAfter = await client.query(`
SELECT COUNT(*)::int AS batches,
ROUND(SUM(COALESCE(available_qty,0))::numeric,2) AS sum_available,
ROUND(SUM(COALESCE(quantity,0))::numeric,2) AS sum_quantity
FROM inventory
`);
console.log(EXECUTE ? '库存清零后:' : '库存(未改):', invAfter.rows[0]);
}
async function main() {
if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL required');
console.log(`=== 苦瓜改自采 + 库存清零 (${EXECUTE ? 'EXECUTE' : 'DRY-RUN'}) ===`);
const client = await pool.connect();
try {
if (EXECUTE) await client.query('BEGIN');
const list = await schemas(client);
for (const s of list) {
await processSchema(client, s);
}
if (EXECUTE) await client.query('COMMIT');
if (!EXECUTE) {
console.log('\n确认后执行: node scripts/prod-kugua-self-purchase-and-zero-inventory.mjs --execute');
}
} catch (err) {
if (EXECUTE) await client.query('ROLLBACK');
throw err;
} finally {
client.release();
await pool.end();
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});