All files / src/routes billing.js

0% Statements 0/156
0% Branches 0/92
0% Functions 0/18
0% Lines 0/150

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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * Routes Billing — Gestion des abonnements Stripe.
 *
 * Routes protegees :
 *   GET  /billing/status      — Statut de l'abonnement actuel
 *   POST /billing/checkout     — Creer une session Stripe Checkout
 *   POST /billing/portal       — Ouvrir le portail client Stripe
 *   GET  /billing/plans        — Lister les plans disponibles (public)
 *
 * Route publique (sans auth, verifiee par signature Stripe) :
 *   POST /billing/webhook      — Recevoir les evenements Stripe
 *
 * @module routes/billing
 */
 
const express = require('express');
const { pool: db } = require('../db');
const { requireAuth } = require('../middleware/auth');
const { getPlanLimits } = require('../config/plans');
 
const router = express.Router();
 
/**
 * Extrait les dates de periode d'un objet subscription Stripe.
 * L'API Stripe recente met ces champs sur les items, pas sur la subscription.
 */
function getSubPeriod(sub) {
  const item = sub.items?.data?.[0];
  return {
    start: sub.current_period_start || item?.current_period_start || null,
    end: sub.current_period_end || sub.cancel_at || item?.current_period_end || null,
  };
}
 
// Stripe est optionnel — si pas configure, les routes retournent une erreur claire
let stripe = null;
if (process.env.STRIPE_SECRET_KEY) {
  stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
}
 
const STRIPE_PRICES = {
  pro_monthly: process.env.STRIPE_PRICE_PRO_MONTHLY,
  pro_yearly: process.env.STRIPE_PRICE_PRO_YEARLY,
  business_monthly: process.env.STRIPE_PRICE_BUSINESS_MONTHLY,
  business_yearly: process.env.STRIPE_PRICE_BUSINESS_YEARLY,
  enterprise_monthly: process.env.STRIPE_PRICE_ENTERPRISE_MONTHLY,
  enterprise_yearly: process.env.STRIPE_PRICE_ENTERPRISE_YEARLY,
};
 
// ─── GET /billing/plans — liste publique des plans (pas d'auth) ─────────────
 
router.get('/plans', async (_req, res, next) => {
  try {
    const [free, pro, business, enterprise] = await Promise.all([
      getPlanLimits('free'),
      getPlanLimits('pro'),
      getPlanLimits('business'),
      getPlanLimits('enterprise'),
    ]);
 
    // Convertir Infinity en -1 pour le JSON
    const toJson = (limits) => {
      const result = {};
      for (const [k, v] of Object.entries(limits)) {
        result[k] = v === Infinity ? -1 : v;
      }
      return result;
    };
 
    res.json({
      plans: [
        { id: 'free', name: 'Free', price_monthly: 0, price_yearly: 0, limits: toJson(free) },
        { id: 'pro', name: 'Pro', price_monthly: 12, price_yearly: 99, limits: toJson(pro) },
        { id: 'business', name: 'Business', price_monthly: 35, price_yearly: 299, limits: toJson(business) },
        { id: 'enterprise', name: 'Enterprise', price_monthly: 99, price_yearly: 899, limits: toJson(enterprise) },
      ],
    });
  } catch (err) {
    next(err);
  }
});
 
// ─── POST /billing/webhook — Stripe webhook (sans auth, signature Stripe) ───
 
/**
 * Determine le plan a partir d'un price ID Stripe.
 * @param {string} priceId
 * @returns {string}
 */
function planFromPriceId(priceId) {
  if (priceId === STRIPE_PRICES.pro_monthly || priceId === STRIPE_PRICES.pro_yearly) return 'pro';
  if (priceId === STRIPE_PRICES.business_monthly || priceId === STRIPE_PRICES.business_yearly) return 'business';
  if (priceId === STRIPE_PRICES.enterprise_monthly || priceId === STRIPE_PRICES.enterprise_yearly) return 'enterprise';
  return 'free';
}
 
/** Handler : checkout.session.completed */
async function handleCheckoutCompleted(session) {
  const userId = session.metadata?.user_id;
  const plan = session.metadata?.plan || 'pro';
  if (!userId) return;
 
  const subscription = await stripe.subscriptions.retrieve(session.subscription);
 
  await db.query(
    `INSERT INTO subscriptions (user_id, stripe_customer_id, stripe_subscription_id, stripe_price_id, plan, status, current_period_start, current_period_end)
     VALUES ($1, $2, $3, $4, $5, 'active', to_timestamp($6), to_timestamp($7))
     ON CONFLICT (user_id) DO UPDATE SET
       stripe_customer_id = $2, stripe_subscription_id = $3, stripe_price_id = $4,
       plan = $5, status = 'active',
       current_period_start = to_timestamp($6), current_period_end = to_timestamp($7),
       updated_at = NOW()`,
    [userId, session.customer, session.subscription, subscription.items.data[0]?.price?.id,
      plan, getSubPeriod(subscription).start, getSubPeriod(subscription).end],
  );
 
  await db.query('UPDATE users SET plan = $1 WHERE id = $2', [plan, userId]);
  console.log(`[billing] Checkout complete: user ${userId} → ${plan}`);
}
 
/** Handler : invoice.paid / invoice.payment_failed */
async function handleInvoiceEvent(invoice, status) {
  if (!invoice.subscription) return;
  await db.query(
    `UPDATE subscriptions SET status = $1, updated_at = NOW()
     WHERE stripe_subscription_id = $2`,
    [status, invoice.subscription],
  );
  if (status === 'past_due') {
    console.log(`[billing] Paiement echoue: subscription ${invoice.subscription}`);
  }
}
 
/** Handler : customer.subscription.updated */
async function handleSubscriptionUpdated(sub) {
  const { rows: subRows } = await db.query(
    'SELECT user_id FROM subscriptions WHERE stripe_subscription_id = $1',
    [sub.id],
  );
  if (subRows.length === 0) {
    console.log(`[billing] Webhook ignore : subscription ${sub.id} inconnue`);
    return;
  }
 
  const priceId = sub.items.data[0]?.price?.id;
  const plan = planFromPriceId(priceId);
 
  await db.query(
    `UPDATE subscriptions SET plan = $1, status = $2, stripe_price_id = $3,
     current_period_start = to_timestamp($4), current_period_end = to_timestamp($5),
     cancel_at_period_end = $6, updated_at = NOW()
     WHERE stripe_subscription_id = $7`,
    [plan, sub.status, priceId, getSubPeriod(sub).start, getSubPeriod(sub).end,
      sub.cancel_at_period_end, sub.id],
  );
 
  await db.query('UPDATE users SET plan = $1 WHERE id = $2', [plan, subRows[0].user_id]);
  console.log(`[billing] Subscription updated : user ${subRows[0].user_id} → ${plan} (status: ${sub.status}, cancel: ${sub.cancel_at_period_end})`);
}
 
/** Handler : customer.subscription.deleted */
async function handleSubscriptionDeleted(sub) {
  const { rows } = await db.query(
    'SELECT user_id FROM subscriptions WHERE stripe_subscription_id = $1',
    [sub.id],
  );
  if (rows.length === 0) return;
 
  await db.query('UPDATE users SET plan = $1 WHERE id = $2', ['free', rows[0].user_id]);
  await db.query(
    `UPDATE subscriptions SET plan = 'free', status = 'canceled', updated_at = NOW()
     WHERE stripe_subscription_id = $1`,
    [sub.id],
  );
  console.log(`[billing] Subscription annulee: user ${rows[0].user_id} → free`);
}
 
/** Map des handlers de webhook par type d'evenement. */
const WEBHOOK_HANDLERS = {
  'checkout.session.completed': (data) => handleCheckoutCompleted(data),
  'invoice.paid': (data) => handleInvoiceEvent(data, 'active'),
  'invoice.payment_failed': (data) => handleInvoiceEvent(data, 'past_due'),
  'customer.subscription.updated': (data) => handleSubscriptionUpdated(data),
  'customer.subscription.deleted': (data) => handleSubscriptionDeleted(data),
};
 
router.post('/webhook', async (req, res) => {
  if (!stripe || !process.env.STRIPE_WEBHOOK_SECRET) {
    return res.status(503).json({ error: 'Stripe non configure.' });
  }
 
  let event;
  try {
    const sig = req.headers['stripe-signature'];
    event = stripe.webhooks.constructEvent(req.body, sig, process.env.STRIPE_WEBHOOK_SECRET);
  } catch (err) {
    console.error('[billing] Signature webhook invalide:', err.message);
    return res.status(400).json({ error: 'Signature invalide.' });
  }
 
  try {
    const handler = WEBHOOK_HANDLERS[event.type];
    if (handler) {
      await handler(event.data.object);
    }
  } catch (err) {
    console.error('[billing] Erreur traitement webhook:', err.message);
  }
 
  res.json({ received: true });
});
 
// ─── Routes protegees ───────────────────────────────────────────────────────
 
router.use(requireAuth);
 
// ─── GET /billing/status ────────────────────────────────────────────────────
 
router.get('/status', async (req, res, next) => {
  try {
    // En mode groupe, retourner le plan du proprietaire du groupe
    const groupId = req.headers['x-group-id'];
    let effectiveUserId = req.user.id;
    let effectivePlan = req.user.plan || 'free';
 
    if (groupId) {
      const { rows: groupRows } = await db.query(
        'SELECT owner_user_id FROM access_groups WHERE id = $1',
        [groupId],
      );
      if (groupRows.length > 0 && groupRows[0].owner_user_id !== req.user.id) {
        effectiveUserId = groupRows[0].owner_user_id;
        const { rows: ownerRows } = await db.query('SELECT plan FROM users WHERE id = $1', [effectiveUserId]);
        effectivePlan = ownerRows[0]?.plan || 'free';
      }
    }
 
    const { rows } = await db.query(
      'SELECT * FROM subscriptions WHERE user_id = $1',
      [effectiveUserId],
    );
 
    const subscription = rows[0] || null;
    const plan = effectivePlan;
    const limits = await getPlanLimits(plan);
 
    // Convertir Infinity en -1 pour le JSON (JSON ne supporte pas Infinity)
    const jsonLimits = {};
    for (const [key, value] of Object.entries(limits)) {
      jsonLimits[key] = value === Infinity ? -1 : value;
    }
 
    res.json({
      plan,
      subscription,
      limits: jsonLimits,
    });
  } catch (err) {
    next(err);
  }
});
 
// ─── POST /billing/checkout ─────────────────────────────────────────────────
// Si l'utilisateur a deja un abonnement actif → migration avec prorata
// Sinon → nouveau checkout Stripe
 
router.post('/checkout', async (req, res, next) => {
  if (!stripe) {
    return res.status(503).json({ error: 'Stripe non configure.' });
  }
 
  try {
    const { plan, interval = 'monthly' } = req.body;
 
    if (!['pro', 'business', 'enterprise'].includes(plan)) {
      return res.status(400).json({ error: 'Plan invalide (pro, business ou enterprise).' });
    }
    if (!['monthly', 'yearly'].includes(interval)) {
      return res.status(400).json({ error: 'Intervalle invalide (monthly ou yearly).' });
    }
 
    const priceId = STRIPE_PRICES[`${plan}_${interval}`];
    if (!priceId) {
      return res.status(500).json({ error: 'Price ID Stripe non configure pour ce plan.' });
    }
 
    // Verifier si l'utilisateur a deja un abonnement actif
    const { rows } = await db.query(
      'SELECT stripe_customer_id, stripe_subscription_id, status FROM subscriptions WHERE user_id = $1',
      [req.user.id],
    );
 
    const existingSub = rows[0];
 
    // ─── Migration d'un abonnement existant (upgrade/downgrade avec prorata) ──
    if (existingSub?.stripe_subscription_id && existingSub.status === 'active') {
      const subscription = await stripe.subscriptions.retrieve(existingSub.stripe_subscription_id);
      const itemId = subscription.items.data[0]?.id;
 
      if (!itemId) {
        return res.status(500).json({ error: 'Abonnement Stripe corrompu — contactez le support.' });
      }
 
      // Si annulation en cours, l'annuler d'abord pour pouvoir migrer
      if (subscription.cancel_at_period_end) {
        await stripe.subscriptions.update(existingSub.stripe_subscription_id, {
          cancel_at_period_end: false,
        });
      }
 
      // Modifier l'abonnement avec prorata immediat
      const updated = await stripe.subscriptions.update(existingSub.stripe_subscription_id, {
        items: [{ id: itemId, price: priceId }],
        proration_behavior: 'create_prorations',
      });
 
      // Mettre a jour la DB (reset cancel_at_period_end)
      await db.query(
        `UPDATE subscriptions SET plan = $1, stripe_price_id = $2, status = 'active',
         cancel_at_period_end = FALSE,
         current_period_start = to_timestamp($3), current_period_end = to_timestamp($4), updated_at = NOW()
         WHERE user_id = $5`,
        [plan, priceId, getSubPeriod(updated).start, getSubPeriod(updated).end, req.user.id],
      );
      await db.query('UPDATE users SET plan = $1 WHERE id = $2', [plan, req.user.id]);
 
      console.log(`[billing] Migration : user ${req.user.id} → ${plan} (prorata)`);
      return res.json({ migrated: true, plan });
    }
 
    // ─── Nouveau checkout (pas d'abonnement existant) ──────────────────────────
    let customerId;
    if (existingSub?.stripe_customer_id) {
      customerId = existingSub.stripe_customer_id;
    } else {
      const customer = await stripe.customers.create({
        email: req.user.email,
        metadata: { user_id: req.user.id },
      });
      customerId = customer.id;
    }
 
    const origin = process.env.CORS_ORIGIN || 'http://localhost:5173';
    const session = await stripe.checkout.sessions.create({
      customer: customerId,
      mode: 'subscription',
      line_items: [{ price: priceId, quantity: 1 }],
      success_url: `${origin}/settings?billing=success`,
      cancel_url: `${origin}/settings?billing=cancel`,
      metadata: { user_id: req.user.id, plan },
    });
 
    res.json({ url: session.url });
  } catch (err) {
    next(err);
  }
});
 
// ─── POST /billing/portal ───────────────────────────────────────────────────
 
router.post('/portal', async (req, res, next) => {
  if (!stripe) {
    return res.status(503).json({ error: 'Stripe non configure.' });
  }
 
  try {
    const { rows } = await db.query(
      'SELECT stripe_customer_id FROM subscriptions WHERE user_id = $1',
      [req.user.id],
    );
 
    if (rows.length === 0 || !rows[0].stripe_customer_id) {
      return res.status(404).json({ error: 'Aucun abonnement actif.' });
    }
 
    const origin = process.env.CORS_ORIGIN || 'http://localhost:5173';
    const session = await stripe.billingPortal.sessions.create({
      customer: rows[0].stripe_customer_id,
      return_url: `${origin}/settings`,
    });
 
    res.json({ url: session.url });
  } catch (err) {
    next(err);
  }
});
 
// ─── POST /billing/cancel — annuler l'abonnement (fin de periode) ───────────
 
router.post('/cancel', async (req, res, next) => {
  if (!stripe) {
    return res.status(503).json({ error: 'Stripe non configure.' });
  }
 
  try {
    const { rows } = await db.query(
      'SELECT stripe_subscription_id FROM subscriptions WHERE user_id = $1',
      [req.user.id],
    );
 
    if (rows.length === 0 || !rows[0].stripe_subscription_id) {
      return res.status(404).json({ error: 'Aucun abonnement actif.' });
    }
 
    // Annuler a la fin de la periode (pas immediatement)
    const updated = await stripe.subscriptions.update(rows[0].stripe_subscription_id, {
      cancel_at_period_end: true,
    });
 
    await db.query(
      `UPDATE subscriptions SET cancel_at_period_end = TRUE,
       current_period_end = to_timestamp($1), updated_at = NOW()
       WHERE user_id = $2`,
      [getSubPeriod(updated).end, req.user.id],
    );
 
    const endDate = getSubPeriod(updated).end;
    console.log(`[billing] Annulation programmee : user ${req.user.id} (fin le ${endDate ? new Date(endDate * 1000).toLocaleDateString('fr-FR') : '?'})`);
    res.json({ message: 'Abonnement annule. Votre plan restera actif jusqu\'a la fin de la periode.' });
  } catch (err) {
    next(err);
  }
});
 
module.exports = router;