All files / services/config-service/src/routes usage.js

11.91% Statements 28/235
100% Branches 1/1
0% Functions 0/1
11.91% Lines 28/235

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 2361x 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 1x 1x  
const express = require('express');
const path = require('path');
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 router = express.Router();
const internalRouter = express.Router();
 
async function getEffectiveLimits(orgPlan) {
  const best = await getBestPlan(orgPlan);

  if (best.code === 'specific_limit' && best.customLimits) {
    return {
      maxKbItems: best.customLimits.maxKbItems,
      maxLlmCost: best.customLimits.maxLlmCost,
      maxOcrCost: best.customLimits.maxOcrCost,
    };
  }

  if (!best.plan) return null;
  return { ...best.plan.limits };
}
 
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' });

    const tracking = await UsageTracking.findOne({
      organizationId: req.params.id,
      periodStart: orgPlan.currentPeriodStart,
    });

    let kbItemCount = tracking?.kbItemCount || 0;
    try {
      const axios = require('axios');
      const kbRes = await axios.get(
        `${process.env.KNOWLEDGE_BASE_SERVICE_URL || 'http://knowledge-base-service:8000'}/${req.params.id}/knowledge-bases`
      );
      const kbs = kbRes.data?.data?.knowledge_bases || [];
      kbItemCount = kbs.reduce((sum, kb) => sum + (kb.fact_count || 0), 0);
    } catch (err) {
      console.error('[Usage] Failed to count KB items:', err.message);
    }

    const daysRemaining = Math.max(0, Math.ceil((orgPlan.currentPeriodEnd.getTime() - Date.now()) / (1000 * 60 * 60 * 24)));

    if (kbItemCount !== (tracking?.kbItemCount || 0)) {
      await UsageTracking.findOneAndUpdate(
        { organizationId: req.params.id, periodStart: orgPlan.currentPeriodStart },
        { $set: { kbItemCount } },
        { upsert: true }
      );
    }

    res.json({
      success: true,
      data: {
        plan: best.code,
        status: orgPlan.status,
        period: {
          start: orgPlan.currentPeriodStart,
          end: orgPlan.currentPeriodEnd,
          daysRemaining,
        },
        trackedServices: {
          llm: await shouldTrackUsage(req.params.id, 'llm'),
          ocr: await shouldTrackUsage(req.params.id, 'ocr'),
        },
        usage: {
          kbItems: {
            used: kbItemCount,
            limit: limits.maxKbItems,
            percent: limits.maxKbItems ? Math.round((kbItemCount / limits.maxKbItems) * 100) : 0,
          },
          llmCost: {
            used: tracking?.llmCostUsed || 0,
            limit: limits.maxLlmCost,
            percent: limits.maxLlmCost ? Math.round(((tracking?.llmCostUsed || 0) / limits.maxLlmCost) * 100) : 0,
          },
          ocrCost: {
            used: tracking?.ocrCostUsed || 0,
            limit: limits.maxOcrCost,
            percent: limits.maxOcrCost ? Math.round(((tracking?.ocrCostUsed || 0) / limits.maxOcrCost) * 100) : 0,
          },
        },
      },
    });
  } 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 update = {};
    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')) update.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')) update.ocrCostUsed = ocrCost;
    }

    await UsageTracking.findOneAndUpdate(
      { organizationId, periodStart: orgPlan.currentPeriodStart },
      { $inc: update },
      { upsert: true }
    );

    res.status(200).json({ status: 'tracked' });
  } 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);
    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 };
    } else {
      return res.status(200).json({ allowed: true });
    }

    const tracking = await UsageTracking.findOne({
      organizationId,
      periodStart: orgPlan.currentPeriodStart,
    });

    const checkLlm = !type || type === 'llm' || type === 'all';
    const checkOcr = !type || type === 'ocr' || type === 'all';

    const llmOk = !checkLlm || !limits.maxLlmCost || !(await shouldTrackUsage(organizationId, 'llm')) || (tracking?.llmCostUsed || 0) < limits.maxLlmCost;
    const ocrOk = !checkOcr || !limits.maxOcrCost || !(await shouldTrackUsage(organizationId, 'ocr')) || (tracking?.ocrCostUsed || 0) < limits.maxOcrCost;

    if (!llmOk) return res.status(429).json({ allowed: false, error: 'LLM cost limit reached', used: tracking?.llmCostUsed || 0, limit: limits.maxLlmCost });
    if (!ocrOk) return res.status(429).json({ allowed: false, error: 'OCR cost limit reached', used: tracking?.ocrCostUsed || 0, limit: limits.maxOcrCost });

    res.status(200).json({ allowed: true, llmCostUsed: tracking?.llmCostUsed || 0, ocrCostUsed: tracking?.ocrCostUsed || 0, llmLimit: limits.maxLlmCost, ocrLimit: limits.maxOcrCost });
  } 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 });

    const axios = require('axios');
    let currentCount = 0;
    try {
      const kbRes = await axios.get(
        `${process.env.KNOWLEDGE_BASE_SERVICE_URL || 'http://knowledge-base-service:8000'}/${organizationId}/knowledge-bases`
      );
      const kbs = kbRes.data?.data?.knowledge_bases || [];
      currentCount = kbs.reduce((sum, kb) => sum + (kb.fact_count || 0), 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;