Documentation
¶
Index ¶
- func RecordSpanError(span trace.Span, err error)
- func RecordSpanSuccess(span trace.Span)
- func TraceInvoiceGeneration(ctx context.Context, subscriptionID string) (context.Context, trace.Span)
- func TraceNotificationSend(ctx context.Context, notificationType, recipientID string) (context.Context, trace.Span)
- func TracePaymentProcessing(ctx context.Context, invoiceID, provider string) (context.Context, trace.Span)
- func TracePricingCalculation(ctx context.Context, subscriptionID string) (context.Context, trace.Span)
- func TraceUsageCollection(ctx context.Context, organizationID string) (context.Context, trace.Span)
- type BillingConfig
- type BillingCycle
- type BillingEventPublisher
- func (p *BillingEventPublisher) PublishCreditApplied(ctx context.Context, credit *models.Credit, invoiceID string, ...) error
- func (p *BillingEventPublisher) PublishInvoiceCreated(ctx context.Context, invoice *models.Invoice) error
- func (p *BillingEventPublisher) PublishInvoiceOverdue(ctx context.Context, invoice *models.Invoice) error
- func (p *BillingEventPublisher) PublishInvoicePaid(ctx context.Context, invoice *models.Invoice, paymentID string) error
- func (p *BillingEventPublisher) PublishPaymentFailed(ctx context.Context, payment *models.Payment) error
- func (p *BillingEventPublisher) PublishPaymentSucceeded(ctx context.Context, payment *models.Payment) error
- func (p *BillingEventPublisher) PublishSubscriptionCanceled(ctx context.Context, subscription *models.Subscription) error
- func (p *BillingEventPublisher) PublishSubscriptionCreated(ctx context.Context, subscription *models.Subscription) error
- func (p *BillingEventPublisher) PublishUsageThresholdReached(ctx context.Context, organizationID string, metricType MetricType, ...) error
- type BillingReport
- type ChargeCalculation
- type Config
- type CreditAppliedEvent
- type CreditStatus
- type EventBus
- type EventType
- type FeatureFlags
- type InvoiceConfig
- type InvoiceCreatedEvent
- type InvoiceLineItem
- type InvoiceOverdueEvent
- type InvoicePaidEvent
- type InvoiceService
- func (is *InvoiceService) FinalizeInvoice(ctx context.Context, invoiceID string) error
- func (is *InvoiceService) GenerateInvoice(ctx context.Context, subscriptionID string) (*models.Invoice, error)
- func (is *InvoiceService) GetInvoice(ctx context.Context, invoiceID string) (*models.Invoice, error)
- func (is *InvoiceService) GetUpcomingInvoice(ctx context.Context, subscriptionID string) (*models.Invoice, error)
- func (is *InvoiceService) ListInvoices(ctx context.Context, organizationID string, limit, offset int) ([]models.Invoice, error)
- func (is *InvoiceService) MarkInvoiceAsPaid(ctx context.Context, invoiceID string, paymentID string, ...) error
- func (is *InvoiceService) ProcessOverdueInvoices(ctx context.Context) error
- func (is *InvoiceService) VoidInvoice(ctx context.Context, invoiceID string) error
- type InvoiceStatus
- type LineItemType
- type MetricType
- type MetricsCollector
- func (mc *MetricsCollector) AggregateUsageMetrics(ctx context.Context) error
- func (mc *MetricsCollector) GetCurrentUsage(ctx context.Context, organizationID string) (map[MetricType]decimal.Decimal, error)
- func (mc *MetricsCollector) GetUsageForPeriod(ctx context.Context, organizationID string, periodStart, periodEnd time.Time) (*UsageAggregation, error)
- func (mc *MetricsCollector) RecordAPICall(organizationID, endpoint, method string)
- func (mc *MetricsCollector) RecordActiveAdapters(organizationID string, count int)
- func (mc *MetricsCollector) RecordKafkaEvent(organizationID, topic string)
- func (mc *MetricsCollector) RecordQuery(organizationID, queryType string, duration time.Duration)
- func (mc *MetricsCollector) RecordStorage(organizationID, storageType string, bytes int64)
- func (mc *MetricsCollector) RecordTransfer(organizationID, direction string, bytes int64)
- func (mc *MetricsCollector) StartAggregationWorker(ctx context.Context)
- type Money
- type NotificationConfig
- type NotificationRequest
- type NotificationService
- func (ns *NotificationService) CreateBillingTemplates(ctx context.Context) error
- func (ns *NotificationService) SendInvoiceCreatedNotification(ctx context.Context, invoice *models.Invoice) error
- func (ns *NotificationService) SendInvoiceOverdueNotification(ctx context.Context, invoice *models.Invoice) error
- func (ns *NotificationService) SendPaymentFailedNotification(ctx context.Context, payment *models.Payment, invoice *models.Invoice) error
- func (ns *NotificationService) SendPaymentSucceededNotification(ctx context.Context, payment *models.Payment, invoice *models.Invoice) error
- func (ns *NotificationService) SendSubscriptionCanceledNotification(ctx context.Context, subscription *models.Subscription) error
- func (ns *NotificationService) SendSubscriptionCreatedNotification(ctx context.Context, subscription *models.Subscription) error
- func (ns *NotificationService) SendUpcomingRenewalNotification(ctx context.Context, subscription *models.Subscription, ...) error
- func (ns *NotificationService) SendUsageThresholdNotification(ctx context.Context, organizationID string, metricType MetricType, ...) error
- type ObservabilityService
- func (o *ObservabilityService) RecordCreditApplied(reason string)
- func (o *ObservabilityService) RecordCreditIssued(reason string)
- func (o *ObservabilityService) RecordInvoiceGenerated(status string, amount float64, currency string)
- func (o *ObservabilityService) RecordPaymentDuration(provider string, seconds float64)
- func (o *ObservabilityService) RecordPaymentFailure(failureCode, provider string)
- func (o *ObservabilityService) RecordPaymentProcessed(status, provider string, amount float64, currency string)
- func (o *ObservabilityService) RecordSubscriptionCanceled(plan, reason string)
- func (o *ObservabilityService) RecordSubscriptionCreated(plan string)
- func (o *ObservabilityService) RecordUsageMetricCollected(metricType string)
- func (o *ObservabilityService) UpdateARR(arr float64)
- func (o *ObservabilityService) UpdateMRR(mrr float64)
- type OrganizationStatus
- type PayPalConfig
- type PaymentFailedEvent
- type PaymentMethod
- type PaymentProvider
- type PaymentService
- func (ps *PaymentService) AttachPaymentMethod(ctx context.Context, organizationID, paymentMethodID string, setAsDefault bool) error
- func (ps *PaymentService) ChargeInvoice(ctx context.Context, invoiceID string) (*models.Payment, error)
- func (ps *PaymentService) CreateStripeCustomer(ctx context.Context, org *models.Organization) (string, error)
- func (ps *PaymentService) HandleWebhook(ctx context.Context, provider PaymentProvider, eventType string, ...) error
- func (ps *PaymentService) ListPayments(ctx context.Context, organizationID string, limit, offset int) ([]models.Payment, error)
- func (ps *PaymentService) RefundPayment(ctx context.Context, paymentID string, amount *decimal.Decimal) error
- type PaymentStatus
- type PaymentSucceededEvent
- type PricingEngine
- func (pe *PricingEngine) CalculateProration(oldPrice, newPrice decimal.Decimal, ...) decimal.Decimal
- func (pe *PricingEngine) CalculateSubscriptionCharge(subscription *models.Subscription, plan *models.SubscriptionPlan, ...) (*ChargeCalculation, error)
- func (pe *PricingEngine) CalculateTieredPrice(usage decimal.Decimal, tiers []models.PricingTier) decimal.Decimal
- func (pe *PricingEngine) EstimateMonthlyCharge(plan *models.SubscriptionPlan, quantity int, ...) decimal.Decimal
- type PricingTier
- type RateLimitConfig
- type StripeConfig
- type SubscriptionCanceledEvent
- type SubscriptionChange
- type SubscriptionCreatedEvent
- type SubscriptionStatus
- type SubscriptionUpdatedEvent
- type UsageAggregation
- type UsageConfig
- type UsageRecord
- type UsageThresholdReachedEvent
- type WebhookEvent
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func RecordSpanError ¶
RecordSpanError records an error in the current span
func RecordSpanSuccess ¶
RecordSpanSuccess records success in the current span
func TraceInvoiceGeneration ¶
func TraceInvoiceGeneration(ctx context.Context, subscriptionID string) (context.Context, trace.Span)
TraceInvoiceGeneration creates a span for invoice generation
func TraceNotificationSend ¶
func TraceNotificationSend(ctx context.Context, notificationType, recipientID string) (context.Context, trace.Span)
TraceNotificationSend creates a span for notification sending
func TracePaymentProcessing ¶
func TracePaymentProcessing(ctx context.Context, invoiceID, provider string) (context.Context, trace.Span)
TracePaymentProcessing creates a span for payment processing
Types ¶
type BillingConfig ¶
type BillingConfig struct {
// Database connection
DatabaseDSN string
// Payment providers
StripeAPIKey string
StripeWebhookSecret string
PayPalClientID string
PayPalClientSecret string
// Invoice settings
InvoiceDueDays int
InvoiceNumberPrefix string
TaxRate decimal.Decimal
DefaultCurrency string
// Usage aggregation
UsageAggregationInterval time.Duration
UsageRetentionDays int
// Notifications
NotificationServiceURL string
// Feature flags
EnableAutoPayment bool
EnableUsageMetrics bool
EnableTieredPricing bool
EnableMultiCurrency bool
}
BillingConfig represents the billing system configuration
type BillingCycle ¶
type BillingCycle string
BillingCycle represents the billing frequency
const ( BillingCycleMonthly BillingCycle = "monthly" BillingCycleAnnual BillingCycle = "annual" )
type BillingEventPublisher ¶
type BillingEventPublisher struct {
// contains filtered or unexported fields
}
BillingEventPublisher publishes billing events to Kafka
func NewBillingEventPublisher ¶
func NewBillingEventPublisher(eventBus EventBus) *BillingEventPublisher
NewBillingEventPublisher creates a new event publisher
func (*BillingEventPublisher) PublishCreditApplied ¶
func (p *BillingEventPublisher) PublishCreditApplied( ctx context.Context, credit *models.Credit, invoiceID string, amountApplied string, ) error
PublishCreditApplied publishes a credit applied event
func (*BillingEventPublisher) PublishInvoiceCreated ¶
func (p *BillingEventPublisher) PublishInvoiceCreated( ctx context.Context, invoice *models.Invoice, ) error
PublishInvoiceCreated publishes an invoice created event
func (*BillingEventPublisher) PublishInvoiceOverdue ¶
func (p *BillingEventPublisher) PublishInvoiceOverdue( ctx context.Context, invoice *models.Invoice, ) error
PublishInvoiceOverdue publishes an invoice overdue event
func (*BillingEventPublisher) PublishInvoicePaid ¶
func (p *BillingEventPublisher) PublishInvoicePaid( ctx context.Context, invoice *models.Invoice, paymentID string, ) error
PublishInvoicePaid publishes an invoice paid event
func (*BillingEventPublisher) PublishPaymentFailed ¶
func (p *BillingEventPublisher) PublishPaymentFailed( ctx context.Context, payment *models.Payment, ) error
PublishPaymentFailed publishes a payment failed event
func (*BillingEventPublisher) PublishPaymentSucceeded ¶
func (p *BillingEventPublisher) PublishPaymentSucceeded( ctx context.Context, payment *models.Payment, ) error
PublishPaymentSucceeded publishes a payment succeeded event
func (*BillingEventPublisher) PublishSubscriptionCanceled ¶
func (p *BillingEventPublisher) PublishSubscriptionCanceled( ctx context.Context, subscription *models.Subscription, ) error
PublishSubscriptionCanceled publishes a subscription canceled event
func (*BillingEventPublisher) PublishSubscriptionCreated ¶
func (p *BillingEventPublisher) PublishSubscriptionCreated( ctx context.Context, subscription *models.Subscription, ) error
PublishSubscriptionCreated publishes a subscription created event
func (*BillingEventPublisher) PublishUsageThresholdReached ¶
func (p *BillingEventPublisher) PublishUsageThresholdReached( ctx context.Context, organizationID string, metricType MetricType, currentUsage, threshold string, percentUsed int, ) error
PublishUsageThresholdReached publishes a usage threshold reached event
type BillingReport ¶
type BillingReport struct {
ReportType string // mrr, revenue, churn, usage
PeriodStart time.Time
PeriodEnd time.Time
Data map[string]interface{}
GeneratedAt time.Time
}
BillingReport represents various billing reports
type ChargeCalculation ¶
type ChargeCalculation struct {
BaseCharge decimal.Decimal
UsageCharges map[MetricType]decimal.Decimal
AddonCharges decimal.Decimal
Subtotal decimal.Decimal
Credits decimal.Decimal
TaxAmount decimal.Decimal
Total decimal.Decimal
LineItems []InvoiceLineItem
}
ChargeCalculation represents the result of pricing calculation
type Config ¶
type Config struct {
// Database
DatabaseDSN string
// Stripe configuration
Stripe StripeConfig
// PayPal configuration
PayPal PayPalConfig
// Invoice settings
Invoice InvoiceConfig
// Usage metrics settings
Usage UsageConfig
// Notification settings
Notifications NotificationConfig
// Feature flags
Features FeatureFlags
// Rate limiting
RateLimits RateLimitConfig
}
Config represents the billing system configuration
func LoadFromEnv ¶
LoadFromEnv loads configuration from environment variables
type CreditAppliedEvent ¶
type CreditAppliedEvent struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt time.Time `json:"occurred_at"`
CreditID string `json:"credit_id"`
OrganizationID string `json:"organization_id"`
InvoiceID string `json:"invoice_id"`
Amount string `json:"amount"`
Currency string `json:"currency"`
Reason string `json:"reason"`
}
CreditAppliedEvent represents a credit application event
type CreditStatus ¶
type CreditStatus string
CreditStatus represents the current state of a credit
const ( CreditStatusActive CreditStatus = "active" CreditStatusExhausted CreditStatus = "exhausted" CreditStatusExpired CreditStatus = "expired" CreditStatusVoided CreditStatus = "voided" )
type EventBus ¶
type EventBus interface {
Publish(ctx context.Context, topic string, key string, value interface{}) error
}
EventBus defines the interface for publishing events
type EventType ¶
type EventType string
EventType represents billing event types for Kafka
const ( EventSubscriptionCreated EventType = "billing.subscription.created" EventSubscriptionUpdated EventType = "billing.subscription.updated" EventSubscriptionCanceled EventType = "billing.subscription.canceled" EventInvoiceCreated EventType = "billing.invoice.created" EventInvoicePaid EventType = "billing.invoice.paid" EventInvoiceOverdue EventType = "billing.invoice.overdue" EventPaymentSucceeded EventType = "billing.payment.succeeded" EventPaymentFailed EventType = "billing.payment.failed" EventUsageThresholdReached EventType = "billing.usage.threshold_reached" EventCreditApplied EventType = "billing.credit.applied" )
type FeatureFlags ¶
type FeatureFlags struct {
EnableAutoPayment bool // Automatically charge payment methods
EnableUsageMetrics bool // Track and bill for usage
EnableTieredPricing bool // Support volume-based pricing tiers
EnableMultiCurrency bool // Support multiple currencies
EnableCredits bool // Support account credits
EnableProration bool // Prorate charges for mid-cycle changes
}
FeatureFlags controls which features are enabled
type InvoiceConfig ¶
type InvoiceConfig struct {
DueDays int // Number of days until invoice is due
NumberPrefix string // Prefix for invoice numbers (e.g., "INV-")
TaxRate decimal.Decimal // Default tax rate (e.g., 0.10 for 10%)
DefaultCurrency string // Default currency code (ISO 4217)
PDFStoragePath string // Path to store generated PDF files
}
InvoiceConfig contains invoice generation settings
type InvoiceCreatedEvent ¶
type InvoiceCreatedEvent struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt time.Time `json:"occurred_at"`
InvoiceID string `json:"invoice_id"`
InvoiceNumber string `json:"invoice_number"`
OrganizationID string `json:"organization_id"`
SubscriptionID string `json:"subscription_id"`
TotalAmount string `json:"total_amount"`
Currency string `json:"currency"`
Status string `json:"status"`
DueDate time.Time `json:"due_date"`
}
InvoiceCreatedEvent represents an invoice creation event
type InvoiceLineItem ¶
type InvoiceLineItem struct {
Description string
Quantity decimal.Decimal
UnitPrice decimal.Decimal
Amount decimal.Decimal
ItemType LineItemType
MetricType MetricType
PeriodStart *time.Time
PeriodEnd *time.Time
Metadata map[string]interface{}
}
InvoiceLineItem represents a single charge on an invoice
type InvoiceOverdueEvent ¶
type InvoiceOverdueEvent struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt time.Time `json:"occurred_at"`
InvoiceID string `json:"invoice_id"`
InvoiceNumber string `json:"invoice_number"`
OrganizationID string `json:"organization_id"`
AmountDue string `json:"amount_due"`
Currency string `json:"currency"`
DueDate time.Time `json:"due_date"`
DaysOverdue int `json:"days_overdue"`
}
InvoiceOverdueEvent represents an overdue invoice event
type InvoicePaidEvent ¶
type InvoicePaidEvent struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt time.Time `json:"occurred_at"`
InvoiceID string `json:"invoice_id"`
InvoiceNumber string `json:"invoice_number"`
OrganizationID string `json:"organization_id"`
PaymentID string `json:"payment_id"`
AmountPaid string `json:"amount_paid"`
Currency string `json:"currency"`
PaidAt time.Time `json:"paid_at"`
}
InvoicePaidEvent represents an invoice payment event
type InvoiceService ¶
type InvoiceService struct {
// contains filtered or unexported fields
}
InvoiceService handles invoice generation and management
func NewInvoiceService ¶
func NewInvoiceService( db *gorm.DB, config *Config, pricingEngine *PricingEngine, metricsCollector *MetricsCollector, ) *InvoiceService
NewInvoiceService creates a new invoice service
func (*InvoiceService) FinalizeInvoice ¶
func (is *InvoiceService) FinalizeInvoice(ctx context.Context, invoiceID string) error
FinalizeInvoice marks an invoice as finalized and ready for payment
func (*InvoiceService) GenerateInvoice ¶
func (is *InvoiceService) GenerateInvoice( ctx context.Context, subscriptionID string, ) (*models.Invoice, error)
GenerateInvoice generates an invoice for a subscription billing period
func (*InvoiceService) GetInvoice ¶
func (is *InvoiceService) GetInvoice(ctx context.Context, invoiceID string) (*models.Invoice, error)
GetInvoice retrieves an invoice by ID
func (*InvoiceService) GetUpcomingInvoice ¶
func (is *InvoiceService) GetUpcomingInvoice( ctx context.Context, subscriptionID string, ) (*models.Invoice, error)
GetUpcomingInvoice calculates what the next invoice will look like
func (*InvoiceService) ListInvoices ¶
func (is *InvoiceService) ListInvoices( ctx context.Context, organizationID string, limit, offset int, ) ([]models.Invoice, error)
ListInvoices retrieves invoices for an organization
func (*InvoiceService) MarkInvoiceAsPaid ¶
func (is *InvoiceService) MarkInvoiceAsPaid( ctx context.Context, invoiceID string, paymentID string, paidAmount decimal.Decimal, ) error
MarkInvoiceAsPaid marks an invoice as paid
func (*InvoiceService) ProcessOverdueInvoices ¶
func (is *InvoiceService) ProcessOverdueInvoices(ctx context.Context) error
ProcessOverdueInvoices marks overdue invoices and triggers notifications
func (*InvoiceService) VoidInvoice ¶
func (is *InvoiceService) VoidInvoice(ctx context.Context, invoiceID string) error
VoidInvoice voids an invoice
type InvoiceStatus ¶
type InvoiceStatus string
InvoiceStatus represents the current state of an invoice
const ( InvoiceStatusDraft InvoiceStatus = "draft" InvoiceStatusOpen InvoiceStatus = "open" InvoiceStatusPaid InvoiceStatus = "paid" InvoiceStatusVoid InvoiceStatus = "void" InvoiceStatusUncollectible InvoiceStatus = "uncollectible" )
type LineItemType ¶
type LineItemType string
LineItemType represents different types of invoice line items
const ( LineItemTypeSubscriptionBase LineItemType = "subscription_base" LineItemTypeUsageAPICalls LineItemType = "usage_api_calls" LineItemTypeUsageStorage LineItemType = "usage_storage" LineItemTypeUsageTransfer LineItemType = "usage_transfer" LineItemTypeAddonSeats LineItemType = "addon_seats" LineItemTypeAddonSupport LineItemType = "addon_support" LineItemTypeCredit LineItemType = "credit" LineItemTypeTax LineItemType = "tax" LineItemTypeDiscount LineItemType = "discount" )
type MetricType ¶
type MetricType string
MetricType represents different billable metrics
const ( MetricTypeAPICalls MetricType = "api_calls" MetricTypeStorageGB MetricType = "storage_gb" MetricTypeTransferGBIn MetricType = "transfer_gb_in" MetricTypeTransferGBOut MetricType = "transfer_gb_out" MetricTypeQuerySeconds MetricType = "query_seconds" MetricTypeGraphQLOperations MetricType = "graphql_operations" MetricTypeKafkaEvents MetricType = "kafka_events" MetricTypeAdaptersActive MetricType = "adapters_active" )
type MetricsCollector ¶
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector handles usage metrics collection and aggregation
func NewMetricsCollector ¶
func NewMetricsCollector(db *gorm.DB, config *Config) *MetricsCollector
NewMetricsCollector creates a new metrics collector
func (*MetricsCollector) AggregateUsageMetrics ¶
func (mc *MetricsCollector) AggregateUsageMetrics(ctx context.Context) error
AggregateUsageMetrics aggregates Prometheus metrics into database records
func (*MetricsCollector) GetCurrentUsage ¶
func (mc *MetricsCollector) GetCurrentUsage( ctx context.Context, organizationID string, ) (map[MetricType]decimal.Decimal, error)
GetCurrentUsage retrieves current usage (real-time)
func (*MetricsCollector) GetUsageForPeriod ¶
func (mc *MetricsCollector) GetUsageForPeriod( ctx context.Context, organizationID string, periodStart, periodEnd time.Time, ) (*UsageAggregation, error)
GetUsageForPeriod retrieves aggregated usage for a billing period
func (*MetricsCollector) RecordAPICall ¶
func (mc *MetricsCollector) RecordAPICall(organizationID, endpoint, method string)
RecordAPICall records an API call metric
func (*MetricsCollector) RecordActiveAdapters ¶
func (mc *MetricsCollector) RecordActiveAdapters(organizationID string, count int)
RecordActiveAdapters records the number of active adapters
func (*MetricsCollector) RecordKafkaEvent ¶
func (mc *MetricsCollector) RecordKafkaEvent(organizationID, topic string)
RecordKafkaEvent records a Kafka event
func (*MetricsCollector) RecordQuery ¶
func (mc *MetricsCollector) RecordQuery(organizationID, queryType string, duration time.Duration)
RecordQuery records a query execution
func (*MetricsCollector) RecordStorage ¶
func (mc *MetricsCollector) RecordStorage(organizationID, storageType string, bytes int64)
RecordStorage records current storage usage
func (*MetricsCollector) RecordTransfer ¶
func (mc *MetricsCollector) RecordTransfer(organizationID, direction string, bytes int64)
RecordTransfer records data transfer
func (*MetricsCollector) StartAggregationWorker ¶
func (mc *MetricsCollector) StartAggregationWorker(ctx context.Context)
StartAggregationWorker starts a background worker to aggregate metrics periodically
type NotificationConfig ¶
type NotificationConfig struct {
ServiceURL string // URL of the notification service
RetryAttempts int // Number of retry attempts for failed notifications
RetryDelay time.Duration // Delay between retry attempts
TimeoutSeconds int // Timeout for notification requests
}
NotificationConfig contains notification integration settings
type NotificationRequest ¶
type NotificationRequest struct {
RecipientID string `json:"recipient_id"`
RecipientType string `json:"recipient_type"`
TemplateCode string `json:"template_code"`
Channels []string `json:"channels"`
Priority string `json:"priority"`
Data map[string]interface{} `json:"data"`
}
NotificationRequest represents a request to the notification service
type NotificationService ¶
type NotificationService struct {
// contains filtered or unexported fields
}
NotificationService handles sending billing-related notifications
func NewNotificationService ¶
func NewNotificationService(config *Config) *NotificationService
NewNotificationService creates a new notification service
func (*NotificationService) CreateBillingTemplates ¶
func (ns *NotificationService) CreateBillingTemplates(ctx context.Context) error
CreateBillingTemplates creates email templates for billing notifications This function should be called during system initialization
func (*NotificationService) SendInvoiceCreatedNotification ¶
func (ns *NotificationService) SendInvoiceCreatedNotification( ctx context.Context, invoice *models.Invoice, ) error
SendInvoiceCreatedNotification sends notification when invoice is created
func (*NotificationService) SendInvoiceOverdueNotification ¶
func (ns *NotificationService) SendInvoiceOverdueNotification( ctx context.Context, invoice *models.Invoice, ) error
SendInvoiceOverdueNotification sends notification when invoice is overdue
func (*NotificationService) SendPaymentFailedNotification ¶
func (ns *NotificationService) SendPaymentFailedNotification( ctx context.Context, payment *models.Payment, invoice *models.Invoice, ) error
SendPaymentFailedNotification sends notification when payment fails
func (*NotificationService) SendPaymentSucceededNotification ¶
func (ns *NotificationService) SendPaymentSucceededNotification( ctx context.Context, payment *models.Payment, invoice *models.Invoice, ) error
SendPaymentSucceededNotification sends notification when payment succeeds
func (*NotificationService) SendSubscriptionCanceledNotification ¶
func (ns *NotificationService) SendSubscriptionCanceledNotification( ctx context.Context, subscription *models.Subscription, ) error
SendSubscriptionCanceledNotification sends notification when subscription is canceled
func (*NotificationService) SendSubscriptionCreatedNotification ¶
func (ns *NotificationService) SendSubscriptionCreatedNotification( ctx context.Context, subscription *models.Subscription, ) error
SendSubscriptionCreatedNotification sends notification when subscription is created
func (*NotificationService) SendUpcomingRenewalNotification ¶
func (ns *NotificationService) SendUpcomingRenewalNotification( ctx context.Context, subscription *models.Subscription, upcomingInvoice *models.Invoice, ) error
SendUpcomingRenewalNotification sends notification before subscription renewal
func (*NotificationService) SendUsageThresholdNotification ¶
func (ns *NotificationService) SendUsageThresholdNotification( ctx context.Context, organizationID string, metricType MetricType, currentUsage, threshold string, percentUsed int, ) error
SendUsageThresholdNotification sends notification when usage threshold is reached
type ObservabilityService ¶
type ObservabilityService struct{}
ObservabilityService provides observability instrumentation
func NewObservabilityService ¶
func NewObservabilityService() *ObservabilityService
NewObservabilityService creates a new observability service
func (*ObservabilityService) RecordCreditApplied ¶
func (o *ObservabilityService) RecordCreditApplied(reason string)
RecordCreditApplied records a credit application
func (*ObservabilityService) RecordCreditIssued ¶
func (o *ObservabilityService) RecordCreditIssued(reason string)
RecordCreditIssued records a credit issuance
func (*ObservabilityService) RecordInvoiceGenerated ¶
func (o *ObservabilityService) RecordInvoiceGenerated(status string, amount float64, currency string)
RecordInvoiceGenerated records an invoice generation
func (*ObservabilityService) RecordPaymentDuration ¶
func (o *ObservabilityService) RecordPaymentDuration(provider string, seconds float64)
RecordPaymentDuration records payment processing duration
func (*ObservabilityService) RecordPaymentFailure ¶
func (o *ObservabilityService) RecordPaymentFailure(failureCode, provider string)
RecordPaymentFailure records a payment failure
func (*ObservabilityService) RecordPaymentProcessed ¶
func (o *ObservabilityService) RecordPaymentProcessed(status, provider string, amount float64, currency string)
RecordPaymentProcessed records a payment attempt
func (*ObservabilityService) RecordSubscriptionCanceled ¶
func (o *ObservabilityService) RecordSubscriptionCanceled(plan, reason string)
RecordSubscriptionCanceled records a subscription cancellation
func (*ObservabilityService) RecordSubscriptionCreated ¶
func (o *ObservabilityService) RecordSubscriptionCreated(plan string)
RecordSubscriptionCreated records a subscription creation
func (*ObservabilityService) RecordUsageMetricCollected ¶
func (o *ObservabilityService) RecordUsageMetricCollected(metricType string)
RecordUsageMetricCollected records a usage metric collection
func (*ObservabilityService) UpdateARR ¶
func (o *ObservabilityService) UpdateARR(arr float64)
UpdateARR updates the annual recurring revenue metric
func (*ObservabilityService) UpdateMRR ¶
func (o *ObservabilityService) UpdateMRR(mrr float64)
UpdateMRR updates the monthly recurring revenue metric
type OrganizationStatus ¶
type OrganizationStatus string
OrganizationStatus represents the current state of a billing organization
const ( OrganizationStatusActive OrganizationStatus = "active" OrganizationStatusSuspended OrganizationStatus = "suspended" OrganizationStatusDeleted OrganizationStatus = "deleted" )
type PayPalConfig ¶
type PayPalConfig struct {
ClientID string
ClientSecret string
Environment string // sandbox or production
Enabled bool
}
PayPalConfig contains PayPal payment provider settings
type PaymentFailedEvent ¶
type PaymentFailedEvent struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt time.Time `json:"occurred_at"`
PaymentID string `json:"payment_id"`
OrganizationID string `json:"organization_id"`
InvoiceID string `json:"invoice_id"`
Amount string `json:"amount"`
Currency string `json:"currency"`
FailureCode string `json:"failure_code"`
FailureMessage string `json:"failure_message"`
FailedAt time.Time `json:"failed_at"`
}
PaymentFailedEvent represents a failed payment event
type PaymentMethod ¶
type PaymentMethod struct {
ID string
Type string // card, ach, paypal, etc.
Last4 string
ExpiryMonth int
ExpiryYear int
Brand string
IsDefault bool
ProviderID string // Stripe payment method ID
OrganizationID string
}
PaymentMethod represents a stored payment method
type PaymentProvider ¶
type PaymentProvider string
PaymentProvider represents payment processing providers
const ( PaymentProviderStripe PaymentProvider = "stripe" PaymentProviderPayPal PaymentProvider = "paypal" PaymentProviderManual PaymentProvider = "manual" )
type PaymentService ¶
type PaymentService struct {
// contains filtered or unexported fields
}
PaymentService handles payment processing
func NewPaymentService ¶
func NewPaymentService( db *gorm.DB, config *Config, invoiceService *InvoiceService, ) *PaymentService
NewPaymentService creates a new payment service
func (*PaymentService) AttachPaymentMethod ¶
func (ps *PaymentService) AttachPaymentMethod( ctx context.Context, organizationID, paymentMethodID string, setAsDefault bool, ) error
AttachPaymentMethod attaches a payment method to a customer
func (*PaymentService) ChargeInvoice ¶
func (ps *PaymentService) ChargeInvoice( ctx context.Context, invoiceID string, ) (*models.Payment, error)
ChargeInvoice charges a payment method for an invoice
func (*PaymentService) CreateStripeCustomer ¶
func (ps *PaymentService) CreateStripeCustomer( ctx context.Context, org *models.Organization, ) (string, error)
CreateStripeCustomer creates a Stripe customer for an organization
func (*PaymentService) HandleWebhook ¶
func (ps *PaymentService) HandleWebhook( ctx context.Context, provider PaymentProvider, eventType string, payload map[string]interface{}, ) error
HandleWebhook processes payment provider webhooks
func (*PaymentService) ListPayments ¶
func (ps *PaymentService) ListPayments( ctx context.Context, organizationID string, limit, offset int, ) ([]models.Payment, error)
ListPayments retrieves payments for an organization
func (*PaymentService) RefundPayment ¶
func (ps *PaymentService) RefundPayment( ctx context.Context, paymentID string, amount *decimal.Decimal, ) error
RefundPayment refunds a payment
type PaymentStatus ¶
type PaymentStatus string
PaymentStatus represents the current state of a payment
const ( PaymentStatusPending PaymentStatus = "pending" PaymentStatusSucceeded PaymentStatus = "succeeded" PaymentStatusFailed PaymentStatus = "failed" PaymentStatusRefunded PaymentStatus = "refunded" PaymentStatusCanceled PaymentStatus = "canceled" )
type PaymentSucceededEvent ¶
type PaymentSucceededEvent struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt time.Time `json:"occurred_at"`
PaymentID string `json:"payment_id"`
OrganizationID string `json:"organization_id"`
InvoiceID string `json:"invoice_id"`
Amount string `json:"amount"`
Currency string `json:"currency"`
PaymentMethod string `json:"payment_method"`
ProviderPaymentID string `json:"provider_payment_id"`
SucceededAt time.Time `json:"succeeded_at"`
}
PaymentSucceededEvent represents a successful payment event
type PricingEngine ¶
type PricingEngine struct {
// contains filtered or unexported fields
}
PricingEngine handles all pricing calculations
func NewPricingEngine ¶
func NewPricingEngine(config *Config) *PricingEngine
NewPricingEngine creates a new pricing engine
func (*PricingEngine) CalculateProration ¶
func (pe *PricingEngine) CalculateProration( oldPrice, newPrice decimal.Decimal, periodStart, periodEnd, changeDate time.Time, ) decimal.Decimal
CalculateProration calculates prorated charges for mid-cycle changes
func (*PricingEngine) CalculateSubscriptionCharge ¶
func (pe *PricingEngine) CalculateSubscriptionCharge( subscription *models.Subscription, plan *models.SubscriptionPlan, usage *UsageAggregation, credits []models.Credit, ) (*ChargeCalculation, error)
CalculateSubscriptionCharge calculates the charge for a subscription period
func (*PricingEngine) CalculateTieredPrice ¶
func (pe *PricingEngine) CalculateTieredPrice( usage decimal.Decimal, tiers []models.PricingTier, ) decimal.Decimal
CalculateTieredPrice calculates price using volume-based tiers
func (*PricingEngine) EstimateMonthlyCharge ¶
func (pe *PricingEngine) EstimateMonthlyCharge( plan *models.SubscriptionPlan, quantity int, estimatedUsage map[MetricType]decimal.Decimal, ) decimal.Decimal
EstimateMonthlyCharge estimates the monthly charge for a subscription
type PricingTier ¶
type PricingTier struct {
TierStart decimal.Decimal // Inclusive lower bound
TierEnd *decimal.Decimal // Exclusive upper bound (nil = infinity)
PricePerUnit decimal.Decimal
FlatFee decimal.Decimal
}
PricingTier represents a volume-based pricing tier
type RateLimitConfig ¶
type RateLimitConfig struct {
RequestsPerSecond int // Maximum requests per second
BurstSize int // Maximum burst size
}
RateLimitConfig contains API rate limiting settings
type StripeConfig ¶
StripeConfig contains Stripe payment provider settings
type SubscriptionCanceledEvent ¶
type SubscriptionCanceledEvent struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt time.Time `json:"occurred_at"`
SubscriptionID string `json:"subscription_id"`
OrganizationID string `json:"organization_id"`
CancellationReason string `json:"cancellation_reason"`
CanceledAt time.Time `json:"canceled_at"`
EndDate time.Time `json:"end_date"`
}
SubscriptionCanceledEvent represents a subscription cancellation event
type SubscriptionChange ¶
type SubscriptionChange struct {
SubscriptionID string
FromPlanID string
ToPlanID string
ChangeType string // upgrade, downgrade
Proration decimal.Decimal
EffectiveDate time.Time
}
SubscriptionChange represents a change to a subscription (upgrade/downgrade)
type SubscriptionCreatedEvent ¶
type SubscriptionCreatedEvent struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt time.Time `json:"occurred_at"`
SubscriptionID string `json:"subscription_id"`
OrganizationID string `json:"organization_id"`
PlanID string `json:"plan_id"`
PlanName string `json:"plan_name"`
Status string `json:"status"`
PeriodStart time.Time `json:"period_start"`
PeriodEnd time.Time `json:"period_end"`
Amount string `json:"amount"`
Currency string `json:"currency"`
}
SubscriptionCreatedEvent represents a subscription creation event
type SubscriptionStatus ¶
type SubscriptionStatus string
SubscriptionStatus represents the current state of a subscription
const ( SubscriptionStatusActive SubscriptionStatus = "active" SubscriptionStatusCanceled SubscriptionStatus = "canceled" SubscriptionStatusPastDue SubscriptionStatus = "past_due" SubscriptionStatusTrialing SubscriptionStatus = "trialing" SubscriptionStatusIncomplete SubscriptionStatus = "incomplete" )
type SubscriptionUpdatedEvent ¶
type SubscriptionUpdatedEvent struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt time.Time `json:"occurred_at"`
SubscriptionID string `json:"subscription_id"`
OrganizationID string `json:"organization_id"`
Changes map[string]interface{} `json:"changes"`
}
SubscriptionUpdatedEvent represents a subscription update event
type UsageAggregation ¶
type UsageAggregation struct {
OrganizationID string
SubscriptionID string
PeriodStart time.Time
PeriodEnd time.Time
Metrics map[MetricType]decimal.Decimal
}
UsageAggregation represents aggregated usage for a billing period
type UsageConfig ¶
type UsageConfig struct {
AggregationInterval time.Duration // How often to aggregate usage metrics
RetentionDays int // How long to retain detailed usage data
BatchSize int // Batch size for metric processing
EnableRealTime bool // Enable real-time usage tracking
}
UsageConfig contains usage metrics collection settings
type UsageRecord ¶
type UsageRecord struct {
OrganizationID string
SubscriptionID string
MetricType MetricType
MetricValue decimal.Decimal
MetricUnit string
RecordedAt time.Time
PeriodStart time.Time
PeriodEnd time.Time
ResourceID string
Metadata map[string]interface{}
}
UsageRecord represents a single usage metric record
type UsageThresholdReachedEvent ¶
type UsageThresholdReachedEvent struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt time.Time `json:"occurred_at"`
OrganizationID string `json:"organization_id"`
MetricType string `json:"metric_type"`
CurrentUsage string `json:"current_usage"`
Threshold string `json:"threshold"`
PercentUsed int `json:"percent_used"`
}
UsageThresholdReachedEvent represents a usage threshold event
type WebhookEvent ¶
type WebhookEvent struct {
Provider PaymentProvider
EventType string
EventID string
Payload map[string]interface{}
Signature string
ReceivedAt time.Time
}
WebhookEvent represents a payment provider webhook event