# All files / controllers PlanLimitsController.js

0% Statements 0/85
0% Branches 0/46
0% Functions 0/4
0% Lines 0/85

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

     /**
     * Plan Limits Controller
     * Provides information about tenant plan limits and current usage
     *
     * @module controllers/PlanLimitsController
     */

    const { pool } = require('../config/database');
    const { logger } = require('../config/logger');
    const { getTenantPlanLimits, getCurrentResourceCount } = require('../middleware/planLimits');

    class PlanLimitsController {
      /**
       * Get tenant plan limits and current usage
       * GET /api/tenant/plan-limits
       */
      static async getLimits(req, res) {
        try {
          const tenantId = req.tenantId || req.user?.tenantId;

          if (!tenantId) {
            return res.status(400).json({
              success: false,
              error: 'Tenant context is required'
            });
          }

          // Get plan limits
          const limits = await getTenantPlanLimits(tenantId);

          // Get current usage for all resources
          const resources = [
            'stores',
            'users',
            'departments',
            'contacts',
            'devices',
            'conversations',
            'faqs',
            'contact_groups'
          ];

          const usage = {};
          for (const resource of resources) {
            try {
              usage[resource] = await getCurrentResourceCount(tenantId, resource);
            } catch (error) {
              logger.warn(`Could not get count for ${resource}`, { error: error.message });
              usage[resource] = 0;
            }
          }

          // Get plan name
          let planName = 'Plano Personalizado';
          if (limits.plan_id) {
            const [plans] = await pool.execute(
              'SELECT name FROM subscription_plans WHERE id = ?',
              [limits.plan_id]
            );
            if (plans.length > 0) {
              planName = plans[0].name;
            }
          }

          // Calculate percentages
          const percentages = {};
          for (const resource of resources) {
            const limitField = `max_${resource}`;
            const max = limits[limitField] || 0;
            const current = usage[resource] || 0;
            percentages[resource] = max > 0 ? Math.round((current / max) * 100) : 0;
          }

          return res.json({
            success: true,
            data: {
              plan: {
                id: limits.plan_id,
                name: planName
              },
              limits: {
                stores: limits.max_stores,
                users: limits.max_users,
                departments: limits.max_departments,
                contacts: limits.max_contacts,
                devices: limits.max_devices,
                conversations: limits.max_conversations,
                messages_per_month: limits.max_messages_per_month,
                faqs: limits.max_faqs,
                contact_groups: limits.max_contact_groups,
                invoices_per_month: limits.max_invoices_per_month,
                quotes_per_month: limits.max_quotes_per_month,
                widgets: limits.max_widgets,
                payment_links_per_month: limits.max_payment_links_per_month
              },
              usage,
              percentages,
              features: {
                invoices: limits.invoices_enabled,
                quotes: limits.quotes_enabled,
                widgets: limits.widgets_enabled,
                payment_links: limits.payment_links_enabled,
                ai: limits.ai_enabled,
                woocommerce: limits.woocommerce_enabled
              }
            }
          });
        } catch (error) {
          logger.error('Error getting plan limits', {
            error: error.message,
            tenantId: req.tenantId
          });

          return res.status(500).json({
            success: false,
            error: 'Erro ao buscar limites do plano',
            message: error.message
          });
        }
      }

      /**
       * Get feature status with addon availability and admin contact
       * GET /api/tenant/feature-status/:feature
       */
      static async getFeatureStatus(req, res) {
        try {
          const tenantId = req.tenantId || req.user?.tenantId;
          const { feature } = req.params;

          logger.info('getFeatureStatus called', { tenantId, feature });

          if (!tenantId) {
            return res.status(400).json({
              success: false,
              error: 'Tenant context is required'
            });
          }

          const validFeatures = ['ai', 'woocommerce', 'mass_send', 'payments', 'invoices', 'quotes', 'widgets', 'payment_links', 'api_access'];
          if (!validFeatures.includes(feature)) {
            return res.status(400).json({
              success: false,
              error: 'Invalid feature'
            });
          }

          // Get plan limits
          let limits;
          try {
            limits = await getTenantPlanLimits(tenantId);
          } catch (limitsError) {
            logger.error('Error getting tenant plan limits', { error: limitsError.message, tenantId });
            // Return default disabled state if we can't get limits
            return res.json({
              success: true,
              data: {
                feature,
                enabled: false,
                canPurchase: false,
                addon: null,
                adminContact: {}
              }
            });
          }

          // Map feature names to enabled fields
          const featureMap = {
            ai: 'ai_enabled',
            woocommerce: 'woocommerce_enabled',
            mass_send: 'ai_enabled', // mass_send uses AI feature flag
            payments: 'payment_links_enabled',
            invoices: 'invoices_enabled',
            quotes: 'quotes_enabled',
            widgets: 'widgets_enabled',
            payment_links: 'payment_links_enabled',
            api_access: 'api_access_enabled'
          };

          const featureField = featureMap[feature];
          const isEnabled = limits[featureField] || false;

          logger.info('Feature status check', { feature, featureField, isEnabled, limits: JSON.stringify(limits) });

          // If feature is enabled, return success
          if (isEnabled) {
            return res.json({
              success: true,
              data: {
                feature,
                enabled: true
              }
            });
          }

          // Feature is disabled - check if addon is available for purchase
          // Map feature names to resource_key in plan_addons table
          const featureToResourceKey = {
            ai: 'ai',
            woocommerce: 'woocommerce',
            mass_send: 'mass_send',
            payments: 'payment_links',
            invoices: 'invoices',
            quotes: 'invoices',
            widgets: 'widgets',
            payment_links: 'payment_links',
            api_access: null
          };

          const resourceKey = featureToResourceKey[feature];

          let addonAvailable = false;
          let addon = null;
          if (resourceKey) {
            try {
              const [addons] = await pool.execute(
                `SELECT id, resource_name as name, unit_price, description
                 FROM plan_addons
                 WHERE resource_key = ? AND active = TRUE
                 LIMIT 1`,
                [resourceKey]
              );
              addonAvailable = addons.length > 0;
              addon = addonAvailable ? addons[0] : null;
            } catch (addonError) {
              logger.warn('Could not check addons table', { error: addonError.message });
            }
          }

          // Get superadmin contact info from system settings (with error handling)
          const adminContact = {};
          try {
            const [settings] = await pool.execute(
              `SELECT setting_key, setting_value
               FROM system_settings
               WHERE setting_key IN ('support_email', 'support_phone', 'company_name')`
            );
            settings.forEach(s => {
              adminContact[s.setting_key] = s.setting_value;
            });
          } catch (settingsError) {
            logger.warn('Could not get system settings', { error: settingsError.message });
          }

          return res.json({
            success: true,
            data: {
              feature,
              enabled: false,
              canPurchase: addonAvailable,
              addon: addon ? {
                id: addon.id,
                name: addon.name,
                price: addon.unit_price,
                description: addon.description
              } : null,
              adminContact: {
                email: adminContact.support_email || null,
                phone: adminContact.support_phone || null,
                company: adminContact.company_name || null
              }
            }
          });
        } catch (error) {
          logger.error('Error getting feature status', {
            error: error.message,
            feature: req.params.feature,
            tenantId: req.tenantId
          });

          return res.status(500).json({
            success: false,
            error: 'Error checking feature status',
            message: error.message
          });
        }
      }

      /**
       * Get specific resource usage
       * GET /api/tenant/plan-limits/:resource
       */
      static async getResourceUsage(req, res) {
        try {
          const tenantId = req.tenantId || req.user?.tenantId;
          const { resource } = req.params;

          if (!tenantId) {
            return res.status(400).json({
              success: false,
              error: 'Tenant context is required'
            });
          }

          const validResources = [
            'stores',
            'users',
            'departments',
            'contacts',
            'devices',
            'conversations',
            'faqs',
            'contact_groups',
            'invoices',
            'quotes',
            'widgets',
            'payment_links'
          ];

          if (!validResources.includes(resource)) {
            return res.status(400).json({
              success: false,
              error: 'Invalid resource'
            });
          }

          // Get plan limits
          const limits = await getTenantPlanLimits(tenantId);
          const limitField = `max_${resource}`;
          const maxAllowed = limits[limitField] || 0;

          // Get current usage
          const current = await getCurrentResourceCount(tenantId, resource);
          const percentage = maxAllowed > 0 ? Math.round((current / maxAllowed) * 100) : 0;
          const remaining = Math.max(0, maxAllowed - current);

          return res.json({
            success: true,
            data: {
              resource,
              current,
              max: maxAllowed,
              remaining,
              percentage,
              canCreate: current < maxAllowed
            }
          });
        } catch (error) {
          logger.error('Error getting resource usage', {
            error: error.message,
            resource: req.params.resource,
            tenantId: req.tenantId
          });

          return res.status(500).json({
            success: false,
            error: 'Erro ao buscar uso do recurso',
            message: error.message
          });
        }
      }
    }

    module.exports = PlanLimitsController;