import { eq } from 'drizzle-orm'; import { db } from '../../db/index'; import { roiStrategies } from '../../db/schema'; import type { RoiCategory, StrategyParams } from './types'; const DEFAULTS: StrategyParams = { hourlyRate: 400, amortYears: 3, commitHourCoef: 0.5, taskHourCoef: 6, }; let cache: Map | null = null; let cacheLoadedAt = 0; const CACHE_TTL_MS = 60_000; // 1 分钟缓存,改完策略最多 1 分钟生效 async function loadCache(): Promise> { const now = Date.now(); if (cache && now - cacheLoadedAt < CACHE_TTL_MS) return cache; const rows = await db.select().from(roiStrategies); const map = new Map(); for (const row of rows) { const p = (row.params as Partial) || {}; map.set(row.category, { hourlyRate: p.hourlyRate ?? DEFAULTS.hourlyRate, amortYears: p.amortYears ?? DEFAULTS.amortYears, commitHourCoef: p.commitHourCoef ?? DEFAULTS.commitHourCoef, taskHourCoef: p.taskHourCoef ?? DEFAULTS.taskHourCoef, }); } cache = map; cacheLoadedAt = now; return map; } /** * 取某个分类的策略参数。未打标(null)时返回 cash_cow 的参数作为默认。 */ export async function getStrategyParams(category: RoiCategory | null): Promise { const map = await loadCache(); const cat: RoiCategory = category ?? 'cash_cow'; return map.get(cat) ?? DEFAULTS; } export function invalidateStrategyCache(): void { cache = null; cacheLoadedAt = 0; }