来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
218 lines
7.1 KiB
TypeScript
218 lines
7.1 KiB
TypeScript
import { pool } from '../db';
|
||
import { notifyRoleUsers } from './notificationService';
|
||
import { isVolcBillingConfigured, queryVolcAccountBalance } from './volcBillingService';
|
||
|
||
export type ArkBalanceAlertLevel = 'ok' | 'warn' | 'critical' | 'overdue' | 'unknown';
|
||
|
||
export interface ArkBalanceAlertThresholds {
|
||
warnYuan: number;
|
||
criticalYuan: number;
|
||
notifyIntervalHours: number;
|
||
}
|
||
|
||
export interface ArkBalanceStatus {
|
||
billingConfigured: boolean;
|
||
queryOk: boolean;
|
||
availableBalanceYuan: number | null;
|
||
cashBalanceYuan: number | null;
|
||
arrearsBalanceYuan: number | null;
|
||
creditLimitYuan: number | null;
|
||
freezeAmountYuan: number | null;
|
||
alertLevel: ArkBalanceAlertLevel;
|
||
alertMessage: string | null;
|
||
thresholds: ArkBalanceAlertThresholds;
|
||
checkedAt: string | null;
|
||
setupHint: string | null;
|
||
error: string | null;
|
||
}
|
||
|
||
const CACHE_TTL_MS = Math.max(60_000, Number(process.env.ARK_BALANCE_CACHE_MS || 5 * 60_000));
|
||
|
||
let cachedStatus: { expiresAt: number; status: ArkBalanceStatus } | null = null;
|
||
let lastNotification: { level: ArkBalanceAlertLevel; at: number } | null = null;
|
||
|
||
const DEFAULT_THRESHOLDS: ArkBalanceAlertThresholds = {
|
||
warnYuan: Number(process.env.ARK_BALANCE_WARN_YUAN) || 100,
|
||
criticalYuan: Number(process.env.ARK_BALANCE_CRITICAL_YUAN) || 20,
|
||
notifyIntervalHours: Number(process.env.ARK_BALANCE_NOTIFY_INTERVAL_HOURS) || 12,
|
||
};
|
||
|
||
async function loadAlertThresholds(): Promise<ArkBalanceAlertThresholds> {
|
||
try {
|
||
const result = await pool.query(
|
||
`SELECT config_value
|
||
FROM system_configs
|
||
WHERE config_key = 'ark_balance_alert' AND branch_code IS NULL
|
||
LIMIT 1`
|
||
);
|
||
const value = (result.rows[0]?.config_value || {}) as Record<string, unknown>;
|
||
return {
|
||
warnYuan: Number(value.warn_yuan) || DEFAULT_THRESHOLDS.warnYuan,
|
||
criticalYuan: Number(value.critical_yuan) || DEFAULT_THRESHOLDS.criticalYuan,
|
||
notifyIntervalHours: Number(value.notify_interval_hours) || DEFAULT_THRESHOLDS.notifyIntervalHours,
|
||
};
|
||
} catch {
|
||
return DEFAULT_THRESHOLDS;
|
||
}
|
||
}
|
||
|
||
function resolveAlertLevel(
|
||
balance: { availableBalanceYuan: number; arrearsBalanceYuan: number },
|
||
thresholds: ArkBalanceAlertThresholds
|
||
): { level: ArkBalanceAlertLevel; message: string | null } {
|
||
const { availableBalanceYuan, arrearsBalanceYuan } = balance;
|
||
|
||
// 火山公式:可用余额 = (现金 - 冻结) + 信控 - 欠费金额;仅可用余额为负时才真正停服
|
||
if (availableBalanceYuan < 0) {
|
||
return {
|
||
level: 'overdue',
|
||
message: `可用余额 ¥${availableBalanceYuan.toFixed(2)}(待结算 ¥${arrearsBalanceYuan.toFixed(2)}),请充值。`,
|
||
};
|
||
}
|
||
|
||
if (availableBalanceYuan <= thresholds.criticalYuan) {
|
||
const pendingBill =
|
||
arrearsBalanceYuan > 0 ? `,待结算 ¥${arrearsBalanceYuan.toFixed(2)}` : '';
|
||
return {
|
||
level: 'critical',
|
||
message: `已低于严重线 ¥${thresholds.criticalYuan}${pendingBill}。`,
|
||
};
|
||
}
|
||
|
||
if (availableBalanceYuan <= thresholds.warnYuan) {
|
||
const pendingBill =
|
||
arrearsBalanceYuan > 0 ? `(待结算 ¥${arrearsBalanceYuan.toFixed(2)})` : '';
|
||
return {
|
||
level: 'warn',
|
||
message: `已低于预警线 ¥${thresholds.warnYuan}${pendingBill}。`,
|
||
};
|
||
}
|
||
|
||
return { level: 'ok', message: null };
|
||
}
|
||
|
||
function buildUnconfiguredStatus(thresholds: ArkBalanceAlertThresholds): ArkBalanceStatus {
|
||
return {
|
||
billingConfigured: false,
|
||
queryOk: false,
|
||
availableBalanceYuan: null,
|
||
cashBalanceYuan: null,
|
||
arrearsBalanceYuan: null,
|
||
creditLimitYuan: null,
|
||
freezeAmountYuan: null,
|
||
alertLevel: 'unknown',
|
||
alertMessage: null,
|
||
thresholds,
|
||
checkedAt: null,
|
||
setupHint:
|
||
'未配置 VOLC_ACCESS_KEY_ID / VOLC_SECRET_ACCESS_KEY(火山 IAM,不是 ARK_API_KEY),无法查余额。',
|
||
error: null,
|
||
};
|
||
}
|
||
|
||
export async function getArkBalanceStatus(options?: { forceRefresh?: boolean }): Promise<ArkBalanceStatus> {
|
||
const thresholds = await loadAlertThresholds();
|
||
|
||
if (!options?.forceRefresh && cachedStatus && cachedStatus.expiresAt > Date.now()) {
|
||
return { ...cachedStatus.status, thresholds };
|
||
}
|
||
|
||
if (!isVolcBillingConfigured()) {
|
||
const status = buildUnconfiguredStatus(thresholds);
|
||
cachedStatus = { expiresAt: Date.now() + CACHE_TTL_MS, status };
|
||
return status;
|
||
}
|
||
|
||
try {
|
||
const balance = await queryVolcAccountBalance();
|
||
const { level, message } = resolveAlertLevel(balance, thresholds);
|
||
const status: ArkBalanceStatus = {
|
||
billingConfigured: true,
|
||
queryOk: true,
|
||
availableBalanceYuan: balance.availableBalanceYuan,
|
||
cashBalanceYuan: balance.cashBalanceYuan,
|
||
arrearsBalanceYuan: balance.arrearsBalanceYuan,
|
||
creditLimitYuan: balance.creditLimitYuan,
|
||
freezeAmountYuan: balance.freezeAmountYuan,
|
||
alertLevel: level,
|
||
alertMessage: message,
|
||
thresholds,
|
||
checkedAt: new Date().toISOString(),
|
||
setupHint: null,
|
||
error: null,
|
||
};
|
||
cachedStatus = { expiresAt: Date.now() + CACHE_TTL_MS, status };
|
||
return status;
|
||
} catch (error: any) {
|
||
const status: ArkBalanceStatus = {
|
||
billingConfigured: true,
|
||
queryOk: false,
|
||
availableBalanceYuan: null,
|
||
cashBalanceYuan: null,
|
||
arrearsBalanceYuan: null,
|
||
creditLimitYuan: null,
|
||
freezeAmountYuan: null,
|
||
alertLevel: 'unknown',
|
||
alertMessage: null,
|
||
thresholds,
|
||
checkedAt: new Date().toISOString(),
|
||
setupHint: null,
|
||
error: error?.message || '余额查询失败',
|
||
};
|
||
cachedStatus = { expiresAt: Date.now() + 60_000, status };
|
||
return status;
|
||
}
|
||
}
|
||
|
||
const LEVEL_RANK: Record<ArkBalanceAlertLevel, number> = {
|
||
ok: 0,
|
||
unknown: 1,
|
||
warn: 2,
|
||
critical: 3,
|
||
overdue: 4,
|
||
};
|
||
|
||
function shouldNotify(level: ArkBalanceAlertLevel, intervalHours: number): boolean {
|
||
if (level === 'ok' || level === 'unknown') return false;
|
||
if (!lastNotification) return true;
|
||
|
||
const elapsedMs = Date.now() - lastNotification.at;
|
||
const intervalMs = Math.max(1, intervalHours) * 60 * 60 * 1000;
|
||
if (LEVEL_RANK[level] > LEVEL_RANK[lastNotification.level]) return true;
|
||
return elapsedMs >= intervalMs;
|
||
}
|
||
|
||
export async function scanArkBalanceAlert(): Promise<{ notified: boolean; status: ArkBalanceStatus }> {
|
||
const status = await getArkBalanceStatus({ forceRefresh: true });
|
||
if (!shouldNotify(status.alertLevel, status.thresholds.notifyIntervalHours)) {
|
||
return { notified: false, status };
|
||
}
|
||
|
||
const title =
|
||
status.alertLevel === 'overdue'
|
||
? 'AI 账户已欠费'
|
||
: status.alertLevel === 'critical'
|
||
? 'AI 账户余额严重不足'
|
||
: 'AI 账户余额预警';
|
||
|
||
const content =
|
||
status.alertMessage ||
|
||
status.error ||
|
||
`当前可用余额 ¥${status.availableBalanceYuan?.toFixed(2) ?? '--'},请登录火山引擎费用中心充值。`;
|
||
|
||
await notifyRoleUsers({
|
||
roles: ['super_admin', 'admin'],
|
||
notifyType: 'system_alert',
|
||
title,
|
||
content: `${content}(查询时间:${status.checkedAt || new Date().toISOString()})`,
|
||
});
|
||
|
||
lastNotification = { level: status.alertLevel, at: Date.now() };
|
||
console.warn(`[ark-balance] ${title}: ${content}`);
|
||
return { notified: true, status };
|
||
}
|
||
|
||
export function invalidateArkBalanceCache() {
|
||
cachedStatus = null;
|
||
}
|