Files
SupplierSystem/server/src/services/marketIndexService.ts
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

213 lines
7.2 KiB
TypeScript

import { pool } from '../db';
import type { TenantContext } from './tenantScope';
type CategoryRow = {
category_code: string;
category_name: string;
level: number;
parent_code: string | null;
};
export interface MarketPriceIndexRow {
id: string;
category_code: string;
category_name: string;
index_value: number;
index_change: number;
trend: 'up' | 'down' | 'stable';
index_date: string;
}
/** 有经营分公司即过滤(含超管切换经营分公司) */
function branchFilter(ctx: TenantContext | null | undefined, alias: string, params: unknown[]) {
if (ctx?.branchCode && !ctx.isSuperAdmin) {
params.push(ctx.branchCode);
return `AND ${alias}.branch_code = $${params.length}`;
}
return '';
}
function rollupSecondaryAvg(
rows: Array<{ category_code: string; avg_price: unknown }>,
categoryMap: Map<string, CategoryRow>
): Map<string, { name: string; avg: number }> {
const buckets = new Map<string, { name: string; prices: number[] }>();
for (const row of rows) {
const skuCategory = String(row.category_code || '');
const avgPrice = Number(row.avg_price) || 0;
if (avgPrice <= 0) continue;
const secondary = resolveSecondaryCategory(skuCategory, categoryMap);
const bucket = buckets.get(secondary.code) || { name: secondary.name, prices: [] };
bucket.prices.push(avgPrice);
buckets.set(secondary.code, bucket);
}
const result = new Map<string, { name: string; avg: number }>();
for (const [code, bucket] of buckets) {
const avg = bucket.prices.reduce((sum, price) => sum + price, 0) / Math.max(bucket.prices.length, 1);
result.set(code, { name: bucket.name, avg });
}
return result;
}
async function loadCategoryMap(): Promise<Map<string, CategoryRow>> {
const result = await pool.query(
`SELECT DISTINCT ON (category_code)
category_code, category_name, level, parent_code
FROM categories
WHERE status = 1
ORDER BY category_code, branch_code`
);
return new Map(
result.rows.map((row) => [
String(row.category_code),
{
category_code: String(row.category_code),
category_name: String(row.category_name || row.category_code),
level: Number(row.level) || 1,
parent_code: row.parent_code ? String(row.parent_code) : null,
},
])
);
}
/** 解析至二级分类(level≤2 的最近祖先) */
export function resolveSecondaryCategory(
categoryCode: string,
categoryMap: Map<string, CategoryRow>
): { code: string; name: string } {
let node = categoryMap.get(categoryCode);
if (!node) {
// 无分类(空串或哨兵 UNCATEGORIZED):展示中文「未分类」,勿把英文哨兵写进 category_name
if (!categoryCode || categoryCode === 'UNCATEGORIZED') {
return { code: 'UNCATEGORIZED', name: '未分类' };
}
return { code: categoryCode, name: categoryCode };
}
while (node.level > 2 && node.parent_code) {
const parent = categoryMap.get(node.parent_code);
if (!parent) break;
node = parent;
}
return { code: node.category_code, name: node.category_name };
}
function trendFromChange(changePct: number): 'up' | 'down' | 'stable' {
if (changePct > 0.5) return 'up';
if (changePct < -0.5) return 'down';
return 'stable';
}
/** 按二级分类聚合市场价,写入价格指数(基准 100,日环比) */
export async function refreshMarketPriceIndices(ctx?: TenantContext | null) {
const categoryMap = await loadCategoryMap();
const params: unknown[] = [];
const branchSql = branchFilter(ctx, 'mp', params);
const today = new Date().toISOString().slice(0, 10);
const branchCode = ctx?.branchCode ? String(ctx.branchCode) : null;
const avgRows = await pool.query(
`SELECT mp.category_code, AVG(mp.market_price)::numeric AS avg_price
FROM market_prices mp
WHERE mp.market_price > 0
AND COALESCE(mp.price_source, '') != 'estimated'
${branchSql}
GROUP BY mp.category_code`,
params
);
const secondaryToday = rollupSecondaryAvg(avgRows.rows, categoryMap);
const prevDayParams: unknown[] = [];
const prevDayBranchSql = branchFilter(ctx, 'mp', prevDayParams);
const prevDayRows = await pool.query(
`SELECT mp.category_code, AVG(mp.market_price)::numeric AS avg_price
FROM market_prices mp
WHERE mp.market_price > 0
AND COALESCE(mp.price_source, '') != 'estimated'
AND COALESCE(mp.quoted_at, mp.updated_at) < CURRENT_DATE
${prevDayBranchSql}
GROUP BY mp.category_code`,
prevDayParams
);
const secondaryYesterday = rollupSecondaryAvg(prevDayRows.rows, categoryMap);
const prevParams: unknown[] = [today];
const prevBranchSql = branchFilter(ctx, 'mpi', prevParams);
const prevResult = await pool.query(
`SELECT category_code, index_value, index_date
FROM market_price_indices mpi
WHERE index_date < $1::date ${prevBranchSql}
ORDER BY index_date DESC`,
prevParams
);
const prevByCategory = new Map<string, number>();
for (const row of prevResult.rows) {
const code = String(row.category_code);
if (!prevByCategory.has(code)) {
prevByCategory.set(code, Number(row.index_value) || 100);
}
}
let upserted = 0;
await pool.query(
`DELETE FROM market_price_indices
WHERE index_date = $1::date
AND branch_code IS NOT DISTINCT FROM $2`,
[today, branchCode]
);
for (const [categoryCode, bucket] of secondaryToday) {
const todayAvg = bucket.avg;
const yesterdayIndex = prevByCategory.get(categoryCode) ?? 100;
const yesterdayAvg = secondaryYesterday.get(categoryCode)?.avg || 0;
let indexValue = yesterdayIndex;
let indexChange = 0;
if (yesterdayAvg > 0) {
indexValue = Math.round(yesterdayIndex * (todayAvg / yesterdayAvg) * 100) / 100;
indexChange = Math.round(((indexValue - yesterdayIndex) / yesterdayIndex) * 10000) / 100;
} else if (!prevByCategory.has(categoryCode)) {
indexValue = 100;
indexChange = 0;
}
const trend = trendFromChange(indexChange);
await pool.query(
`INSERT INTO market_price_indices
(category_code, category_name, index_value, index_change, trend, index_date, branch_code)
VALUES ($1,$2,$3,$4,$5,$6::date,$7)`,
[categoryCode, bucket.name, indexValue, indexChange, trend, today, branchCode]
);
upserted += 1;
}
return { upserted, index_date: today, branch_code: branchCode };
}
export async function listMarketPriceIndices(
ctx?: TenantContext | null,
limit = 100
): Promise<MarketPriceIndexRow[]> {
const params: unknown[] = [limit];
const branchSql = branchFilter(ctx, 'mpi', params);
const result = await pool.query(
`SELECT id, category_code, category_name, index_value, index_change, trend,
to_char(index_date, 'YYYY-MM-DD') AS index_date
FROM market_price_indices mpi
WHERE 1=1 ${branchSql}
ORDER BY index_date DESC, category_name ASC
LIMIT $1`,
params
);
return result.rows.map((row) => ({
id: row.id,
category_code: row.category_code,
category_name: row.category_name || row.category_code,
index_value: Number(row.index_value) || 100,
index_change: Number(row.index_change) || 0,
trend: (row.trend as 'up' | 'down' | 'stable') || 'stable',
index_date: String(row.index_date || '').slice(0, 10),
}));
}