All files / src/config plans.js

62.79% Statements 27/43
38.46% Branches 10/26
66.66% Functions 4/6
69.23% Lines 27/39

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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291                                1x     1x                                                                                                                                                                                                                                                                                                                                               1x               8x 8x 8x   8x                 15x 15x 10x     5x   5x 5x   5x   3x 3x     2x 2x 8x       2x 8x         2x 2x                                 10x 10x                                                             5x     1x  
/**
 * Configuration des plans — Charge les limites depuis la DB avec cache memoire.
 *
 * Fonctionnement :
 *   1. Au demarrage, loadPlans() charge les plans depuis la table `plans`
 *   2. Les valeurs sont gardees en cache pendant CACHE_TTL_MS (5 min)
 *   3. Si la DB est inaccessible, fallback sur les valeurs par defaut
 *   4. Les valeurs -1 en JSONB sont converties en Infinity pour le runtime
 *
 * Utilisation :
 *   const { getPlanLimits, requiredPlanFor } = require('../config/plans');
 *   const limits = await getPlanLimits('free');
 *
 * @module config/plans
 */
 
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
 
// Valeurs par defaut (fallback si DB inaccessible)
const DEFAULT_LIMITS = {
  free: {
    servers: 3,
    uptime_monitors: 10,
    uptime_interval_seconds: 300,
    ssl_certificates: 10,
    webhooks: 2,
    alert_rules: 5,
    quick_actions: 10,
    log_paths: 10,
    backup_schedules: 2,
    backup_manual_per_day: 1,
    backup_retention_days: 3,
    chat_messages_per_day: 30,
    chat_sessions: 5,
    status_pages: 1,
    metrics_retention_days: 7,
    uptime_retention_days: 7,
    ssl_retention_days: 7,
    audit_retention_days: 7,
    terminal_ssh: false,
    file_editor_write: false,
    docker_stats: false,
    docker_logs_streaming: false,
    docker_stacks: false,
    docker_prune: false,
    cron_write: false,
    backup_download: false,
    backup_restore: false,
    chat_tool_use: false,
    export_config: false,
    export_csv_audit: false,
    http_error_alerts: false,
    ssl_alerts: false,
    email_digest: false,
    monthly_report: false,
    status_page_whitelabel: false,
    api_access: false,
    api_requests_per_hour: 0,
    users: 1,
    groups_per_server: 0,
  },
  pro: {
    servers: 10,
    uptime_monitors: 50,
    uptime_interval_seconds: 60,
    ssl_certificates: 50,
    webhooks: 10,
    alert_rules: 50,
    quick_actions: Infinity,
    log_paths: Infinity,
    backup_schedules: 20,
    backup_manual_per_day: Infinity,
    backup_retention_days: 30,
    chat_messages_per_day: 500,
    chat_sessions: Infinity,
    status_pages: 5,
    metrics_retention_days: 90,
    uptime_retention_days: 90,
    ssl_retention_days: 90,
    audit_retention_days: 90,
    terminal_ssh: true,
    file_editor_write: true,
    docker_stats: true,
    docker_logs_streaming: true,
    docker_stacks: true,
    docker_prune: true,
    cron_write: true,
    backup_download: true,
    backup_restore: true,
    chat_tool_use: true,
    export_config: true,
    export_csv_audit: true,
    http_error_alerts: true,
    ssl_alerts: true,
    email_digest: true,
    monthly_report: true,
    status_page_whitelabel: false,
    api_access: true,
    api_requests_per_hour: 1000,
    users: 1,
    groups_per_server: 0,
  },
  business: {
    servers: 30,
    uptime_monitors: 150,
    uptime_interval_seconds: 30,
    ssl_certificates: 150,
    webhooks: 30,
    alert_rules: 150,
    quick_actions: Infinity,
    log_paths: Infinity,
    backup_schedules: 50,
    backup_manual_per_day: Infinity,
    backup_retention_days: 90,
    chat_messages_per_day: 2000,
    chat_sessions: Infinity,
    status_pages: 20,
    metrics_retention_days: 180,
    uptime_retention_days: 180,
    ssl_retention_days: 180,
    audit_retention_days: 180,
    terminal_ssh: true,
    file_editor_write: true,
    docker_stats: true,
    docker_logs_streaming: true,
    docker_stacks: true,
    docker_prune: true,
    cron_write: true,
    backup_download: true,
    backup_restore: true,
    chat_tool_use: true,
    export_config: true,
    export_csv_audit: true,
    http_error_alerts: true,
    ssl_alerts: true,
    email_digest: true,
    monthly_report: true,
    status_page_whitelabel: false,
    api_access: true,
    api_requests_per_hour: 5000,
    users: 3,
    groups_per_server: 10,
  },
  enterprise: {
    servers: Infinity,
    uptime_monitors: Infinity,
    uptime_interval_seconds: 30,
    ssl_certificates: Infinity,
    webhooks: Infinity,
    alert_rules: Infinity,
    quick_actions: Infinity,
    log_paths: Infinity,
    backup_schedules: Infinity,
    backup_manual_per_day: Infinity,
    backup_retention_days: 365,
    chat_messages_per_day: Infinity,
    chat_sessions: Infinity,
    status_pages: Infinity,
    metrics_retention_days: 365,
    uptime_retention_days: 365,
    ssl_retention_days: 365,
    audit_retention_days: 365,
    terminal_ssh: true,
    file_editor_write: true,
    docker_stats: true,
    docker_logs_streaming: true,
    docker_stacks: true,
    docker_prune: true,
    cron_write: true,
    backup_download: true,
    backup_restore: true,
    chat_tool_use: true,
    export_config: true,
    export_csv_audit: true,
    http_error_alerts: true,
    ssl_alerts: true,
    email_digest: true,
    monthly_report: true,
    status_page_whitelabel: true,
    api_access: true,
    api_requests_per_hour: 20000,
    users: Infinity,
    groups_per_server: 20,
  },
};
 
// Cache en memoire
let cache = { data: null, loadedAt: 0 };
 
/**
 * Convertit les valeurs -1 du JSONB en Infinity pour le runtime JS.
 * @param {Object} limits
 * @returns {Object}
 */
function normalizeFromDb(limits) {
  const result = {};
  for (const [key, value] of Object.entries(limits)) {
    result[key] = value === -1 ? Infinity : value;
  }
  return result;
}
 
/**
 * Charge les plans depuis la table `plans`.
 * Rafraichit le cache si expire.
 * @returns {Promise<Object>} — { free: {...}, pro: {...}, business: {...} }
 */
async function loadPlans() {
  const now = Date.now();
  if (cache.data && now - cache.loadedAt < CACHE_TTL_MS) {
    return cache.data;
  }
 
  try {
    // Import dynamique pour eviter les dependances circulaires au boot
    const { pool } = require('../db');
    const { rows } = await pool.query('SELECT name, limits FROM plans');
 
    if (rows.length === 0) {
      // Table vide ou pas encore seedee — utiliser les defaults
      cache = { data: DEFAULT_LIMITS, loadedAt: now };
      return DEFAULT_LIMITS;
    }
 
    const plans = {};
    for (const row of rows) {
      plans[row.name] = normalizeFromDb(row.limits);
    }
 
    // S'assurer que les 4 plans existent (merge avec defaults si manquant)
    for (const name of ['free', 'pro', 'business', 'enterprise']) {
      Iif (!plans[name]) {
        plans[name] = DEFAULT_LIMITS[name];
      }
    }
 
    cache = { data: plans, loadedAt: now };
    return plans;
  } catch (err) {
    console.error('[plans] Erreur chargement DB, fallback sur defaults:', err.message);
    // En cas d'erreur DB, utiliser le cache existant ou les defaults
    if (cache.data) return cache.data;
    cache = { data: DEFAULT_LIMITS, loadedAt: now };
    return DEFAULT_LIMITS;
  }
}
 
/**
 * Retourne les limites pour un plan donne.
 * Fallback sur 'free' si le plan est inconnu.
 * @param {string} plan
 * @returns {Promise<Object>}
 */
async function getPlanLimits(plan) {
  const plans = await loadPlans();
  return plans[plan] || plans.free;
}
 
/**
 * Version synchrone — utilise le cache existant (pour les contextes ou async n'est pas possible).
 * Si le cache n'est pas encore charge, retourne les defaults.
 * @param {string} plan
 * @returns {Object}
 */
function getPlanLimitsSync(plan) {
  const plans = cache.data || DEFAULT_LIMITS;
  return plans[plan] || plans.free;
}
 
/**
 * Determine le plan minimum requis pour une feature.
 * @param {string} feature
 * @returns {'free' | 'pro' | 'business'}
 */
function requiredPlanFor(feature) {
  const plans = cache.data || DEFAULT_LIMITS;
  if (plans.free[feature]) return 'free';
  if (plans.pro[feature]) return 'pro';
  if (plans.business[feature]) return 'business';
  return 'enterprise';
}
 
/**
 * Force le rechargement du cache au prochain appel.
 */
function invalidateCache() {
  cache = { data: cache.data, loadedAt: 0 };
}
 
module.exports = { getPlanLimits, getPlanLimitsSync, requiredPlanFor, loadPlans, invalidateCache, DEFAULT_LIMITS };