service

package
v1.0.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 13, 2025 License: AGPL-3.0 Imports: 82 Imported by: 0

Documentation

Overview

Package service provides business logic implementations for the FlexPrice application.

Index

Constants

View Source
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
)
View Source
const (
	OnboardingEventsTopic = "onboarding_events"
)

Variables

This section is empty.

Functions

This section is empty.

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
}

AddonService interface defines the business logic for addon management

func NewAddonService added in v1.0.21

func NewAddonService(params ServiceParams) AddonService

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)

	// 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 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 CostSheetService added in v1.0.18

type CostSheetService interface {
	// CRUD Operations
	CreateCostSheet(ctx context.Context, req *dto.CreateCostSheetRequest) (*dto.CostSheetResponse, error)
	GetCostSheet(ctx context.Context, id string) (*dto.CostSheetResponse, error)
	ListCostSheets(ctx context.Context, filter *domainCostSheet.Filter) (*dto.ListCostSheetsResponse, error)
	UpdateCostSheet(ctx context.Context, req *dto.UpdateCostSheetRequest) (*dto.CostSheetResponse, error)
	DeleteCostSheet(ctx context.Context, id string) error

	// Calculation Operations
	GetInputCostForMargin(ctx context.Context, req *dto.GetCostBreakdownRequest) (*dto.CostBreakdownResponse, error)
	CalculateMargin(totalCost, totalRevenue decimal.Decimal) decimal.Decimal
	CalculateMarkup(totalCost, totalRevenue decimal.Decimal) decimal.Decimal
	CalculateROI(ctx context.Context, req *dto.CalculateROIRequest) (*dto.ROIResponse, error)

	// TODO: handler business logic -> service methods
	// GetServiceParams retrieves the service parameters
	GetServiceParams() ServiceParams
}

CostSheetService defines the interface for managing cost sheet operations. It provides functionality for calculating input costs and margins based on cost sheet items, usage data, and pricing information.

func NewCostSheetService added in v1.0.18

func NewCostSheetService(params ServiceParams) CostSheetService

NewCostSheetService creates a new instance of the cost sheet 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)
	GetCouponApplicationsByInvoice(ctx context.Context, invoiceID string) ([]*dto.CouponApplicationResponse, error)
	GetCouponApplicationsBySubscription(ctx context.Context, subscriptionID string) ([]*dto.CouponApplicationResponse, error)
	ApplyCouponToInvoice(ctx context.Context, couponID string, invoiceID string, originalPrice decimal.Decimal) (*dto.CouponApplicationResponse, error)
	ApplyCouponsOnInvoice(ctx context.Context, inv *invoice.Invoice, invoiceCoupons []dto.InvoiceCoupon) (*CouponCalculationResult, error)
	ApplyCouponsOnInvoiceWithLineItems(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
	GetCouponAssociationsBySubscription(ctx context.Context, subscriptionID string) ([]*dto.CouponAssociationResponse, error)
	GetBySubscriptionForLineItems(ctx context.Context, subscriptionID string) ([]*dto.CouponAssociationResponse, error)
	ApplyCouponToSubscription(ctx context.Context, couponIDs []string, subscriptionID string) error

	// Line item coupon association methods
	ApplyCouponToSubscriptionLineItem(ctx context.Context, couponIDs []string, subscriptionID string, priceID string) 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)
	CalculateDiscount(ctx context.Context, couponID string, originalPrice decimal.Decimal) (decimal.Decimal, 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 used for both subscription and invoice scenarios
	ValidateCoupon(ctx context.Context, couponID string, subscriptionID *string) 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)

	// ApplyCreditGrant applies a credit grant to a subscription and creates CGA tracking records
	// This method handles both one-time and recurring credit grants
	ApplyCreditGrant(ctx context.Context, grant *creditgrant.CreditGrant, subscription *subscription.Subscription, metadata types.Metadata) error

	// CancelFutureCreditGrantsOfSubscription cancels all future credit grants for this subscription
	CancelFutureCreditGrantsOfSubscription(ctx context.Context, subscriptionID string) 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 CustomerService

type CustomerService interface {
	CreateCustomer(ctx context.Context, req dto.CreateCustomerRequest) (*dto.CustomerResponse, error)
	GetCustomer(ctx context.Context, id string) (*dto.CustomerResponse, error)
	GetCustomers(ctx context.Context, filter *types.CustomerFilter) (*dto.ListCustomersResponse, error)
	UpdateCustomer(ctx context.Context, id string, req dto.UpdateCustomerRequest) (*dto.CustomerResponse, error)
	DeleteCustomer(ctx context.Context, id string) error
	GetCustomerByLookupKey(ctx context.Context, lookupKey string) (*dto.CustomerResponse, error)
}

func NewCustomerService

func NewCustomerService(params ServiceParams) CustomerService

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 interface {
	CreateEntityIntegrationMapping(ctx context.Context, req dto.CreateEntityIntegrationMappingRequest) (*dto.EntityIntegrationMappingResponse, error)
	GetEntityIntegrationMapping(ctx context.Context, id string) (*dto.EntityIntegrationMappingResponse, error)
	GetEntityIntegrationMappings(ctx context.Context, filter *types.EntityIntegrationMappingFilter) (*dto.ListEntityIntegrationMappingsResponse, error)
	DeleteEntityIntegrationMapping(ctx context.Context, id string) error
}

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) EnvironmentService

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)
}

func NewEventService

func NewEventService(
	eventRepo events.Repository,
	meterRepo meter.Repository,
	publisher publisher.EventPublisher,
	logger *logger.Logger,
	config *config.Configuration,
) EventService

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 IntegrationService added in v1.0.21

type IntegrationService interface {
	// SyncEntityToProviders syncs an entity to all available providers for the tenant
	SyncEntityToProviders(ctx context.Context, entityType types.IntegrationEntityType, entityID string) error

	// SyncCustomerFromProvider syncs a customer from a specific provider to FlexPrice
	SyncCustomerFromProvider(ctx context.Context, providerType string, providerCustomerID string, customerData map[string]interface{}) error

	// GetAvailableProviders returns all available providers for the current tenant
	GetAvailableProviders(ctx context.Context) ([]*connection.Connection, error)
}

IntegrationService handles generic integration operations with multiple providers

func NewIntegrationService added in v1.0.21

func NewIntegrationService(params ServiceParams) IntegrationService

type InvoiceService

type InvoiceService interface {
	CreateOneOffInvoice(ctx context.Context, req dto.CreateInvoiceRequest) (*dto.InvoiceResponse, error)
	CreateInvoice(ctx context.Context, req dto.CreateInvoiceRequest) (*dto.InvoiceResponse, error)
	GetInvoice(ctx context.Context, id string) (*dto.InvoiceResponse, error)
	ListInvoices(ctx context.Context, filter *types.InvoiceFilter) (*dto.ListInvoicesResponse, error)
	FinalizeInvoice(ctx context.Context, id string) error
	VoidInvoice(ctx context.Context, id string) error
	ProcessDraftInvoice(ctx context.Context, id string) error
	UpdatePaymentStatus(ctx context.Context, id string, status types.PaymentStatus, amount *decimal.Decimal) error
	ReconcilePaymentStatus(ctx context.Context, id string, status types.PaymentStatus, amount *decimal.Decimal) error
	CreateSubscriptionInvoice(ctx context.Context, req *dto.CreateSubscriptionInvoiceRequest) (*dto.InvoiceResponse, error)
	GetPreviewInvoice(ctx context.Context, req dto.GetPreviewInvoiceRequest) (*dto.InvoiceResponse, error)
	GetCustomerInvoiceSummary(ctx context.Context, customerID string, currency string) (*dto.CustomerInvoiceSummary, 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
	UpdateInvoice(ctx context.Context, id string, req dto.UpdateInvoiceRequest) (*dto.InvoiceResponse, error)
	CalculatePriceBreakdown(ctx context.Context, inv *dto.InvoiceResponse) (map[string][]dto.SourceUsageItem, error)
	TriggerCommunication(ctx context.Context, id string) error
}

func NewInvoiceService

func NewInvoiceService(params ServiceParams) InvoiceService

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 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 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 PaymentGatewayFactory added in v1.0.21

type PaymentGatewayFactory struct {
	// contains filtered or unexported fields
}

PaymentGatewayFactory manages different payment gateway implementations

func NewPaymentGatewayFactory added in v1.0.21

func NewPaymentGatewayFactory(services ServiceParams) *PaymentGatewayFactory

NewPaymentGatewayFactory creates a new payment gateway factory

func (*PaymentGatewayFactory) GetGateway added in v1.0.21

func (f *PaymentGatewayFactory) GetGateway(ctx context.Context, gatewayType types.PaymentGatewayType) (interface{}, error)

GetGateway returns the appropriate payment gateway service for the given type

func (*PaymentGatewayFactory) GetPreferredGateway added in v1.0.21

func (f *PaymentGatewayFactory) GetPreferredGateway(ctx context.Context) (types.PaymentGatewayType, error)

GetPreferredGateway returns the preferred payment gateway for the environment

func (*PaymentGatewayFactory) GetSupportedGateways added in v1.0.21

func (f *PaymentGatewayFactory) GetSupportedGateways() []types.PaymentGatewayType

GetSupportedGateways returns all supported gateway types

type PaymentGatewayService added in v1.0.21

type PaymentGatewayService interface {
	// CreatePaymentLink creates a payment link using the specified or preferred gateway
	CreatePaymentLink(ctx context.Context, req *dto.CreatePaymentLinkRequest) (*dto.PaymentLinkResponse, error)

	// GetPaymentStatus retrieves payment status from any gateway by session ID
	GetPaymentStatus(ctx context.Context, sessionID string) (*dto.GenericPaymentStatusResponse, error)

	// GetSupportedGateways returns all supported payment gateways for the environment
	GetSupportedGateways(ctx context.Context) (*dto.GetSupportedGatewaysResponse, error)
}

PaymentGatewayService provides generic payment gateway operations

func NewPaymentGatewayService added in v1.0.21

func NewPaymentGatewayService(params ServiceParams) PaymentGatewayService

NewPaymentGatewayService creates a new payment gateway service

type PaymentProcessorService

type PaymentProcessorService interface {
	ProcessPayment(ctx context.Context, id string) (*payment.Payment, error)
}

func NewPaymentProcessorService

func NewPaymentProcessorService(params ServiceParams) PaymentProcessorService

type PaymentService

type PaymentService interface {
	// Core payment operations
	CreatePayment(ctx context.Context, req *dto.CreatePaymentRequest) (*dto.PaymentResponse, error)
	GetPayment(ctx context.Context, id string) (*dto.PaymentResponse, error)
	UpdatePayment(ctx context.Context, id string, req dto.UpdatePaymentRequest) (*dto.PaymentResponse, error)
	ListPayments(ctx context.Context, filter *types.PaymentFilter) (*dto.ListPaymentsResponse, error)
	DeletePayment(ctx context.Context, id string) error
}

PaymentService defines the interface for payment operations

func NewPaymentService

func NewPaymentService(params ServiceParams) PaymentService

NewPaymentService creates a new payment service

type PlanService

type PlanService interface {
	CreatePlan(ctx context.Context, req dto.CreatePlanRequest) (*dto.CreatePlanResponse, error)
	GetPlan(ctx context.Context, id string) (*dto.PlanResponse, error)
	GetPlans(ctx context.Context, filter *types.PlanFilter) (*dto.ListPlansResponse, error)
	UpdatePlan(ctx context.Context, id string, req dto.UpdatePlanRequest) (*dto.PlanResponse, error)
	DeletePlan(ctx context.Context, id string) error
	SyncPlanPrices(ctx context.Context, id string) (*SyncPlanPricesResponse, error)
}

func NewPlanService

func NewPlanService(
	params ServiceParams,
) PlanService

type PriceMatch added in v1.0.17

type PriceMatch struct {
	Price *price.Price
	Meter *meter.Meter
}

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, planID string) (*dto.ListPricesResponse, error)
	GetPricesBySubscriptionID(ctx context.Context, subscriptionID string) (*dto.ListPricesResponse, error)
	GetPricesByAddonID(ctx context.Context, addonID 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) error
	CalculateCost(ctx context.Context, price *price.Price, quantity 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
}

func NewPriceService

func NewPriceService(params ServiceParams) PriceService

type PriceUnitService added in v1.0.21

type PriceUnitService struct {
	// contains filtered or unexported fields
}

PriceUnitService handles business logic for price units

func NewPriceUnitService added in v1.0.21

func NewPriceUnitService(repo domainPriceUnit.Repository, client *ent.Client, log *logger.Logger) *PriceUnitService

NewPriceUnitService creates a new instance of PriceUnitService

func (*PriceUnitService) ConvertToBaseCurrency added in v1.0.21

func (s *PriceUnitService) ConvertToBaseCurrency(ctx context.Context, code, tenantID, environmentID string, priceUnitAmount decimal.Decimal) (decimal.Decimal, error)

ConvertToBaseCurrency converts an amount from pricing unit to base currency amount in fiat currency = amount in pricing unit * conversion_rate

func (*PriceUnitService) ConvertToPriceUnit added in v1.0.21

func (s *PriceUnitService) ConvertToPriceUnit(ctx context.Context, code, tenantID, environmentID string, fiatAmount decimal.Decimal) (decimal.Decimal, error)

ConvertToPriceUnit converts an amount from base currency to pricing unit amount in pricing unit = amount in fiat currency / conversion_rate

func (*PriceUnitService) Create added in v1.0.21

func (*PriceUnitService) Delete added in v1.0.21

func (s *PriceUnitService) Delete(ctx context.Context, id string) error

func (*PriceUnitService) GetByCode added in v1.0.21

func (s *PriceUnitService) GetByCode(ctx context.Context, code, tenantID, environmentID string) (*dto.PriceUnitResponse, error)

func (*PriceUnitService) GetByID added in v1.0.21

GetByID retrieves a pricing unit by ID

func (*PriceUnitService) List added in v1.0.21

List returns a paginated list of pricing units

func (*PriceUnitService) Update added in v1.0.21

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,
	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
	ProcessedEventRepo           events.ProcessedEventRepository
	MeterRepo                    meter.Repository
	PriceRepo                    price.Repository
	PriceUnitRepo                priceunit.Repository
	CustomerRepo                 customer.Repository
	PlanRepo                     plan.Repository
	SubRepo                      subscription.Repository
	SubscriptionScheduleRepo     subscription.SubscriptionScheduleRepository
	SubscriptionLineItemRepo     subscription.LineItemRepository
	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

	// Publishers
	EventPublisher   publisher.EventPublisher
	WebhookPublisher webhookPublisher.WebhookPublisher

	// http client
	Client httpclient.Client
}

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,
	processedEventRepo events.ProcessedEventRepository,
	meterRepo meter.Repository,
	priceRepo price.Repository,
	priceUnitRepo priceunit.Repository,
	customerRepo customer.Repository,
	planRepo plan.Repository,
	subRepo subscription.Repository,
	subscriptionScheduleRepo subscription.SubscriptionScheduleRepository,
	subscriptionLineItemRepo subscription.LineItemRepository,
	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,
) ServiceParams

Common service params

type StateAction added in v1.0.18

type StateAction string
const (
	StateActionApply  StateAction = "apply"
	StateActionSkip   StateAction = "skip"
	StateActionDefer  StateAction = "defer"
	StateActionCancel StateAction = "cancel"
)

type StripeService added in v1.0.21

type StripeService struct {
	ServiceParams
	// contains filtered or unexported fields
}

StripeService handles Stripe integration operations

func NewStripeService added in v1.0.21

func NewStripeService(params ServiceParams) *StripeService

NewStripeService creates a new Stripe service instance

func (*StripeService) CreateCustomerFromStripe added in v1.0.21

func (s *StripeService) CreateCustomerFromStripe(ctx context.Context, stripeCustomer *stripe.Customer, environmentID string) error

CreateCustomerFromStripe creates a customer in our system from Stripe webhook data

func (*StripeService) CreateCustomerInStripe added in v1.0.21

func (s *StripeService) CreateCustomerInStripe(ctx context.Context, customerID string) error

CreateCustomerInStripe creates a customer in Stripe and updates our customer with Stripe ID

CreatePaymentLink creates a Stripe checkout session for payment

func (*StripeService) GetDecryptedStripeConfig added in v1.0.21

func (s *StripeService) GetDecryptedStripeConfig(conn *connection.Connection) (*connection.StripeConnection, error)

GetDecryptedStripeConfig gets the decrypted Stripe configuration from a connection

func (*StripeService) GetPaymentStatus added in v1.0.21

func (s *StripeService) GetPaymentStatus(ctx context.Context, sessionID string, environmentID string) (*dto.PaymentStatusResponse, error)

GetPaymentStatus gets the payment status from Stripe checkout session

func (*StripeService) GetPaymentStatusByPaymentIntent added in v1.0.21

func (s *StripeService) GetPaymentStatusByPaymentIntent(ctx context.Context, paymentIntentID string, environmentID string) (*dto.PaymentStatusResponse, error)

GetPaymentStatusByPaymentIntent gets payment status directly from a payment intent ID

func (*StripeService) ParseWebhookEvent added in v1.0.21

func (s *StripeService) ParseWebhookEvent(payload []byte, signature string, webhookSecret string) (*stripe.Event, error)

ParseWebhookEvent parses a Stripe webhook event with signature verification

func (*StripeService) ReconcilePaymentWithInvoice added in v1.0.21

func (s *StripeService) ReconcilePaymentWithInvoice(ctx context.Context, paymentID string, paymentAmount decimal.Decimal) error

ReconcilePaymentWithInvoice updates the invoice payment status and amounts when a payment succeeds

func (*StripeService) VerifyWebhookSignature added in v1.0.21

func (s *StripeService) VerifyWebhookSignature(payload []byte, signature string, webhookSecret string) error

VerifyWebhookSignature verifies the Stripe webhook signature

type SubscriptionService

type SubscriptionService interface {
	CreateSubscription(ctx context.Context, req dto.CreateSubscriptionRequest) (*dto.SubscriptionResponse, error)
	GetSubscription(ctx context.Context, id string) (*dto.SubscriptionResponse, error)
	CancelSubscription(ctx context.Context, id string, cancelAtPeriodEnd bool) error
	ListSubscriptions(ctx context.Context, filter *types.SubscriptionFilter) (*dto.ListSubscriptionsResponse, error)
	GetUsageBySubscription(ctx context.Context, req *dto.GetUsageBySubscriptionRequest) (*dto.GetUsageBySubscriptionResponse, error)
	UpdateBillingPeriods(ctx context.Context) (*dto.SubscriptionUpdatePeriodResponse, error)

	// Pause-related methods
	PauseSubscription(ctx context.Context, subscriptionID string, req *dto.PauseSubscriptionRequest) (*dto.PauseSubscriptionResponse, error)
	ResumeSubscription(ctx context.Context, subscriptionID string, req *dto.ResumeSubscriptionRequest) (*dto.ResumeSubscriptionResponse, error)
	GetPause(ctx context.Context, pauseID string) (*subscription.SubscriptionPause, error)
	ListPauses(ctx context.Context, subscriptionID string) (*dto.ListSubscriptionPausesResponse, error)
	CalculatePauseImpact(ctx context.Context, subscriptionID string, req *dto.PauseSubscriptionRequest) (*types.BillingImpactDetails, error)
	CalculateResumeImpact(ctx context.Context, subscriptionID string, req *dto.ResumeSubscriptionRequest) (*types.BillingImpactDetails, error)

	// Schedule-related methods
	CreateSubscriptionSchedule(ctx context.Context, req *dto.CreateSubscriptionScheduleRequest) (*dto.SubscriptionScheduleResponse, error)
	GetSubscriptionSchedule(ctx context.Context, id string) (*dto.SubscriptionScheduleResponse, error)
	GetScheduleBySubscriptionID(ctx context.Context, subscriptionID string) (*dto.SubscriptionScheduleResponse, error)
	UpdateSubscriptionSchedule(ctx context.Context, id string, req *dto.UpdateSubscriptionScheduleRequest) (*dto.SubscriptionScheduleResponse, error)
	AddSchedulePhase(ctx context.Context, scheduleID string, req *dto.AddSchedulePhaseRequest) (*dto.SubscriptionScheduleResponse, error)
	AddSubscriptionPhase(ctx context.Context, subscriptionID string, req *dto.AddSchedulePhaseRequest) (*dto.SubscriptionScheduleResponse, error)

	// Coupon-related methods
	ApplyCouponsToSubscriptionWithLineItems(ctx context.Context, subscriptionID string, subscriptionCoupons []string, lineItemCoupons map[string][]string, lineItems []*subscription.SubscriptionLineItem) error

	ValidateAndFilterPricesForSubscription(ctx context.Context, entityID string, entityType types.PriceEntityType, subscription *subscription.Subscription) ([]*dto.PriceResponse, error)

	// Addon management for subscriptions
	AddAddonToSubscription(ctx context.Context, subscriptionID string, req *dto.AddAddonToSubscriptionRequest) (*addonassociation.AddonAssociation, error)
	RemoveAddonFromSubscription(ctx context.Context, subscriptionID string, addonID string, reason string) error
}

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 SyncPlanPricesResponse added in v1.0.18

type SyncPlanPricesResponse struct {
	Message                string `json:"message"`
	PlanID                 string `json:"plan_id"`
	PlanName               string `json:"plan_name"`
	SynchronizationSummary struct {
		SubscriptionsProcessed int `json:"subscriptions_processed"`
		PricesAdded            int `json:"prices_added"`
		PricesRemoved          int `json:"prices_removed"`
		PricesSkipped          int `json:"prices_skipped"`
	} `json:"synchronization_summary"`
}

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
	ProcessTask(ctx context.Context, id 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)
}

func NewUserService

func NewUserService(userRepo user.Repository, tenantRepo tenant.Repository) UserService

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.WalletResponse, error)

	// GetWalletTransactionByID retrieves a transaction by its ID
	GetWalletTransactionByID(ctx context.Context, transactionID string) (*dto.WalletTransactionResponse, error)

	// GetWalletBalance retrieves the real-time balance of a wallet
	GetWalletBalance(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

	// 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
}

WalletService defines the interface for wallet operations

func NewWalletService

func NewWalletService(params ServiceParams) WalletService

NewWalletService creates a new instance of WalletService

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL