Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x | const express = require('express');
const axios = require('axios');
const OrganizationPlan = require('../models/OrganizationPlan');
const UsageTracking = require('../models/UsageTracking');
const Membership = require('../models/Membership');
const { getBestPlan } = require('../services/planResolver');
const { shouldTrackUsage } = require('../services/usageGate');
const { ensurePeriods, getActivePeriods, resolveLimits } = require('../services/usagePeriods');
const { resolveQuotaLimits } = require('../services/quotaLimits');
const { addInternalKey } = require('../../shared/internalAuth');
const SERVICE_NAME = process.env.SERVICE_NAME || 'config-service';
const KNOWLEDGE_BASE_SERVICE_URL = process.env.KNOWLEDGE_BASE_SERVICE_URL || 'http://knowledge-base-service:8000';
const router = express.Router();
const internalRouter = express.Router();
router.get('/organizations/:id/usage', async (req, res) => {
try {
// Seul un membre de l'organisation peut consulter sa consommation
const membership = await Membership.findOne({ userId: req.user._id, organizationId: req.params.id });
if (!membership) {
return res.status(403).json({ success: false, message: 'Access denied to this organization' });
}
const orgPlan = await OrganizationPlan.findOne({ organizationId: req.params.id });
if (!orgPlan) return res.status(404).json({ success: false, message: 'Organization not found' });
const best = await getBestPlan(orgPlan);
let limits;
if (best.code === 'specific_limit' && best.customLimits) {
limits = {
maxKbItems: best.customLimits.maxKbItems,
maxLlmCost: best.customLimits.maxLlmCost,
maxOcrCost: best.customLimits.maxOcrCost,
};
} else if (best.plan) {
limits = { ...best.plan.limits };
}
if (!limits) return res.status(404).json({ success: false, message: 'Plan not found' });
// Pas de cron : crée les périodes manquantes (de la dernière connue à maintenant).
await ensurePeriods(req.params.id);
const active = await getActivePeriods(req.params.id);
let kbItemCount = 0;
try {
const kbRes = await axios.get(
`${KNOWLEDGE_BASE_SERVICE_URL}/internal/${req.params.id}/knowledge-bases/count`,
{ headers: addInternalKey({}, SERVICE_NAME), timeout: 5000 }
);
kbItemCount = kbRes.data?.data?.kbItemCount || 0;
} catch (err) {
console.error('[Usage] Failed to count KB items:', err.message);
}
const pct = (used, lim) => (lim ? Math.round((used / lim) * 100) : 0);
const days = (end) => Math.max(0, Math.ceil((new Date(end).getTime() - Date.now()) / 86400000));
// Le plan effectif fait foi ; le snapshot de la période n'est qu'un repli (cf. quotaLimits).
// Sinon un changement de plan en cours de période resterait invisible jusqu'à la suivante.
// Une entrée par période ACTIVE (aucune conso écrasée : l'historique reste en base).
const periods = active.map((p) => {
const effective = resolveQuotaLimits(limits, p.limits);
return {
id: String(p._id),
start: p.periodStart,
end: p.periodEnd,
daysRemaining: days(p.periodEnd),
planCode: best.code || p.planCode || null,
// `plans-config.json` nomme le plan « Limite spécifique » ; l'UI l'appelle « Sur mesure ».
planName: best.code === 'specific_limit' ? 'Sur mesure' : (best.plan?.name || null),
usage: {
kbItems: { used: kbItemCount, limit: effective.maxKbItems, percent: pct(kbItemCount, effective.maxKbItems) },
llmCost: { used: p.llmCostUsed || 0, limit: effective.maxLlmCost, percent: pct(p.llmCostUsed || 0, effective.maxLlmCost) },
ocrCost: { used: p.ocrCostUsed || 0, limit: effective.maxOcrCost, percent: pct(p.ocrCostUsed || 0, effective.maxOcrCost) },
},
};
});
// Le stock (kbItems) est global : on synchronise toutes les périodes actives.
if (active.length) {
await UsageTracking.updateMany(
{ _id: { $in: active.map((p) => p._id) } },
{ $set: { kbItemCount } },
);
}
const current = periods[0] || {
start: orgPlan.currentPeriodStart,
end: orgPlan.currentPeriodEnd,
daysRemaining: days(orgPlan.currentPeriodEnd),
usage: {
kbItems: { used: kbItemCount, limit: limits.maxKbItems, percent: pct(kbItemCount, limits.maxKbItems) },
llmCost: { used: 0, limit: limits.maxLlmCost, percent: 0 },
ocrCost: { used: 0, limit: limits.maxOcrCost, percent: 0 },
},
};
res.json({
success: true,
data: {
plan: best.code,
status: orgPlan.status,
period: { start: current.start, end: current.end, daysRemaining: current.daysRemaining },
periods,
trackedServices: {
llm: await shouldTrackUsage(req.params.id, 'llm'),
ocr: await shouldTrackUsage(req.params.id, 'ocr'),
},
usage: current.usage,
},
});
} catch (error) {
console.error('[Usage] Error getting usage:', error.message);
res.status(500).json({ success: false, message: 'Error getting usage' });
}
});
internalRouter.post('/internal/usage/track', async (req, res) => {
try {
const { organizationId, llmCost, ocrCost } = req.body;
const orgPlan = await OrganizationPlan.findOne({ organizationId });
if (!orgPlan) return res.status(404).json({ error: 'Organization not found' });
const inc = {};
if (llmCost != null) {
if (!Number.isFinite(llmCost) || llmCost < 0) {
return res.status(400).json({ error: 'llmCost must be a non-negative number' });
}
if (await shouldTrackUsage(organizationId, 'llm')) inc.llmCostUsed = llmCost;
}
if (ocrCost != null) {
if (!Number.isFinite(ocrCost) || ocrCost < 0) {
return res.status(400).json({ error: 'ocrCost must be a non-negative number' });
}
if (await shouldTrackUsage(organizationId, 'ocr')) inc.ocrCostUsed = ocrCost;
}
if (!Object.keys(inc).length) return res.status(200).json({ status: 'ignored' });
// Crée les périodes manquantes puis impute la consommation à TOUTES les périodes actives.
await ensurePeriods(organizationId);
const active = await getActivePeriods(organizationId);
if (active.length) {
await UsageTracking.updateMany(
{ _id: { $in: active.map((p) => p._id) } },
{ $inc: inc },
);
} else {
// Repli : période courante du plan (créée si absente).
await UsageTracking.findOneAndUpdate(
{ organizationId, periodStart: orgPlan.currentPeriodStart },
{
$inc: inc,
$setOnInsert: {
organizationId,
periodStart: orgPlan.currentPeriodStart,
periodEnd: orgPlan.currentPeriodEnd,
kbItemCount: 0,
llmCostUsed: 0,
ocrCostUsed: 0,
},
},
{ upsert: true, setDefaultsOnInsert: true },
);
}
res.status(200).json({ status: 'tracked', periods: active.length });
} catch (error) {
console.error('[Usage] Error tracking usage:', error.message);
res.status(500).json({ error: 'Error tracking usage' });
}
});
// Vérifier si l'orga peut consommer (limites non déjà atteintes)
internalRouter.get('/internal/usage/can-consume', async (req, res) => {
try {
const { organizationId, type } = req.query;
if (!organizationId) return res.status(400).json({ error: 'organizationId required' });
const orgPlan = await OrganizationPlan.findOne({ organizationId });
if (!orgPlan) return res.status(404).json({ error: 'Organization not found' });
const best = await getBestPlan(orgPlan);
const globalLimits = resolveLimits(best);
const checkLlm = !type || type === 'llm' || type === 'all';
const checkOcr = !type || type === 'ocr' || type === 'all';
const trackLlm = checkLlm && (await shouldTrackUsage(organizationId, 'llm'));
const trackOcr = checkOcr && (await shouldTrackUsage(organizationId, 'ocr'));
// Crée les périodes manquantes puis évalue TOUTES les périodes actives.
await ensurePeriods(organizationId);
const active = await getActivePeriods(organizationId);
if (!active.length) return res.status(200).json({ allowed: true });
// Quotas du plan effectif (le snapshot de période ne sert que de repli, cf. quotaLimits).
const quotaOf = (p) => resolveQuotaLimits(globalLimits, p.limits);
// Une période a de la place si, pour chaque type suivi, elle n'a pas dépassé sa limite.
const hasRoom = (p) => {
const quota = quotaOf(p);
const llmOk = !trackLlm || quota.maxLlmCost == null || (p.llmCostUsed || 0) < quota.maxLlmCost;
const ocrOk = !trackOcr || quota.maxOcrCost == null || (p.ocrCostUsed || 0) < quota.maxOcrCost;
return llmOk && ocrOk;
};
const ok = active.find(hasRoom);
if (ok) {
return res.status(200).json({
allowed: true,
periodId: String(ok._id),
periods: active.length,
llmCostUsed: ok.llmCostUsed || 0,
ocrCostUsed: ok.ocrCostUsed || 0,
});
}
// Aucune période active n'a de reste → refus.
const p0 = active[0];
const quota0 = quotaOf(p0);
const isOcr = type === 'ocr' || type === 'all';
return res.status(429).json({
allowed: false,
error: 'Quota reached on all active periods',
used: isOcr ? (p0.ocrCostUsed || 0) : (p0.llmCostUsed || 0),
limit: isOcr ? quota0.maxOcrCost : quota0.maxLlmCost,
periods: active.length,
});
} catch (error) {
console.error('[Usage] Error checking usage:', error.message);
res.status(200).json({ allowed: true }); // fail open
}
});
// Vérifier si l'orga peut ajouter des faits KB (limite de stock)
internalRouter.post('/internal/usage/check-kb', async (req, res) => {
try {
const { organizationId, count } = req.body;
const orgPlan = await OrganizationPlan.findOne({ organizationId });
if (!orgPlan) return res.status(404).json({ error: 'Organization not found' });
const best = await getBestPlan(orgPlan);
let maxKbItems;
if (best.code === 'specific_limit' && best.customLimits) {
maxKbItems = best.customLimits.maxKbItems;
} else if (best.plan) {
maxKbItems = best.plan.limits?.maxKbItems;
}
if (maxKbItems == null) return res.status(200).json({ allowed: true });
let currentCount = 0;
try {
const kbRes = await axios.get(
`${KNOWLEDGE_BASE_SERVICE_URL}/internal/${organizationId}/knowledge-bases/count`,
{ headers: addInternalKey({}, SERVICE_NAME), timeout: 5000 }
);
currentCount = kbRes.data?.data?.kbItemCount || 0;
} catch (err) {
console.error('[Usage] Failed to count KB items:', err.message);
}
const remaining = maxKbItems - currentCount;
if (remaining <= 0) return res.status(429).json({ allowed: false, error: 'KB item limit exceeded', current: currentCount, limit: maxKbItems });
if ((count || 1) > remaining) return res.status(429).json({ allowed: false, error: 'Not enough KB item capacity', current: currentCount, limit: maxKbItems, remaining });
res.status(200).json({ allowed: true, current: currentCount, limit: maxKbItems, remaining });
} catch (error) {
console.error('[Usage] Error checking KB limit:', error.message);
res.status(200).json({ allowed: true }); // fail open
}
});
module.exports = router;
module.exports.internalRouter = internalRouter;
|