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

11.37% Statements 29/255
50% Branches 1/2
0% Functions 0/2
11.37% Lines 29/255

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 2561x 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 1x  
const express = require('express');
const path = require('path');
const OrganizationPlan = require('../models/OrganizationPlan');
const Membership = require('../models/Membership');
const User = require('../models/User');
const UsageTracking = require('../models/UsageTracking');
 
const router = express.Router();
const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:5173';
 
const { getBestPlan, getPlans } = require('../services/planResolver');
 
function getStripe() {
  if (!process.env.STRIPE_SECRET_KEY) return null;
  return require('stripe')(process.env.STRIPE_SECRET_KEY);
}
 
async function getMembershipRole(userId, organizationId) {
  const membership = await Membership.findOne({ userId, organizationId });
  return membership?.role || null;
}
 
 
 
router.get('/organizations/:id/subscription', async (req, res) => {
  try {
    const orgPlan = await OrganizationPlan.findOne({ organizationId: req.params.id });
    if (!orgPlan) return res.status(404).json({ success: false, message: 'Subscription not found' });

    // Syncer status/periodes avec Stripe sans toucher au planCode
    const stripe = getStripe();
    if (orgPlan.stripeCustomerId && stripe && orgPlan.stripeSubscriptionId) {
      try {
        const stripeSub = await stripe.subscriptions.retrieve(orgPlan.stripeSubscriptionId);
        if (stripeSub.status !== orgPlan.status || new Date(stripeSub.current_period_end * 1000).getTime() !== orgPlan.currentPeriodEnd?.getTime()) {
          orgPlan.status = stripeSub.status;
          orgPlan.currentPeriodEnd = new Date(stripeSub.current_period_end * 1000);
          await orgPlan.save();
        }
      } catch {}
    }

    const best = await getBestPlan(orgPlan);
    const allPlans = getPlans();

    // Liste de tous les abonnements Stripe
    let stripeSubscriptions = [];
    if (orgPlan.stripeCustomerId && stripe) {
      try {
        const allSubs = await stripe.subscriptions.list({ customer: orgPlan.stripeCustomerId, limit: 10, status: 'all' });
        stripeSubscriptions = allSubs.data
          .filter(s => s.status !== 'canceled' && s.status !== 'incomplete_expired')
          .map(s => {
            const priceId = s.items.data[0]?.price?.id;
            const p = allPlans.find(pl => pl.stripePriceId === priceId);
            return {
              id: s.id, planCode: p?.code || null, planName: p?.name || 'Inconnu',
              price: p?.displayPrice?.amount || null, status: s.status,
              cancelAtPeriodEnd: s.cancel_at_period_end,
              currentPeriodEnd: new Date(s.current_period_end * 1000).toISOString(),
              currentPeriodStart: new Date(s.current_period_start * 1000).toISOString(),
              limits: p?.limits || null,
            };
          });
      } catch {}
    }

    // Plan en cours (stocké en base, ou forcé par admin pour specific_limit)
    const storedPlan = allPlans.find(p => p.code === orgPlan.planCode);
    const currentPlan = orgPlan.planCode === 'specific_limit'
      ? { code: 'specific_limit', name: 'Sur mesure', limits: orgPlan.customLimits || {}, billingType: 'custom' }
      : storedPlan ? { code: storedPlan.code, name: storedPlan.name, limits: storedPlan.limits, billingType: storedPlan.billingType } : null;

    // Meilleur plan actif (depuis Stripe, pour les limites de consommation)
    const bestActivePlan = best.plan ? { code: best.code, name: best.plan.name, limits: best.code === 'specific_limit' ? (orgPlan.customLimits || {}) : best.plan.limits } : null;

    res.json({
      success: true,
      data: {
        organizationPlan: orgPlan.toJSON(),
        currentPlan,
        activePlans: stripeSubscriptions,
        bestActivePlan,
      },
    });
  } catch (error) {
    console.error('[Subscription] Error getting subscription:', error.message);
    res.status(500).json({ success: false, message: 'Error getting subscription' });
  }
});
 
router.post('/organizations/:id/subscriptions', async (req, res) => {
  try {
    const role = await getMembershipRole(req.user._id, req.params.id);
    if (role !== 'owner') {
      return res.status(403).json({ success: false, message: 'Only owners can manage subscriptions' });
    }

    const { planCode } = req.body;
    const plan = getPlans().find(p => p.code === planCode && p.billingType === 'stripe_paid');
    if (!plan || !plan.stripePriceId) {
      return res.status(400).json({ success: false, message: 'Invalid or non-billable plan' });
    }

    // Plans non-publics (ex: offre de test) réservés aux administrateurs
    if (!plan.isPublic && req.user.role !== 'admin') {
      return res.status(403).json({ success: false, message: 'This plan is restricted to administrators' });
    }

    const stripe = getStripe();
    if (!stripe) {
      return res.status(500).json({ success: false, message: 'Stripe not configured' });
    }

    let orgPlan = await OrganizationPlan.findOne({ organizationId: req.params.id });
    let stripeCustomerId = orgPlan?.stripeCustomerId;

    if (!stripeCustomerId) {
      const user = await User.findById(req.user._id);
      const customer = await stripe.customers.create({
        email: user.email,
        name: user.name,
        metadata: { organizationId: req.params.id.toString() },
      });
      stripeCustomerId = customer.id;
      await OrganizationPlan.findOneAndUpdate(
        { organizationId: req.params.id },
        { $set: { stripeCustomerId: customer.id } },
        { upsert: true }
      );
    }

    // Annuler les anciens abonnements Stripe actifs avant d'en créer un nouveau
    const subsToCancel = [];
    if (orgPlan?.stripeSubscriptionId) subsToCancel.push(orgPlan.stripeSubscriptionId);
    if (stripeCustomerId) {
      try {
        const activeSubs = await stripe.subscriptions.list({ customer: stripeCustomerId, limit: 10, status: 'all' });
        for (const sub of activeSubs.data) {
          if (sub.status !== 'canceled' && !subsToCancel.includes(sub.id)) subsToCancel.push(sub.id);
        }
      } catch {}
    }
    for (const subId of subsToCancel) {
      try {
        await stripe.subscriptions.update(subId, { cancel_at_period_end: true });
      } catch (err) {
        console.warn('[Subscription] Failed to cancel subscription ' + subId + ':', err.message);
      }
    }

    const session = await stripe.checkout.sessions.create({
      customer: stripeCustomerId,
      line_items: [{ price: plan.stripePriceId, quantity: 1 }],
      mode: 'subscription',
      allow_promotion_codes: true,
      tax_id_collection: { enabled: true },
      customer_update: {
        name: 'auto',
        address: 'auto',
      },
      metadata: {
        organizationId: req.params.id.toString(),
        planCode: plan.code,
      },
      success_url: `${FRONTEND_URL}/${req.params.id}/backoffice/subscription`,
      cancel_url: `${FRONTEND_URL}/${req.params.id}/backoffice/subscription`,
    });

    // Le plan est changé UNIQUEMENT à la confirmation Stripe (webhook
    // checkout.session.completed), pour éviter qu'un abonnement annulé
    // (retour arrière, paiement refusé) soit considéré comme pris.
    res.json({ success: true, data: { url: session.url } });
  } catch (error) {
    console.error('[Subscription] Error creating checkout session:', error.message);
    res.status(500).json({ success: false, message: 'Error creating checkout session' });
  }
});
 
router.post('/organizations/:id/subscriptions/portal', async (req, res) => {
  try {
    const role = await getMembershipRole(req.user._id, req.params.id);
    if (role !== 'owner') {
      return res.status(403).json({ success: false, message: 'Only owners can manage subscriptions' });
    }

    const stripe = getStripe();
    if (!stripe) {
      return res.status(500).json({ success: false, message: 'Stripe not configured' });
    }

    const orgPlan = await OrganizationPlan.findOne({ organizationId: req.params.id });
    if (!orgPlan || !orgPlan.stripeCustomerId) {
      return res.status(400).json({ success: false, message: 'No active subscription to manage' });
    }

    const session = await stripe.billingPortal.sessions.create({
      customer: orgPlan.stripeCustomerId,
      return_url: `${FRONTEND_URL}/${req.params.id}/backoffice/subscription`,
    });

    res.json({ success: true, data: { url: session.url } });
  } catch (error) {
    console.error('[Subscription] Error creating portal session:', error.message);
    res.status(500).json({ success: false, message: 'Error creating portal session' });
  }
});
 
router.delete('/organizations/:id/subscriptions', async (req, res) => {
  try {
    const role = await getMembershipRole(req.user._id, req.params.id);
    if (role !== 'owner') {
      return res.status(403).json({ success: false, message: 'Only owners can manage subscriptions' });
    }

    const stripe = getStripe();
    if (!stripe) {
      return res.status(500).json({ success: false, message: 'Stripe not configured' });
    }

    const orgPlan = await OrganizationPlan.findOne({ organizationId: req.params.id });
    if (!orgPlan || !orgPlan.stripeCustomerId) {
      return res.status(400).json({ success: false, message: 'No active subscription to cancel' });
    }

    if (stripe) {
      const subs = await stripe.subscriptions.list({ customer: orgPlan.stripeCustomerId, limit: 10, status: 'all' });
      for (const sub of subs.data) {
        if (sub.status !== 'canceled') {
          await stripe.subscriptions.cancel(sub.id);
        }
      }
    }

    orgPlan.stripeSubscriptionId = null;
    orgPlan.planCode = 'free';
    orgPlan.currentPeriodStart = new Date();
    orgPlan.currentPeriodEnd = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
    await orgPlan.save();

    // Réinitialiser le compteur d'usage pour la nouvelle période free
    await UsageTracking.findOneAndUpdate(
      { organizationId: orgPlan.organizationId, periodStart: orgPlan.currentPeriodStart },
      { $set: { llmCostUsed: 0, ocrCostUsed: 0 } },
      { upsert: true }
    );

    res.json({ success: true, message: 'Subscription cancelled, returning to free plan' });
  } catch (error) {
    console.error('[Subscription] Error cancelling subscription:', error.message);
    res.status(500).json({ success: false, message: 'Error cancelling subscription' });
  }
});
 
module.exports = router;