# All files / controllers SuperAdminPlanController.js

0% Statements 0/146
0% Branches 0/129
0% Functions 0/6
0% Lines 0/146

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
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443

     /**
     * Super Admin Plan Controller
     * Manages subscription plans
     */

    const BaseController = require('./BaseController');
    const { pool } = require('../config/database');
    const { logger } = require('../config/logger');
    const i18n = require('../services/TranslationService');

    class SuperAdminPlanController extends BaseController {
      /**
       * Get all subscription plans
       * GET /api/superadmin/plans
       */
      static async getAllPlans(req, res) {
        try {
          const [plans] = await pool.execute(
            `SELECT
               sp.*,
               (SELECT COUNT(*) FROM tenants t WHERE t.plan_id = sp.id AND t.id != 0) AS tenant_count
             FROM subscription_plans sp
             ORDER BY sp.sort_order, sp.price`
          );

          return res.json({
            success: true,
            data: plans
          });
        } catch (error) {
          logger.error('Error getting plans', { error: error.message });
          return res.status(500).json({
            success: false,
            message: 'Error loading plans'
          });
        }
      }

      /**
       * Get plan by ID
       * GET /api/superadmin/plans/:id
       */
      static async getPlanById(req, res) {
        try {
          const { id } = req.params;

          const [plans] = await pool.execute(
            'SELECT * FROM subscription_plans WHERE id = ?',
            [id]
          );

          if (plans.length === 0) {
            return res.status(404).json({
              success: false,
              message: 'Plan not found'
            });
          }

          return res.json({
            success: true,
            data: plans[0]
          });
        } catch (error) {
          logger.error('Error getting plan', { error: error.message });
          return res.status(500).json({
            success: false,
            message: 'Error loading plan'
          });
        }
      }

      /**
       * Create new subscription plan
       * POST /api/superadmin/plans
       */
      static async createPlan(req, res) {
        try {
          console.log('=== CREATE PLAN DEBUG ===');
          console.log('Body:', JSON.stringify(req.body, null, 2));
          console.log('Content-Type:', req.headers['content-type']);

          logger.info('Creating plan - Request details:', {
            body: req.body,
            headers: req.headers['content-type'],
            method: req.method
          });

          // Extract and convert values
          const name = req.body.name;
          const description = req.body.description;
          const price = req.body.price !== undefined ? parseFloat(req.body.price) : undefined;
          const currency = req.body.currency;
          const billing_period = req.body.billing_period || 'monthly';
          const max_stores = parseInt(req.body.max_stores) || 1;
          const max_users = parseInt(req.body.max_users) || 5;
          const max_departments = parseInt(req.body.max_departments) || 5;
          const max_contacts = parseInt(req.body.max_contacts) || 1000;
          const max_devices = parseInt(req.body.max_devices) || 1;
          const max_whatsapp_instances = parseInt(req.body.max_whatsapp_instances) || 1;
          const max_conversations = parseInt(req.body.max_conversations) || 1000;
          const max_messages_per_month = parseInt(req.body.max_messages_per_month) || 10000;
          const max_faqs = parseInt(req.body.max_faqs) || 10;
          const max_contact_groups = parseInt(req.body.max_contact_groups) || 10;
          const whatsapp_enabled = req.body.whatsapp_enabled === true || req.body.whatsapp_enabled === 'true';
          const ai_enabled = req.body.ai_enabled === true || req.body.ai_enabled === 'true';
          const woocommerce_enabled = req.body.woocommerce_enabled === true || req.body.woocommerce_enabled === 'true';
          const analytics_enabled = req.body.analytics_enabled === true || req.body.analytics_enabled === 'true';
          const priority_support_enabled = req.body.priority_support_enabled === true || req.body.priority_support_enabled === 'true';
          const api_access_enabled = req.body.api_access_enabled === true || req.body.api_access_enabled === 'true';
          const custom_branding_enabled = req.body.custom_branding_enabled === true || req.body.custom_branding_enabled === 'true';
          const invoices_enabled = req.body.invoices_enabled === true || req.body.invoices_enabled === 'true';
          const max_invoices_per_month = parseInt(req.body.max_invoices_per_month) || 0;
          const quotes_enabled = req.body.quotes_enabled === true || req.body.quotes_enabled === 'true';
          const max_quotes_per_month = parseInt(req.body.max_quotes_per_month) || 0;
          const widgets_enabled = req.body.widgets_enabled === true || req.body.widgets_enabled === 'true';
          const max_widgets = parseInt(req.body.max_widgets) || 0;
          const payment_links_enabled = req.body.payment_links_enabled === true || req.body.payment_links_enabled === 'true';
          const max_payment_links_per_month = parseInt(req.body.max_payment_links_per_month) || 0;
          const max_email_accounts = parseInt(req.body.max_email_accounts) || 0;
          const max_emails_per_month = parseInt(req.body.max_emails_per_month) || 0;
          const max_omnichannel_accounts = parseInt(req.body.max_omnichannel_accounts) || 0;

          // Bio Link fields
          const biolink_enabled = req.body.biolink_enabled === true || req.body.biolink_enabled === 'true';
          const max_bio_pages = parseInt(req.body.max_bio_pages) || 0;
          const max_short_links = parseInt(req.body.max_short_links) || 0;
          const max_file_transfers = parseInt(req.body.max_file_transfers) || 0;
          const max_vcards = parseInt(req.body.max_vcards) || 0;
          const max_event_links = parseInt(req.body.max_event_links) || 0;
          const max_html_pages = parseInt(req.body.max_html_pages) || 0;
          const max_qr_codes = parseInt(req.body.max_qr_codes) || 0;

          const pix_enabled = req.body.pix_enabled === true || req.body.pix_enabled === 'true';
          const cash_enabled = req.body.cash_enabled === true || req.body.cash_enabled === 'true';

          const is_trial = req.body.is_trial === true || req.body.is_trial === 'true';
          const trial_days = parseInt(req.body.trial_days) || 0;
          const is_free = req.body.is_free === true || req.body.is_free === 'true';
          const stripe_price_id = req.body.stripe_price_id;
          const paypal_plan_id = req.body.paypal_plan_id;
          const sort_order = parseInt(req.body.sort_order) || 0;

          logger.info('Extracted values:', { name, price, priceType: typeof price });
          console.log('=== EXTRACTED VALUES ===');
          console.log('Name:', name);
          console.log('Price:', price, 'Type:', typeof price);
          console.log('Is NaN:', isNaN(price));

          // Validation
          if (!name || price === undefined || isNaN(price)) {
            logger.warn('Plan creation validation failed', {
              name,
              price,
              nameExists: !!name,
              priceExists: price !== undefined,
              priceIsNaN: isNaN(price)
            });
            return res.status(400).json({
              success: false,
              message: 'Name and valid price are required',
              debug: {
                name: name || 'missing',
                price: price === undefined ? 'undefined' : price,
                priceIsNaN: isNaN(price)
              }
            });
          }

          // Check if only one free plan exists
          if (is_free) {
            const [freePlans] = await pool.execute(
              'SELECT id, name FROM subscription_plans WHERE is_free = TRUE'
            );
            if (freePlans.length > 0) {
              logger.warn('Attempt to create second free plan', { existingPlan: freePlans[0] });
              return res.status(400).json({
                success: false,
                message: `Only one free plan is allowed. A free plan already exists: "${freePlans[0].name}". Please uncheck "Free Plan" or edit the existing free plan.`
              });
            }
          }

          let resolvedCurrency = currency;
          if (!resolvedCurrency) {
            const [defaultCurrencyRows] = await pool.execute(
              'SELECT code FROM currencies WHERE is_default = TRUE AND active = TRUE ORDER BY id LIMIT 1'
            );
            resolvedCurrency = defaultCurrencyRows?.[0]?.code || 'USD';
          }

          const [result] = await pool.execute(
            `INSERT INTO subscription_plans (
              name, description, price, currency, billing_period,
              max_stores, max_users, max_departments, max_contacts, max_devices, max_whatsapp_instances,
              max_whatsapp_cloud_accounts,
              max_conversations, max_messages_per_month, max_contact_groups, max_faqs,
              max_widgets, max_invoices_per_month, max_quotes_per_month, max_payment_links_per_month,
              max_email_accounts, max_emails_per_month, max_omnichannel_accounts,
              whatsapp_enabled, ai_enabled, woocommerce_enabled, analytics_enabled,
              priority_support_enabled, api_access_enabled, custom_branding_enabled,
              invoices_enabled, quotes_enabled, widgets_enabled, payment_links_enabled,
              biolink_enabled, max_bio_pages, max_short_links, max_file_transfers,
              max_vcards, max_event_links, max_html_pages, max_qr_codes,
              pix_enabled, cash_enabled,
              is_trial, trial_days, is_free,
              stripe_price_id, paypal_plan_id, sort_order
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [
              name, description, price, resolvedCurrency, billing_period,
              max_stores, max_users, max_departments, max_contacts, max_devices, max_whatsapp_instances,
              max_whatsapp_instances, // Use same value as max_whatsapp_instances by default
              max_conversations, max_messages_per_month, max_contact_groups, max_faqs,
              max_widgets, max_invoices_per_month, max_quotes_per_month, max_payment_links_per_month,
              max_email_accounts, max_emails_per_month, max_omnichannel_accounts,
              whatsapp_enabled, ai_enabled, woocommerce_enabled, analytics_enabled,
              priority_support_enabled, api_access_enabled, custom_branding_enabled,
              invoices_enabled, quotes_enabled, widgets_enabled, payment_links_enabled,
              biolink_enabled, max_bio_pages, max_short_links, max_file_transfers,
              max_vcards, max_event_links, max_html_pages, max_qr_codes,
              pix_enabled, cash_enabled,
              is_trial, trial_days, is_free,
              stripe_price_id, paypal_plan_id, sort_order
            ]
          );

          logger.info('Plan created', { planId: result.insertId, name });

          return res.status(201).json({
            success: true,
            message: 'Plan created successfully',
            data: { id: result.insertId }
          });
        } catch (error) {
          logger.error('Error creating plan', {
            error: error.message,
            stack: error.stack,
            sqlMessage: error.sqlMessage,
            sqlState: error.sqlState,
            errno: error.errno,
            sql: error.sql
          });

          console.error('=== ERROR DETAILS ===');
          console.error('Message:', error.message);
          console.error('SQL:', error.sql);
          console.error('SQL Message:', error.sqlMessage);

          // Check for specific SQL errors
          if (error.errno === 1054) {
            return res.status(500).json({
              success: false,
              message: 'Database schema error: Unknown column',
              details: error.sqlMessage
            });
          }

          return res.status(500).json({
            success: false,
            message: 'Error creating plan',
            details: process.env.NODE_ENV === 'development' ? error.message : undefined
          });
        }
      }

      /**
       * Update subscription plan
       * PUT /api/superadmin/plans/:id
       */
      static async updatePlan(req, res) {
        try {
          const { id } = req.params;
          const updates = req.body;

          // Check if plan exists
          const [existingPlan] = await pool.execute(
            'SELECT * FROM subscription_plans WHERE id = ?',
            [id]
          );

          if (existingPlan.length === 0) {
            return res.status(404).json({
              success: false,
              message: 'Plan not found'
            });
          }

          // Check free plan constraint
          if (updates.is_free && !existingPlan[0].is_free) {
            const [freePlans] = await pool.execute(
              'SELECT id FROM subscription_plans WHERE is_free = TRUE AND id != ?',
              [id]
            );
            if (freePlans.length > 0) {
              return res.status(400).json({
                success: false,
                message: 'Only one free plan is allowed'
              });
            }
          }

          // Build update query
          const updateFields = [];
          const values = [];

          const allowedFields = [
            'name', 'description', 'price', 'currency', 'billing_period',
            'max_stores', 'max_users', 'max_departments', 'max_contacts', 'max_devices', 'max_whatsapp_instances',
            'max_whatsapp_cloud_accounts',
            'max_conversations', 'max_messages_per_month', 'max_faqs', 'max_contact_groups',
            'whatsapp_enabled', 'ai_enabled', 'woocommerce_enabled', 'analytics_enabled',
            'priority_support_enabled', 'api_access_enabled', 'custom_branding_enabled',
            'invoices_enabled', 'max_invoices_per_month',
            'quotes_enabled', 'max_quotes_per_month',
            'widgets_enabled', 'max_widgets',
            'payment_links_enabled', 'max_payment_links_per_month',
            'max_email_accounts', 'max_emails_per_month', 'max_omnichannel_accounts',
            'biolink_enabled', 'max_bio_pages', 'max_short_links', 'max_file_transfers',
            'max_vcards', 'max_event_links', 'max_html_pages', 'max_qr_codes',
            'pix_enabled', 'cash_enabled',
            'is_trial', 'trial_days', 'is_free',
            'stripe_price_id', 'paypal_plan_id', 'sort_order', 'active'
          ];

          for (const field of allowedFields) {
            if (updates[field] !== undefined) {
              updateFields.push(`${field} = ?`);
              values.push(updates[field]);
            }
          }

          if (updateFields.length === 0) {
            return res.status(400).json({
              success: false,
              message: 'No fields to update'
            });
          }

          values.push(id);

          await pool.execute(
            `UPDATE subscription_plans SET ${updateFields.join(', ')} WHERE id = ?`,
            values
          );

          logger.info('Plan updated', { planId: id });

          return res.json({
            success: true,
            message: 'Plan updated successfully'
          });
        } catch (error) {
          logger.error('Error updating plan', { error: error.message });
          return res.status(500).json({
            success: false,
            message: 'Error updating plan'
          });
        }
      }

      /**
       * Delete subscription plan
       * DELETE /api/superadmin/plans/:id
       */
      static async deletePlan(req, res) {
        try {
          const { id } = req.params;

          // Check if plan has active subscriptions
          const [tenants] = await pool.execute(
            'SELECT COUNT(*) as count FROM tenants WHERE plan_id = ? AND status = ?',
            [id, 'active']
          );

          if (tenants[0].count > 0) {
            return res.status(400).json({
              success: false,
              message: 'Cannot delete plan with active subscriptions'
            });
          }

          await pool.execute('DELETE FROM subscription_plans WHERE id = ?', [id]);

          logger.info('Plan deleted', { planId: id });

          return res.json({
            success: true,
            message: 'Plan deleted successfully'
          });
        } catch (error) {
          logger.error('Error deleting plan', { error: error.message });
          return res.status(500).json({
            success: false,
            message: 'Error deleting plan'
          });
        }
      }

      /**
       * Toggle plan status
       * PUT /api/superadmin/plans/:id/toggle-status
       */
      static async togglePlanStatus(req, res) {
        try {
          const { id } = req.params;

          const [plan] = await pool.execute(
            'SELECT active FROM subscription_plans WHERE id = ?',
            [id]
          );

          if (plan.length === 0) {
            return res.status(404).json({
              success: false,
              message: 'Plan not found'
            });
          }

          const newStatus = !plan[0].active;

          await pool.execute(
            'UPDATE subscription_plans SET active = ? WHERE id = ?',
            [newStatus, id]
          );

          logger.info('Plan status toggled', { planId: id, newStatus });

          return res.json({
            success: true,
            message: `Plan ${newStatus ? 'activated' : 'deactivated'} successfully`,
            data: { active: newStatus }
          });
        } catch (error) {
          logger.error('Error toggling plan status', { error: error.message });
          return res.status(500).json({
            success: false,
            message: 'Error updating plan status'
          });
        }
      }
    }

    module.exports = SuperAdminPlanController;