Documentation
¶
Overview ¶
Package service provides business logic implementations for the FlexPrice application.
Package service provides file processing capabilities with support for multiple cloud storage providers.
The file download system is designed to be generic and extensible, supporting various providers: - Direct URLs (http/https) - Google Drive - AWS S3 - Microsoft OneDrive - Dropbox - GitHub (raw files)
Example usage:
processor := NewFileProcessor(httpClient, logger)
content, err := processor.DownloadFile(ctx, &task.Task{FileURL: "https://drive.google.com/file/d/123/view"})
if err != nil {
// Handle error - simple error message, no complex error objects
log.Printf("Download failed: %v", err)
}
Adding a new provider:
- Implement the FileProvider interface
- Register it with the FileProviderRegistry
- Update the GetProvider method to detect URLs for your provider
Index ¶
- Constants
- func CalculateCreditGrantPeriods(grant creditgrant.CreditGrant, initialPeriodStart time.Time, ...) ([]types.Period, error)
- func CalculateNextCreditGrantPeriod(grant creditgrant.CreditGrant, nextPeriodStart time.Time) (time.Time, time.Time, error)
- func GetSetting[T any](s *settingsService, ctx context.Context, key types.SettingKey) (T, error)
- func NewProrationService(serviceParams ServiceParams) proration.Service
- func UpdateSetting[T types.SettingConfig](s *settingsService, ctx context.Context, key types.SettingKey, value T) error
- type AddonService
- type AlertLogsService
- type AnalyticsData
- type AuthService
- type BillingCalculationResult
- type BillingService
- type CSVProcessor
- type ChunkProcessor
- type ChunkResult
- type ConnectionService
- type CostSheetUsageTrackingService
- type CostsheetService
- type CouponApplicationService
- type CouponAssociationService
- type CouponCalculationResult
- type CouponService
- type CouponValidationError
- type CouponValidationService
- type CreditGrantService
- type CreditNoteService
- type CustomerPortalService
- type CustomerService
- type CustomersChunkProcessor
- type DirectURLProvider
- type DropboxProvider
- type EntitlementService
- type EntityIntegrationMappingService
- type EnvAccessService
- type EnvironmentService
- type EventConsumptionService
- type EventPostProcessingService
- type EventService
- type EventsChunkProcessor
- type FeatureService
- type FeatureUsageTrackingService
- type FeaturesChunkProcessor
- type FileProcessor
- func (fp *FileProcessor) DetectFileType(fileContent []byte) FileType
- func (fp *FileProcessor) DownloadFile(ctx context.Context, t *task.Task) ([]byte, error)
- func (fp *FileProcessor) DownloadFileStream(ctx context.Context, t *task.Task) (io.ReadCloser, error)
- func (fp *FileProcessor) GetFileSize(ctx context.Context, t *task.Task) (int64, error)
- func (fp *FileProcessor) PrepareCSVReader(fileContent []byte) (*csv.Reader, error)
- func (fp *FileProcessor) PrepareJSONReader(fileContent []byte) (*jsoniter.Decoder, error)
- func (fp *FileProcessor) ShouldUseStreaming(fileSize int64) bool
- func (fp *FileProcessor) ValidateFileSize(fileSize int64) error
- type FileProvider
- type FileProviderRegistry
- type FileProviderType
- type FileType
- type GitHubProvider
- type GoogleDriveProvider
- type GroupService
- type InvoiceService
- type JSONProcessor
- type LineItemClassification
- type LogAlertRequest
- type MeterService
- type OAuthService
- type OnboardingService
- type OneDriveProvider
- type PaymentMethodUsed
- type PaymentProcessorService
- type PaymentResult
- type PaymentService
- type PlanService
- type PriceMatch
- type PriceService
- type PriceUnitService
- type PricesChunkProcessor
- type RevenueAnalyticsService
- type S3Provider
- type ScheduledTaskService
- type SecretService
- type ServiceParams
- type SettingsService
- type StateAction
- type StreamingConfig
- type StreamingProcessor
- type SubscriptionChangeService
- type SubscriptionPaymentProcessor
- type SubscriptionPhaseService
- type SubscriptionService
- type SubscriptionStateHandler
- type TaskService
- type TaxCalculationResult
- type TaxService
- type TenantService
- type UserService
- type WalletBalanceAlertService
- type WalletPaymentOptions
- type WalletPaymentService
- type WalletPaymentStrategy
- type WalletService
- type WebhookEventMapping
Constants ¶
const ( // CreditNoteNumberPrefix is the prefix for credit note numbers CreditNoteNumberPrefix = "CN" // CreditNoteNumberLength is the length of the random part of credit note number CreditNoteNumberLength = 8 )
const ( // Event sources for tracking where alerts originated EventSourceFeatureUsage = "feature_usage" EventSourceWalletTransaction = "wallet_transaction" // Throttle duration for wallet balance recalculations WalletAlertThrottleDuration = 1 * time.Minute )
const ( // OAuthSessionTTL is the lifetime of an OAuth session (5 minutes) // This matches typical OAuth authorization code expiry times OAuthSessionTTL = 5 * time.Minute )
const (
OnboardingEventsTopic = "onboarding_events"
)
Variables ¶
This section is empty.
Functions ¶
func CalculateCreditGrantPeriods ¶ added in v1.0.49
func CalculateCreditGrantPeriods( grant creditgrant.CreditGrant, initialPeriodStart time.Time, endDate *time.Time, ) ([]types.Period, error)
CalculateCreditGrantPeriods calculates all billing periods for a credit grant from an initial period start until an end date. This function decouples credit grant period calculations from subscription cron processing. Parameters:
- grant: The credit grant for which to calculate periods
- initialPeriodStart: Start of the first period
- endDate: Calculate periods until this date (typically grant end date or current time)
Returns an array of Period structs and an error if calculation fails.
func CalculateNextCreditGrantPeriod ¶ added in v1.0.49
func CalculateNextCreditGrantPeriod(grant creditgrant.CreditGrant, nextPeriodStart time.Time) (time.Time, time.Time, error)
func GetSetting ¶ added in v1.0.47
GetSetting retrieves a setting and returns it as a typed struct
WHEN TO USE:
- Use this when you need the setting value as a typed struct in your business logic
- Use this in other services (e.g., subscription service needs InvoiceConfig)
- Returns default values if setting doesn't exist
- Use this for type-safe access to setting values
WHEN NOT TO USE:
- Don't use for API responses (use GetSettingByKey instead)
- Don't use if you need the Setting object with metadata (ID, timestamps, etc.)
- Don't call repository methods directly - always use service methods
Example:
config, err := service.GetSetting[types.InvoiceConfig](ctx, types.SettingKeyInvoiceConfig)
if err != nil {
return err
}
prefix := config.InvoiceNumberPrefix // Type-safe access
func NewProrationService ¶ added in v1.0.25
func NewProrationService( serviceParams ServiceParams, ) proration.Service
NewProrationService creates a new proration service.
func UpdateSetting ¶ added in v1.0.47
func UpdateSetting[T types.SettingConfig](s *settingsService, ctx context.Context, key types.SettingKey, value T) error
UpdateSetting updates a setting value (creates if doesn't exist)
WHEN TO USE:
- Use this when you have a complete typed struct and want to update the setting
- Use this in other services when you need to update settings programmatically
- Automatically creates the setting if it doesn't exist
- Use this for full replacement of setting values
WHEN NOT TO USE:
- Don't use for API endpoints with partial updates (use UpdateSettingByKey instead)
- Don't use if you need to merge with existing values
- Don't call repository methods directly - always use service methods
Example:
config := types.InvoiceConfig{
InvoiceNumberPrefix: "INV",
InvoiceNumberFormat: types.InvoiceNumberFormatYYYYMM,
// ... other fields
}
err := service.UpdateSetting(ctx, types.SettingKeyInvoiceConfig, config)
Types ¶
type AddonService ¶ added in v1.0.21
type AddonService interface {
// Addon CRUD operations
CreateAddon(ctx context.Context, req dto.CreateAddonRequest) (*dto.CreateAddonResponse, error)
GetAddon(ctx context.Context, id string) (*dto.AddonResponse, error)
GetAddonByLookupKey(ctx context.Context, lookupKey string) (*dto.AddonResponse, error)
GetAddons(ctx context.Context, filter *types.AddonFilter) (*dto.ListAddonsResponse, error)
UpdateAddon(ctx context.Context, id string, req dto.UpdateAddonRequest) (*dto.AddonResponse, error)
DeleteAddon(ctx context.Context, id string) error
// Addon Association operations
ListAddonAssociations(ctx context.Context, filter *types.AddonAssociationFilter) (*dto.ListAddonAssociationsResponse, error)
GetActiveAddonAssociation(ctx context.Context, req dto.GetActiveAddonAssociationRequest) (*dto.ListAddonAssociationsResponse, error)
}
AddonService interface defines the business logic for addon management
func NewAddonService ¶ added in v1.0.21
func NewAddonService(params ServiceParams) AddonService
type AlertLogsService ¶ added in v1.0.29
type AlertLogsService interface {
// LogAlert creates a new alert log entry and triggers webhook if status changes
// This is the main method used by cron jobs or other internal processes
LogAlert(ctx context.Context, req *LogAlertRequest) error
// GetLatestAlert retrieves the latest alert log based on provided filters
GetLatestAlert(ctx context.Context, entityType types.AlertEntityType, entityID string, alertType *types.AlertType, parentEntityType *string, parentEntityID *string) (*alertlogs.AlertLog, error)
// ListAlertsByEntity retrieves alert logs for a specific entity
ListAlertsByEntity(ctx context.Context, entityType types.AlertEntityType, entityID string, limit int) ([]*alertlogs.AlertLog, error)
// ListAlertLogsByFilter retrieves alert logs by filter
ListAlertLogsByFilter(ctx context.Context, filter *types.AlertLogFilter) (*types.ListResponse[*alertlogs.AlertLog], error)
}
AlertLogsService defines the interface for alert logs operations
func NewAlertLogsService ¶ added in v1.0.29
func NewAlertLogsService(params ServiceParams) AlertLogsService
type AnalyticsData ¶ added in v1.0.29
type AnalyticsData struct {
Customer *customer.Customer
Subscriptions []*subscription.Subscription
SubscriptionLineItems map[string]*subscription.SubscriptionLineItem // Map of line item ID -> line item
SubscriptionsMap map[string]*subscription.Subscription // Map of subscription ID -> subscription
Analytics []*events.DetailedUsageAnalytic
Features map[string]*feature.Feature
Meters map[string]*meter.Meter
Prices map[string]*price.Price
PriceResponses map[string]*dto.PriceResponse // Map of price ID -> PriceResponse (used when groups need to be expanded)
Plans map[string]*plan.Plan // Map of plan ID -> plan
Addons map[string]*addon.Addon // Map of addon ID -> addon
Currency string
Params *events.UsageAnalyticsParams
}
AnalyticsData holds all data required for analytics processing
type AuthService ¶
type AuthService interface {
SignUp(ctx context.Context, req *dto.SignUpRequest) (*dto.AuthResponse, error)
Login(ctx context.Context, req *dto.LoginRequest) (*dto.AuthResponse, error)
}
func NewAuthService ¶
func NewAuthService( params ServiceParams, pubSub pubsub.PubSub, ) AuthService
type BillingCalculationResult ¶
type BillingCalculationResult struct {
FixedCharges []dto.CreateInvoiceLineItemRequest
UsageCharges []dto.CreateInvoiceLineItemRequest
TotalAmount decimal.Decimal
Currency string
}
BillingCalculationResult holds all calculated charges for a billing period
type BillingService ¶
type BillingService interface {
// CalculateFixedCharges calculates all fixed charges for a subscription
CalculateFixedCharges(ctx context.Context, sub *subscription.Subscription, periodStart, periodEnd time.Time) ([]dto.CreateInvoiceLineItemRequest, decimal.Decimal, error)
// CalculateUsageCharges calculates all usage-based charges
CalculateUsageCharges(ctx context.Context, sub *subscription.Subscription, usage *dto.GetUsageBySubscriptionResponse, periodStart, periodEnd time.Time) ([]dto.CreateInvoiceLineItemRequest, decimal.Decimal, error)
// CalculateAllCharges calculates both fixed and usage charges
CalculateAllCharges(ctx context.Context, sub *subscription.Subscription, usage *dto.GetUsageBySubscriptionResponse, periodStart, periodEnd time.Time) (*BillingCalculationResult, error)
// PrepareSubscriptionInvoiceRequest prepares a complete invoice request for a subscription period
// using the reference point to determine which charges to include
PrepareSubscriptionInvoiceRequest(ctx context.Context, sub *subscription.Subscription, periodStart, periodEnd time.Time, referencePoint types.InvoiceReferencePoint) (*dto.CreateInvoiceRequest, error)
// ClassifyLineItems classifies line items based on cadence and type
ClassifyLineItems(sub *subscription.Subscription, currentPeriodStart, currentPeriodEnd time.Time, nextPeriodStart, nextPeriodEnd time.Time) *LineItemClassification
// FilterLineItemsToBeInvoiced filters the line items to be invoiced for the given period
FilterLineItemsToBeInvoiced(ctx context.Context, sub *subscription.Subscription, periodStart, periodEnd time.Time, lineItems []*subscription.SubscriptionLineItem) ([]*subscription.SubscriptionLineItem, error)
// CalculateCharges calculates charges for the given line items and period
CalculateCharges(ctx context.Context, sub *subscription.Subscription, lineItems []*subscription.SubscriptionLineItem, periodStart, periodEnd time.Time, includeUsage bool) (*BillingCalculationResult, error)
// CreateInvoiceRequestForCharges creates an invoice creation request for the given charges
CreateInvoiceRequestForCharges(ctx context.Context, sub *subscription.Subscription, result *BillingCalculationResult, periodStart, periodEnd time.Time, description string, metadata types.Metadata) (*dto.CreateInvoiceRequest, error)
// GetCustomerEntitlements returns aggregated entitlements for a customer across all subscriptions
GetCustomerEntitlements(ctx context.Context, customerID string, req *dto.GetCustomerEntitlementsRequest) (*dto.CustomerEntitlementsResponse, error)
// AggregateEntitlements aggregates entitlements from multiple sources into a unified view
// If subscriptionID is provided, it will be used for sources that don't have a subscription ID set
AggregateEntitlements(entitlements []*dto.EntitlementResponse, subscriptionID string) []*dto.AggregatedFeature
// GetCustomerUsageSummary returns usage summaries for a customer's features
GetCustomerUsageSummary(ctx context.Context, customerID string, req *dto.GetCustomerUsageSummaryRequest) (*dto.CustomerUsageSummaryResponse, error)
}
BillingService handles all billing calculations
func NewBillingService ¶
func NewBillingService(params ServiceParams) BillingService
type CSVProcessor ¶ added in v1.0.27
CSVProcessor handles CSV-specific operations
func NewCSVProcessor ¶ added in v1.0.27
func NewCSVProcessor(logger *logger.Logger) *CSVProcessor
NewCSVProcessor creates a new CSV processor
func (*CSVProcessor) PrepareCSVReader ¶ added in v1.0.27
func (cp *CSVProcessor) PrepareCSVReader(fileContent []byte) (*csv.Reader, error)
PrepareCSVReader creates a configured CSV reader from the file content
type ChunkProcessor ¶ added in v1.0.27
type ChunkProcessor interface {
ProcessChunk(ctx context.Context, chunk [][]string, headers []string, chunkIndex int) (*ChunkResult, error)
}
ChunkProcessor defines the interface for processing file chunks
type ChunkResult ¶ added in v1.0.27
type ChunkResult struct {
ProcessedRecords int `json:"processed_records"`
SuccessfulRecords int `json:"successful_records"`
FailedRecords int `json:"failed_records"`
ErrorSummary *string `json:"error_summary,omitempty"`
}
ChunkResult represents the result of processing a chunk
type ConnectionService ¶ added in v1.0.21
type ConnectionService interface {
CreateConnection(ctx context.Context, req dto.CreateConnectionRequest) (*dto.ConnectionResponse, error)
GetConnection(ctx context.Context, id string) (*dto.ConnectionResponse, error)
GetConnections(ctx context.Context, filter *types.ConnectionFilter) (*dto.ListConnectionsResponse, error)
UpdateConnection(ctx context.Context, id string, req dto.UpdateConnectionRequest) (*dto.ConnectionResponse, error)
DeleteConnection(ctx context.Context, id string) error
}
ConnectionService defines the interface for connection operations
func NewConnectionService ¶ added in v1.0.21
func NewConnectionService(params ServiceParams, encryptionService security.EncryptionService) ConnectionService
NewConnectionService creates a new connection service
type CostSheetUsageTrackingService ¶ added in v1.0.47
type CostSheetUsageTrackingService interface {
// Publish an event for cost sheet usage tracking
PublishEvent(ctx context.Context, event *events.Event, isBackfill bool) error
// Register message handler with the router
RegisterHandler(router *pubsubRouter.Router, cfg *config.Configuration)
// Register message handler with the router
RegisterHandlerLazy(router *pubsubRouter.Router, cfg *config.Configuration)
// Get Analytics
GetCostSheetUsageAnalytics(ctx context.Context, req *dto.GetCostAnalyticsRequest) (*dto.GetCostAnalyticsResponse, error)
// Reprocess cost sheet usage
ReprocessEvents(ctx context.Context, params *events.ReprocessEventsParams) error
}
CostSheetUsageTrackingService handles cost sheet usage tracking operations for metered events
func NewCostSheetUsageTrackingService ¶ added in v1.0.47
func NewCostSheetUsageTrackingService( params ServiceParams, eventRepo events.Repository, costUsageRepo events.CostSheetUsageRepository, ) CostSheetUsageTrackingService
NewCostSheetUsageTrackingService creates a new cost sheet usage tracking service
type CostsheetService ¶ added in v1.0.33
type CostsheetService interface {
// CRUD Operations
CreateCostsheet(ctx context.Context, req dto.CreateCostsheetRequest) (*dto.CreateCostsheetResponse, error)
GetCostsheet(ctx context.Context, id string) (*dto.CostsheetResponse, error)
GetCostsheets(ctx context.Context, filter *domainCostsheet.Filter) (*dto.ListCostsheetResponse, error)
UpdateCostsheet(ctx context.Context, id string, req dto.UpdateCostsheetRequest) (*dto.UpdateCostsheetResponse, error)
DeleteCostsheet(ctx context.Context, id string) (*dto.DeleteCostsheetResponse, error)
GetActiveCostsheetForTenant(ctx context.Context) (*dto.CostsheetResponse, error)
// Calculation Operations (legacy methods for backward compatibility)
GetInputCostForMargin(ctx context.Context, req *dto.GetCostBreakdownRequest) (*dto.CostBreakdownResponse, error)
CalculateMargin(totalCost, totalRevenue decimal.Decimal) decimal.Decimal
CalculateMarkup(totalCost, totalRevenue decimal.Decimal) decimal.Decimal
}
CostsheetService defines the interface for managing costsheet operations. It provides functionality for CRUD operations and cost calculations.
func NewCostsheetService ¶ added in v1.0.33
func NewCostsheetService(params ServiceParams) CostsheetService
NewCostsheetService creates a new instance of the costsheet service with the required dependencies.
type CouponApplicationService ¶ added in v1.0.21
type CouponApplicationService interface {
CreateCouponApplication(ctx context.Context, req dto.CreateCouponApplicationRequest) (*dto.CouponApplicationResponse, error)
GetCouponApplication(ctx context.Context, id string) (*dto.CouponApplicationResponse, error)
ApplyCouponsToInvoice(ctx context.Context, inv *invoice.Invoice, invoiceCoupons []dto.InvoiceCoupon, lineItemCoupons []dto.InvoiceLineItemCoupon) (*CouponCalculationResult, error)
}
func NewCouponApplicationService ¶ added in v1.0.21
func NewCouponApplicationService( params ServiceParams, ) CouponApplicationService
type CouponAssociationService ¶ added in v1.0.21
type CouponAssociationService interface {
CreateCouponAssociation(ctx context.Context, req dto.CreateCouponAssociationRequest) (*dto.CouponAssociationResponse, error)
GetCouponAssociation(ctx context.Context, id string) (*dto.CouponAssociationResponse, error)
DeleteCouponAssociation(ctx context.Context, id string) error
ListCouponAssociations(ctx context.Context, filter *types.CouponAssociationFilter) (*dto.ListCouponAssociationsResponse, error)
ApplyCouponsToSubscription(ctx context.Context, subscription *subscription.Subscription, coupons []dto.SubscriptionCouponRequest) error
}
func NewCouponAssociationService ¶ added in v1.0.21
func NewCouponAssociationService( params ServiceParams, ) CouponAssociationService
type CouponCalculationResult ¶ added in v1.0.21
type CouponCalculationResult struct {
TotalDiscountAmount decimal.Decimal
AppliedCoupons []*dto.CouponApplicationResponse
Currency string
Metadata map[string]interface{}
}
CouponCalculationResult holds the result of applying coupons to an invoice
type CouponService ¶ added in v1.0.21
type CouponService interface {
// Core coupon operations
CreateCoupon(ctx context.Context, req dto.CreateCouponRequest) (*dto.CouponResponse, error)
GetCoupon(ctx context.Context, id string) (*dto.CouponResponse, error)
UpdateCoupon(ctx context.Context, id string, req dto.UpdateCouponRequest) (*dto.CouponResponse, error)
DeleteCoupon(ctx context.Context, id string) error
ListCoupons(ctx context.Context, filter *types.CouponFilter) (*dto.ListCouponsResponse, error)
ApplyDiscount(ctx context.Context, coupon coupon.Coupon, originalPrice decimal.Decimal) (dto.DiscountResult, error)
}
CouponService defines the interface for core coupon CRUD operations
func NewCouponService ¶ added in v1.0.21
func NewCouponService( params ServiceParams, ) CouponService
NewCouponService creates a new coupon service
type CouponValidationError ¶ added in v1.0.21
type CouponValidationError struct {
Code types.CouponValidationErrorCode `json:"code"`
Message string `json:"message"`
Details map[string]interface{} `json:"details,omitempty"`
}
CouponValidationError represents validation errors with structured details
func (*CouponValidationError) Error ¶ added in v1.0.21
func (e *CouponValidationError) Error() string
type CouponValidationService ¶ added in v1.0.21
type CouponValidationService interface {
// Core validation method - stateless, accepts coupon and subscription objects directly
ValidateCoupon(ctx context.Context, coupon coupon.Coupon, subscription *subscription.Subscription) error
// Basic coupon validation (status, validity, etc.)
ValidateCouponBasic(coupon coupon.Coupon) error
}
CouponValidationService defines the interface for coupon validation operations
func NewCouponValidationService ¶ added in v1.0.21
func NewCouponValidationService(params ServiceParams) CouponValidationService
NewCouponValidationService creates a new coupon validation service
type CreditGrantService ¶ added in v1.0.18
type CreditGrantService interface {
// CreateCreditGrant creates a new credit grant
CreateCreditGrant(ctx context.Context, req dto.CreateCreditGrantRequest) (*dto.CreditGrantResponse, error)
// GetCreditGrant retrieves a credit grant by ID
GetCreditGrant(ctx context.Context, id string) (*dto.CreditGrantResponse, error)
// ListCreditGrants retrieves credit grants based on filter
ListCreditGrants(ctx context.Context, filter *types.CreditGrantFilter) (*dto.ListCreditGrantsResponse, error)
// UpdateCreditGrant updates an existing credit grant
UpdateCreditGrant(ctx context.Context, id string, req dto.UpdateCreditGrantRequest) (*dto.CreditGrantResponse, error)
// DeleteCreditGrant deletes a credit grant by ID
DeleteCreditGrant(ctx context.Context, id string) error
// GetCreditGrantsByPlan retrieves credit grants for a specific plan
GetCreditGrantsByPlan(ctx context.Context, planID string) (*dto.ListCreditGrantsResponse, error)
// GetCreditGrantsBySubscription retrieves credit grants for a specific subscription
GetCreditGrantsBySubscription(ctx context.Context, subscriptionID string) (*dto.ListCreditGrantsResponse, error)
// NOTE: THIS IS ONLY FOR CRON JOB SHOULD NOT BE USED ELSEWHERE IN OTHER WORKFLOWS
// This runs every 15 mins
// ProcessScheduledCreditGrantApplications processes scheduled credit grant applications
ProcessScheduledCreditGrantApplications(ctx context.Context) (*dto.ProcessScheduledCreditGrantApplicationsResponse, error)
// InitializeCreditGrantWorkflow initializes the workflow for a credit grant
// This creates the first CGA and triggers eager application if applicable
InitializeCreditGrantWorkflow(ctx context.Context, cg creditgrant.CreditGrant) (*creditgrant.CreditGrant, error)
// ProcessCreditGrantApplication processes a single credit grant application
// Use this to manually trigger processing of a pending/failed application
ProcessCreditGrantApplication(ctx context.Context, applicationID string) error
// CancelFutureSubscriptionGrants cancels all future credit grants for this subscription
// Sets the grant end date to the effective cancellation date (defaults to now if not provided), then archives the grants
CancelFutureSubscriptionGrants(ctx context.Context, req dto.CancelFutureSubscriptionGrantsRequest) error
// ListCreditGrantApplications retrieves credit grant applications based on filter
ListCreditGrantApplications(ctx context.Context, filter *types.CreditGrantApplicationFilter) (*dto.ListCreditGrantApplicationsResponse, error)
}
CreditGrantService defines the interface for credit grant service
func NewCreditGrantService ¶ added in v1.0.18
func NewCreditGrantService( serviceParams ServiceParams, ) CreditGrantService
type CreditNoteService ¶ added in v1.0.18
type CreditNoteService interface {
CreateCreditNote(ctx context.Context, req *dto.CreateCreditNoteRequest) (*dto.CreditNoteResponse, error)
GetCreditNote(ctx context.Context, id string) (*dto.CreditNoteResponse, error)
ListCreditNotes(ctx context.Context, filter *types.CreditNoteFilter) (*dto.ListCreditNotesResponse, error)
// This method is used to void a credit note
// this can be done when credit note is a adjustment and not a refund so we can cancel the adjustment
VoidCreditNote(ctx context.Context, id string) error
// This method is used to finalize a credit note
// this can be done when credit note is a adjustment and not a refund so we can cancel the adjustment
FinalizeCreditNote(ctx context.Context, id string) error
}
func NewCreditNoteService ¶ added in v1.0.18
func NewCreditNoteService(params ServiceParams) CreditNoteService
type CustomerPortalService ¶ added in v1.0.50
type CustomerPortalService interface {
// CreatePortalSession creates a portal session URL for a customer
CreatePortalSession(ctx context.Context, externalID string) (*dto.PortalSessionResponse, error)
// GetCustomer returns customer info for the portal
GetCustomer(ctx context.Context) (*dto.CustomerResponse, error)
// UpdateCustomer updates customer info from the portal
UpdateCustomer(ctx context.Context, req dto.UpdateCustomerRequest) (*dto.CustomerResponse, error)
// GetSubscriptions returns subscriptions for the portal customer
GetSubscriptions(ctx context.Context, req dto.PortalPaginatedRequest) (*dto.ListSubscriptionsResponse, error)
// GetSubscription returns a specific subscription
GetSubscription(ctx context.Context, subscriptionID string) (*dto.SubscriptionResponse, error)
// GetInvoices returns invoices for the portal customer
GetInvoices(ctx context.Context, req dto.PortalPaginatedRequest) (*dto.ListInvoicesResponse, error)
// GetInvoice returns a specific invoice
GetInvoice(ctx context.Context, invoiceID string) (*dto.InvoiceResponse, error)
// GetWallets returns wallet balances for the portal customer
GetWallets(ctx context.Context) ([]*dto.WalletBalanceResponse, error)
// GetWallet returns a specific wallet
GetWallet(ctx context.Context, walletID string) (*dto.WalletBalanceResponse, error)
// GetInvoicePDFUrl returns a presigned URL for an invoice PDF
GetInvoicePDFUrl(ctx context.Context, invoiceID string) (string, error)
// GetWalletTransactions returns wallet transactions for the portal customer
GetWalletTransactions(ctx context.Context, walletID string, filter *types.WalletTransactionFilter) (*dto.ListWalletTransactionsResponse, error)
// GetAnalytics returns usage analytics for the portal customer
GetAnalytics(ctx context.Context, req dto.PortalAnalyticsRequest) (*dto.GetUsageAnalyticsResponse, error)
// GetCostAnalytics returns cost analytics for the portal customer
GetCostAnalytics(ctx context.Context, req dto.PortalCostAnalyticsRequest) (*dto.GetDetailedCostAnalyticsResponse, error)
// GetUsageSummary returns usage summary for the portal customer
GetUsageSummary(ctx context.Context, req dto.GetCustomerUsageSummaryRequest) (*dto.CustomerUsageSummaryResponse, error)
}
CustomerPortalService provides customer portal functionality
func NewCustomerPortalService ¶ added in v1.0.50
func NewCustomerPortalService( params ServiceParams, customerService CustomerService, revenueAnalyticsService RevenueAnalyticsService, ) CustomerPortalService
NewCustomerPortalService creates a new customer portal service
type CustomerService ¶
type CustomerService = interfaces.CustomerService
func NewCustomerService ¶
func NewCustomerService(params ServiceParams) CustomerService
type CustomersChunkProcessor ¶ added in v1.0.27
type CustomersChunkProcessor struct {
// contains filtered or unexported fields
}
CustomersChunkProcessor processes chunks of customer data
func (*CustomersChunkProcessor) ProcessChunk ¶ added in v1.0.27
func (p *CustomersChunkProcessor) ProcessChunk(ctx context.Context, chunk [][]string, headers []string, chunkIndex int) (*ChunkResult, error)
ProcessChunk processes a chunk of customer records
type DirectURLProvider ¶ added in v1.0.27
type DirectURLProvider struct{}
DirectURLProvider handles direct file URLs
func (*DirectURLProvider) GetDownloadURL ¶ added in v1.0.27
func (*DirectURLProvider) GetProviderName ¶ added in v1.0.27
func (p *DirectURLProvider) GetProviderName() FileProviderType
type DropboxProvider ¶ added in v1.0.27
type DropboxProvider struct{}
DropboxProvider handles Dropbox URLs
func (*DropboxProvider) GetDownloadURL ¶ added in v1.0.27
func (*DropboxProvider) GetProviderName ¶ added in v1.0.27
func (p *DropboxProvider) GetProviderName() FileProviderType
type EntitlementService ¶
type EntitlementService interface {
CreateEntitlement(ctx context.Context, req dto.CreateEntitlementRequest) (*dto.EntitlementResponse, error)
CreateBulkEntitlement(ctx context.Context, req dto.CreateBulkEntitlementRequest) (*dto.CreateBulkEntitlementResponse, error)
GetEntitlement(ctx context.Context, id string) (*dto.EntitlementResponse, error)
ListEntitlements(ctx context.Context, filter *types.EntitlementFilter) (*dto.ListEntitlementsResponse, error)
UpdateEntitlement(ctx context.Context, id string, req dto.UpdateEntitlementRequest) (*dto.EntitlementResponse, error)
DeleteEntitlement(ctx context.Context, id string) error
GetPlanEntitlements(ctx context.Context, planID string) (*dto.ListEntitlementsResponse, error)
GetPlanFeatureEntitlements(ctx context.Context, planID, featureID string) (*dto.ListEntitlementsResponse, error)
GetAddonEntitlements(ctx context.Context, addonID string) (*dto.ListEntitlementsResponse, error)
}
EntitlementService defines the interface for entitlement operations
func NewEntitlementService ¶
func NewEntitlementService(params ServiceParams) EntitlementService
type EntityIntegrationMappingService ¶ added in v1.0.21
type EntityIntegrationMappingService = interfaces.EntityIntegrationMappingService
func NewEntityIntegrationMappingService ¶ added in v1.0.21
func NewEntityIntegrationMappingService(params ServiceParams) EntityIntegrationMappingService
type EnvAccessService ¶ added in v1.0.18
type EnvAccessService interface {
// HasEnvironmentAccess checks if a user has access to a specific environment
HasEnvironmentAccess(ctx context.Context, userID, tenantID, environmentID string) bool
// GetAllowedEnvironments returns the list of environment IDs a user can access
GetAllowedEnvironments(ctx context.Context, userID, tenantID string) []string
}
EnvAccessService handles environment access control
func NewEnvAccessService ¶ added in v1.0.18
func NewEnvAccessService(cfg *config.Configuration) EnvAccessService
NewEnvAccessService creates a new environment access service
type EnvironmentService ¶
type EnvironmentService interface {
CreateEnvironment(ctx context.Context, req dto.CreateEnvironmentRequest) (*dto.EnvironmentResponse, error)
GetEnvironment(ctx context.Context, id string) (*dto.EnvironmentResponse, error)
GetEnvironments(ctx context.Context, filter types.Filter) (*dto.ListEnvironmentsResponse, error)
UpdateEnvironment(ctx context.Context, id string, req dto.UpdateEnvironmentRequest) (*dto.EnvironmentResponse, error)
}
func NewEnvironmentService ¶
func NewEnvironmentService(repo environment.Repository, envAccessService EnvAccessService, settingsService SettingsService, params ServiceParams) EnvironmentService
type EventConsumptionService ¶ added in v1.0.31
type EventConsumptionService interface {
// Register message handler with the router
RegisterHandler(router *pubsubRouter.Router, cfg *config.Configuration)
// Register message handler with the router
RegisterHandlerLazy(router *pubsubRouter.Router, cfg *config.Configuration)
// Process a raw event payload (used for AWS Lambda and direct processing)
ProcessRawEvent(ctx context.Context, payload []byte) error
}
EventConsumptionService handles consuming raw events from Kafka and inserting them into ClickHouse
func NewEventConsumptionService ¶ added in v1.0.31
func NewEventConsumptionService( params ServiceParams, eventRepo events.Repository, sentryService *sentry.Service, eventPostProcessingSvc EventPostProcessingService, ) EventConsumptionService
NewEventConsumptionService creates a new event consumption service
type EventPostProcessingService ¶ added in v1.0.17
type EventPostProcessingService interface {
// Publish an event for post-processing
PublishEvent(ctx context.Context, event *events.Event, isBackfill bool) error
// Register message handler with the router
RegisterHandler(router *pubsubRouter.Router, cfg *config.Configuration)
// Get usage cost for a specific period
GetPeriodCost(ctx context.Context, tenantID, environmentID, customerID, subscriptionID string, periodID uint64) (decimal.Decimal, error)
// Get usage totals per feature for a period
GetPeriodFeatureTotals(ctx context.Context, tenantID, environmentID, customerID, subscriptionID string, periodID uint64) ([]*events.PeriodFeatureTotal, error)
// Get usage analytics for a customer
GetUsageAnalytics(ctx context.Context, tenantID, environmentID, customerID string, lookbackHours int) ([]*events.UsageAnalytic, error)
// Get detailed usage analytics with filtering, grouping, and time-series data
GetDetailedUsageAnalytics(ctx context.Context, req *dto.GetUsageAnalyticsRequest) (*dto.GetUsageAnalyticsResponse, error)
// Reprocess events for a specific customer or with other filters
ReprocessEvents(ctx context.Context, params *events.ReprocessEventsParams) error
}
EventPostProcessingService handles post-processing operations for metered events
func NewEventPostProcessingService ¶ added in v1.0.17
func NewEventPostProcessingService( params ServiceParams, eventRepo events.Repository, processedEventRepo events.ProcessedEventRepository, ) EventPostProcessingService
NewEventPostProcessingService creates a new event post-processing service
type EventService ¶
type EventService interface {
CreateEvent(ctx context.Context, createEventRequest *dto.IngestEventRequest) error
BulkCreateEvents(ctx context.Context, createEventRequest *dto.BulkIngestEventRequest) error
GetUsage(ctx context.Context, getUsageRequest *dto.GetUsageRequest) (*events.AggregationResult, error)
GetUsageByMeter(ctx context.Context, getUsageByMeterRequest *dto.GetUsageByMeterRequest) (*events.AggregationResult, error)
BulkGetUsageByMeter(ctx context.Context, req []*dto.GetUsageByMeterRequest) (map[string]*events.AggregationResult, error)
GetUsageByMeterWithFilters(ctx context.Context, req *dto.GetUsageByMeterRequest, filterGroups map[string]map[string][]string) ([]*events.AggregationResult, error)
GetEvents(ctx context.Context, req *dto.GetEventsRequest) (*dto.GetEventsResponse, error)
GetMonitoringData(ctx context.Context, req *dto.GetMonitoringDataRequest) (*dto.GetMonitoringDataResponse, error)
MonitorKafkaLag(ctx context.Context) error
}
func NewEventService ¶
func NewEventService( eventRepo events.Repository, meterRepo meter.Repository, publisher publisher.EventPublisher, logger *logger.Logger, config *config.Configuration, ) EventService
type EventsChunkProcessor ¶ added in v1.0.27
type EventsChunkProcessor struct {
// contains filtered or unexported fields
}
EventsChunkProcessor processes chunks of event data
func (*EventsChunkProcessor) ProcessChunk ¶ added in v1.0.27
func (p *EventsChunkProcessor) ProcessChunk(ctx context.Context, chunk [][]string, headers []string, chunkIndex int) (*ChunkResult, error)
ProcessChunk processes a chunk of event records
type FeatureService ¶
type FeatureService interface {
CreateFeature(ctx context.Context, req dto.CreateFeatureRequest) (*dto.FeatureResponse, error)
GetFeature(ctx context.Context, id string) (*dto.FeatureResponse, error)
GetFeatures(ctx context.Context, filter *types.FeatureFilter) (*dto.ListFeaturesResponse, error)
UpdateFeature(ctx context.Context, id string, req dto.UpdateFeatureRequest) (*dto.FeatureResponse, error)
DeleteFeature(ctx context.Context, id string) error
}
func NewFeatureService ¶
func NewFeatureService(params ServiceParams) FeatureService
type FeatureUsageTrackingService ¶ added in v1.0.27
type FeatureUsageTrackingService interface {
// Publish an event for feature usage tracking
PublishEvent(ctx context.Context, event *events.Event, isBackfill bool) error
// Register message handler with the router
RegisterHandler(router *pubsubRouter.Router, cfg *config.Configuration)
// Register message handler with the router
RegisterHandlerLazy(router *pubsubRouter.Router, cfg *config.Configuration)
// GetDetailedUsageAnalytics provides comprehensive usage analytics with filtering, grouping, and time-series data
GetDetailedUsageAnalytics(ctx context.Context, req *dto.GetUsageAnalyticsRequest) (*dto.GetUsageAnalyticsResponse, error)
// Get detailed usage analytics version 2 with filtering, grouping, and time-series data
GetDetailedUsageAnalyticsV2(ctx context.Context, req *dto.GetUsageAnalyticsRequest) (*dto.GetUsageAnalyticsResponse, error)
// Reprocess events for a specific customer or with other filters
ReprocessEvents(ctx context.Context, params *events.ReprocessEventsParams) error
// Get HuggingFace Inference
GetHuggingFaceBillingData(ctx context.Context, req *dto.GetHuggingFaceBillingDataRequest) (*dto.GetHuggingFaceBillingDataResponse, error)
}
FeatureUsageTrackingService handles feature usage tracking operations for metered events
func NewFeatureUsageTrackingService ¶ added in v1.0.27
func NewFeatureUsageTrackingService( params ServiceParams, eventRepo events.Repository, featureUsageRepo events.FeatureUsageRepository, ) FeatureUsageTrackingService
NewFeatureUsageTrackingService creates a new feature usage tracking service
type FeaturesChunkProcessor ¶ added in v1.0.59
type FeaturesChunkProcessor struct {
// contains filtered or unexported fields
}
FeaturesChunkProcessor processes chunks of feature data
func (*FeaturesChunkProcessor) ProcessChunk ¶ added in v1.0.59
func (f *FeaturesChunkProcessor) ProcessChunk(ctx context.Context, chunk [][]string, headers []string, chunkIndex int) (*ChunkResult, error)
ProcessChunk processes a chunk of feature records
type FileProcessor ¶ added in v1.0.27
type FileProcessor struct {
*StreamingProcessor
ProviderRegistry *FileProviderRegistry
CSVProcessor *CSVProcessor
JSONProcessor *JSONProcessor
RetryClient *retryablehttp.Client
// Configuration for file size thresholds
MaxMemoryFileSize int64 // Maximum file size to process in memory (default: 10MB)
MaxFileSize int64 // Maximum file size allowed (default: 1GB)
}
FileProcessor handles both streaming and regular file processing It provides intelligent file processing by automatically choosing between: - Memory-based processing for small files (< 10MB) - Streaming processing for large files (>= 10MB) This prevents OOM errors while maintaining performance for small files
func NewFileProcessor ¶ added in v1.0.27
func NewFileProcessor(client httpclient.Client, logger *logger.Logger) *FileProcessor
NewFileProcessor creates a new file processor with default configuration Default settings: - MaxMemoryFileSize: 10MB (files smaller than this are processed in memory) - MaxFileSize: 1GB (maximum file size allowed)
func (*FileProcessor) DetectFileType ¶ added in v1.0.27
func (fp *FileProcessor) DetectFileType(fileContent []byte) FileType
DetectFileType attempts to determine if the file is CSV or JSON using battle-tested filetype package
func (*FileProcessor) DownloadFile ¶ added in v1.0.27
DownloadFile downloads a file and returns the full content (for regular processing) WARNING: This method loads the entire file into memory. Use DownloadFileStream for large files. This method is suitable for small files (< 10MB) to avoid OOM errors.
func (*FileProcessor) DownloadFileStream ¶ added in v1.0.27
func (fp *FileProcessor) DownloadFileStream(ctx context.Context, t *task.Task) (io.ReadCloser, error)
DownloadFileStream downloads a file and returns a stream for large file processing This method is memory-efficient and suitable for large files (>= 10MB) The returned io.ReadCloser must be closed by the caller to prevent resource leaks
func (*FileProcessor) GetFileSize ¶ added in v1.0.27
GetFileSize retrieves the file size without downloading the entire file This is useful for determining whether to use memory-based or streaming processing
func (*FileProcessor) PrepareCSVReader ¶ added in v1.0.27
func (fp *FileProcessor) PrepareCSVReader(fileContent []byte) (*csv.Reader, error)
PrepareCSVReader creates a configured CSV reader from the file content
func (*FileProcessor) PrepareJSONReader ¶ added in v1.0.27
func (fp *FileProcessor) PrepareJSONReader(fileContent []byte) (*jsoniter.Decoder, error)
PrepareJSONReader creates a configured JSON decoder from the file content using jsoniter
func (*FileProcessor) ShouldUseStreaming ¶ added in v1.0.27
func (fp *FileProcessor) ShouldUseStreaming(fileSize int64) bool
ShouldUseStreaming determines if a file should be processed using streaming based on its size and configuration thresholds
func (*FileProcessor) ValidateFileSize ¶ added in v1.0.27
func (fp *FileProcessor) ValidateFileSize(fileSize int64) error
ValidateFileSize checks if the file size is within acceptable limits
type FileProvider ¶ added in v1.0.27
type FileProvider interface {
GetDownloadURL(ctx context.Context, fileURL string) (string, error)
GetProviderName() FileProviderType
}
FileProvider defines the interface for different file providers This allows the system to handle various cloud storage providers and file sharing services by converting their URLs to direct download URLs that can be fetched via HTTP.
type FileProviderRegistry ¶ added in v1.0.27
type FileProviderRegistry struct {
// contains filtered or unexported fields
}
FileProviderRegistry manages different file providers
func NewFileProviderRegistry ¶ added in v1.0.27
func NewFileProviderRegistry() *FileProviderRegistry
NewFileProviderRegistry creates a new file provider registry
func (*FileProviderRegistry) GetProvider ¶ added in v1.0.27
func (r *FileProviderRegistry) GetProvider(fileURL string) FileProvider
GetProvider returns the appropriate provider for a given URL
func (*FileProviderRegistry) RegisterProvider ¶ added in v1.0.27
func (r *FileProviderRegistry) RegisterProvider(provider FileProvider)
RegisterProvider registers a file provider
type FileProviderType ¶ added in v1.0.27
type FileProviderType string
const ( FileProviderTypeDirect FileProviderType = "direct" FileProviderTypeGoogleDrive FileProviderType = "google_drive" FileProviderTypeS3 FileProviderType = "s3" FileProviderTypeOneDrive FileProviderType = "onedrive" FileProviderTypeDropbox FileProviderType = "dropbox" FileProviderTypeGitHub FileProviderType = "github" )
type FileType ¶ added in v1.0.27
type FileType string
FileType represents the type of file being processed
type GitHubProvider ¶ added in v1.0.27
type GitHubProvider struct{}
GitHubProvider handles GitHub raw file URLs
func (*GitHubProvider) GetDownloadURL ¶ added in v1.0.27
func (*GitHubProvider) GetProviderName ¶ added in v1.0.27
func (p *GitHubProvider) GetProviderName() FileProviderType
type GoogleDriveProvider ¶ added in v1.0.27
type GoogleDriveProvider struct{}
GoogleDriveProvider handles Google Drive URLs
func (*GoogleDriveProvider) GetDownloadURL ¶ added in v1.0.27
func (*GoogleDriveProvider) GetProviderName ¶ added in v1.0.27
func (p *GoogleDriveProvider) GetProviderName() FileProviderType
type GroupService ¶ added in v1.0.34
type GroupService interface {
CreateGroup(ctx context.Context, req dto.CreateGroupRequest) (*dto.GroupResponse, error)
GetGroup(ctx context.Context, id string) (*dto.GroupResponse, error)
DeleteGroup(ctx context.Context, id string) error
ListGroups(ctx context.Context, filter *types.GroupFilter) (*dto.ListGroupsResponse, error)
ValidateGroup(ctx context.Context, id string, entityType types.GroupEntityType) error
ValidateGroupBulk(ctx context.Context, groupIDs []string, entityType types.GroupEntityType) error
}
GroupService interface defines the business logic for group management
func NewGroupService ¶ added in v1.0.34
func NewGroupService(params ServiceParams) GroupService
type InvoiceService ¶
type InvoiceService interface {
// Embed the basic interface from interfaces package
interfaces.InvoiceService
// Additional methods specific to this service
CreateOneOffInvoice(ctx context.Context, req dto.CreateInvoiceRequest) (*dto.InvoiceResponse, error)
FinalizeInvoice(ctx context.Context, id string) error
VoidInvoice(ctx context.Context, id string, req dto.InvoiceVoidRequest) error
ProcessDraftInvoice(ctx context.Context, id string, paymentParams *dto.PaymentParameters, sub *subscription.Subscription, flowType types.InvoiceFlowType) error
UpdatePaymentStatus(ctx context.Context, id string, status types.PaymentStatus, amount *decimal.Decimal) error
CreateSubscriptionInvoice(ctx context.Context, req *dto.CreateSubscriptionInvoiceRequest, paymentParams *dto.PaymentParameters, flowType types.InvoiceFlowType, isDraftSubscription bool) (*dto.InvoiceResponse, *subscription.Subscription, error)
GetPreviewInvoice(ctx context.Context, req dto.GetPreviewInvoiceRequest) (*dto.InvoiceResponse, error)
GetCustomerInvoiceSummary(ctx context.Context, customerID string, currency string) (*dto.CustomerInvoiceSummary, error)
GetUnpaidInvoicesToBePaid(ctx context.Context, req dto.GetUnpaidInvoicesToBePaidRequest) (*dto.GetUnpaidInvoicesToBePaidResponse, error)
GetCustomerMultiCurrencyInvoiceSummary(ctx context.Context, customerID string) (*dto.CustomerMultiCurrencyInvoiceSummary, error)
AttemptPayment(ctx context.Context, id string) error
GetInvoicePDF(ctx context.Context, id string) ([]byte, error)
GetInvoicePDFUrl(ctx context.Context, id string) (string, error)
RecalculateInvoice(ctx context.Context, id string, finalize bool) (*dto.InvoiceResponse, error)
RecalculateInvoiceAmounts(ctx context.Context, invoiceID string) error
CalculatePriceBreakdown(ctx context.Context, inv *dto.InvoiceResponse) (map[string][]dto.SourceUsageItem, error)
CalculateUsageBreakdown(ctx context.Context, inv *dto.InvoiceResponse, groupBy []string, forceRealtimeRecalculation bool) (map[string][]dto.UsageBreakdownItem, error)
GetInvoiceWithBreakdown(ctx context.Context, req dto.GetInvoiceWithBreakdownRequest) (*dto.InvoiceResponse, error)
TriggerCommunication(ctx context.Context, id string) error
HandleIncompleteSubscriptionPayment(ctx context.Context, invoice *invoice.Invoice) error
// Cron methods
SyncInvoiceToExternalVendors(ctx context.Context, invoiceID string) error
}
func NewInvoiceService ¶
func NewInvoiceService(params ServiceParams) InvoiceService
type JSONProcessor ¶ added in v1.0.27
JSONProcessor handles JSON-specific operations
func NewJSONProcessor ¶ added in v1.0.27
func NewJSONProcessor(logger *logger.Logger) *JSONProcessor
NewJSONProcessor creates a new JSON processor
func (*JSONProcessor) ExtractHeaders ¶ added in v1.0.27
func (jp *JSONProcessor) ExtractHeaders(decoder *json.Decoder) ([]string, error)
ExtractHeaders extracts the field names from the first object in the JSON array
func (*JSONProcessor) PrepareJSONReader ¶ added in v1.0.27
func (jp *JSONProcessor) PrepareJSONReader(fileContent []byte) (*json.Decoder, error)
PrepareJSONReader creates a configured JSON decoder from the file content
func (*JSONProcessor) ValidateJSONStructure ¶ added in v1.0.27
func (jp *JSONProcessor) ValidateJSONStructure(decoder *json.Decoder) error
ValidateJSONStructure validates that the JSON content is an array of objects
type LineItemClassification ¶ added in v1.0.0
type LineItemClassification struct {
CurrentPeriodAdvance []*subscription.SubscriptionLineItem
CurrentPeriodArrear []*subscription.SubscriptionLineItem
NextPeriodAdvance []*subscription.SubscriptionLineItem
HasUsageCharges bool
}
LineItemClassification represents the classification of line items based on cadence and type
type LogAlertRequest ¶ added in v1.0.29
type LogAlertRequest struct {
EntityType types.AlertEntityType `json:"entity_type" validate:"required"`
EntityID string `json:"entity_id" validate:"required"`
ParentEntityType *string `json:"parent_entity_type,omitempty"` // Optional parent entity type (e.g., "wallet")
ParentEntityID *string `json:"parent_entity_id,omitempty"` // Optional parent entity ID (e.g., wallet_id)
CustomerID *string `json:"customer_id,omitempty"` // Optional customer ID for whom alert has been raised
AlertType types.AlertType `json:"alert_type" validate:"required"`
AlertStatus types.AlertState `json:"alert_status" validate:"required"`
AlertInfo types.AlertInfo `json:"alert_info" validate:"required"`
}
LogAlertRequest represents the request to log an alert
func (*LogAlertRequest) Validate ¶ added in v1.0.29
func (r *LogAlertRequest) Validate() error
Validate validates the log alert request
type MeterService ¶
type MeterService interface {
CreateMeter(ctx context.Context, req *dto.CreateMeterRequest) (*meter.Meter, error)
GetMeter(ctx context.Context, id string) (*meter.Meter, error)
GetMeters(ctx context.Context, filter *types.MeterFilter) (*dto.ListMetersResponse, error)
GetAllMeters(ctx context.Context) (*dto.ListMetersResponse, error)
DisableMeter(ctx context.Context, id string) error
UpdateMeter(ctx context.Context, id string, filters []meter.Filter) (*meter.Meter, error)
}
func NewMeterService ¶
func NewMeterService(meterRepo meter.Repository) MeterService
type OAuthService ¶ added in v1.0.47
type OAuthService interface {
// StoreOAuthSession creates an incomplete connection with encrypted OAuth session data
StoreOAuthSession(ctx context.Context, session *types.OAuthSession) error
// GetOAuthSession retrieves and decrypts an OAuth session from connection
GetOAuthSession(ctx context.Context, sessionID string) (*types.OAuthSession, error)
// DeleteOAuthSession removes an incomplete OAuth connection (cleanup on error)
DeleteOAuthSession(ctx context.Context, sessionID string) error
// GenerateSessionID generates a cryptographically secure random session ID
GenerateSessionID() (string, error)
// GenerateCSRFState generates a cryptographically secure random CSRF state token
GenerateCSRFState() (string, error)
// BuildOAuthURL builds the provider-specific OAuth authorization URL
BuildOAuthURL(provider types.OAuthProvider, clientID, redirectURI, state string, metadata map[string]string) (string, error)
// ExchangeCodeForConnection exchanges the authorization code for tokens and updates the connection
ExchangeCodeForConnection(ctx context.Context, session *types.OAuthSession, code, realmID string) (connectionID string, err error)
}
OAuthService manages OAuth sessions during OAuth flows for multiple providers Sessions are stored in connections table as incomplete connections
func NewOAuthService ¶ added in v1.0.47
func NewOAuthService( connectionRepo connection.Repository, encryptionService security.EncryptionService, connectionService ConnectionService, integrationFactory *integration.Factory, logger *logger.Logger, ) OAuthService
NewOAuthService creates a new OAuth service
type OnboardingService ¶ added in v1.0.0
type OnboardingService interface {
GenerateEvents(ctx context.Context, req *dto.OnboardingEventsRequest) (*dto.OnboardingEventsResponse, error)
RegisterHandler(router *pubsubRouter.Router)
OnboardNewUserWithTenant(ctx context.Context, userID, email, tenantName, tenantID string) error
SetupSandboxEnvironment(ctx context.Context, tenantID, userID, envID string) error
}
OnboardingService handles onboarding-related operations
func NewOnboardingService ¶ added in v1.0.0
func NewOnboardingService( params ServiceParams, pubSub pubsub.PubSub, ) OnboardingService
NewOnboardingService creates a new onboarding service
type OneDriveProvider ¶ added in v1.0.27
type OneDriveProvider struct{}
OneDriveProvider handles Microsoft OneDrive URLs
func (*OneDriveProvider) GetDownloadURL ¶ added in v1.0.27
func (*OneDriveProvider) GetProviderName ¶ added in v1.0.27
func (p *OneDriveProvider) GetProviderName() FileProviderType
type PaymentMethodUsed ¶ added in v1.0.25
type PaymentMethodUsed struct {
Type types.PaymentMethodType `json:"type"`
ID string `json:"id"`
Amount decimal.Decimal `json:"amount"`
Status types.PaymentStatus `json:"status"`
}
PaymentMethodUsed represents a payment method that was used
type PaymentProcessorService ¶
type PaymentProcessorService interface {
ProcessPayment(ctx context.Context, id string) (*payment.Payment, error)
}
func NewPaymentProcessorService ¶
func NewPaymentProcessorService(params ServiceParams) PaymentProcessorService
type PaymentResult ¶ added in v1.0.25
type PaymentResult struct {
Success bool `json:"success"`
AmountPaid decimal.Decimal `json:"amount_paid"`
RemainingAmount decimal.Decimal `json:"remaining_amount"`
PaymentMethods []PaymentMethodUsed `json:"payment_methods_used"`
RequiresManualConfirmation bool `json:"requires_manual_confirmation"`
Error error `json:"error,omitempty"`
}
PaymentResult represents the result of a payment attempt
type PaymentService ¶
type PaymentService = interfaces.PaymentService
PaymentService defines the interface for payment operations
func NewPaymentService ¶
func NewPaymentService(params ServiceParams) PaymentService
NewPaymentService creates a new payment service
type PlanService ¶
type PlanService = interfaces.PlanService
func NewPlanService ¶
func NewPlanService( params ServiceParams, ) PlanService
type PriceMatch ¶ added in v1.0.17
PriceMatch represents a matching price and meter for an event
type PriceService ¶
type PriceService interface {
CreatePrice(ctx context.Context, req dto.CreatePriceRequest) (*dto.PriceResponse, error)
CreateBulkPrice(ctx context.Context, req dto.CreateBulkPriceRequest) (*dto.CreateBulkPriceResponse, error)
GetPrice(ctx context.Context, id string) (*dto.PriceResponse, error)
GetPricesByPlanID(ctx context.Context, req dto.GetPricesByPlanRequest) (*dto.ListPricesResponse, error)
GetPricesBySubscriptionID(ctx context.Context, subscriptionID string) (*dto.ListPricesResponse, error)
GetPricesByAddonID(ctx context.Context, addonID string) (*dto.ListPricesResponse, error)
GetPricesByCostsheetID(ctx context.Context, costsheetID string) (*dto.ListPricesResponse, error)
GetPrices(ctx context.Context, filter *types.PriceFilter) (*dto.ListPricesResponse, error)
UpdatePrice(ctx context.Context, id string, req dto.UpdatePriceRequest) (*dto.PriceResponse, error)
DeletePrice(ctx context.Context, id string, req dto.DeletePriceRequest) error
CalculateCost(ctx context.Context, price *price.Price, quantity decimal.Decimal) decimal.Decimal
// CalculateBucketedCost calculates cost for bucketed max values where each value represents max in its time bucket
CalculateBucketedCost(ctx context.Context, price *price.Price, bucketedValues []decimal.Decimal) decimal.Decimal
// CalculateCostWithBreakup calculates the cost for a given price and quantity
// and returns detailed information about the calculation
CalculateCostWithBreakup(ctx context.Context, price *price.Price, quantity decimal.Decimal, round bool) dto.CostBreakup
// CalculateCostSheetPrice calculates the cost for a given price and quantity
// specifically for costsheet calculations
CalculateCostSheetPrice(ctx context.Context, price *price.Price, quantity decimal.Decimal) decimal.Decimal
GetByLookupKey(ctx context.Context, lookupKey string) (*dto.PriceResponse, error)
}
func NewPriceService ¶
func NewPriceService(params ServiceParams) PriceService
type PriceUnitService ¶ added in v1.0.21
type PriceUnitService = interfaces.PriceUnitService
func NewPriceUnitService ¶ added in v1.0.21
func NewPriceUnitService(params ServiceParams) PriceUnitService
type PricesChunkProcessor ¶ added in v1.0.59
type PricesChunkProcessor struct {
// contains filtered or unexported fields
}
PricesChunkProcessor processes chunks of price data
func (*PricesChunkProcessor) ProcessChunk ¶ added in v1.0.59
func (p *PricesChunkProcessor) ProcessChunk(ctx context.Context, chunk [][]string, headers []string, chunkIndex int) (*ChunkResult, error)
ProcessChunk processes a chunk of price records
type RevenueAnalyticsService ¶ added in v1.0.33
type RevenueAnalyticsService = interfaces.RevenueAnalyticsService
func NewRevenueAnalyticsService ¶ added in v1.0.33
func NewRevenueAnalyticsService(params ServiceParams, featureUsageTrackingService FeatureUsageTrackingService, costsheetUsageTrackingService CostSheetUsageTrackingService) RevenueAnalyticsService
type S3Provider ¶ added in v1.0.27
type S3Provider struct{}
S3Provider handles AWS S3 URLs
func (*S3Provider) GetDownloadURL ¶ added in v1.0.27
func (*S3Provider) GetProviderName ¶ added in v1.0.27
func (p *S3Provider) GetProviderName() FileProviderType
type ScheduledTaskService ¶ added in v1.0.32
type ScheduledTaskService interface {
CreateScheduledTask(ctx context.Context, req dto.CreateScheduledTaskRequest) (*dto.ScheduledTaskResponse, error)
GetScheduledTask(ctx context.Context, id string) (*dto.ScheduledTaskResponse, error)
ListScheduledTasks(ctx context.Context, filter *types.QueryFilter, connectionID string, entityType types.ScheduledTaskEntityType, interval types.ScheduledTaskInterval, enabled string) (*dto.ListScheduledTasksResponse, error)
UpdateScheduledTask(ctx context.Context, id string, req dto.UpdateScheduledTaskRequest) (*dto.ScheduledTaskResponse, error)
DeleteScheduledTask(ctx context.Context, id string) error
TriggerForceRun(ctx context.Context, id string, req dto.TriggerForceRunRequest) (*dto.TriggerForceRunResponse, error)
CalculateIntervalBoundaries(currentTime time.Time, interval types.ScheduledTaskInterval) (startTime, endTime time.Time)
ScheduleUpdateBillingPeriod(ctx context.Context) (string, error)
}
ScheduledTaskService handles scheduled task operations
func NewScheduledTaskService ¶ added in v1.0.32
func NewScheduledTaskService( repo scheduledtask.Repository, connectionRepo connection.Repository, temporalClient temporalClient.TemporalClient, logger *logger.Logger, config *config.Configuration, ) ScheduledTaskService
NewScheduledTaskService creates a new scheduled task service
type SecretService ¶
type SecretService interface {
// API Key operations
CreateAPIKey(ctx context.Context, req *dto.CreateAPIKeyRequest) (*secret.Secret, string, error)
ListAPIKeys(ctx context.Context, filter *types.SecretFilter) (*dto.ListSecretsResponse, error)
Delete(ctx context.Context, id string) error
// Integration operations
CreateIntegration(ctx context.Context, req *dto.CreateIntegrationRequest) (*secret.Secret, error)
ListIntegrations(ctx context.Context, filter *types.SecretFilter) (*dto.ListSecretsResponse, error)
// Verification operations
VerifyAPIKey(ctx context.Context, apiKey string) (*secret.Secret, error)
ListLinkedIntegrations(ctx context.Context) ([]string, error)
// contains filtered or unexported methods
}
SecretService defines the interface for secret business logic
func NewSecretService ¶
func NewSecretService( repo secret.Repository, userRepo user.Repository, config *config.Configuration, logger *logger.Logger, ) SecretService
NewSecretService creates a new secret service
type ServiceParams ¶
type ServiceParams struct {
Logger *logger.Logger
Config *config.Configuration
DB postgres.IClient
PDFGenerator pdf.Generator
S3 s3.Service
// Repositories
AuthRepo auth.Repository
UserRepo user.Repository
EventRepo events.Repository
CostSheetUsageRepo events.CostSheetUsageRepository
ProcessedEventRepo events.ProcessedEventRepository
FeatureUsageRepo events.FeatureUsageRepository
MeterRepo meter.Repository
PriceRepo price.Repository
PriceUnitRepo priceunit.Repository
CustomerRepo customer.Repository
PlanRepo plan.Repository
SubRepo subscription.Repository
SubscriptionLineItemRepo subscription.LineItemRepository
SubscriptionPhaseRepo subscription.SubscriptionPhaseRepository
WalletRepo wallet.Repository
TenantRepo tenant.Repository
InvoiceRepo invoice.Repository
FeatureRepo feature.Repository
EntitlementRepo entitlement.Repository
PaymentRepo payment.Repository
SecretRepo secret.Repository
EnvironmentRepo environment.Repository
TaskRepo task.Repository
CreditGrantRepo creditgrant.Repository
CostSheetRepo costsheet.Repository
CreditNoteRepo creditnote.Repository
CreditNoteLineItemRepo creditnote.CreditNoteLineItemRepository
CreditGrantApplicationRepo creditgrantapplication.Repository
TaxRateRepo taxrate.Repository
TaxAssociationRepo taxassociation.Repository
TaxAppliedRepo taxapplied.Repository
CouponRepo coupon.Repository
CouponAssociationRepo coupon_association.Repository
CouponApplicationRepo coupon_application.Repository
AddonRepo addon.Repository
AddonAssociationRepo addonassociation.Repository
ConnectionRepo connection.Repository
EntityIntegrationMappingRepo entityintegrationmapping.Repository
SettingsRepo settings.Repository
AlertLogsRepo alertlogs.Repository
GroupRepo group.Repository
ScheduledTaskRepo scheduledtask.Repository
// Publishers
EventPublisher publisher.EventPublisher
WebhookPublisher webhookPublisher.WebhookPublisher
// http client
Client httpclient.Client
// Proration
ProrationCalculator proration.Calculator
// Integration Factory
IntegrationFactory *integration.Factory
// PubSubs
WalletBalanceAlertPubSub types.WalletBalanceAlertPubSub
WebhookPubSub pubsub.PubSub
}
ServiceParams holds common dependencies for services TODO: start using this for all services init
func NewServiceParams ¶
func NewServiceParams( logger *logger.Logger, config *config.Configuration, db postgres.IClient, pdfGenerator pdf.Generator, authRepo auth.Repository, userRepo user.Repository, eventRepo events.Repository, costSheetUsageRepo events.CostSheetUsageRepository, processedEventRepo events.ProcessedEventRepository, featureUsageRepo events.FeatureUsageRepository, meterRepo meter.Repository, priceRepo price.Repository, priceUnitRepo priceunit.Repository, customerRepo customer.Repository, planRepo plan.Repository, subRepo subscription.Repository, subscriptionLineItemRepo subscription.LineItemRepository, subscriptionPhaseRepo subscription.SubscriptionPhaseRepository, walletRepo wallet.Repository, tenantRepo tenant.Repository, invoiceRepo invoice.Repository, featureRepo feature.Repository, creditGrantApplicationRepo creditgrantapplication.Repository, entitlementRepo entitlement.Repository, paymentRepo payment.Repository, secretRepo secret.Repository, environmentRepo environment.Repository, creditGrantRepo creditgrant.Repository, creditNoteRepo creditnote.Repository, creditNoteLineItemRepo creditnote.CreditNoteLineItemRepository, taxConfigRepo taxassociation.Repository, taskRepo task.Repository, costSheetRepo costsheet.Repository, taxAppliedRepo taxapplied.Repository, taxRateRepo taxrate.Repository, couponRepo coupon.Repository, couponAssociationRepo coupon_association.Repository, couponApplicationRepo coupon_application.Repository, eventPublisher publisher.EventPublisher, webhookPublisher webhookPublisher.WebhookPublisher, s3Service s3.Service, client httpclient.Client, addonRepo addon.Repository, addonAssociationRepo addonassociation.Repository, connectionRepo connection.Repository, entityIntegrationMappingRepo entityintegrationmapping.Repository, settingsRepo settings.Repository, alertLogsRepo alertlogs.Repository, groupRepo group.Repository, scheduledTaskRepo scheduledtask.Repository, prorationCalculator proration.Calculator, integrationFactory *integration.Factory, walletBalanceAlertPubSub types.WalletBalanceAlertPubSub, webhookPubSub pubsub.PubSub, ) ServiceParams
Common service params
type SettingsService ¶ added in v1.0.22
type SettingsService interface {
// GetSettingByKey returns a setting as a DTO response (for API endpoints)
// Use this when you need the full Setting object with metadata (ID, timestamps, etc.)
GetSettingByKey(ctx context.Context, key types.SettingKey) (*dto.SettingResponse, error)
// UpdateSettingByKey updates a setting with partial values (merges with existing)
// Use this for API endpoints that accept partial updates
UpdateSettingByKey(ctx context.Context, key types.SettingKey, req *dto.UpdateSettingRequest) (*dto.SettingResponse, error)
// DeleteSettingByKey deletes a setting by key
DeleteSettingByKey(ctx context.Context, key types.SettingKey) error
}
func NewSettingsService ¶ added in v1.0.22
func NewSettingsService(params ServiceParams) SettingsService
type StateAction ¶ added in v1.0.18
type StateAction string
const ( StateActionApply StateAction = "apply" StateActionSkip StateAction = "skip" StateActionDefer StateAction = "defer" StateActionCancel StateAction = "cancel" )
type StreamingConfig ¶ added in v1.0.27
type StreamingConfig struct {
ChunkSize int `json:"chunk_size"` // Number of records per chunk
BufferSize int `json:"buffer_size"` // Buffer size for reading
UpdateInterval time.Duration `json:"update_interval"` // Progress update interval
MaxRetries int `json:"max_retries"` // Maximum retries for failed chunks
RetryDelay time.Duration `json:"retry_delay"` // Delay between retries
MaxErrors int `json:"max_errors"` // Maximum errors to accumulate before stopping
BatchSize int `json:"batch_size"` // Number of chunks to process before updating progress
}
StreamingConfig holds configuration for streaming processing
func DefaultStreamingConfig ¶ added in v1.0.27
func DefaultStreamingConfig() *StreamingConfig
DefaultStreamingConfig returns default streaming configuration
type StreamingProcessor ¶ added in v1.0.27
type StreamingProcessor struct {
Client httpclient.Client
Logger *logger.Logger
ProviderRegistry *FileProviderRegistry
CSVProcessor *CSVProcessor
JSONProcessor *JSONProcessor
RetryClient *retryablehttp.Client
}
StreamingProcessor handles streaming processing of large files
func NewStreamingProcessor ¶ added in v1.0.27
func NewStreamingProcessor(client httpclient.Client, logger *logger.Logger) *StreamingProcessor
NewStreamingProcessor creates a new streaming processor
func (*StreamingProcessor) Close ¶ added in v1.0.27
func (sp *StreamingProcessor) Close()
Close cleans up resources
func (*StreamingProcessor) ProcessFileStream ¶ added in v1.0.27
func (sp *StreamingProcessor) ProcessFileStream( ctx context.Context, t *task.Task, processor ChunkProcessor, config *StreamingConfig, ) error
ProcessFileStream processes a file in streaming fashion
type SubscriptionChangeService ¶ added in v1.0.25
type SubscriptionChangeService interface {
// PreviewSubscriptionChange shows the impact of changing subscription plan
PreviewSubscriptionChange(ctx context.Context, subscriptionID string, req dto.SubscriptionChangeRequest) (*dto.SubscriptionChangePreviewResponse, error)
// ExecuteSubscriptionChange performs the actual subscription plan change
ExecuteSubscriptionChange(ctx context.Context, subscriptionID string, req dto.SubscriptionChangeRequest) (*dto.SubscriptionChangeExecuteResponse, error)
}
SubscriptionChangeService handles subscription plan changes (upgrades/downgrades)
func NewSubscriptionChangeService ¶ added in v1.0.25
func NewSubscriptionChangeService(serviceParams ServiceParams) SubscriptionChangeService
NewSubscriptionChangeService creates a new subscription change service
type SubscriptionPaymentProcessor ¶ added in v1.0.25
type SubscriptionPaymentProcessor interface {
HandlePaymentBehavior(ctx context.Context, subscription *subscription.Subscription, invoice *dto.InvoiceResponse, behavior types.PaymentBehavior, flowType types.InvoiceFlowType) error
ProcessCreditsPaymentForInvoice(ctx context.Context, inv *dto.InvoiceResponse, sub *subscription.Subscription) decimal.Decimal
}
SubscriptionPaymentProcessor handles payment processing for subscriptions
func NewSubscriptionPaymentProcessor ¶ added in v1.0.25
func NewSubscriptionPaymentProcessor(params *ServiceParams) SubscriptionPaymentProcessor
NewSubscriptionPaymentProcessor creates a new subscription payment processor
type SubscriptionPhaseService ¶ added in v1.0.38
type SubscriptionPhaseService interface {
CreateSubscriptionPhase(ctx context.Context, req dto.CreateSubscriptionPhaseRequest) (*dto.SubscriptionPhaseResponse, error)
GetSubscriptionPhase(ctx context.Context, id string) (*dto.SubscriptionPhaseResponse, error)
GetSubscriptionPhases(ctx context.Context, filter *types.SubscriptionPhaseFilter) (*dto.ListSubscriptionPhasesResponse, error)
UpdateSubscriptionPhase(ctx context.Context, id string, req dto.UpdateSubscriptionPhaseRequest) (*dto.SubscriptionPhaseResponse, error)
DeleteSubscriptionPhase(ctx context.Context, id string) error
}
func NewSubscriptionPhaseService ¶ added in v1.0.38
func NewSubscriptionPhaseService(params ServiceParams) SubscriptionPhaseService
type SubscriptionService ¶
type SubscriptionService = interfaces.SubscriptionService
func NewSubscriptionService ¶
func NewSubscriptionService(params ServiceParams) SubscriptionService
type SubscriptionStateHandler ¶ added in v1.0.18
type SubscriptionStateHandler struct {
// contains filtered or unexported fields
}
func NewSubscriptionStateHandler ¶ added in v1.0.18
func NewSubscriptionStateHandler(subscription *subscription.Subscription, grant *creditgrant.CreditGrant) *SubscriptionStateHandler
func (*SubscriptionStateHandler) DetermineCreditGrantAction ¶ added in v1.0.18
func (h *SubscriptionStateHandler) DetermineCreditGrantAction() (StateAction, error)
type TaskService ¶
type TaskService interface {
CreateTask(ctx context.Context, req dto.CreateTaskRequest) (*dto.TaskResponse, error)
GetTask(ctx context.Context, id string) (*dto.TaskResponse, error)
ListTasks(ctx context.Context, filter *types.TaskFilter) (*dto.ListTasksResponse, error)
UpdateTaskStatus(ctx context.Context, id string, status types.TaskStatus) error
ProcessTaskWithStreaming(ctx context.Context, id string) error
GenerateDownloadURL(ctx context.Context, id string) (string, error)
}
func NewTaskService ¶
func NewTaskService( serviceParams ServiceParams, ) TaskService
type TaxCalculationResult ¶ added in v1.0.21
type TaxCalculationResult struct {
TotalTaxAmount decimal.Decimal
TaxAppliedRecords []*dto.TaxAppliedResponse
TaxRates []*dto.TaxRateResponse
}
TaxCalculationResult represents the result of tax calculations
type TaxService ¶ added in v1.0.21
type TaxService interface {
// Core CRUD operations
CreateTaxRate(ctx context.Context, req dto.CreateTaxRateRequest) (*dto.TaxRateResponse, error)
GetTaxRate(ctx context.Context, id string) (*dto.TaxRateResponse, error)
ListTaxRates(ctx context.Context, filter *types.TaxRateFilter) (*dto.ListTaxRatesResponse, error)
UpdateTaxRate(ctx context.Context, id string, req dto.UpdateTaxRateRequest) (*dto.TaxRateResponse, error)
GetTaxRateByCode(ctx context.Context, code string) (*dto.TaxRateResponse, error)
DeleteTaxRate(ctx context.Context, id string) error
// Tax Applied operations
RecalculateInvoiceTaxes(ctx context.Context, invoiceId string) error
// tax association operations
CreateTaxAssociation(ctx context.Context, ta *dto.CreateTaxAssociationRequest) (*dto.TaxAssociationResponse, error)
GetTaxAssociation(ctx context.Context, id string) (*dto.TaxAssociationResponse, error)
UpdateTaxAssociation(ctx context.Context, id string, ta *dto.TaxAssociationUpdateRequest) (*dto.TaxAssociationResponse, error)
DeleteTaxAssociation(ctx context.Context, id string) error
ListTaxAssociations(ctx context.Context, filter *types.TaxAssociationFilter) (*dto.ListTaxAssociationsResponse, error)
// LinkTaxRatesToEntity links tax rates to any entity type
LinkTaxRatesToEntity(ctx context.Context, req dto.LinkTaxRateToEntityRequest) error
// tax application operations
CreateTaxApplied(ctx context.Context, req dto.CreateTaxAppliedRequest) (*dto.TaxAppliedResponse, error)
GetTaxApplied(ctx context.Context, id string) (*dto.TaxAppliedResponse, error)
ListTaxApplied(ctx context.Context, filter *types.TaxAppliedFilter) (*dto.ListTaxAppliedResponse, error)
DeleteTaxApplied(ctx context.Context, id string) error
// Invoice tax operations
PrepareTaxRatesForInvoice(ctx context.Context, req dto.CreateInvoiceRequest) ([]*dto.TaxRateResponse, error)
ApplyTaxesOnInvoice(ctx context.Context, inv *invoice.Invoice, taxRates []*dto.TaxRateResponse) (*TaxCalculationResult, error)
}
func NewTaxService ¶ added in v1.0.21
func NewTaxService(params ServiceParams) TaxService
NewTaxService creates a new instance of TaxService
type TenantService ¶
type TenantService interface {
CreateTenant(ctx context.Context, req dto.CreateTenantRequest) (*dto.TenantResponse, error)
GetTenantByID(ctx context.Context, id string) (*dto.TenantResponse, error)
AssignTenantToUser(ctx context.Context, req dto.AssignTenantRequest) error
GetAllTenants(ctx context.Context) ([]*dto.TenantResponse, error)
UpdateTenant(ctx context.Context, id string, req dto.UpdateTenantRequest) (*dto.TenantResponse, error)
GetBillingUsage(ctx context.Context) (*dto.TenantBillingUsage, error)
CreateTenantAsBillingCustomer(ctx context.Context, t *tenant.Tenant) error
}
func NewTenantService ¶
func NewTenantService( params ServiceParams, ) TenantService
type UserService ¶
type UserService interface {
GetUserInfo(ctx context.Context) (*dto.UserResponse, error)
CreateUser(ctx context.Context, req *dto.CreateUserRequest) (*dto.UserResponse, error)
ListUsersByFilter(ctx context.Context, filter *types.UserFilter) (*dto.ListUsersResponse, error)
}
func NewUserService ¶
func NewUserService(userRepo user.Repository, tenantRepo tenant.Repository, rbacService *rbac.RBACService) UserService
type WalletBalanceAlertService ¶ added in v1.0.42
type WalletBalanceAlertService interface {
// PublishEvent publishes a wallet balance alert event to Kafka
PublishEvent(ctx context.Context, event *wallet.WalletBalanceAlertEvent) error
// RegisterHandler registers the Kafka consumer handler
RegisterHandler(router *pubsubRouter.Router, cfg *config.Configuration)
}
WalletBalanceAlertService handles wallet balance alert operations via Kafka
func NewWalletBalanceAlertService ¶ added in v1.0.42
func NewWalletBalanceAlertService( params ServiceParams, ) WalletBalanceAlertService
NewWalletBalanceAlertService creates a new wallet balance alert service
type WalletPaymentOptions ¶ added in v1.0.0
type WalletPaymentOptions struct {
// Strategy determines the order in which wallets are selected
Strategy WalletPaymentStrategy
// MaxWalletsToUse limits the number of wallets to use (0 means no limit)
MaxWalletsToUse int
// AdditionalMetadata to include in payment requests
AdditionalMetadata types.Metadata
}
WalletPaymentOptions defines options for wallet payment processing
func DefaultWalletPaymentOptions ¶ added in v1.0.0
func DefaultWalletPaymentOptions() WalletPaymentOptions
DefaultWalletPaymentOptions returns the default options for wallet payments
type WalletPaymentService ¶ added in v1.0.0
type WalletPaymentService interface {
// ProcessInvoicePaymentWithWallets attempts to pay an invoice using available wallets
ProcessInvoicePaymentWithWallets(ctx context.Context, inv *invoice.Invoice, options WalletPaymentOptions) (decimal.Decimal, error)
// GetWalletsForPayment retrieves and filters wallets suitable for payment
GetWalletsForPayment(ctx context.Context, customerID string, currency string, options WalletPaymentOptions) ([]*wallet.Wallet, error)
}
WalletPaymentService defines the interface for wallet payment operations
func NewWalletPaymentService ¶ added in v1.0.0
func NewWalletPaymentService(params ServiceParams) WalletPaymentService
NewWalletPaymentService creates a new wallet payment service
type WalletPaymentStrategy ¶ added in v1.0.0
type WalletPaymentStrategy string
WalletPaymentStrategy defines the strategy for selecting wallets for payment
const ( // PromotionalFirstStrategy prioritizes promotional wallets before prepaid wallets PromotionalFirstStrategy WalletPaymentStrategy = "promotional_first" // PrepaidFirstStrategy prioritizes prepaid wallets before promotional wallets PrepaidFirstStrategy WalletPaymentStrategy = "prepaid_first" // BalanceOptimizedStrategy selects wallets to minimize leftover balances BalanceOptimizedStrategy WalletPaymentStrategy = "balance_optimized" )
type WalletService ¶
type WalletService interface {
// CreateWallet creates a new wallet for a customer
CreateWallet(ctx context.Context, req *dto.CreateWalletRequest) (*dto.WalletResponse, error)
// GetWalletsByCustomerID retrieves all wallets for a customer
GetWalletsByCustomerID(ctx context.Context, customerID string) ([]*dto.WalletResponse, error)
// GetWalletByID retrieves a wallet by its ID and calculates real-time balance
GetWalletByID(ctx context.Context, id string) (*dto.WalletResponse, error)
// GetWalletTransactions retrieves transactions for a wallet with pagination
GetWalletTransactions(ctx context.Context, walletID string, filter *types.WalletTransactionFilter) (*dto.ListWalletTransactionsResponse, error)
// TopUpWallet adds credits to a wallet
TopUpWallet(ctx context.Context, walletID string, req *dto.TopUpWalletRequest) (*dto.TopUpWalletResponse, error)
// GetWalletTransactionByID retrieves a transaction by its ID
GetWalletTransactionByID(ctx context.Context, transactionID string) (*dto.WalletTransactionResponse, error)
// ListWalletTransactionsByFilter lists wallet transactions by filter
ListWalletTransactionsByFilter(ctx context.Context, filter *types.WalletTransactionFilter) (*dto.ListWalletTransactionsResponse, error)
// GetWalletBalance retrieves the real-time balance of a wallet
GetWalletBalance(ctx context.Context, walletID string) (*dto.WalletBalanceResponse, error)
// GetWalletBalance Version 2
GetWalletBalanceV2(ctx context.Context, walletID string) (*dto.WalletBalanceResponse, error)
// TerminateWallet terminates a wallet by closing it and debiting remaining balance
TerminateWallet(ctx context.Context, walletID string) error
// UpdateWallet updates a wallet
UpdateWallet(ctx context.Context, id string, req *dto.UpdateWalletRequest) (*wallet.Wallet, error)
// DebitWallet processes a debit operation on a wallet
DebitWallet(ctx context.Context, req *wallet.WalletOperation) error
// ManualBalanceDebit processes a manual balance debit operation on a wallet
ManualBalanceDebit(ctx context.Context, walletID string, req *dto.ManualBalanceDebitRequest) (*dto.WalletResponse, error)
// CreditWallet processes a credit operation on a wallet
CreditWallet(ctx context.Context, req *wallet.WalletOperation) error
// ExpireCredits expires credits for a given transaction
ExpireCredits(ctx context.Context, transactionID string) error
// conversion rate operations
GetCurrencyAmountFromCredits(credits decimal.Decimal, conversionRate decimal.Decimal) decimal.Decimal
GetCreditsFromCurrencyAmount(amount decimal.Decimal, conversionRate decimal.Decimal) decimal.Decimal
// GetCustomerWallets retrieves all wallets for a customer
GetCustomerWallets(ctx context.Context, req *dto.GetCustomerWalletsRequest) ([]*dto.WalletBalanceResponse, error)
// GetWallets retrieves wallets based on filter
GetWallets(ctx context.Context, filter *types.WalletFilter) (*types.ListResponse[*wallet.Wallet], error)
// UpdateWalletAlertState updates the alert state of a wallet
UpdateWalletAlertState(ctx context.Context, walletID string, state types.AlertState) error
// PublishEvent publishes a webhook event for a wallet
PublishEvent(ctx context.Context, eventName string, w *wallet.Wallet) error
// CheckBalanceThresholds checks if wallet balance is below threshold and triggers alerts
CheckBalanceThresholds(ctx context.Context, w *wallet.Wallet, balance *dto.WalletBalanceResponse) error
// TopUpWalletForProratedCharge tops up a wallet for proration credits from subscription changes
TopUpWalletForProratedCharge(ctx context.Context, customerID string, amount decimal.Decimal, currency string) error
// CompletePurchasedCreditTransaction completes a pending wallet transaction when payment succeeds
CompletePurchasedCreditTransactionWithRetry(ctx context.Context, walletTransactionID string) error
CheckWalletBalanceAlert(ctx context.Context, req *wallet.WalletBalanceAlertEvent) error
// PublishWalletBalanceAlertEvent publishes a wallet balance alert event
PublishWalletBalanceAlertEvent(ctx context.Context, customerID string, forceCalculateBalance bool, walletID string)
}
WalletService defines the interface for wallet operations
func NewWalletService ¶
func NewWalletService(params ServiceParams) WalletService
NewWalletService creates a new instance of WalletService
type WebhookEventMapping ¶ added in v1.0.29
type WebhookEventMapping struct {
WebhookEvent string `json:"webhook_event"`
}
WebhookEventMapping represents the mapping configuration for alert types and statuses to webhook events
Source Files
¶
- addon.go
- alertlogs.go
- auth.go
- billing.go
- billing_commitment.go
- connection.go
- costsheet.go
- costsheet_usage_tracking.go
- coupon.go
- coupon_application.go
- coupon_association.go
- coupon_validation.go
- creditgrant.go
- creditnote.go
- csv_processor.go
- customer.go
- customer_portal.go
- entitlement.go
- entityintegrationmapping.go
- env_access.go
- environment.go
- event.go
- event_consumption.go
- event_post_processing.go
- factory.go
- feature.go
- feature_usage_tracking.go
- file_processor.go
- file_provider.go
- group.go
- invoice.go
- json_processor.go
- meter.go
- oauth.go
- onboarding.go
- payment.go
- payment_processor.go
- plan.go
- price.go
- priceunit.go
- proration.go
- revenue_analytics.go
- scheduled_task.go
- secret.go
- settings.go
- streaming_processor.go
- subscription.go
- subscription_change.go
- subscription_line_item.go
- subscription_payment_processor.go
- subscription_phase.go
- subscription_state_handler.go
- task.go
- tax.go
- tenant.go
- user.go
- wallet.go
- wallet_balance_alert.go
- wallet_payment.go