HbarSuite Docs
  • Welcome to HbarSuite
  • HbarSuite Developer Documentation
    • HbarSuite Smart Engine Applications
      • @hsuite/cross-chain-exchange
      • @hsuite/dao
        • DAO Application Testing
      • @hsuite/exchange
      • @hsuite/launchpad
      • @hsuite/multisig
      • @hsuite/nft-exchange
      • HSuite Smart App - Enterprise Hedera Application Framework
    • HSuite Libraries
      • @hsuite/api-key - Enterprise API Key Authentication System
      • @hsuite/auth-types
      • @hsuite/auth - Authentication Module
      • @hsuite/client-types
      • @hsuite/client - Client Service Module
      • @hsuite/dkg-types - Distributed Key Generation Type Definitions
      • @hsuite/hashgraph-types - Hedera Hashgraph Type Definitions
      • @hsuite/health - Comprehensive System Health Monitoring
      • @hsuite/helpers - Utility Library
      • @hsuite/ipfs - InterPlanetary File System Integration
      • @hsuite/shared-types - Shared Type Definitions
      • @hsuite/smart-config - Configuration Management
      • @hsuite/smart-ledgers - Multi-Ledger Management
      • @hsuite/smart-network-types - Smart Network Type Definitions
      • @hsuite/smart-transaction-types - Smart Transaction Type Definitions
      • @hsuite/smartnode-sdk - SmartNode Software Development Kit
      • @hsuite/snapshots - Multi-Ledger Token Snapshot Management
      • @hsuite/subscriptions-types - Subscription Management Type Definitions
      • @hsuite/subscriptions - Enterprise Subscription Management System
      • @hsuite/throttler-types - Rate Limiting Type Definitions
      • @hsuite/throttler - Advanced Rate Limiting for NestJS
      • @hsuite/users-types - User Type Definitions
      • @hsuite/users - User Management Module
      • @hsuite/validators-types
  • General Documentation
    • Smart Apps and Interaction
      • Subscription-Based Model
      • Token-Gate Model
    • The Smart Node Network
      • security-layer
      • Type of Validators Explained
      • Understanding Validators in Our System
      • Automating Responses to Network Changes & Key Rotation
      • Ensuring Continuous Operation and Recovery
      • Generating and Sharing Keys Collaboratively
      • Handling Node Expulsion and Replacement
      • Managing Cluster Membership
      • Protecting Secrets with Shamir's Method
      • Security Layer Integration
      • Setting Up Secure Clusters
    • Tokenomics
      • Tokenomics v1
      • Tokenomics V2
    • What is a Smart Node?
  • Restful APIs Documentation
Powered by GitBook
On this page
  • 📚 Table of Contents
  • ✨ Quick Start
  • Installation
  • Basic Setup
  • NestJS Integration
  • 🏗️ Architecture
  • Core Component Areas
  • Dual Namespace System
  • Module Structure
  • 🔧 API Reference
  • Core Interface Types
  • Configuration Types
  • Plan Comparison Matrix
  • 📖 Guides
  • Subscription Lifecycle Guide
  • Web3 Integration Guide
  • Payment Processing Guide
  • Analytics Implementation Guide
  • 🎯 Examples
  • Subscription Lifecycle Management
  • Payment Processing and Activity Tracking
  • Configuration Management
  • Multi-Tenant Subscription Management
  • 🔗 Integration
  • Required Dependencies
  • Module Integration
  • Documentation Generation
  • Integration with HSuite Ecosystem
  • Use Cases
  • 💳 SaaS Subscription Management
  • 🌐 Web3 dApp Monetization
  • 📊 Enterprise Analytics Platform
  • 🏢 Multi-Tenant Applications
  1. HbarSuite Developer Documentation
  2. HSuite Libraries

@hsuite/subscriptions-types - Subscription Management Type Definitions

Previous@hsuite/snapshots - Multi-Ledger Token Snapshot ManagementNext@hsuite/subscriptions - Enterprise Subscription Management System

Last updated 2 days ago

💳 Comprehensive TypeScript type definitions for HSuite subscription management with Web3 blockchain integration

Enterprise-grade type definitions and interfaces providing a complete subscription lifecycle management system with Web3 blockchain integration, payment processing, analytics tracking, and multi-tier subscription plans.


📚 Table of Contents


✨ Quick Start

Installation

npm install @hsuite/subscriptions-types

Basic Setup

import { ISubscription, Subscription } from '@hsuite/subscriptions-types';

// Interface-based type definitions
const plan: ISubscription.IPlan = ISubscription.IPlan.PREMIUM;
const status: ISubscription.IStatus = ISubscription.IStatus.ACTIVE;
const period: ISubscription.IPeriodicity = ISubscription.IPeriodicity.MONTHLY;

// Model-based runtime validation
const subscription = new Subscription.Web3.Entity();
const payment = new Subscription.Web3.Payment.Entity();
const analytics = new Subscription.Web3.Analytics.Entity();

NestJS Integration

import { Subscription } from '@hsuite/subscriptions-types';

@Controller('subscriptions')
export class SubscriptionController {
  @Post('create')
  @ApiResponse({ type: Subscription.Web3.Entity })
  async createSubscription(@Body() data: any): Promise<Subscription.Web3.Entity> {
    return new Subscription.Web3.Entity(data);
  }
}

🏗️ Architecture

Core Component Areas

💳 Subscription Management

  • Plan System - Basic, Premium, and Enterprise subscription tiers

  • Billing Cycles - Monthly and yearly periodicity options

  • Status Lifecycle - Complete status tracking from pending to expired

  • Configuration Management - Flexible plan and system configuration

🌐 Web3 Blockchain Integration

  • Wallet Integration - Web3 wallet address and blockchain connectivity

  • Token Management - Subscription NFTs with serial numbers and metadata

  • Transaction Tracking - Complete blockchain transaction history

  • Smart Contract Support - Token gate authentication and blockchain operations

💰 Payment Processing

  • Transaction Management - Payment tracking with blockchain integration

  • Activity Monitoring - API usage tracking across HTTP methods

  • Renewal Automation - Automated subscription renewal management

  • Usage Analytics - Comprehensive API usage analytics and reporting

📊 Analytics & Monitoring

  • API Usage Tracking - Detailed HTTP method and endpoint monitoring

  • Performance Metrics - Subscription performance and usage analytics

  • Real-time Monitoring - Live subscription status and usage tracking

  • Reporting System - Comprehensive analytics reporting capabilities

Dual Namespace System

🔧 ISubscription Namespace (Interfaces)

  • Type Definitions - Pure TypeScript interfaces for type safety

  • Plan Management - Subscription plan and billing cycle interfaces

  • Web3 Operations - Blockchain subscription management interfaces

  • Configuration Types - System and subscription configuration interfaces

🏛️ Subscription Namespace (Models)

  • Runtime Validation - Concrete classes with built-in validation

  • Swagger Integration - Complete API documentation decorators

  • Web3 Implementation - Blockchain subscription management classes

  • Configuration Models - System configuration and plan management

Module Structure

src/
├── index.ts                           # Main exports and documentation
├── interfaces/                        # ISubscription namespace
│   ├── subscription.namespace.ts      # Central interface hub
│   ├── shared-types/                  # Common enums and utilities
│   └── namespaces/                    # Specialized domains
│       ├── web3/                      # Web3 subscription interfaces
│       └── config/                    # Configuration interfaces
└── models/                            # Subscription namespace
    ├── subscription.namespace.ts      # Central model hub
    └── namespaces/                    # Domain implementations
        ├── web3/                      # Web3 implementations
        └── config/                    # Configuration implementations

🔧 API Reference

Core Interface Types

Plan Management Types

ISubscription.IPlan

enum IPlan {
  BASIC = 'basic',        // Entry-level plan with core features
  PREMIUM = 'premium',    // Mid-tier plan with enhanced capabilities
  ENTERPRISE = 'enterprise' // Top-tier plan with complete feature access
}

ISubscription.IPeriodicity

enum IPeriodicity {
  MONTHLY = 'monthly',    // Monthly billing and renewal
  YEARLY = 'yearly'       // Yearly billing and renewal
}

ISubscription.IStatus

enum IStatus {
  PENDING = 'pending',        // Awaiting processing or confirmation
  PROCESSING = 'processing',  // Currently being processed
  MINTED = 'minted',         // Subscription token minted on blockchain
  DELIVERED = 'delivered',    // Successfully delivered to user
  ACTIVE = 'active',         // Currently active and in use
  CANCELLED = 'cancelled',   // Terminated by user or system
  EXPIRED = 'expired',       // Reached end date
  FAILED = 'failed'          // Processing or activation failed
}

Web3 Subscription Types

ISubscription.IWeb3.IEntity

  • Purpose: Core Web3 subscription entity structure

  • Properties: walletId, operatorId, status, details, payments, analytics

  • Usage: Complete subscription lifecycle management

ISubscription.IWeb3.IDetails

  • Purpose: Subscription detail management interface

  • Properties: tokenId, serialNumber, metadata

  • Usage: Blockchain token and metadata management

ISubscription.IWeb3.IPayment.IEntity

  • Purpose: Payment transaction tracking interface

  • Properties: date, renewal, transaction, activity

  • Usage: Payment processing and activity monitoring

Configuration Types

ISubscription.IConfig.IEntity

  • Purpose: Complete subscription system configuration

  • Properties: basic, premium, enterprise, redis, token, tokenGate

  • Usage: System-wide subscription configuration

ISubscription.IConfig.IPlan.IEntity

  • Purpose: Individual subscription plan configuration

  • Properties: price, requests, description, image

  • Usage: Plan-specific settings and limits

Plan Comparison Matrix

Feature
Basic
Premium
Enterprise

Monthly Price

$9.99

$19.99

$49.99

Yearly Price

$99.99

$199.99

$499.99

API Requests

Limited

Enhanced

Unlimited

Blockchain Features

Basic

Advanced

Enterprise

Analytics

Basic

Advanced

Full Suite

Support

Community

Priority

Dedicated


📖 Guides

Subscription Lifecycle Guide

Complete guide to managing subscription lifecycle from creation to expiration. Comprehensive lifecycle management covering subscription creation, status transitions, renewal workflows, cancellation processes, and enterprise-grade subscription lifecycle automation.

Web3 Integration Guide

Learn how to integrate blockchain features and token management. Advanced integration guide covering Web3 wallet integration, blockchain token operations, NFT-based subscriptions, smart contract interactions, and enterprise Web3 subscription systems.

Payment Processing Guide

Implement payment tracking and transaction management. Detailed implementation guide covering payment gateway integration, transaction monitoring, billing automation, revenue tracking, and enterprise payment processing for subscription services.

Analytics Implementation Guide

Set up comprehensive analytics and usage monitoring. Advanced analytics guide covering usage tracking, performance metrics, user behavior analysis, revenue analytics, and enterprise-grade subscription analytics and reporting systems.


🎯 Examples

Subscription Lifecycle Management

import { ISubscription, Subscription } from '@hsuite/subscriptions-types';

@Injectable()
export class SubscriptionLifecycleService {
  
  async createSubscription(subscriptionData: any) {
    try {
      // Create subscription metadata
      const metadata = new Subscription.Web3.Metadata({
        plan: ISubscription.IPlan.PREMIUM,
        periodicity: ISubscription.IPeriodicity.MONTHLY,
        app: {
          name: subscriptionData.appName,
          description: subscriptionData.appDescription,
          logo: subscriptionData.appLogo,
          url: subscriptionData.appUrl
        }
      });

      // Create subscription details
      const details = new Subscription.Web3.Details({
        tokenId: subscriptionData.tokenId,
        serialNumber: subscriptionData.serialNumber,
        metadata: metadata
      });

      // Create subscription entity
      const subscription = new Subscription.Web3.Entity({
        walletId: subscriptionData.walletId,
        operatorId: subscriptionData.operatorId,
        status: ISubscription.IStatus.PENDING,
        details: details,
        payments: [],
        analytics: []
      });

      return {
        success: true,
        subscription: subscription,
        subscriptionId: subscription.details.tokenId,
        status: subscription.status,
        plan: metadata.plan,
        nextBilling: this.calculateNextBilling(metadata.periodicity)
      };
    } catch (error) {
      throw new Error(`Subscription creation failed: ${error.message}`);
    }
  }

  async updateSubscriptionStatus(tokenId: string, newStatus: ISubscription.IStatus) {
    try {
      const statusTransitions = {
        [ISubscription.IStatus.PENDING]: [
          ISubscription.IStatus.PROCESSING,
          ISubscription.IStatus.FAILED
        ],
        [ISubscription.IStatus.PROCESSING]: [
          ISubscription.IStatus.MINTED,
          ISubscription.IStatus.FAILED
        ],
        [ISubscription.IStatus.MINTED]: [
          ISubscription.IStatus.DELIVERED,
          ISubscription.IStatus.FAILED
        ],
        [ISubscription.IStatus.DELIVERED]: [
          ISubscription.IStatus.ACTIVE
        ],
        [ISubscription.IStatus.ACTIVE]: [
          ISubscription.IStatus.CANCELLED,
          ISubscription.IStatus.EXPIRED
        ]
      };

      // Validate status transition
      const currentSubscription = await this.getSubscription(tokenId);
      const allowedTransitions = statusTransitions[currentSubscription.status] || [];
      
      if (!allowedTransitions.includes(newStatus)) {
        throw new Error(`Invalid status transition from ${currentSubscription.status} to ${newStatus}`);
      }

      // Update subscription status
      currentSubscription.status = newStatus;

      return {
        success: true,
        tokenId,
        previousStatus: currentSubscription.status,
        newStatus,
        updatedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Status update failed: ${error.message}`);
    }
  }

  private calculateNextBilling(periodicity: ISubscription.IPeriodicity): string {
    const now = new Date();
    const nextBilling = new Date(now);
    
    if (periodicity === ISubscription.IPeriodicity.MONTHLY) {
      nextBilling.setMonth(now.getMonth() + 1);
    } else {
      nextBilling.setFullYear(now.getFullYear() + 1);
    }
    
    return nextBilling.toISOString();
  }

  private async getSubscription(tokenId: string): Promise<any> {
    // Mock implementation - replace with actual subscription retrieval
    return {
      tokenId,
      status: ISubscription.IStatus.PENDING
    };
  }
}

Payment Processing and Activity Tracking

import { ISubscription, Subscription } from '@hsuite/subscriptions-types';

@Injectable()
export class PaymentProcessingService {
  
  async processPayment(paymentData: any) {
    try {
      // Create activity tracking
      const activity = new Subscription.Web3.Payment.Activity({
        http_get: paymentData.usage.get || 0,
        http_post: paymentData.usage.post || 0,
        http_put: paymentData.usage.put || 0,
        http_delete: paymentData.usage.delete || 0,
        http_patch: paymentData.usage.patch || 0
      });

      // Create payment entity
      const payment = new Subscription.Web3.Payment.Entity({
        date: Date.now(),
        renewal: this.calculateRenewalDate(paymentData.periodicity),
        transaction: paymentData.transactionHash,
        activity: activity
      });

      // Update subscription with payment
      await this.addPaymentToSubscription(paymentData.tokenId, payment);

      return {
        success: true,
        paymentId: payment.transaction,
        amount: paymentData.amount,
        currency: paymentData.currency,
        nextRenewal: new Date(payment.renewal).toISOString(),
        usage: activity
      };
    } catch (error) {
      throw new Error(`Payment processing failed: ${error.message}`);
    }
  }

  async trackAPIUsage(usageData: any) {
    try {
      const analytics = new Subscription.Web3.Analytics.Entity({
        httpMethod: usageData.method,
        endpointUrl: usageData.endpoint,
        timestamp: Date.now()
      });

      // Add analytics to subscription
      await this.addAnalyticsToSubscription(usageData.tokenId, analytics);

      return {
        success: true,
        analyticsId: analytics.timestamp,
        method: analytics.httpMethod,
        endpoint: analytics.endpointUrl,
        recordedAt: new Date(analytics.timestamp).toISOString()
      };
    } catch (error) {
      throw new Error(`Analytics tracking failed: ${error.message}`);
    }
  }

  async generateUsageReport(tokenId: string, timeRange: { start: number; end: number }) {
    try {
      const subscription = await this.getSubscription(tokenId);
      const analytics = subscription.analytics.filter(
        (record: any) => record.timestamp >= timeRange.start && record.timestamp <= timeRange.end
      );

      const usageSummary = {
        totalRequests: analytics.length,
        methodBreakdown: this.aggregateByMethod(analytics),
        endpointBreakdown: this.aggregateByEndpoint(analytics),
        timeRange: {
          start: new Date(timeRange.start).toISOString(),
          end: new Date(timeRange.end).toISOString()
        }
      };

      return {
        success: true,
        tokenId,
        reportGenerated: new Date().toISOString(),
        usage: usageSummary
      };
    } catch (error) {
      throw new Error(`Usage report generation failed: ${error.message}`);
    }
  }

  private calculateRenewalDate(periodicity: ISubscription.IPeriodicity): number {
    const now = Date.now();
    const msInDay = 24 * 60 * 60 * 1000;
    
    if (periodicity === ISubscription.IPeriodicity.MONTHLY) {
      return now + (30 * msInDay);
    } else {
      return now + (365 * msInDay);
    }
  }

  private aggregateByMethod(analytics: any[]): Record<string, number> {
    return analytics.reduce((acc, record) => {
      acc[record.httpMethod] = (acc[record.httpMethod] || 0) + 1;
      return acc;
    }, {});
  }

  private aggregateByEndpoint(analytics: any[]): Record<string, number> {
    return analytics.reduce((acc, record) => {
      acc[record.endpointUrl] = (acc[record.endpointUrl] || 0) + 1;
      return acc;
    }, {});
  }

  private async addPaymentToSubscription(tokenId: string, payment: any): Promise<void> {
    // Implementation for adding payment to subscription
  }

  private async addAnalyticsToSubscription(tokenId: string, analytics: any): Promise<void> {
    // Implementation for adding analytics to subscription
  }

  private async getSubscription(tokenId: string): Promise<any> {
    // Implementation for retrieving subscription
    return {
      tokenId,
      analytics: []
    };
  }
}

Configuration Management

import { ISubscription, Subscription } from '@hsuite/subscriptions-types';

@Injectable()
export class SubscriptionConfigurationService {
  
  async setupSubscriptionConfiguration(configData: any) {
    try {
      // Create plan configurations
      const basicPlan = new Subscription.Config.Plan.Entity({
        price: {
          monthly: 999,  // $9.99 in cents
          yearly: 9999   // $99.99 in cents
        },
        requests: {
          get: 1000,
          post: 500,
          put: 100,
          delete: 50,
          patch: 25
        },
        description: "Basic Plan - Perfect for small projects",
        image: "https://assets.hsuite.com/plans/basic.png"
      });

      const premiumPlan = new Subscription.Config.Plan.Entity({
        price: {
          monthly: 1999,  // $19.99 in cents
          yearly: 19999   // $199.99 in cents
        },
        requests: {
          get: 5000,
          post: 2500,
          put: 500,
          delete: 250,
          patch: 125
        },
        description: "Premium Plan - Enhanced capabilities for growing businesses",
        image: "https://assets.hsuite.com/plans/premium.png"
      });

      const enterprisePlan = new Subscription.Config.Plan.Entity({
        price: {
          monthly: 4999,  // $49.99 in cents
          yearly: 49999   // $499.99 in cents
        },
        requests: {
          get: -1,    // Unlimited
          post: -1,   // Unlimited
          put: -1,    // Unlimited
          delete: -1, // Unlimited
          patch: -1   // Unlimited
        },
        description: "Enterprise Plan - Complete feature access with dedicated support",
        image: "https://assets.hsuite.com/plans/enterprise.png"
      });

      // Create main configuration
      const config = new Subscription.Config.Entity({
        basic: basicPlan,
        premium: premiumPlan,
        enterprise: enterprisePlan,
        redis: {
          host: configData.redis.host || 'localhost',
          port: configData.redis.port || 6379,
          ttl: configData.redis.ttl || 3600
        },
        token: {
          issuer: configData.token.issuer,
          secret: configData.token.secret
        },
        tokenGate: {
          enabled: true,
          options: {
            guardType: 'subscriptions'
          }
        },
        payment: {
          provider: configData.payment.provider || 'stripe',
          webhookSecret: configData.payment.webhookSecret
        }
      });

      return {
        success: true,
        configuration: config,
        plansConfigured: 3,
        features: {
          tokenGate: config.tokenGate.enabled,
          redis: !!config.redis,
          payments: !!config.payment
        }
      };
    } catch (error) {
      throw new Error(`Configuration setup failed: ${error.message}`);
    }
  }

  async validatePlanLimits(tokenId: string, requestType: string): Promise<boolean> {
    try {
      const subscription = await this.getSubscription(tokenId);
      const plan = await this.getPlanConfiguration(subscription.metadata.plan);
      const currentUsage = await this.getCurrentUsage(tokenId);

      const requestLimit = plan.requests[requestType];
      
      // Unlimited access (-1) or within limits
      if (requestLimit === -1 || currentUsage[requestType] < requestLimit) {
        return true;
      }

      return false;
    } catch (error) {
      console.error('Plan limit validation failed:', error);
      return false;
    }
  }

  async upgradePlan(tokenId: string, newPlan: ISubscription.IPlan) {
    try {
      const subscription = await this.getSubscription(tokenId);
      const currentPlan = subscription.metadata.plan;
      
      // Validate upgrade path
      const upgradeMatrix = {
        [ISubscription.IPlan.BASIC]: [ISubscription.IPlan.PREMIUM, ISubscription.IPlan.ENTERPRISE],
        [ISubscription.IPlan.PREMIUM]: [ISubscription.IPlan.ENTERPRISE],
        [ISubscription.IPlan.ENTERPRISE]: [] // Cannot upgrade from enterprise
      };

      const allowedUpgrades = upgradeMatrix[currentPlan] || [];
      
      if (!allowedUpgrades.includes(newPlan)) {
        throw new Error(`Cannot upgrade from ${currentPlan} to ${newPlan}`);
      }

      // Update subscription plan
      subscription.metadata.plan = newPlan;
      
      // Calculate pro-rated pricing
      const proRatedAmount = await this.calculateProRatedAmount(subscription, newPlan);

      return {
        success: true,
        tokenId,
        previousPlan: currentPlan,
        newPlan,
        proRatedAmount,
        effectiveDate: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Plan upgrade failed: ${error.message}`);
    }
  }

  private async getPlanConfiguration(plan: ISubscription.IPlan): Promise<any> {
    // Mock implementation - replace with actual plan retrieval
    const plans = {
      [ISubscription.IPlan.BASIC]: {
        requests: { get: 1000, post: 500, put: 100, delete: 50, patch: 25 }
      },
      [ISubscription.IPlan.PREMIUM]: {
        requests: { get: 5000, post: 2500, put: 500, delete: 250, patch: 125 }
      },
      [ISubscription.IPlan.ENTERPRISE]: {
        requests: { get: -1, post: -1, put: -1, delete: -1, patch: -1 }
      }
    };
    
    return plans[plan];
  }

  private async getCurrentUsage(tokenId: string): Promise<Record<string, number>> {
    // Mock implementation - replace with actual usage tracking
    return {
      get: 500,
      post: 250,
      put: 50,
      delete: 25,
      patch: 10
    };
  }

  private async getSubscription(tokenId: string): Promise<any> {
    // Mock implementation
    return {
      tokenId,
      metadata: {
        plan: ISubscription.IPlan.BASIC
      }
    };
  }

  private async calculateProRatedAmount(subscription: any, newPlan: ISubscription.IPlan): Promise<number> {
    // Mock implementation for pro-rated amount calculation
    const planPrices = {
      [ISubscription.IPlan.BASIC]: 999,
      [ISubscription.IPlan.PREMIUM]: 1999,
      [ISubscription.IPlan.ENTERPRISE]: 4999
    };
    
    return planPrices[newPlan] - planPrices[subscription.metadata.plan];
  }
}

Multi-Tenant Subscription Management

import { ISubscription, Subscription } from '@hsuite/subscriptions-types';

@Injectable()
export class MultiTenantSubscriptionService {
  
  async createTenantSubscription(tenantData: any) {
    try {
      // Create tenant-specific app metadata
      const appMetadata = new Subscription.Web3.App({
        name: tenantData.applicationName,
        description: tenantData.applicationDescription,
        logo: tenantData.applicationLogo,
        url: tenantData.applicationUrl
      });

      // Create subscription for tenant
      const subscription = await this.createSubscription({
        walletId: tenantData.walletId,
        operatorId: tenantData.operatorId,
        plan: tenantData.selectedPlan,
        periodicity: tenantData.billingPeriod,
        app: appMetadata
      });

      // Setup tenant-specific limits
      await this.setupTenantLimits(subscription.details.tokenId, tenantData.customLimits);

      return {
        success: true,
        tenantId: tenantData.tenantId,
        subscription: subscription,
        features: this.getTenantFeatures(tenantData.selectedPlan),
        setupComplete: true
      };
    } catch (error) {
      throw new Error(`Tenant subscription creation failed: ${error.message}`);
    }
  }

  async manageTenantBilling(tenantId: string, billingData: any) {
    try {
      const subscriptions = await this.getTenantSubscriptions(tenantId);
      const billingResults = [];

      for (const subscription of subscriptions) {
        const usage = await this.calculateTenantUsage(subscription.details.tokenId);
        const bill = await this.generateBill(subscription, usage, billingData.billingCycle);
        
        billingResults.push({
          subscriptionId: subscription.details.tokenId,
          plan: subscription.metadata.plan,
          usage: usage,
          bill: bill
        });
      }

      return {
        success: true,
        tenantId,
        billingPeriod: billingData.billingCycle,
        subscriptions: billingResults.length,
        totalAmount: billingResults.reduce((sum, result) => sum + result.bill.amount, 0),
        generatedAt: new Date().toISOString()
      };
    } catch (error) {
      throw new Error(`Tenant billing management failed: ${error.message}`);
    }
  }

  async monitorTenantUsage(tenantId: string) {
    try {
      const subscriptions = await this.getTenantSubscriptions(tenantId);
      const usageData = [];

      for (const subscription of subscriptions) {
        const analytics = subscription.analytics || [];
        const recentUsage = analytics.filter(
          (record: any) => record.timestamp > Date.now() - (24 * 60 * 60 * 1000) // Last 24 hours
        );

        const usage = {
          subscriptionId: subscription.details.tokenId,
          plan: subscription.metadata.plan,
          dailyUsage: {
            totalRequests: recentUsage.length,
            methodBreakdown: this.aggregateByMethod(recentUsage),
            topEndpoints: this.getTopEndpoints(recentUsage, 5)
          },
          limits: await this.getPlanLimits(subscription.metadata.plan),
          utilizationPercentage: this.calculateUtilization(recentUsage, subscription.metadata.plan)
        };

        usageData.push(usage);
      }

      return {
        success: true,
        tenantId,
        monitoringPeriod: '24 hours',
        subscriptions: usageData,
        totalUsage: usageData.reduce((sum, data) => sum + data.dailyUsage.totalRequests, 0),
        alertsRequired: usageData.filter(data => data.utilizationPercentage > 80)
      };
    } catch (error) {
      throw new Error(`Tenant usage monitoring failed: ${error.message}`);
    }
  }

  private getTenantFeatures(plan: ISubscription.IPlan): string[] {
    const features = {
      [ISubscription.IPlan.BASIC]: [
        'Basic API Access',
        'Standard Support',
        'Monthly Billing'
      ],
      [ISubscription.IPlan.PREMIUM]: [
        'Enhanced API Access',
        'Priority Support',
        'Advanced Analytics',
        'Monthly/Yearly Billing'
      ],
      [ISubscription.IPlan.ENTERPRISE]: [
        'Unlimited API Access',
        'Dedicated Support',
        'Complete Analytics Suite',
        'Custom Billing Terms',
        'SLA Guarantees'
      ]
    };

    return features[plan] || [];
  }

  private async setupTenantLimits(tokenId: string, customLimits: any): Promise<void> {
    // Implementation for setting up tenant-specific limits
  }

  private async getTenantSubscriptions(tenantId: string): Promise<any[]> {
    // Mock implementation - replace with actual tenant subscription retrieval
    return [];
  }

  private async calculateTenantUsage(tokenId: string): Promise<any> {
    // Mock implementation for calculating tenant usage
    return {
      requests: 1500,
      methods: { get: 1000, post: 300, put: 150, delete: 50 }
    };
  }

  private async generateBill(subscription: any, usage: any, billingCycle: string): Promise<any> {
    // Mock implementation for bill generation
    return {
      amount: 1999, // $19.99 in cents
      currency: 'USD',
      period: billingCycle
    };
  }

  private aggregateByMethod(analytics: any[]): Record<string, number> {
    return analytics.reduce((acc, record) => {
      acc[record.httpMethod] = (acc[record.httpMethod] || 0) + 1;
      return acc;
    }, {});
  }

  private getTopEndpoints(analytics: any[], limit: number): Array<{ endpoint: string; count: number }> {
    const endpointCounts = analytics.reduce((acc, record) => {
      acc[record.endpointUrl] = (acc[record.endpointUrl] || 0) + 1;
      return acc;
    }, {});

    return Object.entries(endpointCounts)
      .map(([endpoint, count]) => ({ endpoint, count: count as number }))
      .sort((a, b) => b.count - a.count)
      .slice(0, limit);
  }

  private async getPlanLimits(plan: ISubscription.IPlan): Promise<any> {
    // Mock implementation
    return { monthly: 10000 };
  }

  private calculateUtilization(recentUsage: any[], plan: ISubscription.IPlan): number {
    // Mock calculation - replace with actual utilization logic
    return Math.min(100, (recentUsage.length / 1000) * 100);
  }
}

🔗 Integration

Required Dependencies

{
  "@nestjs/common": "^10.4.2",
  "@nestjs/core": "^10.4.2",
  "@hsuite/smart-network-types": "^2.0.0",
  "@hsuite/nestjs-swagger": "^1.0.3",
  "@compodoc/compodoc": "^1.1.23"
}

Module Integration

import { Module } from '@nestjs/common';
import { Subscription, ISubscription } from '@hsuite/subscriptions-types';

@Module({
  providers: [
    SubscriptionLifecycleService,
    PaymentProcessingService,
    SubscriptionConfigurationService,
    MultiTenantSubscriptionService
  ],
  exports: [
    SubscriptionLifecycleService,
    PaymentProcessingService,
    SubscriptionConfigurationService,
    MultiTenantSubscriptionService
  ]
})
export class SubscriptionTypesModule {}

Documentation Generation

# Generate comprehensive documentation
npm run compodoc

# Generate documentation with coverage report
npm run compodoc:coverage

Integration with HSuite Ecosystem

// Complete integration with other HSuite modules
import { Subscription, ISubscription } from '@hsuite/subscriptions-types';
import { AuthModule } from '@hsuite/auth';
import { SmartNetworkModule } from '@hsuite/smart-network';
import { HashgraphModule } from '@hsuite/hashgraph';

@Module({
  imports: [
    AuthModule,
    SmartNetworkModule,
    HashgraphModule
  ]
})
export class SubscriptionEcosystemModule {}

@Injectable()
export class IntegratedSubscriptionService {
  constructor(
    private authService: AuthService,
    private networkService: SmartNetworkService,
    private hashgraphService: HashgraphService
  ) {}

  async createSecureSubscription(
    subscriptionData: any,
    session: IAuth.ICredentials.IWeb3.IEntity
  ): Promise<Subscription.Web3.Entity> {
    // 1. Validate permissions
    const hasPermission = await this.authService.validatePermission(
      session,
      'subscription:create'
    );

    if (!hasPermission) {
      throw new Error('Insufficient permissions for subscription creation');
    }

    // 2. Create blockchain subscription
    const subscription = new Subscription.Web3.Entity({
      walletId: session.walletId,
      operatorId: subscriptionData.operatorId,
      status: ISubscription.IStatus.PENDING,
      details: subscriptionData.details,
      payments: [],
      analytics: []
    });

    // 3. Submit to Hashgraph
    const txResponse = await this.hashgraphService.createSubscriptionToken(subscription);
    
    // 4. Update with blockchain data
    subscription.details.tokenId = txResponse.tokenId;
    subscription.status = ISubscription.IStatus.MINTED;

    return subscription;
  }
}

Use Cases

💳 SaaS Subscription Management

  • Multi-tier subscription plans with different feature sets

  • Automated billing and renewal management

  • Usage-based pricing and API rate limiting

  • Customer analytics and usage reporting

🌐 Web3 dApp Monetization

  • Blockchain-based subscription NFTs

  • Token-gated access control

  • Decentralized payment processing

  • Smart contract integration

📊 Enterprise Analytics Platform

  • Comprehensive API usage tracking

  • Real-time monitoring and alerting

  • Performance analytics and reporting

  • Multi-tenant management capabilities

🏢 Multi-Tenant Applications

  • Tenant-specific subscription management

  • Custom billing and pricing models

  • Isolated analytics and reporting

  • Scalable configuration management


💳 Enterprise Subscription System: Comprehensive TypeScript definitions with Web3 blockchain integration and multi-tier subscription management.

🌐 Blockchain-Native: Complete Web3 support with NFT subscriptions, token gates, and smart contract integration.

📊 Advanced Analytics: Real-time usage tracking, performance monitoring, and comprehensive reporting capabilities.


Built with ❤️ by the HbarSuite Team Copyright © 2024 HbarSuite. All rights reserved.

✨ Quick Start
🏗️ Architecture
🔧 API Reference
📖 Guides
🎯 Examples
🔗 Integration