mirror of
https://github.com/andwati/telecom-platform.git
synced 2026-11-29 15:28:48 +00:00
refactor: Move tenant repository files to repository package and update imports
- Move tenant_aware_repository.go from internal/tenant to internal/repository package - Move repository.go to tenant_repository.go in internal/repository package - Add tenant package import for type references in tenant_repository.go - Update filter type references to use tenant package prefix (TenantFilter, TenantUserFilter, TenantUsageFilter) - Update return type for GetUsageStats to use tenant.TenantUsageStats
This commit is contained in:
@@ -1,595 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// TenantAnalyticsService provides analytics and monitoring for tenants
|
||||
type TenantAnalyticsService struct {
|
||||
repository Repository
|
||||
metricsCollector MetricsCollector
|
||||
eventPublisher EventPublisher
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewTenantAnalyticsService creates a new tenant analytics service
|
||||
func NewTenantAnalyticsService(
|
||||
repository Repository,
|
||||
metricsCollector MetricsCollector,
|
||||
eventPublisher EventPublisher,
|
||||
logger *logrus.Logger,
|
||||
) *TenantAnalyticsService {
|
||||
return &TenantAnalyticsService{
|
||||
repository: repository,
|
||||
metricsCollector: metricsCollector,
|
||||
eventPublisher: eventPublisher,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// GetTenantDashboard returns dashboard data for a tenant
|
||||
func (s *TenantAnalyticsService) GetTenantDashboard(ctx context.Context, tenantID string) (*TenantDashboard, error) {
|
||||
// Get usage stats
|
||||
usageStats, err := s.repository.GetUsageStats(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get usage stats: %w", err)
|
||||
}
|
||||
|
||||
// Get tenant metrics
|
||||
metrics, err := s.GetTenantMetrics(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant metrics: %w", err)
|
||||
}
|
||||
|
||||
// Get recent events
|
||||
events, err := s.repository.ListEvents(ctx, tenantID, 10)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant events: %w", err)
|
||||
}
|
||||
|
||||
// Get quota status
|
||||
var quotaStatus []*TenantUsage
|
||||
quotaFilter := &TenantUsageFilter{TenantID: tenantID}
|
||||
quotaStatus, err = s.repository.ListUsage(ctx, quotaFilter)
|
||||
if err != nil {
|
||||
// Handle gracefully - quota might not exist yet
|
||||
quotaStatus = []*TenantUsage{}
|
||||
}
|
||||
|
||||
dashboard := &TenantDashboard{
|
||||
TenantID: tenantID,
|
||||
UsageStats: usageStats,
|
||||
Metrics: metrics,
|
||||
RecentEvents: events,
|
||||
QuotaStatus: quotaStatus,
|
||||
LastUpdated: time.Now(),
|
||||
}
|
||||
|
||||
return dashboard, nil
|
||||
}
|
||||
|
||||
// GetTenantMetrics returns comprehensive metrics for a tenant
|
||||
func (s *TenantAnalyticsService) GetTenantMetrics(ctx context.Context, tenantID string) (*TenantMetrics, error) {
|
||||
// Get basic metrics from repository
|
||||
basicMetrics, err := s.repository.GetUsageStats(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Get events for activity analysis
|
||||
events, err := s.repository.ListEvents(ctx, tenantID, 1000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Build comprehensive metrics
|
||||
metrics := &TenantMetrics{
|
||||
TenantID: tenantID,
|
||||
ActiveUsers: basicMetrics.ActiveUsers,
|
||||
TotalRequests: 0,
|
||||
ErrorRate: 0,
|
||||
ResponseTime: 0,
|
||||
StorageUsed: 0,
|
||||
LastActivity: time.Time{},
|
||||
HealthScore: 100.0,
|
||||
Alerts: []string{},
|
||||
}
|
||||
|
||||
// Analyze events for metrics
|
||||
errorCount := 0
|
||||
totalRequests := 0
|
||||
var totalResponseTime time.Duration
|
||||
lastActivity := time.Time{}
|
||||
|
||||
for _, event := range events {
|
||||
if event.Timestamp.After(lastActivity) {
|
||||
lastActivity = event.Timestamp
|
||||
}
|
||||
|
||||
switch event.EventType {
|
||||
case "api_request":
|
||||
totalRequests++
|
||||
if statusCode, exists := event.EventData["status_code"]; exists {
|
||||
if code, ok := statusCode.(float64); ok && code >= 400 {
|
||||
errorCount++
|
||||
}
|
||||
}
|
||||
if responseTime, exists := event.EventData["response_time"]; exists {
|
||||
if rt, ok := responseTime.(float64); ok {
|
||||
totalResponseTime += time.Duration(rt) * time.Millisecond
|
||||
}
|
||||
}
|
||||
case "resource_created", "resource_updated", "resource_deleted":
|
||||
metrics.TotalRequests++
|
||||
}
|
||||
}
|
||||
|
||||
if totalRequests > 0 {
|
||||
metrics.ErrorRate = float64(errorCount) / float64(totalRequests) * 100
|
||||
metrics.ResponseTime = float64(totalResponseTime) / float64(totalRequests) / float64(time.Millisecond)
|
||||
}
|
||||
|
||||
metrics.TotalRequests = int64(totalRequests)
|
||||
metrics.LastActivity = lastActivity
|
||||
|
||||
// Calculate health score and alerts
|
||||
metrics.HealthScore = s.calculateHealthScore(basicMetrics, metrics.ErrorRate)
|
||||
metrics.Alerts = s.generateAlerts(basicMetrics, metrics.ErrorRate)
|
||||
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
// GetUsageAnalytics returns detailed usage analytics for a tenant
|
||||
func (s *TenantAnalyticsService) GetUsageAnalytics(ctx context.Context, tenantID string, timeRange string) (*TenantUsageAnalytics, error) {
|
||||
// Parse time range
|
||||
startDate, endDate := s.parseTimeRange(timeRange)
|
||||
|
||||
// Get usage records
|
||||
usageFilter := &TenantUsageFilter{
|
||||
TenantID: tenantID,
|
||||
PeriodStart: startDate,
|
||||
PeriodEnd: endDate,
|
||||
}
|
||||
|
||||
usageRecords, err := s.repository.ListUsage(ctx, usageFilter)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get usage records: %w", err)
|
||||
}
|
||||
|
||||
// Build analytics
|
||||
analytics := &TenantUsageAnalytics{
|
||||
TenantID: tenantID,
|
||||
TimeRange: timeRange,
|
||||
StartDate: startDate,
|
||||
EndDate: endDate,
|
||||
UsageByType: make(map[string]*ResourceUsageAnalytics),
|
||||
Trends: make(map[string][]*UsageTrend),
|
||||
Peaks: make(map[string]*UsagePeak),
|
||||
}
|
||||
|
||||
// Process usage records
|
||||
for _, usage := range usageRecords {
|
||||
if _, exists := analytics.UsageByType[usage.ResourceType]; !exists {
|
||||
analytics.UsageByType[usage.ResourceType] = &ResourceUsageAnalytics{
|
||||
ResourceType: usage.ResourceType,
|
||||
TotalUsage: 0,
|
||||
AverageUsage: 0,
|
||||
PeakUsage: 0,
|
||||
PeakTime: time.Time{},
|
||||
}
|
||||
}
|
||||
|
||||
resourceAnalytics := analytics.UsageByType[usage.ResourceType]
|
||||
resourceAnalytics.TotalUsage += usage.QuotaUsed
|
||||
|
||||
if usage.QuotaUsed > resourceAnalytics.PeakUsage {
|
||||
resourceAnalytics.PeakUsage = usage.QuotaUsed
|
||||
resourceAnalytics.PeakTime = usage.UpdatedAt
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate averages
|
||||
for _, resourceAnalytics := range analytics.UsageByType {
|
||||
if len(usageRecords) > 0 {
|
||||
resourceAnalytics.AverageUsage = resourceAnalytics.TotalUsage / len(usageRecords)
|
||||
}
|
||||
}
|
||||
|
||||
return analytics, nil
|
||||
}
|
||||
|
||||
// GetPerformanceAnalytics returns performance analytics for a tenant
|
||||
func (s *TenantAnalyticsService) GetPerformanceAnalytics(ctx context.Context, tenantID string, timeRange string) (*TenantPerformanceAnalytics, error) {
|
||||
// Get events for performance analysis
|
||||
events, err := s.repository.ListEvents(ctx, tenantID, 10000)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant events: %w", err)
|
||||
}
|
||||
|
||||
// Parse time range
|
||||
startDate, endDate := s.parseTimeRange(timeRange)
|
||||
|
||||
// Build performance analytics
|
||||
analytics := &TenantPerformanceAnalytics{
|
||||
TenantID: tenantID,
|
||||
TimeRange: timeRange,
|
||||
StartDate: startDate,
|
||||
EndDate: endDate,
|
||||
APIPerformance: &APIPerformance{},
|
||||
ResourcePerformance: make(map[string]*ResourcePerformance),
|
||||
Errors: []*ErrorEvent{},
|
||||
SlowQueries: []*SlowQuery{},
|
||||
}
|
||||
|
||||
// Process events
|
||||
apiRequests := []*APIRequestEvent{}
|
||||
for _, event := range events {
|
||||
if event.Timestamp.Before(startDate) || event.Timestamp.After(endDate) {
|
||||
continue
|
||||
}
|
||||
|
||||
switch event.EventType {
|
||||
case "api_request":
|
||||
apiRequest := s.parseAPIRequestEvent(event)
|
||||
if apiRequest != nil {
|
||||
apiRequests = append(apiRequests, apiRequest)
|
||||
}
|
||||
case "error":
|
||||
errorEvent := s.parseErrorEvent(event)
|
||||
if errorEvent != nil {
|
||||
analytics.Errors = append(analytics.Errors, errorEvent)
|
||||
}
|
||||
case "slow_query":
|
||||
slowQuery := s.parseSlowQueryEvent(event)
|
||||
if slowQuery != nil {
|
||||
analytics.SlowQueries = append(analytics.SlowQueries, slowQuery)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate API performance metrics
|
||||
analytics.APIPerformance = s.calculateAPIPerformance(apiRequests)
|
||||
|
||||
return analytics, nil
|
||||
}
|
||||
|
||||
// GetCostAnalytics returns cost analytics for a tenant
|
||||
func (s *TenantAnalyticsService) GetCostAnalytics(ctx context.Context, tenantID string, timeRange string) (*TenantCostAnalytics, error) {
|
||||
// Parse time range
|
||||
startDate, endDate := s.parseTimeRange(timeRange)
|
||||
|
||||
// Get tenant configuration to understand pricing
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
// Build cost analytics
|
||||
analytics := &TenantCostAnalytics{
|
||||
TenantID: tenantID,
|
||||
TimeRange: timeRange,
|
||||
StartDate: startDate,
|
||||
EndDate: endDate,
|
||||
TotalCost: 0,
|
||||
CostByType: make(map[string]float64),
|
||||
CostTrends: []*CostTrend{},
|
||||
Predictions: &CostPrediction{},
|
||||
Savings: &CostSavings{},
|
||||
}
|
||||
|
||||
// Calculate costs based on usage and plan
|
||||
plan := s.getTenantPlan(tenantID, config)
|
||||
analytics.TotalCost = s.calculateTotalCost(plan, analytics.TimeRange)
|
||||
analytics.CostByType = s.calculateCostByType(plan, analytics.TimeRange)
|
||||
|
||||
return analytics, nil
|
||||
}
|
||||
|
||||
// GenerateTenantReport generates a comprehensive tenant report
|
||||
func (s *TenantAnalyticsService) GenerateTenantReport(ctx context.Context, tenantID string, reportType string, timeRange string) (*TenantReport, error) {
|
||||
report := &TenantReport{
|
||||
TenantID: tenantID,
|
||||
ReportType: reportType,
|
||||
TimeRange: timeRange,
|
||||
GeneratedAt: time.Now(),
|
||||
}
|
||||
|
||||
switch reportType {
|
||||
case "dashboard":
|
||||
dashboard, err := s.GetTenantDashboard(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
report.Dashboard = dashboard
|
||||
|
||||
case "usage":
|
||||
usageAnalytics, err := s.GetUsageAnalytics(ctx, tenantID, timeRange)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
report.UsageAnalytics = usageAnalytics
|
||||
|
||||
case "performance":
|
||||
performanceAnalytics, err := s.GetPerformanceAnalytics(ctx, tenantID, timeRange)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
report.PerformanceAnalytics = performanceAnalytics
|
||||
|
||||
case "cost":
|
||||
costAnalytics, err := s.GetCostAnalytics(ctx, tenantID, timeRange)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
report.CostAnalytics = costAnalytics
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported report type: %s", reportType)
|
||||
}
|
||||
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
|
||||
func (s *TenantAnalyticsService) calculateHealthScore(usageStats *TenantUsageStats, errorRate float64) float64 {
|
||||
score := 100.0
|
||||
|
||||
// Deduct points for high error rate
|
||||
if errorRate > 10 {
|
||||
score -= 30
|
||||
} else if errorRate > 5 {
|
||||
score -= 15
|
||||
} else if errorRate > 1 {
|
||||
score -= 5
|
||||
}
|
||||
|
||||
// Deduct points for quota issues
|
||||
for _, quotaStatus := range usageStats.QuotaStatus {
|
||||
if quotaStatus.Critical {
|
||||
score -= 20
|
||||
} else if quotaStatus.Warning {
|
||||
score -= 10
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure score doesn't go below 0
|
||||
if score < 0 {
|
||||
score = 0
|
||||
}
|
||||
|
||||
return score
|
||||
}
|
||||
|
||||
func (s *TenantAnalyticsService) generateAlerts(usageStats *TenantUsageStats, errorRate float64) []string {
|
||||
alerts := []string{}
|
||||
|
||||
// Error rate alerts
|
||||
if errorRate > 10 {
|
||||
alerts = append(alerts, "Critical: High error rate detected")
|
||||
} else if errorRate > 5 {
|
||||
alerts = append(alerts, "Warning: Elevated error rate")
|
||||
}
|
||||
|
||||
// Quota alerts
|
||||
for resourceType, quotaStatus := range usageStats.QuotaStatus {
|
||||
if quotaStatus.Critical {
|
||||
alerts = append(alerts, fmt.Sprintf("Critical: %s quota at %.1f%%", resourceType, quotaStatus.Percent))
|
||||
} else if quotaStatus.Warning {
|
||||
alerts = append(alerts, fmt.Sprintf("Warning: %s quota at %.1f%%", resourceType, quotaStatus.Percent))
|
||||
}
|
||||
}
|
||||
|
||||
return alerts
|
||||
}
|
||||
|
||||
func (s *TenantAnalyticsService) parseTimeRange(timeRange string) (time.Time, time.Time) {
|
||||
now := time.Now()
|
||||
|
||||
switch timeRange {
|
||||
case "1h":
|
||||
return now.Add(-1 * time.Hour), now
|
||||
case "24h":
|
||||
return now.Add(-24 * time.Hour), now
|
||||
case "7d":
|
||||
return now.Add(-7 * 24 * time.Hour), now
|
||||
case "30d":
|
||||
return now.Add(-30 * 24 * time.Hour), now
|
||||
case "90d":
|
||||
return now.Add(-90 * 24 * time.Hour), now
|
||||
default:
|
||||
return now.Add(-24 * time.Hour), now
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TenantAnalyticsService) parseAPIRequestEvent(event *TenantEvent) *APIRequestEvent {
|
||||
// Implementation depends on event structure
|
||||
return &APIRequestEvent{
|
||||
Timestamp: event.Timestamp,
|
||||
Endpoint: "",
|
||||
Method: "",
|
||||
StatusCode: 200,
|
||||
ResponseTime: 0,
|
||||
UserID: event.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TenantAnalyticsService) parseErrorEvent(event *TenantEvent) *ErrorEvent {
|
||||
// Implementation depends on event structure
|
||||
return &ErrorEvent{
|
||||
Timestamp: event.Timestamp,
|
||||
Error: "",
|
||||
Context: event.EventData,
|
||||
UserID: event.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TenantAnalyticsService) parseSlowQueryEvent(event *TenantEvent) *SlowQuery {
|
||||
// Implementation depends on event structure
|
||||
return &SlowQuery{
|
||||
Timestamp: event.Timestamp,
|
||||
Query: "",
|
||||
Duration: 0,
|
||||
Context: event.EventData,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TenantAnalyticsService) calculateAPIPerformance(requests []*APIRequestEvent) *APIPerformance {
|
||||
// Implementation would calculate performance metrics
|
||||
return &APIPerformance{
|
||||
TotalRequests: len(requests),
|
||||
AverageResponseTime: 0,
|
||||
P95ResponseTime: 0,
|
||||
ErrorRate: 0,
|
||||
RequestsPerSecond: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TenantAnalyticsService) getTenantPlan(tenantID string, config *TenantConfig) TenantPlan {
|
||||
// Extract plan from tenant config or database
|
||||
return TenantPlanPro // Default
|
||||
}
|
||||
|
||||
func (s *TenantAnalyticsService) calculateTotalCost(plan TenantPlan, timeRange string) float64 {
|
||||
// Implementation would calculate cost based on plan and usage
|
||||
return 0.0
|
||||
}
|
||||
|
||||
func (s *TenantAnalyticsService) calculateCostByType(plan TenantPlan, timeRange string) map[string]float64 {
|
||||
// Implementation would calculate cost breakdown by resource type
|
||||
return make(map[string]float64)
|
||||
}
|
||||
|
||||
// Data structures for analytics
|
||||
|
||||
type TenantDashboard struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
UsageStats *TenantUsageStats `json:"usage_stats"`
|
||||
Metrics *TenantMetrics `json:"metrics"`
|
||||
RecentEvents []*TenantEvent `json:"recent_events"`
|
||||
QuotaStatus []*TenantUsage `json:"quota_status"`
|
||||
LastUpdated time.Time `json:"last_updated"`
|
||||
}
|
||||
|
||||
type TenantUsageAnalytics struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
TimeRange string `json:"time_range"`
|
||||
StartDate time.Time `json:"start_date"`
|
||||
EndDate time.Time `json:"end_date"`
|
||||
UsageByType map[string]*ResourceUsageAnalytics `json:"usage_by_type"`
|
||||
Trends map[string][]*UsageTrend `json:"trends"`
|
||||
Peaks map[string]*UsagePeak `json:"peaks"`
|
||||
}
|
||||
|
||||
type ResourceUsageAnalytics struct {
|
||||
ResourceType string `json:"resource_type"`
|
||||
TotalUsage int `json:"total_usage"`
|
||||
AverageUsage int `json:"average_usage"`
|
||||
PeakUsage int `json:"peak_usage"`
|
||||
PeakTime time.Time `json:"peak_time"`
|
||||
}
|
||||
|
||||
type UsageTrend struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Usage int `json:"usage"`
|
||||
}
|
||||
|
||||
type UsagePeak struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Usage int `json:"usage"`
|
||||
Context map[string]interface{} `json:"context"`
|
||||
}
|
||||
|
||||
type TenantPerformanceAnalytics struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
TimeRange string `json:"time_range"`
|
||||
StartDate time.Time `json:"start_date"`
|
||||
EndDate time.Time `json:"end_date"`
|
||||
APIPerformance *APIPerformance `json:"api_performance"`
|
||||
ResourcePerformance map[string]*ResourcePerformance `json:"resource_performance"`
|
||||
Errors []*ErrorEvent `json:"errors"`
|
||||
SlowQueries []*SlowQuery `json:"slow_queries"`
|
||||
}
|
||||
|
||||
type APIPerformance struct {
|
||||
TotalRequests int `json:"total_requests"`
|
||||
AverageResponseTime float64 `json:"average_response_time"`
|
||||
P95ResponseTime float64 `json:"p95_response_time"`
|
||||
ErrorRate float64 `json:"error_rate"`
|
||||
RequestsPerSecond float64 `json:"requests_per_second"`
|
||||
}
|
||||
|
||||
type ResourcePerformance struct {
|
||||
ResourceType string `json:"resource_type"`
|
||||
AvgLatency float64 `json:"avg_latency"`
|
||||
P95Latency float64 `json:"p95_latency"`
|
||||
Throughput float64 `json:"throughput"`
|
||||
ErrorRate float64 `json:"error_rate"`
|
||||
}
|
||||
|
||||
type APIRequestEvent struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
Method string `json:"method"`
|
||||
StatusCode int `json:"status_code"`
|
||||
ResponseTime time.Duration `json:"response_time"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
type ErrorEvent struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Error string `json:"error"`
|
||||
Context map[string]interface{} `json:"context"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
type SlowQuery struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Query string `json:"query"`
|
||||
Duration time.Duration `json:"duration"`
|
||||
Context map[string]interface{} `json:"context"`
|
||||
}
|
||||
|
||||
type TenantCostAnalytics struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
TimeRange string `json:"time_range"`
|
||||
StartDate time.Time `json:"start_date"`
|
||||
EndDate time.Time `json:"end_date"`
|
||||
TotalCost float64 `json:"total_cost"`
|
||||
CostByType map[string]float64 `json:"cost_by_type"`
|
||||
CostTrends []*CostTrend `json:"cost_trends"`
|
||||
Predictions *CostPrediction `json:"predictions"`
|
||||
Savings *CostSavings `json:"savings"`
|
||||
}
|
||||
|
||||
type CostTrend struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Cost float64 `json:"cost"`
|
||||
}
|
||||
|
||||
type CostPrediction struct {
|
||||
PredictedCost float64 `json:"predicted_cost"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
Factors []string `json:"factors"`
|
||||
}
|
||||
|
||||
type CostSavings struct {
|
||||
PotentialSavings float64 `json:"potential_savings"`
|
||||
Recommendations []string `json:"recommendations"`
|
||||
Optimizations map[string]float64 `json:"optimizations"`
|
||||
}
|
||||
|
||||
type TenantReport struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
ReportType string `json:"report_type"`
|
||||
TimeRange string `json:"time_range"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
Dashboard *TenantDashboard `json:"dashboard,omitempty"`
|
||||
UsageAnalytics *TenantUsageAnalytics `json:"usage_analytics,omitempty"`
|
||||
PerformanceAnalytics *TenantPerformanceAnalytics `json:"performance_analytics,omitempty"`
|
||||
CostAnalytics *TenantCostAnalytics `json:"cost_analytics,omitempty"`
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/currency"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// TenantAwareCurrencyRepository wraps the currency repository with tenant isolation
|
||||
type TenantAwareCurrencyRepository struct {
|
||||
baseRepo currency.Repository
|
||||
tenantID string
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewTenantAwareCurrencyRepository creates a new tenant-aware currency repository
|
||||
func NewTenantAwareCurrencyRepository(baseRepo currency.Repository, tenantID string, logger *logrus.Logger) currency.Repository {
|
||||
return &TenantAwareCurrencyRepository{
|
||||
baseRepo: baseRepo,
|
||||
tenantID: tenantID,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// WithTenant creates a new instance with the specified tenant ID
|
||||
func (r *TenantAwareCurrencyRepository) WithTenant(tenantID string) currency.Repository {
|
||||
return &TenantAwareCurrencyRepository{
|
||||
baseRepo: r.baseRepo,
|
||||
tenantID: tenantID,
|
||||
logger: r.logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Tenant-aware currency repository methods
|
||||
func (r *TenantAwareCurrencyRepository) CreateCurrency(ctx context.Context, currency *currency.Currency) error {
|
||||
// Add tenant context
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.CreateCurrency(ctx, currency)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) GetCurrency(ctx context.Context, code string) (*currency.Currency, error) {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.GetCurrency(ctx, code)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) UpdateCurrency(ctx context.Context, currency *currency.Currency) error {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.UpdateCurrency(ctx, currency)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) DeleteCurrency(ctx context.Context, code string) error {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.DeleteCurrency(ctx, code)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) ListCurrencies(ctx context.Context, filter *currency.CurrencyFilter) ([]*currency.Currency, error) {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.ListCurrencies(ctx, filter)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) CountCurrencies(ctx context.Context, filter *currency.CurrencyFilter) (int, error) {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.CountCurrencies(ctx, filter)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) CreateExchangeRate(ctx context.Context, rate *currency.ExchangeRate) error {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.CreateExchangeRate(ctx, rate)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) GetExchangeRate(ctx context.Context, fromCurrency, toCurrency string) (*currency.ExchangeRate, error) {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.GetExchangeRate(ctx, fromCurrency, toCurrency)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) UpdateExchangeRate(ctx context.Context, rate *currency.ExchangeRate) error {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.UpdateExchangeRate(ctx, rate)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) DeleteExchangeRate(ctx context.Context, id string) error {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.DeleteExchangeRate(ctx, id)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) ListExchangeRates(ctx context.Context, filter *currency.ExchangeRateFilter) ([]*currency.ExchangeRate, error) {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.ListExchangeRates(ctx, filter)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) GetLatestExchangeRate(ctx context.Context, fromCurrency, toCurrency string) (*currency.ExchangeRate, error) {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.GetLatestExchangeRate(ctx, fromCurrency, toCurrency)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) CreateTransaction(ctx context.Context, transaction *currency.Transaction) error {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.CreateTransaction(ctx, transaction)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) GetTransaction(ctx context.Context, id string) (*currency.Transaction, error) {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.GetTransaction(ctx, id)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) UpdateTransaction(ctx context.Context, transaction *currency.Transaction) error {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.UpdateTransaction(ctx, transaction)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) DeleteTransaction(ctx context.Context, id string) error {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.DeleteTransaction(ctx, id)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) ListTransactions(ctx context.Context, filter *currency.TransactionFilter) ([]*currency.Transaction, error) {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.ListTransactions(ctx, filter)
|
||||
}
|
||||
|
||||
func (r *TenantAwareCurrencyRepository) CountTransactions(ctx context.Context, filter *currency.TransactionFilter) (int, error) {
|
||||
ctx = SetTenantInContext(ctx, r.tenantID)
|
||||
return r.baseRepo.CountTransactions(ctx, filter)
|
||||
}
|
||||
|
||||
// TenantIntegrationManager manages tenant integration across all services
|
||||
type TenantIntegrationManager struct {
|
||||
tenantService Service
|
||||
currencyService currency.BillingService
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewTenantIntegrationManager creates a new tenant integration manager
|
||||
func NewTenantIntegrationManager(
|
||||
tenantService Service,
|
||||
currencyService currency.BillingService,
|
||||
logger *logrus.Logger,
|
||||
) *TenantIntegrationManager {
|
||||
return &TenantIntegrationManager{
|
||||
tenantService: tenantService,
|
||||
currencyService: currencyService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// GetTenantAwareServices returns tenant-aware service instances
|
||||
func (m *TenantIntegrationManager) GetTenantAwareServices(ctx context.Context, tenantID string) (*TenantAwareServices, error) {
|
||||
// Validate tenant
|
||||
tenantCtx, err := m.tenantService.ValidateTenantAccess(ctx, tenantID, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to validate tenant: %w", err)
|
||||
}
|
||||
|
||||
// Get tenant configuration
|
||||
config, err := m.tenantService.GetTenantConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
// Create tenant-aware services
|
||||
services := &TenantAwareServices{
|
||||
TenantID: tenantID,
|
||||
TenantContext: tenantCtx,
|
||||
Config: config,
|
||||
CurrencyService: m.wrapCurrencyService(tenantID),
|
||||
}
|
||||
|
||||
return services, nil
|
||||
}
|
||||
|
||||
// TenantAwareServices provides tenant-aware service instances
|
||||
type TenantAwareServices struct {
|
||||
TenantID string
|
||||
TenantContext *TenantContext
|
||||
Config *TenantConfig
|
||||
CurrencyService currency.BillingService
|
||||
}
|
||||
|
||||
// wrapCurrencyService creates a tenant-aware currency service
|
||||
func (m *TenantIntegrationManager) wrapCurrencyService(tenantID string) currency.BillingService {
|
||||
// This would wrap the existing currency service with tenant isolation
|
||||
// Implementation depends on the actual currency service structure
|
||||
return m.currencyService // Placeholder - would need actual wrapping
|
||||
}
|
||||
|
||||
// TenantResourceQuotaChecker checks resource quotas before operations
|
||||
type TenantResourceQuotaChecker struct {
|
||||
tenantService Service
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewTenantResourceQuotaChecker creates a new quota checker
|
||||
func NewTenantResourceQuotaChecker(tenantService Service, logger *logrus.Logger) *TenantResourceQuotaChecker {
|
||||
return &TenantResourceQuotaChecker{
|
||||
tenantService: tenantService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CheckQuota checks if tenant has sufficient quota for a resource operation
|
||||
func (c *TenantResourceQuotaChecker) CheckQuota(ctx context.Context, tenantID, resourceType string, count int) error {
|
||||
return c.tenantService.CheckQuota(ctx, tenantID, resourceType, count)
|
||||
}
|
||||
|
||||
// UpdateUsage updates resource usage after an operation
|
||||
func (c *TenantResourceQuotaChecker) UpdateUsage(ctx context.Context, tenantID, resourceType string, count int) error {
|
||||
return c.tenantService.UpdateUsage(ctx, tenantID, resourceType, count)
|
||||
}
|
||||
|
||||
// TenantEventLogger logs tenant events for audit purposes
|
||||
type TenantEventLogger struct {
|
||||
tenantService Service
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewTenantEventLogger creates a new tenant event logger
|
||||
func NewTenantEventLogger(tenantService Service, logger *logrus.Logger) *TenantEventLogger {
|
||||
return &TenantEventLogger{
|
||||
tenantService: tenantService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// LogResourceAccess logs resource access events
|
||||
func (l *TenantEventLogger) LogResourceAccess(ctx context.Context, tenantID, userID, resourceType, resourceID, action string) {
|
||||
event := &TenantEvent{
|
||||
ID: generateID(),
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
EventType: TenantEventType("resource_access"),
|
||||
EventData: map[string]interface{}{
|
||||
"resource_type": resourceType,
|
||||
"resource_id": resourceID,
|
||||
"action": action,
|
||||
},
|
||||
Timestamp: getCurrentTimestamp(),
|
||||
}
|
||||
|
||||
if err := l.tenantService.LogTenantEvent(ctx, event); err != nil {
|
||||
l.logger.WithError(err).Error("Failed to log resource access event")
|
||||
}
|
||||
}
|
||||
|
||||
// LogQuotaViolation logs quota violation events
|
||||
func (l *TenantEventLogger) LogQuotaViolation(ctx context.Context, tenantID, resourceType string, usage, limit int) {
|
||||
event := &TenantEvent{
|
||||
ID: generateID(),
|
||||
TenantID: tenantID,
|
||||
UserID: "",
|
||||
EventType: TenantEventQuotaExceeded,
|
||||
EventData: map[string]interface{}{
|
||||
"resource_type": resourceType,
|
||||
"usage": usage,
|
||||
"limit": limit,
|
||||
},
|
||||
Timestamp: getCurrentTimestamp(),
|
||||
}
|
||||
|
||||
if err := l.tenantService.LogTenantEvent(ctx, event); err != nil {
|
||||
l.logger.WithError(err).Error("Failed to log quota violation event")
|
||||
}
|
||||
}
|
||||
@@ -1,535 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// GormTenantRepository implements the tenant repository interface using GORM
|
||||
type GormTenantRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewGormTenantRepository creates a new GORM tenant repository
|
||||
func NewGormTenantRepository(db *gorm.DB) Repository {
|
||||
return &GormTenantRepository{db: db}
|
||||
}
|
||||
|
||||
// CreateTenant creates a new tenant
|
||||
func (r *GormTenantRepository) CreateTenant(ctx context.Context, tenant *Tenant) error {
|
||||
return r.db.WithContext(ctx).Create(tenant).Error
|
||||
}
|
||||
|
||||
// GetTenant retrieves a tenant by ID
|
||||
func (r *GormTenantRepository) GetTenant(ctx context.Context, id string) (*Tenant, error) {
|
||||
var tenant Tenant
|
||||
err := r.db.WithContext(ctx).Where("id = ?", id).First(&tenant).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tenant, nil
|
||||
}
|
||||
|
||||
// GetTenantByDomain retrieves a tenant by domain
|
||||
func (r *GormTenantRepository) GetTenantByDomain(ctx context.Context, domain string) (*Tenant, error) {
|
||||
var tenant Tenant
|
||||
err := r.db.WithContext(ctx).Where("domain = ?", domain).First(&tenant).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tenant, nil
|
||||
}
|
||||
|
||||
// UpdateTenant updates an existing tenant
|
||||
func (r *GormTenantRepository) UpdateTenant(ctx context.Context, tenant *Tenant) error {
|
||||
return r.db.WithContext(ctx).Save(tenant).Error
|
||||
}
|
||||
|
||||
// DeleteTenant deletes a tenant
|
||||
func (r *GormTenantRepository) DeleteTenant(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Delete(&Tenant{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// ListTenants lists tenants with filtering
|
||||
func (r *GormTenantRepository) ListTenants(ctx context.Context, filter *TenantFilter) ([]*Tenant, error) {
|
||||
query := r.db.WithContext(ctx).Model(&Tenant{})
|
||||
|
||||
// Apply filters
|
||||
if filter.ID != "" {
|
||||
query = query.Where("id = ?", filter.ID)
|
||||
}
|
||||
if filter.Name != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+filter.Name+"%")
|
||||
}
|
||||
if filter.Domain != "" {
|
||||
query = query.Where("domain ILIKE ?", "%"+filter.Domain+"%")
|
||||
}
|
||||
if filter.Status != "" {
|
||||
query = query.Where("status = ?", filter.Status)
|
||||
}
|
||||
if filter.Plan != "" {
|
||||
query = query.Where("plan = ?", filter.Plan)
|
||||
}
|
||||
|
||||
// Apply sorting
|
||||
if filter.SortBy != "" {
|
||||
order := filter.SortBy
|
||||
if filter.SortOrder == "desc" {
|
||||
order += " DESC"
|
||||
}
|
||||
query = query.Order(order)
|
||||
} else {
|
||||
query = query.Order("created_at DESC")
|
||||
}
|
||||
|
||||
// Apply pagination
|
||||
if filter.Limit > 0 {
|
||||
query = query.Limit(filter.Limit)
|
||||
}
|
||||
if filter.Offset > 0 {
|
||||
query = query.Offset(filter.Offset)
|
||||
}
|
||||
|
||||
var tenants []*Tenant
|
||||
err := query.Find(&tenants).Error
|
||||
return tenants, err
|
||||
}
|
||||
|
||||
// CountTenants counts tenants with filtering
|
||||
func (r *GormTenantRepository) CountTenants(ctx context.Context, filter *TenantFilter) (int, error) {
|
||||
query := r.db.WithContext(ctx).Model(&Tenant{})
|
||||
|
||||
// Apply filters
|
||||
if filter.ID != "" {
|
||||
query = query.Where("id = ?", filter.ID)
|
||||
}
|
||||
if filter.Name != "" {
|
||||
query = query.Where("name ILIKE ?", "%"+filter.Name+"%")
|
||||
}
|
||||
if filter.Domain != "" {
|
||||
query = query.Where("domain ILIKE ?", "%"+filter.Domain+"%")
|
||||
}
|
||||
if filter.Status != "" {
|
||||
query = query.Where("status = ?", filter.Status)
|
||||
}
|
||||
if filter.Plan != "" {
|
||||
query = query.Where("plan = ?", filter.Plan)
|
||||
}
|
||||
|
||||
var count int64
|
||||
err := query.Count(&count).Error
|
||||
return int(count), err
|
||||
}
|
||||
|
||||
// CreateTenantUser creates a new tenant user
|
||||
func (r *GormTenantRepository) CreateTenantUser(ctx context.Context, user *TenantUser) error {
|
||||
return r.db.WithContext(ctx).Create(user).Error
|
||||
}
|
||||
|
||||
// GetTenantUser retrieves a tenant user
|
||||
func (r *GormTenantRepository) GetTenantUser(ctx context.Context, tenantID, userID string) (*TenantUser, error) {
|
||||
var user TenantUser
|
||||
err := r.db.WithContext(ctx).Where("tenant_id = ? AND user_id = ?", tenantID, userID).First(&user).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// UpdateTenantUser updates a tenant user
|
||||
func (r *GormTenantRepository) UpdateTenantUser(ctx context.Context, user *TenantUser) error {
|
||||
return r.db.WithContext(ctx).Save(user).Error
|
||||
}
|
||||
|
||||
// DeleteTenantUser deletes a tenant user
|
||||
func (r *GormTenantRepository) DeleteTenantUser(ctx context.Context, tenantID, userID string) error {
|
||||
return r.db.WithContext(ctx).Delete(&TenantUser{}, "tenant_id = ? AND user_id = ?", tenantID, userID).Error
|
||||
}
|
||||
|
||||
// ListTenantUsers lists tenant users with filtering
|
||||
func (r *GormTenantRepository) ListTenantUsers(ctx context.Context, filter *TenantUserFilter) ([]*TenantUser, error) {
|
||||
query := r.db.WithContext(ctx).Model(&TenantUser{})
|
||||
|
||||
// Apply filters
|
||||
if filter.TenantID != "" {
|
||||
query = query.Where("tenant_id = ?", filter.TenantID)
|
||||
}
|
||||
if filter.UserID != "" {
|
||||
query = query.Where("user_id = ?", filter.UserID)
|
||||
}
|
||||
if filter.Email != "" {
|
||||
query = query.Where("email ILIKE ?", "%"+filter.Email+"%")
|
||||
}
|
||||
if filter.Role != "" {
|
||||
query = query.Where("role = ?", filter.Role)
|
||||
}
|
||||
if filter.Status != "" {
|
||||
query = query.Where("status = ?", filter.Status)
|
||||
}
|
||||
|
||||
// Apply pagination
|
||||
if filter.Limit > 0 {
|
||||
query = query.Limit(filter.Limit)
|
||||
}
|
||||
if filter.Offset > 0 {
|
||||
query = query.Offset(filter.Offset)
|
||||
}
|
||||
|
||||
var users []*TenantUser
|
||||
err := query.Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
// CountTenantUsers counts tenant users with filtering
|
||||
func (r *GormTenantRepository) CountTenantUsers(ctx context.Context, filter *TenantUserFilter) (int, error) {
|
||||
query := r.db.WithContext(ctx).Model(&TenantUser{})
|
||||
|
||||
// Apply filters
|
||||
if filter.TenantID != "" {
|
||||
query = query.Where("tenant_id = ?", filter.TenantID)
|
||||
}
|
||||
if filter.UserID != "" {
|
||||
query = query.Where("user_id = ?", filter.UserID)
|
||||
}
|
||||
if filter.Email != "" {
|
||||
query = query.Where("email ILIKE ?", "%"+filter.Email+"%")
|
||||
}
|
||||
if filter.Role != "" {
|
||||
query = query.Where("role = ?", filter.Role)
|
||||
}
|
||||
if filter.Status != "" {
|
||||
query = query.Where("status = ?", filter.Status)
|
||||
}
|
||||
|
||||
var count int64
|
||||
err := query.Count(&count).Error
|
||||
return int(count), err
|
||||
}
|
||||
|
||||
// CreateAPIKey creates a new API key
|
||||
func (r *GormTenantRepository) CreateAPIKey(ctx context.Context, apiKey *TenantAPIKey) error {
|
||||
return r.db.WithContext(ctx).Create(apiKey).Error
|
||||
}
|
||||
|
||||
// GetAPIKey retrieves an API key by ID
|
||||
func (r *GormTenantRepository) GetAPIKey(ctx context.Context, id string) (*TenantAPIKey, error) {
|
||||
var apiKey TenantAPIKey
|
||||
err := r.db.WithContext(ctx).Where("id = ?", id).First(&apiKey).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &apiKey, nil
|
||||
}
|
||||
|
||||
// GetAPIKeyByHash retrieves an API key by hash
|
||||
func (r *GormTenantRepository) GetAPIKeyByHash(ctx context.Context, keyHash string) (*TenantAPIKey, error) {
|
||||
var apiKey TenantAPIKey
|
||||
err := r.db.WithContext(ctx).Where("key_hash = ?", keyHash).First(&apiKey).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &apiKey, nil
|
||||
}
|
||||
|
||||
// UpdateAPIKey updates an API key
|
||||
func (r *GormTenantRepository) UpdateAPIKey(ctx context.Context, apiKey *TenantAPIKey) error {
|
||||
return r.db.WithContext(ctx).Save(apiKey).Error
|
||||
}
|
||||
|
||||
// DeleteAPIKey deletes an API key
|
||||
func (r *GormTenantRepository) DeleteAPIKey(ctx context.Context, id string) error {
|
||||
return r.db.WithContext(ctx).Delete(&TenantAPIKey{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
// ListAPIKeys lists API keys for a tenant
|
||||
func (r *GormTenantRepository) ListAPIKeys(ctx context.Context, tenantID string) ([]*TenantAPIKey, error) {
|
||||
var apiKeys []*TenantAPIKey
|
||||
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Order("created_at DESC").Find(&apiKeys).Error
|
||||
return apiKeys, err
|
||||
}
|
||||
|
||||
// CreateUsage creates a new usage record
|
||||
func (r *GormTenantRepository) CreateUsage(ctx context.Context, usage *TenantUsage) error {
|
||||
return r.db.WithContext(ctx).Create(usage).Error
|
||||
}
|
||||
|
||||
// GetUsage retrieves usage by tenant and resource type
|
||||
func (r *GormTenantRepository) GetUsage(ctx context.Context, tenantID, resourceType string) (*TenantUsage, error) {
|
||||
var usage TenantUsage
|
||||
err := r.db.WithContext(ctx).Where("tenant_id = ? AND resource_type = ?", tenantID, resourceType).First(&usage).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &usage, nil
|
||||
}
|
||||
|
||||
// UpdateUsage updates a usage record
|
||||
func (r *GormTenantRepository) UpdateUsage(ctx context.Context, usage *TenantUsage) error {
|
||||
return r.db.WithContext(ctx).Save(usage).Error
|
||||
}
|
||||
|
||||
// ListUsage lists usage records with filtering
|
||||
func (r *GormTenantRepository) ListUsage(ctx context.Context, filter *TenantUsageFilter) ([]*TenantUsage, error) {
|
||||
query := r.db.WithContext(ctx).Model(&TenantUsage{})
|
||||
|
||||
// Apply filters
|
||||
if filter.TenantID != "" {
|
||||
query = query.Where("tenant_id = ?", filter.TenantID)
|
||||
}
|
||||
if filter.ResourceType != "" {
|
||||
query = query.Where("resource_type = ?", filter.ResourceType)
|
||||
}
|
||||
if !filter.PeriodStart.IsZero() {
|
||||
query = query.Where("period_start >= ?", filter.PeriodStart)
|
||||
}
|
||||
if !filter.PeriodEnd.IsZero() {
|
||||
query = query.Where("period_end <= ?", filter.PeriodEnd)
|
||||
}
|
||||
|
||||
// Apply pagination
|
||||
if filter.Limit > 0 {
|
||||
query = query.Limit(filter.Limit)
|
||||
}
|
||||
if filter.Offset > 0 {
|
||||
query = query.Offset(filter.Offset)
|
||||
}
|
||||
|
||||
var usage []*TenantUsage
|
||||
err := query.Find(&usage).Error
|
||||
return usage, err
|
||||
}
|
||||
|
||||
// GetUsageStats retrieves usage statistics for a tenant
|
||||
func (r *GormTenantRepository) GetUsageStats(ctx context.Context, tenantID string) (*TenantUsageStats, error) {
|
||||
// This is a complex query that would typically involve joins and aggregations
|
||||
// For now, return a basic implementation
|
||||
stats := &TenantUsageStats{
|
||||
TenantID: tenantID,
|
||||
ResourceBreakdown: make(map[string]int64),
|
||||
QuotaStatus: make(map[string]QuotaStatus),
|
||||
}
|
||||
|
||||
// Get all usage records for the tenant
|
||||
usageRecords, err := r.ListUsage(ctx, &TenantUsageFilter{TenantID: tenantID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Process usage records
|
||||
for _, usage := range usageRecords {
|
||||
stats.ResourceBreakdown[usage.ResourceType] = int64(usage.QuotaUsed)
|
||||
stats.QuotaStatus[usage.ResourceType] = QuotaStatus{
|
||||
Used: usage.QuotaUsed,
|
||||
Limit: usage.QuotaLimit,
|
||||
Remaining: usage.QuotaRemaining,
|
||||
}
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// GetConfig retrieves tenant configuration
|
||||
func (r *GormTenantRepository) GetConfig(ctx context.Context, tenantID string) (*TenantConfig, error) {
|
||||
// Get tenant to extract settings
|
||||
tenant, err := r.GetTenant(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create basic config
|
||||
config := &TenantConfig{
|
||||
TenantID: tenantID,
|
||||
Config: make(map[string]interface{}),
|
||||
Settings: tenant.Settings,
|
||||
Quotas: []ResourceQuota{},
|
||||
Features: make(map[string]bool),
|
||||
}
|
||||
|
||||
// Add default quotas based on plan
|
||||
switch tenant.Plan {
|
||||
case TenantPlanFree:
|
||||
config.Quotas = []ResourceQuota{
|
||||
{ResourceType: "users", Limit: 5, Period: "monthly"},
|
||||
{ResourceType: "profiles", Limit: 100, Period: "monthly"},
|
||||
{ResourceType: "carriers", Limit: 3, Period: "monthly"},
|
||||
}
|
||||
case TenantPlanBasic:
|
||||
config.Quotas = []ResourceQuota{
|
||||
{ResourceType: "users", Limit: 25, Period: "monthly"},
|
||||
{ResourceType: "profiles", Limit: 1000, Period: "monthly"},
|
||||
{ResourceType: "carriers", Limit: 10, Period: "monthly"},
|
||||
}
|
||||
case TenantPlanPro:
|
||||
config.Quotas = []ResourceQuota{
|
||||
{ResourceType: "users", Limit: 100, Period: "monthly"},
|
||||
{ResourceType: "profiles", Limit: 10000, Period: "monthly"},
|
||||
{ResourceType: "carriers", Limit: 50, Period: "monthly"},
|
||||
}
|
||||
case TenantPlanEnterprise:
|
||||
config.Quotas = []ResourceQuota{
|
||||
{ResourceType: "users", Limit: -1, Period: "monthly"},
|
||||
{ResourceType: "profiles", Limit: -1, Period: "monthly"},
|
||||
{ResourceType: "carriers", Limit: -1, Period: "monthly"},
|
||||
}
|
||||
}
|
||||
|
||||
// Add default features based on plan
|
||||
switch tenant.Plan {
|
||||
case TenantPlanFree:
|
||||
config.Features = map[string]bool{
|
||||
"multi_currency": false,
|
||||
"advanced_analytics": false,
|
||||
"api_access": true,
|
||||
"webhooks": false,
|
||||
}
|
||||
case TenantPlanBasic:
|
||||
config.Features = map[string]bool{
|
||||
"multi_currency": true,
|
||||
"advanced_analytics": false,
|
||||
"api_access": true,
|
||||
"webhooks": false,
|
||||
}
|
||||
case TenantPlanPro, TenantPlanEnterprise:
|
||||
config.Features = map[string]bool{
|
||||
"multi_currency": true,
|
||||
"advanced_analytics": true,
|
||||
"api_access": true,
|
||||
"webhooks": true,
|
||||
}
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// UpdateConfig updates tenant configuration
|
||||
func (r *GormTenantRepository) UpdateConfig(ctx context.Context, config *TenantConfig) error {
|
||||
// Store configuration in tenant metadata or separate table
|
||||
// For now, update tenant settings
|
||||
tenant, err := r.GetTenant(ctx, config.TenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tenant.Settings = config.Settings
|
||||
tenant.Metadata = config.Config
|
||||
tenant.UpdatedAt = time.Now()
|
||||
|
||||
return r.UpdateTenant(ctx, tenant)
|
||||
}
|
||||
|
||||
// CreateEvent creates a new tenant event
|
||||
func (r *GormTenantRepository) CreateEvent(ctx context.Context, event *TenantEvent) error {
|
||||
// Store events in a separate table or log system
|
||||
// For now, we'll use a simple approach with JSON storage
|
||||
eventData, err := json.Marshal(event)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create a simple event record (in a real implementation, this would be a proper table)
|
||||
eventRecord := struct {
|
||||
ID string `gorm:"primaryKey"`
|
||||
TenantID string `gorm:"index"`
|
||||
EventData string `gorm:"type:text"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
}{
|
||||
ID: event.ID,
|
||||
TenantID: event.TenantID,
|
||||
EventData: string(eventData),
|
||||
CreatedAt: event.Timestamp,
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Table("tenant_events").Create(&eventRecord).Error
|
||||
}
|
||||
|
||||
// ListEvents lists tenant events
|
||||
func (r *GormTenantRepository) ListEvents(ctx context.Context, tenantID string, limit int) ([]*TenantEvent, error) {
|
||||
// Query events from the events table
|
||||
var eventRecords []struct {
|
||||
ID string `gorm:"primaryKey"`
|
||||
TenantID string `gorm:"index"`
|
||||
EventData string `gorm:"type:text"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||
}
|
||||
|
||||
query := r.db.WithContext(ctx).Table("tenant_events").Where("tenant_id = ?", tenantID)
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
query = query.Order("created_at DESC")
|
||||
|
||||
err := query.Find(&eventRecords).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Unmarshal events
|
||||
var events []*TenantEvent
|
||||
for _, record := range eventRecords {
|
||||
var event TenantEvent
|
||||
if err := json.Unmarshal([]byte(record.EventData), &event); err != nil {
|
||||
continue // Skip malformed events
|
||||
}
|
||||
events = append(events, &event)
|
||||
}
|
||||
|
||||
return events, nil
|
||||
}
|
||||
|
||||
// Helper methods for tenant isolation in other repositories
|
||||
|
||||
// TenantAwareQuery adds tenant filtering to database queries
|
||||
func (r *GormTenantRepository) TenantAwareQuery(ctx context.Context, model interface{}, tenantID string) *gorm.DB {
|
||||
query := r.db.WithContext(ctx).Model(model)
|
||||
|
||||
// Add tenant filter if the model has tenant_id field
|
||||
if tenantID != "" {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
|
||||
return query
|
||||
}
|
||||
|
||||
// EnsureTenantIsolation ensures that queries are tenant-isolated
|
||||
func (r *GormTenantRepository) EnsureTenantIsolation(ctx context.Context, tenantID string) error {
|
||||
if tenantID == "" {
|
||||
return fmt.Errorf("tenant ID is required for tenant-isolated operations")
|
||||
}
|
||||
|
||||
// Validate tenant exists
|
||||
_, err := r.GetTenant(ctx, tenantID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid tenant ID: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetTenantFromContext extracts tenant ID from context
|
||||
func (r *GormTenantRepository) GetTenantFromContext(ctx context.Context) string {
|
||||
if tenantID, ok := ctx.Value("tenant_id").(string); ok {
|
||||
return tenantID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// WithTenantIsolation applies tenant isolation to a database operation
|
||||
func (r *GormTenantRepository) WithTenantIsolation(ctx context.Context, operation func(*gorm.DB) error) error {
|
||||
tenantID := r.GetTenantFromContext(ctx)
|
||||
if tenantID == "" {
|
||||
return fmt.Errorf("tenant ID not found in context")
|
||||
}
|
||||
|
||||
// Validate tenant exists
|
||||
if err := r.EnsureTenantIsolation(ctx, tenantID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Execute operation with tenant filtering
|
||||
tx := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID)
|
||||
return operation(tx)
|
||||
}
|
||||
@@ -1,771 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/sirupsen/logrus"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// ServiceImpl implements the tenant service interface
|
||||
type ServiceImpl struct {
|
||||
repository Repository
|
||||
rateLimiter RateLimiter
|
||||
eventPublisher EventPublisher
|
||||
configManager ConfigManager
|
||||
auditLogger AuditLogger
|
||||
metricsCollector MetricsCollector
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewService creates a new tenant service
|
||||
func NewService(
|
||||
repository Repository,
|
||||
rateLimiter RateLimiter,
|
||||
eventPublisher EventPublisher,
|
||||
configManager ConfigManager,
|
||||
auditLogger AuditLogger,
|
||||
metricsCollector MetricsCollector,
|
||||
logger *logrus.Logger,
|
||||
) Service {
|
||||
return &ServiceImpl{
|
||||
repository: repository,
|
||||
rateLimiter: rateLimiter,
|
||||
eventPublisher: eventPublisher,
|
||||
configManager: configManager,
|
||||
auditLogger: auditLogger,
|
||||
metricsCollector: metricsCollector,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateTenant creates a new tenant
|
||||
func (s *ServiceImpl) CreateTenant(ctx context.Context, req *CreateTenantRequest) (*Tenant, error) {
|
||||
// Validate request
|
||||
if err := s.validateCreateTenantRequest(req); err != nil {
|
||||
return nil, fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Check if domain already exists
|
||||
existing, err := s.repository.GetTenantByDomain(ctx, req.Domain)
|
||||
if err == nil && existing != nil {
|
||||
return nil, errors.New("domain already exists")
|
||||
}
|
||||
|
||||
// Create tenant
|
||||
tenant := &Tenant{
|
||||
ID: uuid.New().String(),
|
||||
Name: req.Name,
|
||||
Domain: req.Domain,
|
||||
Status: TenantStatusActive,
|
||||
Plan: req.Plan,
|
||||
MaxUsers: req.MaxUsers,
|
||||
MaxProfiles: req.MaxProfiles,
|
||||
MaxCarriers: req.MaxCarriers,
|
||||
Settings: req.Settings,
|
||||
Metadata: req.Metadata,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Set default settings if not provided
|
||||
if tenant.Settings == nil {
|
||||
tenant.Settings = s.getDefaultSettings(req.Plan)
|
||||
}
|
||||
|
||||
// Save tenant
|
||||
if err := s.repository.CreateTenant(ctx, tenant); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant")
|
||||
return nil, fmt.Errorf("failed to create tenant: %w", err)
|
||||
}
|
||||
|
||||
// Create initial configuration
|
||||
config := &TenantConfig{
|
||||
TenantID: tenant.ID,
|
||||
Config: make(map[string]interface{}),
|
||||
Settings: tenant.Settings,
|
||||
Quotas: s.getDefaultQuotas(req.Plan),
|
||||
Features: s.getDefaultFeatures(req.Plan),
|
||||
}
|
||||
|
||||
if err := s.repository.UpdateConfig(ctx, config); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant config")
|
||||
}
|
||||
|
||||
// Publish tenant created event
|
||||
event := &TenantEvent{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenant.ID,
|
||||
UserID: "",
|
||||
EventType: TenantEventCreated,
|
||||
EventData: map[string]interface{}{
|
||||
"tenant_id": tenant.ID,
|
||||
"name": tenant.Name,
|
||||
"domain": tenant.Domain,
|
||||
"plan": tenant.Plan,
|
||||
},
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant event")
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"tenant_id": tenant.ID,
|
||||
"name": tenant.Name,
|
||||
"domain": tenant.Domain,
|
||||
}).Info("Tenant created successfully")
|
||||
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
// GetTenant retrieves a tenant by ID
|
||||
func (s *ServiceImpl) GetTenant(ctx context.Context, id string) (*Tenant, error) {
|
||||
tenant, err := s.repository.GetTenant(ctx, id)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("tenant_id", id).Error("Failed to get tenant")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
// GetTenantByDomain retrieves a tenant by domain
|
||||
func (s *ServiceImpl) GetTenantByDomain(ctx context.Context, domain string) (*Tenant, error) {
|
||||
tenant, err := s.repository.GetTenantByDomain(ctx, domain)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("domain", domain).Error("Failed to get tenant by domain")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
// UpdateTenant updates an existing tenant
|
||||
func (s *ServiceImpl) UpdateTenant(ctx context.Context, id string, req *UpdateTenantRequest) (*Tenant, error) {
|
||||
// Get existing tenant
|
||||
tenant, err := s.repository.GetTenant(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Apply updates
|
||||
if req.Name != nil {
|
||||
tenant.Name = *req.Name
|
||||
}
|
||||
if req.Status != nil {
|
||||
tenant.Status = *req.Status
|
||||
}
|
||||
if req.Plan != nil {
|
||||
tenant.Plan = *req.Plan
|
||||
}
|
||||
if req.MaxUsers != nil {
|
||||
tenant.MaxUsers = *req.MaxUsers
|
||||
}
|
||||
if req.MaxProfiles != nil {
|
||||
tenant.MaxProfiles = *req.MaxProfiles
|
||||
}
|
||||
if req.MaxCarriers != nil {
|
||||
tenant.MaxCarriers = *req.MaxCarriers
|
||||
}
|
||||
if req.Settings != nil {
|
||||
tenant.Settings = req.Settings
|
||||
}
|
||||
if req.Metadata != nil {
|
||||
tenant.Metadata = req.Metadata
|
||||
}
|
||||
|
||||
tenant.UpdatedAt = time.Now()
|
||||
|
||||
// Save tenant
|
||||
if err := s.repository.UpdateTenant(ctx, tenant); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update tenant")
|
||||
return nil, fmt.Errorf("failed to update tenant: %w", err)
|
||||
}
|
||||
|
||||
// Log tenant updated event
|
||||
event := &TenantEvent{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenant.ID,
|
||||
UserID: "",
|
||||
EventType: TenantEventUpdated,
|
||||
EventData: map[string]interface{}{
|
||||
"tenant_id": tenant.ID,
|
||||
"updates": req,
|
||||
},
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant event")
|
||||
}
|
||||
|
||||
s.logger.WithField("tenant_id", tenant.ID).Info("Tenant updated successfully")
|
||||
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
// DeleteTenant deletes a tenant
|
||||
func (s *ServiceImpl) DeleteTenant(ctx context.Context, id string) error {
|
||||
// Get tenant for logging
|
||||
tenant, err := s.repository.GetTenant(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete tenant
|
||||
if err := s.repository.DeleteTenant(ctx, id); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to delete tenant")
|
||||
return fmt.Errorf("failed to delete tenant: %w", err)
|
||||
}
|
||||
|
||||
// Log tenant deleted event
|
||||
event := &TenantEvent{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: id,
|
||||
UserID: "",
|
||||
EventType: TenantEventDeleted,
|
||||
EventData: map[string]interface{}{
|
||||
"tenant_id": id,
|
||||
"name": tenant.Name,
|
||||
},
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant event")
|
||||
}
|
||||
|
||||
s.logger.WithField("tenant_id", id).Info("Tenant deleted successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListTenants lists tenants with filtering
|
||||
func (s *ServiceImpl) ListTenants(ctx context.Context, filter *TenantFilter) ([]*Tenant, error) {
|
||||
tenants, err := s.repository.ListTenants(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to list tenants")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tenants, nil
|
||||
}
|
||||
|
||||
// AddUserToTenant adds a user to a tenant
|
||||
func (s *ServiceImpl) AddUserToTenant(ctx context.Context, req *CreateTenantUserRequest) (*TenantUser, error) {
|
||||
// Validate request
|
||||
if err := s.validateCreateTenantUserRequest(req); err != nil {
|
||||
return nil, fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
existing, err := s.repository.GetTenantUser(ctx, req.TenantID, req.UserID)
|
||||
if err == nil && existing != nil {
|
||||
return nil, errors.New("user already exists in tenant")
|
||||
}
|
||||
|
||||
// Create tenant user
|
||||
tenantUser := &TenantUser{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: req.TenantID,
|
||||
UserID: req.UserID,
|
||||
Email: req.Email,
|
||||
Role: req.Role,
|
||||
Status: TenantUserStatusActive,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Save tenant user
|
||||
if err := s.repository.CreateTenantUser(ctx, tenantUser); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant user")
|
||||
return nil, fmt.Errorf("failed to add user to tenant: %w", err)
|
||||
}
|
||||
|
||||
// Log user added event
|
||||
event := &TenantEvent{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: req.TenantID,
|
||||
UserID: req.UserID,
|
||||
EventType: TenantEventUserAdded,
|
||||
EventData: map[string]interface{}{
|
||||
"tenant_id": req.TenantID,
|
||||
"user_id": req.UserID,
|
||||
"email": req.Email,
|
||||
"role": req.Role,
|
||||
},
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant event")
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"tenant_id": req.TenantID,
|
||||
"user_id": req.UserID,
|
||||
"role": req.Role,
|
||||
}).Info("User added to tenant successfully")
|
||||
|
||||
return tenantUser, nil
|
||||
}
|
||||
|
||||
// GetTenantUser retrieves a tenant user
|
||||
func (s *ServiceImpl) GetTenantUser(ctx context.Context, tenantID, userID string) (*TenantUser, error) {
|
||||
user, err := s.repository.GetTenantUser(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithFields(logrus.Fields{
|
||||
"tenant_id": tenantID,
|
||||
"user_id": userID,
|
||||
}).Error("Failed to get tenant user")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// UpdateTenantUser updates a tenant user
|
||||
func (s *ServiceImpl) UpdateTenantUser(ctx context.Context, tenantID, userID string, req *UpdateTenantUserRequest) (*TenantUser, error) {
|
||||
// Get existing user
|
||||
user, err := s.repository.GetTenantUser(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Apply updates
|
||||
if req.Role != nil {
|
||||
user.Role = *req.Role
|
||||
}
|
||||
if req.Status != nil {
|
||||
user.Status = *req.Status
|
||||
}
|
||||
|
||||
user.UpdatedAt = time.Now()
|
||||
|
||||
// Save user
|
||||
if err := s.repository.UpdateTenantUser(ctx, user); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update tenant user")
|
||||
return nil, fmt.Errorf("failed to update tenant user: %w", err)
|
||||
}
|
||||
|
||||
// Log user updated event
|
||||
event := &TenantEvent{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
EventType: TenantEventUserUpdated,
|
||||
EventData: map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
"user_id": userID,
|
||||
"updates": req,
|
||||
},
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant event")
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"tenant_id": tenantID,
|
||||
"user_id": userID,
|
||||
}).Info("Tenant user updated successfully")
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// RemoveUserFromTenant removes a user from a tenant
|
||||
func (s *ServiceImpl) RemoveUserFromTenant(ctx context.Context, tenantID, userID string) error {
|
||||
// Delete tenant user
|
||||
if err := s.repository.DeleteTenantUser(ctx, tenantID, userID); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to remove user from tenant")
|
||||
return fmt.Errorf("failed to remove user from tenant: %w", err)
|
||||
}
|
||||
|
||||
// Log user removed event
|
||||
event := &TenantEvent{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
EventType: TenantEventUserRemoved,
|
||||
EventData: map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
"user_id": userID,
|
||||
},
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant event")
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"tenant_id": tenantID,
|
||||
"user_id": userID,
|
||||
}).Info("User removed from tenant successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListTenantUsers lists tenant users with filtering
|
||||
func (s *ServiceImpl) ListTenantUsers(ctx context.Context, filter *TenantUserFilter) ([]*TenantUser, error) {
|
||||
users, err := s.repository.ListTenantUsers(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to list tenant users")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// CreateAPIKey creates a new API key for a tenant
|
||||
func (s *ServiceImpl) CreateAPIKey(ctx context.Context, tenantID string, req *CreateAPIKeyRequest) (*TenantAPIKey, string, error) {
|
||||
// Validate request
|
||||
if err := s.validateCreateAPIKeyRequest(req); err != nil {
|
||||
return nil, "", fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Generate API key
|
||||
apiKey := s.generateAPIKey()
|
||||
keyHash, err := s.hashAPIKey(apiKey)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to hash API key: %w", err)
|
||||
}
|
||||
|
||||
// Create API key record
|
||||
apiKeyRecord := &TenantAPIKey{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenantID,
|
||||
Name: req.Name,
|
||||
KeyHash: keyHash,
|
||||
KeyPrefix: apiKey[:8],
|
||||
Permissions: req.Permissions,
|
||||
RateLimit: req.RateLimit,
|
||||
ExpiresAt: req.ExpiresAt,
|
||||
Status: APIKeyStatusActive,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Save API key
|
||||
if err := s.repository.CreateAPIKey(ctx, apiKeyRecord); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create API key")
|
||||
return nil, "", fmt.Errorf("failed to create API key: %w", err)
|
||||
}
|
||||
|
||||
// Log API key created event
|
||||
event := &TenantEvent{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenantID,
|
||||
UserID: "",
|
||||
EventType: TenantEventAPIKeyCreated,
|
||||
EventData: map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
"key_id": apiKeyRecord.ID,
|
||||
"name": req.Name,
|
||||
},
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant event")
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"tenant_id": tenantID,
|
||||
"key_id": apiKeyRecord.ID,
|
||||
"name": req.Name,
|
||||
}).Info("API key created successfully")
|
||||
|
||||
return apiKeyRecord, apiKey, nil
|
||||
}
|
||||
|
||||
// GetAPIKey retrieves an API key by ID
|
||||
func (s *ServiceImpl) GetAPIKey(ctx context.Context, id string) (*TenantAPIKey, error) {
|
||||
apiKey, err := s.repository.GetAPIKey(ctx, id)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("key_id", id).Error("Failed to get API key")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return apiKey, nil
|
||||
}
|
||||
|
||||
// UpdateAPIKey updates an API key
|
||||
func (s *ServiceImpl) UpdateAPIKey(ctx context.Context, id string, req *UpdateAPIKeyRequest) (*TenantAPIKey, error) {
|
||||
// Get existing API key
|
||||
apiKey, err := s.repository.GetAPIKey(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Apply updates
|
||||
if req.Name != nil {
|
||||
apiKey.Name = *req.Name
|
||||
}
|
||||
if req.Permissions != nil {
|
||||
apiKey.Permissions = req.Permissions
|
||||
}
|
||||
if req.RateLimit != nil {
|
||||
apiKey.RateLimit = *req.RateLimit
|
||||
}
|
||||
if req.ExpiresAt != nil {
|
||||
apiKey.ExpiresAt = req.ExpiresAt
|
||||
}
|
||||
if req.Status != nil {
|
||||
apiKey.Status = *req.Status
|
||||
}
|
||||
|
||||
apiKey.UpdatedAt = time.Now()
|
||||
|
||||
// Save API key
|
||||
if err := s.repository.UpdateAPIKey(ctx, apiKey); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update API key")
|
||||
return nil, fmt.Errorf("failed to update API key: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("key_id", id).Info("API key updated successfully")
|
||||
|
||||
return apiKey, nil
|
||||
}
|
||||
|
||||
// DeleteAPIKey deletes an API key
|
||||
func (s *ServiceImpl) DeleteAPIKey(ctx context.Context, id string) error {
|
||||
// Get API key for logging
|
||||
apiKey, err := s.repository.GetAPIKey(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete API key
|
||||
if err := s.repository.DeleteAPIKey(ctx, id); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to delete API key")
|
||||
return fmt.Errorf("failed to delete API key: %w", err)
|
||||
}
|
||||
|
||||
// Log API key revoked event
|
||||
event := &TenantEvent{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: apiKey.TenantID,
|
||||
UserID: "",
|
||||
EventType: TenantEventAPIKeyRevoked,
|
||||
EventData: map[string]interface{}{
|
||||
"tenant_id": apiKey.TenantID,
|
||||
"key_id": id,
|
||||
"name": apiKey.Name,
|
||||
},
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant event")
|
||||
}
|
||||
|
||||
s.logger.WithField("key_id", id).Info("API key deleted successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListAPIKeys lists API keys for a tenant
|
||||
func (s *ServiceImpl) ListAPIKeys(ctx context.Context, tenantID string) ([]*TenantAPIKey, error) {
|
||||
apiKeys, err := s.repository.ListAPIKeys(ctx, tenantID)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("tenant_id", tenantID).Error("Failed to list API keys")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return apiKeys, nil
|
||||
}
|
||||
|
||||
// ValidateAPIKey validates an API key and returns the key record
|
||||
func (s *ServiceImpl) ValidateAPIKey(ctx context.Context, key string) (*TenantAPIKey, error) {
|
||||
// Hash the provided key
|
||||
keyHash, err := s.hashAPIKey(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to hash API key: %w", err)
|
||||
}
|
||||
|
||||
// Look up API key by hash
|
||||
apiKey, err := s.repository.GetAPIKeyByHash(ctx, keyHash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if key is active
|
||||
if apiKey.Status != APIKeyStatusActive {
|
||||
return nil, errors.New("API key is not active")
|
||||
}
|
||||
|
||||
// Check if key has expired
|
||||
if apiKey.ExpiresAt != nil && time.Now().After(*apiKey.ExpiresAt) {
|
||||
return nil, errors.New("API key has expired")
|
||||
}
|
||||
|
||||
// Update last used timestamp
|
||||
now := time.Now()
|
||||
apiKey.LastUsed = &now
|
||||
if err := s.repository.UpdateAPIKey(ctx, apiKey); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update API key last used")
|
||||
}
|
||||
|
||||
return apiKey, nil
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
func (s *ServiceImpl) validateCreateTenantRequest(req *CreateTenantRequest) error {
|
||||
if req.Name == "" {
|
||||
return errors.New("name is required")
|
||||
}
|
||||
if req.Domain == "" {
|
||||
return errors.New("domain is required")
|
||||
}
|
||||
if req.Plan == "" {
|
||||
return errors.New("plan is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ServiceImpl) validateCreateTenantUserRequest(req *CreateTenantUserRequest) error {
|
||||
if req.TenantID == "" {
|
||||
return errors.New("tenant ID is required")
|
||||
}
|
||||
if req.UserID == "" {
|
||||
return errors.New("user ID is required")
|
||||
}
|
||||
if req.Email == "" {
|
||||
return errors.New("email is required")
|
||||
}
|
||||
if req.Role == "" {
|
||||
return errors.New("role is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ServiceImpl) validateCreateAPIKeyRequest(req *CreateAPIKeyRequest) error {
|
||||
if req.Name == "" {
|
||||
return errors.New("name is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ServiceImpl) getDefaultSettings(plan TenantPlan) *TenantSettings {
|
||||
settings := &TenantSettings{
|
||||
DefaultCurrency: "USD",
|
||||
SupportedCurrencies: []string{"USD", "EUR", "GBP"},
|
||||
APIRateLimitPerMinute: 60,
|
||||
APIRateLimitPerHour: 1000,
|
||||
SessionTimeout: 120, // 2 hours
|
||||
DataRetentionDays: 90,
|
||||
ComplianceRegions: []string{"US", "EU"},
|
||||
}
|
||||
|
||||
switch plan {
|
||||
case TenantPlanFree:
|
||||
settings.EnableMultiCurrency = false
|
||||
settings.EnableAdvancedAnalytics = false
|
||||
settings.EnableAPIAccess = true
|
||||
settings.EnableWebhooks = false
|
||||
settings.Require2FA = false
|
||||
case TenantPlanBasic:
|
||||
settings.EnableMultiCurrency = true
|
||||
settings.EnableAdvancedAnalytics = false
|
||||
settings.EnableAPIAccess = true
|
||||
settings.EnableWebhooks = false
|
||||
settings.Require2FA = false
|
||||
case TenantPlanPro:
|
||||
settings.EnableMultiCurrency = true
|
||||
settings.EnableAdvancedAnalytics = true
|
||||
settings.EnableAPIAccess = true
|
||||
settings.EnableWebhooks = true
|
||||
settings.Require2FA = true
|
||||
case TenantPlanEnterprise:
|
||||
settings.EnableMultiCurrency = true
|
||||
settings.EnableAdvancedAnalytics = true
|
||||
settings.EnableAPIAccess = true
|
||||
settings.EnableWebhooks = true
|
||||
settings.Require2FA = true
|
||||
settings.APIRateLimitPerMinute = 1000
|
||||
settings.APIRateLimitPerHour = 10000
|
||||
}
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
func (s *ServiceImpl) getDefaultQuotas(plan TenantPlan) []ResourceQuota {
|
||||
quotas := []ResourceQuota{}
|
||||
|
||||
switch plan {
|
||||
case TenantPlanFree:
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "users", Limit: 5, Period: "monthly"})
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "profiles", Limit: 100, Period: "monthly"})
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "carriers", Limit: 3, Period: "monthly"})
|
||||
case TenantPlanBasic:
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "users", Limit: 25, Period: "monthly"})
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "profiles", Limit: 1000, Period: "monthly"})
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "carriers", Limit: 10, Period: "monthly"})
|
||||
case TenantPlanPro:
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "users", Limit: 100, Period: "monthly"})
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "profiles", Limit: 10000, Period: "monthly"})
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "carriers", Limit: 50, Period: "monthly"})
|
||||
case TenantPlanEnterprise:
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "users", Limit: -1, Period: "monthly"}) // Unlimited
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "profiles", Limit: -1, Period: "monthly"}) // Unlimited
|
||||
quotas = append(quotas, ResourceQuota{ResourceType: "carriers", Limit: -1, Period: "monthly"}) // Unlimited
|
||||
}
|
||||
|
||||
return quotas
|
||||
}
|
||||
|
||||
func (s *ServiceImpl) getDefaultFeatures(plan TenantPlan) map[string]bool {
|
||||
features := map[string]bool{
|
||||
"multi_currency": false,
|
||||
"advanced_analytics": false,
|
||||
"api_access": true,
|
||||
"webhooks": false,
|
||||
"custom_branding": false,
|
||||
"priority_support": false,
|
||||
}
|
||||
|
||||
switch plan {
|
||||
case TenantPlanBasic:
|
||||
features["multi_currency"] = true
|
||||
case TenantPlanPro:
|
||||
features["multi_currency"] = true
|
||||
features["advanced_analytics"] = true
|
||||
features["webhooks"] = true
|
||||
features["custom_branding"] = true
|
||||
case TenantPlanEnterprise:
|
||||
features["multi_currency"] = true
|
||||
features["advanced_analytics"] = true
|
||||
features["webhooks"] = true
|
||||
features["custom_branding"] = true
|
||||
features["priority_support"] = true
|
||||
}
|
||||
|
||||
return features
|
||||
}
|
||||
|
||||
func (s *ServiceImpl) generateAPIKey() string {
|
||||
bytes := make([]byte, 32)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
// Fallback to less secure method if crypto/rand fails
|
||||
return uuid.New().String()
|
||||
}
|
||||
return "tk_" + hex.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
func (s *ServiceImpl) hashAPIKey(key string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(key), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(hash), nil
|
||||
}
|
||||
@@ -1,476 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CheckQuota checks if tenant has sufficient quota for a resource
|
||||
func (s *ServiceImpl) CheckQuota(ctx context.Context, tenantID, resourceType string, count int) error {
|
||||
// Get current usage
|
||||
usage, err := s.repository.GetUsage(ctx, tenantID, resourceType)
|
||||
if err != nil {
|
||||
// If no usage record exists, create one
|
||||
usage = &TenantUsage{
|
||||
ID: generateID(),
|
||||
TenantID: tenantID,
|
||||
ResourceType: resourceType,
|
||||
ResourceCount: 0,
|
||||
QuotaUsed: 0,
|
||||
QuotaRemaining: 0,
|
||||
PeriodStart: time.Now().Truncate(24 * time.Hour),
|
||||
PeriodEnd: time.Now().Truncate(24 * time.Hour).Add(24 * time.Hour),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
// Get tenant configuration
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
// Find quota for resource type
|
||||
var quotaLimit int
|
||||
for _, quota := range config.Quotas {
|
||||
if quota.ResourceType == resourceType {
|
||||
quotaLimit = quota.Limit
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Check if quota is unlimited (-1)
|
||||
if quotaLimit == -1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Check if adding count would exceed quota
|
||||
if usage.QuotaUsed+count > quotaLimit {
|
||||
// Log quota exceeded event
|
||||
event := &TenantEvent{
|
||||
ID: generateID(),
|
||||
TenantID: tenantID,
|
||||
UserID: "",
|
||||
EventType: TenantEventQuotaExceeded,
|
||||
EventData: map[string]interface{}{
|
||||
"resource_type": resourceType,
|
||||
"requested": count,
|
||||
"current_usage": usage.QuotaUsed,
|
||||
"quota_limit": quotaLimit,
|
||||
},
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create quota exceeded event")
|
||||
}
|
||||
|
||||
return fmt.Errorf("quota exceeded for %s: %d/%d used", resourceType, usage.QuotaUsed, quotaLimit)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetUsageStats retrieves usage statistics for a tenant
|
||||
func (s *ServiceImpl) GetUsageStats(ctx context.Context, tenantID string) (*TenantUsageStats, error) {
|
||||
// Get usage records
|
||||
usageFilter := &TenantUsageFilter{
|
||||
TenantID: tenantID,
|
||||
}
|
||||
|
||||
usageRecords, err := s.repository.ListUsage(ctx, usageFilter)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get usage records: %w", err)
|
||||
}
|
||||
|
||||
// Get tenant configuration
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
// Get tenant users
|
||||
userFilter := &TenantUserFilter{
|
||||
TenantID: tenantID,
|
||||
Status: TenantUserStatusActive,
|
||||
}
|
||||
|
||||
users, err := s.repository.ListTenantUsers(ctx, userFilter)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant users: %w", err)
|
||||
}
|
||||
|
||||
// Build usage stats
|
||||
stats := &TenantUsageStats{
|
||||
TenantID: tenantID,
|
||||
TotalUsers: len(users),
|
||||
ActiveUsers: len(users),
|
||||
ResourceBreakdown: make(map[string]int64),
|
||||
QuotaStatus: make(map[string]QuotaStatus),
|
||||
}
|
||||
|
||||
// Process usage records
|
||||
for _, usage := range usageRecords {
|
||||
stats.ResourceBreakdown[usage.ResourceType] = int64(usage.QuotaUsed)
|
||||
|
||||
// Calculate quota status
|
||||
var quotaLimit int
|
||||
for _, quota := range config.Quotas {
|
||||
if quota.ResourceType == usage.ResourceType {
|
||||
quotaLimit = quota.Limit
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
quotaStatus := QuotaStatus{
|
||||
Used: usage.QuotaUsed,
|
||||
Limit: quotaLimit,
|
||||
Remaining: quotaLimit - usage.QuotaUsed,
|
||||
}
|
||||
|
||||
if quotaLimit > 0 {
|
||||
quotaStatus.Percent = float64(usage.QuotaUsed) / float64(quotaLimit) * 100
|
||||
quotaStatus.Warning = quotaStatus.Percent >= 80
|
||||
quotaStatus.Critical = quotaStatus.Percent >= 95
|
||||
}
|
||||
|
||||
stats.QuotaStatus[usage.ResourceType] = quotaStatus
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// UpdateUsage updates resource usage for a tenant
|
||||
func (s *ServiceImpl) UpdateUsage(ctx context.Context, tenantID, resourceType string, count int) error {
|
||||
// Get current usage
|
||||
usage, err := s.repository.GetUsage(ctx, tenantID, resourceType)
|
||||
if err != nil {
|
||||
// Create new usage record
|
||||
usage = &TenantUsage{
|
||||
ID: generateID(),
|
||||
TenantID: tenantID,
|
||||
ResourceType: resourceType,
|
||||
ResourceCount: count,
|
||||
QuotaUsed: count,
|
||||
PeriodStart: time.Now().Truncate(24 * time.Hour),
|
||||
PeriodEnd: time.Now().Truncate(24 * time.Hour).Add(24 * time.Hour),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
} else {
|
||||
// Update existing usage
|
||||
usage.ResourceCount += count
|
||||
usage.QuotaUsed += count
|
||||
usage.UpdatedAt = time.Now()
|
||||
}
|
||||
|
||||
// Save usage
|
||||
if err := s.repository.UpdateUsage(ctx, usage); err != nil {
|
||||
return fmt.Errorf("failed to update usage: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetQuotaStatus retrieves quota status for all tenant resources
|
||||
func (s *ServiceImpl) GetQuotaStatus(ctx context.Context, tenantID string) (map[string]QuotaStatus, error) {
|
||||
// Get usage stats
|
||||
stats, err := s.GetUsageStats(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return stats.QuotaStatus, nil
|
||||
}
|
||||
|
||||
// GetTenantConfig retrieves tenant configuration
|
||||
func (s *ServiceImpl) GetTenantConfig(ctx context.Context, tenantID string) (*TenantConfig, error) {
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// UpdateTenantConfig updates tenant configuration
|
||||
func (s *ServiceImpl) UpdateTenantConfig(ctx context.Context, tenantID string, config *TenantConfig) error {
|
||||
config.TenantID = tenantID
|
||||
|
||||
if err := s.repository.UpdateConfig(ctx, config); err != nil {
|
||||
return fmt.Errorf("failed to update tenant config: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("tenant_id", tenantID).Info("Tenant config updated successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetTenantSettings retrieves tenant settings
|
||||
func (s *ServiceImpl) GetTenantSettings(ctx context.Context, tenantID string) (*TenantSettings, error) {
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
return config.Settings, nil
|
||||
}
|
||||
|
||||
// ValidateTenantAccess validates tenant access
|
||||
func (s *ServiceImpl) ValidateTenantAccess(ctx context.Context, tenantID, userID string) (*TenantContext, error) {
|
||||
// Get tenant
|
||||
tenant, err := s.repository.GetTenant(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tenant not found: %w", err)
|
||||
}
|
||||
|
||||
// Check tenant status
|
||||
if tenant.Status != TenantStatusActive {
|
||||
return nil, errors.New("tenant is not active")
|
||||
}
|
||||
|
||||
// Get tenant configuration
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
// Get user role if userID provided
|
||||
var userRole TenantRole
|
||||
if userID != "" {
|
||||
user, err := s.repository.GetTenantUser(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("user not found in tenant: %w", err)
|
||||
}
|
||||
|
||||
if user.Status != TenantUserStatusActive {
|
||||
return nil, errors.New("user is not active in tenant")
|
||||
}
|
||||
|
||||
userRole = user.Role
|
||||
}
|
||||
|
||||
// Create tenant context
|
||||
tenantCtx := &TenantContext{
|
||||
TenantID: tenantID,
|
||||
TenantName: tenant.Name,
|
||||
Plan: tenant.Plan,
|
||||
UserID: userID,
|
||||
UserRole: userRole,
|
||||
Settings: config.Settings,
|
||||
Metadata: tenant.Metadata,
|
||||
}
|
||||
|
||||
return tenantCtx, nil
|
||||
}
|
||||
|
||||
// HasPermission checks if user has specific permission
|
||||
func (s *ServiceImpl) HasPermission(ctx context.Context, tenantID, userID string, permission string) (bool, error) {
|
||||
// Get tenant user
|
||||
user, err := s.repository.GetTenantUser(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("user not found in tenant: %w", err)
|
||||
}
|
||||
|
||||
// Define permission matrix
|
||||
permissionMatrix := map[TenantRole]map[string]bool{
|
||||
TenantRoleOwner: {
|
||||
"tenant:read": true,
|
||||
"tenant:write": true,
|
||||
"tenant:delete": true,
|
||||
"user:read": true,
|
||||
"user:write": true,
|
||||
"user:delete": true,
|
||||
"apikey:read": true,
|
||||
"apikey:write": true,
|
||||
"apikey:delete": true,
|
||||
"config:read": true,
|
||||
"config:write": true,
|
||||
},
|
||||
TenantRoleAdmin: {
|
||||
"tenant:read": true,
|
||||
"tenant:write": true,
|
||||
"user:read": true,
|
||||
"user:write": true,
|
||||
"user:delete": true,
|
||||
"apikey:read": true,
|
||||
"apikey:write": true,
|
||||
"apikey:delete": true,
|
||||
"config:read": true,
|
||||
"config:write": true,
|
||||
},
|
||||
TenantRoleManager: {
|
||||
"tenant:read": true,
|
||||
"user:read": true,
|
||||
"user:write": true,
|
||||
"apikey:read": true,
|
||||
"apikey:write": true,
|
||||
"config:read": true,
|
||||
},
|
||||
TenantRoleUser: {
|
||||
"tenant:read": true,
|
||||
"apikey:read": true,
|
||||
"config:read": true,
|
||||
},
|
||||
TenantRoleViewer: {
|
||||
"tenant:read": true,
|
||||
"apikey:read": true,
|
||||
"config:read": true,
|
||||
},
|
||||
}
|
||||
|
||||
// Check permission
|
||||
rolePermissions, exists := permissionMatrix[user.Role]
|
||||
if !exists {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
hasPermission, exists := rolePermissions[permission]
|
||||
if !exists {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return hasPermission, nil
|
||||
}
|
||||
|
||||
// GetTenantContext retrieves tenant context
|
||||
func (s *ServiceImpl) GetTenantContext(ctx context.Context, tenantID string) (*TenantContext, error) {
|
||||
return s.ValidateTenantAccess(ctx, tenantID, "")
|
||||
}
|
||||
|
||||
// CheckRateLimit checks rate limit for tenant
|
||||
func (s *ServiceImpl) CheckRateLimit(ctx context.Context, tenantCtx *TenantContext, endpoint string) error {
|
||||
// Use rate limiter to check if request is allowed
|
||||
key := fmt.Sprintf("%s:%s", tenantCtx.TenantID, endpoint)
|
||||
|
||||
if !s.rateLimiter.Allow(ctx, tenantCtx.TenantID, key) {
|
||||
return errors.New("rate limit exceeded")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecordAPIUsage records API usage for rate limiting
|
||||
func (s *ServiceImpl) RecordAPIUsage(ctx context.Context, tenantCtx *TenantContext, endpoint string) {
|
||||
// Record metrics
|
||||
if s.metricsCollector != nil {
|
||||
s.metricsCollector.RecordAPIRequest(ctx, tenantCtx.TenantID, endpoint, "", "", 0)
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateResourceAccess validates resource access
|
||||
func (s *ServiceImpl) ValidateResourceAccess(ctx context.Context, tenantCtx *TenantContext, resource string, resourceID string) error {
|
||||
// For now, implement basic validation
|
||||
// In a real implementation, this would check resource ownership
|
||||
// and access patterns based on resource type
|
||||
|
||||
switch resource {
|
||||
case "tenant":
|
||||
if resourceID != tenantCtx.TenantID {
|
||||
return errors.New("access denied: tenant mismatch")
|
||||
}
|
||||
case "user", "apikey", "config":
|
||||
// These resources belong to the tenant, so basic tenant validation is sufficient
|
||||
return nil
|
||||
default:
|
||||
// Unknown resource type, deny access
|
||||
return errors.New("access denied: unknown resource type")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetTenantMetrics retrieves tenant metrics
|
||||
func (s *ServiceImpl) GetTenantMetrics(ctx context.Context, tenantID string) (*TenantMetrics, error) {
|
||||
// Get usage stats
|
||||
usageStats, err := s.GetUsageStats(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get usage stats: %w", err)
|
||||
}
|
||||
|
||||
// Get recent events
|
||||
events, err := s.repository.ListEvents(ctx, tenantID, 100)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant events: %w", err)
|
||||
}
|
||||
|
||||
// Calculate metrics
|
||||
metrics := &TenantMetrics{
|
||||
TenantID: tenantID,
|
||||
ActiveUsers: usageStats.ActiveUsers,
|
||||
StorageUsed: 0, // Would be calculated from actual storage usage
|
||||
HealthScore: 100.0,
|
||||
Alerts: []string{},
|
||||
}
|
||||
|
||||
// Calculate last activity
|
||||
if len(events) > 0 {
|
||||
metrics.LastActivity = events[0].Timestamp
|
||||
}
|
||||
|
||||
// Calculate error rate and response time from events
|
||||
errorCount := 0
|
||||
totalRequests := 0
|
||||
var totalResponseTime time.Duration
|
||||
|
||||
for _, event := range events {
|
||||
if event.EventType == "api_request" {
|
||||
totalRequests++
|
||||
if statusCode, exists := event.EventData["status_code"]; exists {
|
||||
if code, ok := statusCode.(float64); ok && code >= 400 {
|
||||
errorCount++
|
||||
}
|
||||
}
|
||||
if responseTime, exists := event.EventData["response_time"]; exists {
|
||||
if rt, ok := responseTime.(float64); ok {
|
||||
totalResponseTime += time.Duration(rt) * time.Millisecond
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if totalRequests > 0 {
|
||||
metrics.ErrorRate = float64(errorCount) / float64(totalRequests) * 100
|
||||
metrics.ResponseTime = float64(totalResponseTime) / float64(totalRequests) / float64(time.Millisecond)
|
||||
}
|
||||
|
||||
// Check for alerts
|
||||
for resourceType, quotaStatus := range usageStats.QuotaStatus {
|
||||
if quotaStatus.Critical {
|
||||
metrics.Alerts = append(metrics.Alerts, fmt.Sprintf("Critical: %s quota at %.1f%%", resourceType, quotaStatus.Percent))
|
||||
metrics.HealthScore -= 20
|
||||
} else if quotaStatus.Warning {
|
||||
metrics.Alerts = append(metrics.Alerts, fmt.Sprintf("Warning: %s quota at %.1f%%", resourceType, quotaStatus.Percent))
|
||||
metrics.HealthScore -= 10
|
||||
}
|
||||
}
|
||||
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
// GetTenantEvents retrieves tenant events
|
||||
func (s *ServiceImpl) GetTenantEvents(ctx context.Context, tenantID string, limit int) ([]*TenantEvent, error) {
|
||||
events, err := s.repository.ListEvents(ctx, tenantID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant events: %w", err)
|
||||
}
|
||||
|
||||
return events, nil
|
||||
}
|
||||
|
||||
// LogTenantEvent logs a tenant event
|
||||
func (s *ServiceImpl) LogTenantEvent(ctx context.Context, event *TenantEvent) error {
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
return fmt.Errorf("failed to create tenant event: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
func generateID() string {
|
||||
return fmt.Sprintf("tnt_%d", time.Now().UnixNano())
|
||||
}
|
||||
@@ -1,328 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TenantAwareRepository provides tenant isolation for existing repositories
|
||||
type TenantAwareRepository struct {
|
||||
db *gorm.DB
|
||||
tenantID string
|
||||
}
|
||||
|
||||
// NewTenantAwareRepository creates a new tenant-aware repository
|
||||
func NewTenantAwareRepository(db *gorm.DB, tenantID string) *TenantAwareRepository {
|
||||
return &TenantAwareRepository{
|
||||
db: db,
|
||||
tenantID: tenantID,
|
||||
}
|
||||
}
|
||||
|
||||
// WithTenant creates a new tenant-aware repository instance
|
||||
func (r *TenantAwareRepository) WithTenant(tenantID string) *TenantAwareRepository {
|
||||
return &TenantAwareRepository{
|
||||
db: r.db,
|
||||
tenantID: tenantID,
|
||||
}
|
||||
}
|
||||
|
||||
// GetTenantID returns the current tenant ID
|
||||
func (r *TenantAwareRepository) GetTenantID() string {
|
||||
return r.tenantID
|
||||
}
|
||||
|
||||
// ValidateTenant validates that the tenant exists and is active
|
||||
func (r *TenantAwareRepository) ValidateTenant(ctx context.Context) error {
|
||||
if r.tenantID == "" {
|
||||
return fmt.Errorf("tenant ID is required")
|
||||
}
|
||||
|
||||
var tenant Tenant
|
||||
err := r.db.WithContext(ctx).Where("id = ? AND status = ?", r.tenantID, TenantStatusActive).First(&tenant).Error
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return fmt.Errorf("tenant not found or inactive")
|
||||
}
|
||||
return fmt.Errorf("failed to validate tenant: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// TenantScopedQuery creates a query scoped to the current tenant
|
||||
func (r *TenantAwareRepository) TenantScopedQuery(ctx context.Context, model interface{}) *gorm.DB {
|
||||
query := r.db.WithContext(ctx).Model(model)
|
||||
if r.tenantID != "" {
|
||||
query = query.Where("tenant_id = ?", r.tenantID)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// TenantScopedTransaction creates a transaction scoped to the current tenant
|
||||
func (r *TenantAwareRepository) TenantScopedTransaction(ctx context.Context, fn func(*gorm.DB) error) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// Apply tenant filtering to all operations within the transaction
|
||||
if r.tenantID != "" {
|
||||
// This would need to be implemented based on specific requirements
|
||||
// For now, we'll rely on the tenant-scoped queries within the transaction
|
||||
}
|
||||
return fn(tx)
|
||||
})
|
||||
}
|
||||
|
||||
// Helper methods for common tenant-aware operations
|
||||
|
||||
// CreateWithTenant creates a record with tenant ID
|
||||
func (r *TenantAwareRepository) CreateWithTenant(ctx context.Context, model interface{}) error {
|
||||
if err := r.ValidateTenant(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Set tenant ID if the model has a TenantID field
|
||||
if modelWithTenant, ok := model.(interface{ SetTenantID(string) }); ok {
|
||||
modelWithTenant.SetTenantID(r.tenantID)
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Create(model).Error
|
||||
}
|
||||
|
||||
// GetByTenantID retrieves a record by ID within the current tenant
|
||||
func (r *TenantAwareRepository) GetByTenantID(ctx context.Context, model interface{}, id string) error {
|
||||
if err := r.ValidateTenant(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return r.TenantScopedQuery(ctx, model).Where("id = ?", id).First(model).Error
|
||||
}
|
||||
|
||||
// UpdateWithTenant updates a record within the current tenant
|
||||
func (r *TenantAwareRepository) UpdateWithTenant(ctx context.Context, model interface{}) error {
|
||||
if err := r.ValidateTenant(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return r.db.WithContext(ctx).Save(model).Error
|
||||
}
|
||||
|
||||
// DeleteWithTenant deletes a record within the current tenant
|
||||
func (r *TenantAwareRepository) DeleteWithTenant(ctx context.Context, model interface{}, id string) error {
|
||||
if err := r.ValidateTenant(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return r.TenantScopedQuery(ctx, model).Where("id = ?", id).Delete(model).Error
|
||||
}
|
||||
|
||||
// ListWithTenant lists records within the current tenant
|
||||
func (r *TenantAwareRepository) ListWithTenant(ctx context.Context, model interface{}, results interface{}, filters map[string]interface{}) error {
|
||||
if err := r.ValidateTenant(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
query := r.TenantScopedQuery(ctx, model)
|
||||
|
||||
// Apply filters
|
||||
for key, value := range filters {
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
|
||||
return query.Find(results).Error
|
||||
}
|
||||
|
||||
// CountWithTenant counts records within the current tenant
|
||||
func (r *TenantAwareRepository) CountWithTenant(ctx context.Context, model interface{}, filters map[string]interface{}) (int64, error) {
|
||||
if err := r.ValidateTenant(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
query := r.TenantScopedQuery(ctx, model)
|
||||
|
||||
// Apply filters
|
||||
for key, value := range filters {
|
||||
query = query.Where(key+" = ?", value)
|
||||
}
|
||||
|
||||
var count int64
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// TenantAwareModel is an interface for models that support tenant isolation
|
||||
type TenantAwareModel interface {
|
||||
SetTenantID(tenantID string)
|
||||
GetTenantID() string
|
||||
}
|
||||
|
||||
// BaseTenantModel provides a base implementation for tenant-aware models
|
||||
type BaseTenantModel struct {
|
||||
TenantID string `json:"tenant_id" gorm:"column:tenant_id;index;not null"`
|
||||
}
|
||||
|
||||
// SetTenantID sets the tenant ID
|
||||
func (m *BaseTenantModel) SetTenantID(tenantID string) {
|
||||
m.TenantID = tenantID
|
||||
}
|
||||
|
||||
// GetTenantID returns the tenant ID
|
||||
func (m *BaseTenantModel) GetTenantID() string {
|
||||
return m.TenantID
|
||||
}
|
||||
|
||||
// TenantIsolationMiddleware provides database-level tenant isolation
|
||||
type TenantIsolationMiddleware struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewTenantIsolationMiddleware creates a new tenant isolation middleware
|
||||
func NewTenantIsolationMiddleware(db *gorm.DB) *TenantIsolationMiddleware {
|
||||
return &TenantIsolationMiddleware{db: db}
|
||||
}
|
||||
|
||||
// WithTenantIsolation applies tenant isolation to a database operation
|
||||
func (m *TenantIsolationMiddleware) WithTenantIsolation(ctx context.Context, tenantID string, operation func(*gorm.DB) error) error {
|
||||
if tenantID == "" {
|
||||
return fmt.Errorf("tenant ID is required for tenant-isolated operations")
|
||||
}
|
||||
|
||||
// Validate tenant exists
|
||||
var tenant Tenant
|
||||
err := m.db.WithContext(ctx).Where("id = ? AND status = ?", tenantID, TenantStatusActive).First(&tenant).Error
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return fmt.Errorf("tenant not found or inactive")
|
||||
}
|
||||
return fmt.Errorf("failed to validate tenant: %w", err)
|
||||
}
|
||||
|
||||
// Execute operation with tenant context
|
||||
tx := m.db.WithContext(ctx).Where("tenant_id = ?", tenantID)
|
||||
return operation(tx)
|
||||
}
|
||||
|
||||
// GetTenantFromContext extracts tenant ID from context
|
||||
func GetTenantFromContext(ctx context.Context) string {
|
||||
if tenantID, ok := ctx.Value("tenant_id").(string); ok {
|
||||
return tenantID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// SetTenantInContext sets tenant ID in context
|
||||
func SetTenantInContext(ctx context.Context, tenantID string) context.Context {
|
||||
return context.WithValue(ctx, "tenant_id", tenantID)
|
||||
}
|
||||
|
||||
// TenantQueryBuilder helps build tenant-aware queries
|
||||
type TenantQueryBuilder struct {
|
||||
db *gorm.DB
|
||||
tenantID string
|
||||
query *gorm.DB
|
||||
}
|
||||
|
||||
// NewTenantQueryBuilder creates a new tenant query builder
|
||||
func NewTenantQueryBuilder(db *gorm.DB, tenantID string) *TenantQueryBuilder {
|
||||
return &TenantQueryBuilder{
|
||||
db: db,
|
||||
tenantID: tenantID,
|
||||
query: db.Where("tenant_id = ?", tenantID),
|
||||
}
|
||||
}
|
||||
|
||||
// Where adds a where clause to the query
|
||||
func (b *TenantQueryBuilder) Where(query string, args ...interface{}) *TenantQueryBuilder {
|
||||
b.query = b.query.Where(query, args...)
|
||||
return b
|
||||
}
|
||||
|
||||
// Order adds ordering to the query
|
||||
func (b *TenantQueryBuilder) Order(value string) *TenantQueryBuilder {
|
||||
b.query = b.query.Order(value)
|
||||
return b
|
||||
}
|
||||
|
||||
// Limit adds a limit to the query
|
||||
func (b *TenantQueryBuilder) Limit(limit int) *TenantQueryBuilder {
|
||||
b.query = b.query.Limit(limit)
|
||||
return b
|
||||
}
|
||||
|
||||
// Offset adds an offset to the query
|
||||
func (b *TenantQueryBuilder) Offset(offset int) *TenantQueryBuilder {
|
||||
b.query = b.query.Offset(offset)
|
||||
return b
|
||||
}
|
||||
|
||||
// Find executes the find operation
|
||||
func (b *TenantQueryBuilder) Find(dest interface{}) error {
|
||||
return b.query.Find(dest).Error
|
||||
}
|
||||
|
||||
// First executes the first operation
|
||||
func (b *TenantQueryBuilder) First(dest interface{}) error {
|
||||
return b.query.First(dest).Error
|
||||
}
|
||||
|
||||
// Count executes the count operation
|
||||
func (b *TenantQueryBuilder) Count() (int64, error) {
|
||||
var count int64
|
||||
err := b.query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// GetQuery returns the underlying gorm query
|
||||
func (b *TenantQueryBuilder) GetQuery() *gorm.DB {
|
||||
return b.query
|
||||
}
|
||||
|
||||
// TenantResourceValidator validates resource access across tenants
|
||||
type TenantResourceValidator struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewTenantResourceValidator creates a new tenant resource validator
|
||||
func NewTenantResourceValidator(db *gorm.DB) *TenantResourceValidator {
|
||||
return &TenantResourceValidator{db: db}
|
||||
}
|
||||
|
||||
// ValidateResourceAccess validates that a resource belongs to a tenant
|
||||
func (v *TenantResourceValidator) ValidateResourceAccess(ctx context.Context, tenantID, resourceType, resourceID string) error {
|
||||
switch resourceType {
|
||||
case "profile":
|
||||
return v.validateProfileAccess(ctx, tenantID, resourceID)
|
||||
case "rateplan":
|
||||
return v.validateRatePlanAccess(ctx, tenantID, resourceID)
|
||||
case "carrier":
|
||||
return v.validateCarrierAccess(ctx, tenantID, resourceID)
|
||||
case "subscription":
|
||||
return v.validateSubscriptionAccess(ctx, tenantID, resourceID)
|
||||
default:
|
||||
return fmt.Errorf("unsupported resource type: %s", resourceType)
|
||||
}
|
||||
}
|
||||
|
||||
func (v *TenantResourceValidator) validateProfileAccess(ctx context.Context, tenantID, profileID string) error {
|
||||
// This would check if the profile belongs to the tenant
|
||||
// Implementation depends on the actual profile schema
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *TenantResourceValidator) validateRatePlanAccess(ctx context.Context, tenantID, ratePlanID string) error {
|
||||
// This would check if the rate plan belongs to the tenant
|
||||
// Implementation depends on the actual rate plan schema
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *TenantResourceValidator) validateCarrierAccess(ctx context.Context, tenantID, carrierID string) error {
|
||||
// This would check if the carrier belongs to the tenant
|
||||
// Implementation depends on the actual carrier schema
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *TenantResourceValidator) validateSubscriptionAccess(ctx context.Context, tenantID, subscriptionID string) error {
|
||||
// This would check if the subscription belongs to the tenant
|
||||
// Implementation depends on the actual subscription schema
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user