unified gateway interface
This commit is contained in:
@@ -2,16 +2,12 @@ package model
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/pkg/db/storable"
|
||||
"github.com/tech/sendico/pkg/model"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
feesv1 "github.com/tech/sendico/pkg/proto/billing/fees/v1"
|
||||
fxv1 "github.com/tech/sendico/pkg/proto/common/fx/v1"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
oraclev1 "github.com/tech/sendico/pkg/proto/oracle/v1"
|
||||
orchestratorv1 "github.com/tech/sendico/pkg/proto/payments/orchestrator/v1"
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
)
|
||||
|
||||
// PaymentKind captures the orchestrator intent type.
|
||||
@@ -24,6 +20,15 @@ const (
|
||||
PaymentKindFXConversion PaymentKind = "fx_conversion"
|
||||
)
|
||||
|
||||
// SettlementMode defines how fees/FX variance is handled.
|
||||
type SettlementMode string
|
||||
|
||||
const (
|
||||
SettlementModeUnspecified SettlementMode = "unspecified"
|
||||
SettlementModeFixSource SettlementMode = "fix_source"
|
||||
SettlementModeFixReceived SettlementMode = "fix_received"
|
||||
)
|
||||
|
||||
// PaymentState enumerates lifecycle phases.
|
||||
type PaymentState string
|
||||
|
||||
@@ -50,6 +55,73 @@ const (
|
||||
PaymentFailureCodePolicy PaymentFailureCode = "policy"
|
||||
)
|
||||
|
||||
// Rail identifies a payment rail for orchestration.
|
||||
type Rail string
|
||||
|
||||
const (
|
||||
RailUnspecified Rail = "UNSPECIFIED"
|
||||
RailCrypto Rail = "CRYPTO"
|
||||
RailProviderSettlement Rail = "PROVIDER_SETTLEMENT"
|
||||
RailLedger Rail = "LEDGER"
|
||||
RailCardPayout Rail = "CARD_PAYOUT"
|
||||
RailFiatOnRamp Rail = "FIAT_ONRAMP"
|
||||
)
|
||||
|
||||
// RailOperation identifies an explicit action within a payment plan.
|
||||
type RailOperation string
|
||||
|
||||
const (
|
||||
RailOperationUnspecified RailOperation = "UNSPECIFIED"
|
||||
RailOperationDebit RailOperation = "DEBIT"
|
||||
RailOperationCredit RailOperation = "CREDIT"
|
||||
RailOperationSend RailOperation = "SEND"
|
||||
RailOperationFee RailOperation = "FEE"
|
||||
RailOperationObserveConfirm RailOperation = "OBSERVE_CONFIRM"
|
||||
RailOperationFXConvert RailOperation = "FX_CONVERT"
|
||||
)
|
||||
|
||||
// RailCapabilities are declared per gateway instance.
|
||||
type RailCapabilities struct {
|
||||
CanPayIn bool `bson:"canPayIn,omitempty" json:"canPayIn,omitempty"`
|
||||
CanPayOut bool `bson:"canPayOut,omitempty" json:"canPayOut,omitempty"`
|
||||
CanReadBalance bool `bson:"canReadBalance,omitempty" json:"canReadBalance,omitempty"`
|
||||
CanSendFee bool `bson:"canSendFee,omitempty" json:"canSendFee,omitempty"`
|
||||
RequiresObserveConfirm bool `bson:"requiresObserveConfirm,omitempty" json:"requiresObserveConfirm,omitempty"`
|
||||
}
|
||||
|
||||
// LimitsOverride applies per-currency overrides for limits.
|
||||
type LimitsOverride struct {
|
||||
MaxVolume string `bson:"maxVolume,omitempty" json:"maxVolume,omitempty"`
|
||||
MinAmount string `bson:"minAmount,omitempty" json:"minAmount,omitempty"`
|
||||
MaxAmount string `bson:"maxAmount,omitempty" json:"maxAmount,omitempty"`
|
||||
MaxFee string `bson:"maxFee,omitempty" json:"maxFee,omitempty"`
|
||||
MaxOps int `bson:"maxOps,omitempty" json:"maxOps,omitempty"`
|
||||
}
|
||||
|
||||
// Limits define time-bucketed and per-tx constraints.
|
||||
type Limits struct {
|
||||
MinAmount string `bson:"minAmount,omitempty" json:"minAmount,omitempty"`
|
||||
MaxAmount string `bson:"maxAmount,omitempty" json:"maxAmount,omitempty"`
|
||||
PerTxMaxFee string `bson:"perTxMaxFee,omitempty" json:"perTxMaxFee,omitempty"`
|
||||
PerTxMinAmount string `bson:"perTxMinAmount,omitempty" json:"perTxMinAmount,omitempty"`
|
||||
PerTxMaxAmount string `bson:"perTxMaxAmount,omitempty" json:"perTxMaxAmount,omitempty"`
|
||||
VolumeLimit map[string]string `bson:"volumeLimit,omitempty" json:"volumeLimit,omitempty"`
|
||||
VelocityLimit map[string]int `bson:"velocityLimit,omitempty" json:"velocityLimit,omitempty"`
|
||||
CurrencyLimits map[string]LimitsOverride `bson:"currencyLimits,omitempty" json:"currencyLimits,omitempty"`
|
||||
}
|
||||
|
||||
// GatewayInstanceDescriptor standardizes gateway instance self-declaration.
|
||||
type GatewayInstanceDescriptor struct {
|
||||
ID string `bson:"id" json:"id"`
|
||||
Rail Rail `bson:"rail" json:"rail"`
|
||||
Network string `bson:"network,omitempty" json:"network,omitempty"`
|
||||
Currencies []string `bson:"currencies,omitempty" json:"currencies,omitempty"`
|
||||
Capabilities RailCapabilities `bson:"capabilities,omitempty" json:"capabilities,omitempty"`
|
||||
Limits Limits `bson:"limits,omitempty" json:"limits,omitempty"`
|
||||
Version string `bson:"version,omitempty" json:"version,omitempty"`
|
||||
IsEnabled bool `bson:"isEnabled" json:"isEnabled"`
|
||||
}
|
||||
|
||||
// PaymentEndpointType indicates how value should be routed.
|
||||
type PaymentEndpointType string
|
||||
|
||||
@@ -69,15 +141,15 @@ type LedgerEndpoint struct {
|
||||
|
||||
// ManagedWalletEndpoint describes managed wallet routing.
|
||||
type ManagedWalletEndpoint struct {
|
||||
ManagedWalletRef string `bson:"managedWalletRef" json:"managedWalletRef"`
|
||||
Asset *chainv1.Asset `bson:"asset,omitempty" json:"asset,omitempty"`
|
||||
ManagedWalletRef string `bson:"managedWalletRef" json:"managedWalletRef"`
|
||||
Asset *paymenttypes.Asset `bson:"asset,omitempty" json:"asset,omitempty"`
|
||||
}
|
||||
|
||||
// ExternalChainEndpoint describes an external address.
|
||||
type ExternalChainEndpoint struct {
|
||||
Asset *chainv1.Asset `bson:"asset,omitempty" json:"asset,omitempty"`
|
||||
Address string `bson:"address" json:"address"`
|
||||
Memo string `bson:"memo,omitempty" json:"memo,omitempty"`
|
||||
Asset *paymenttypes.Asset `bson:"asset,omitempty" json:"asset,omitempty"`
|
||||
Address string `bson:"address" json:"address"`
|
||||
Memo string `bson:"memo,omitempty" json:"memo,omitempty"`
|
||||
}
|
||||
|
||||
// CardEndpoint describes a card payout destination.
|
||||
@@ -116,26 +188,26 @@ type PaymentEndpoint struct {
|
||||
|
||||
// FXIntent captures FX conversion preferences.
|
||||
type FXIntent struct {
|
||||
Pair *fxv1.CurrencyPair `bson:"pair,omitempty" json:"pair,omitempty"`
|
||||
Side fxv1.Side `bson:"side,omitempty" json:"side,omitempty"`
|
||||
Firm bool `bson:"firm,omitempty" json:"firm,omitempty"`
|
||||
TTLMillis int64 `bson:"ttlMillis,omitempty" json:"ttlMillis,omitempty"`
|
||||
PreferredProvider string `bson:"preferredProvider,omitempty" json:"preferredProvider,omitempty"`
|
||||
MaxAgeMillis int32 `bson:"maxAgeMillis,omitempty" json:"maxAgeMillis,omitempty"`
|
||||
Pair *paymenttypes.CurrencyPair `bson:"pair,omitempty" json:"pair,omitempty"`
|
||||
Side paymenttypes.FXSide `bson:"side,omitempty" json:"side,omitempty"`
|
||||
Firm bool `bson:"firm,omitempty" json:"firm,omitempty"`
|
||||
TTLMillis int64 `bson:"ttlMillis,omitempty" json:"ttlMillis,omitempty"`
|
||||
PreferredProvider string `bson:"preferredProvider,omitempty" json:"preferredProvider,omitempty"`
|
||||
MaxAgeMillis int32 `bson:"maxAgeMillis,omitempty" json:"maxAgeMillis,omitempty"`
|
||||
}
|
||||
|
||||
// PaymentIntent models the requested payment operation.
|
||||
type PaymentIntent struct {
|
||||
Kind PaymentKind `bson:"kind" json:"kind"`
|
||||
Source PaymentEndpoint `bson:"source" json:"source"`
|
||||
Destination PaymentEndpoint `bson:"destination" json:"destination"`
|
||||
Amount *moneyv1.Money `bson:"amount" json:"amount"`
|
||||
RequiresFX bool `bson:"requiresFx,omitempty" json:"requiresFx,omitempty"`
|
||||
FX *FXIntent `bson:"fx,omitempty" json:"fx,omitempty"`
|
||||
FeePolicy *feesv1.PolicyOverrides `bson:"feePolicy,omitempty" json:"feePolicy,omitempty"`
|
||||
SettlementMode orchestratorv1.SettlementMode `bson:"settlementMode,omitempty" json:"settlementMode,omitempty"`
|
||||
Attributes map[string]string `bson:"attributes,omitempty" json:"attributes,omitempty"`
|
||||
Customer *Customer `bson:"customer,omitempty" json:"customer,omitempty"`
|
||||
Kind PaymentKind `bson:"kind" json:"kind"`
|
||||
Source PaymentEndpoint `bson:"source" json:"source"`
|
||||
Destination PaymentEndpoint `bson:"destination" json:"destination"`
|
||||
Amount *paymenttypes.Money `bson:"amount" json:"amount"`
|
||||
RequiresFX bool `bson:"requiresFx,omitempty" json:"requiresFx,omitempty"`
|
||||
FX *FXIntent `bson:"fx,omitempty" json:"fx,omitempty"`
|
||||
FeePolicy *paymenttypes.FeePolicy `bson:"feePolicy,omitempty" json:"feePolicy,omitempty"`
|
||||
SettlementMode SettlementMode `bson:"settlementMode,omitempty" json:"settlementMode,omitempty"`
|
||||
Attributes map[string]string `bson:"attributes,omitempty" json:"attributes,omitempty"`
|
||||
Customer *Customer `bson:"customer,omitempty" json:"customer,omitempty"`
|
||||
}
|
||||
|
||||
// Customer captures payer/recipient identity details for downstream processing.
|
||||
@@ -154,14 +226,14 @@ type Customer struct {
|
||||
|
||||
// PaymentQuoteSnapshot stores the latest quote info.
|
||||
type PaymentQuoteSnapshot struct {
|
||||
DebitAmount *moneyv1.Money `bson:"debitAmount,omitempty" json:"debitAmount,omitempty"`
|
||||
ExpectedSettlementAmount *moneyv1.Money `bson:"expectedSettlementAmount,omitempty" json:"expectedSettlementAmount,omitempty"`
|
||||
ExpectedFeeTotal *moneyv1.Money `bson:"expectedFeeTotal,omitempty" json:"expectedFeeTotal,omitempty"`
|
||||
FeeLines []*feesv1.DerivedPostingLine `bson:"feeLines,omitempty" json:"feeLines,omitempty"`
|
||||
FeeRules []*feesv1.AppliedRule `bson:"feeRules,omitempty" json:"feeRules,omitempty"`
|
||||
FXQuote *oraclev1.Quote `bson:"fxQuote,omitempty" json:"fxQuote,omitempty"`
|
||||
NetworkFee *chainv1.EstimateTransferFeeResponse `bson:"networkFee,omitempty" json:"networkFee,omitempty"`
|
||||
QuoteRef string `bson:"quoteRef,omitempty" json:"quoteRef,omitempty"`
|
||||
DebitAmount *paymenttypes.Money `bson:"debitAmount,omitempty" json:"debitAmount,omitempty"`
|
||||
ExpectedSettlementAmount *paymenttypes.Money `bson:"expectedSettlementAmount,omitempty" json:"expectedSettlementAmount,omitempty"`
|
||||
ExpectedFeeTotal *paymenttypes.Money `bson:"expectedFeeTotal,omitempty" json:"expectedFeeTotal,omitempty"`
|
||||
FeeLines []*paymenttypes.FeeLine `bson:"feeLines,omitempty" json:"feeLines,omitempty"`
|
||||
FeeRules []*paymenttypes.AppliedRule `bson:"feeRules,omitempty" json:"feeRules,omitempty"`
|
||||
FXQuote *paymenttypes.FXQuote `bson:"fxQuote,omitempty" json:"fxQuote,omitempty"`
|
||||
NetworkFee *paymenttypes.NetworkFeeEstimate `bson:"networkFee,omitempty" json:"networkFee,omitempty"`
|
||||
QuoteRef string `bson:"quoteRef,omitempty" json:"quoteRef,omitempty"`
|
||||
}
|
||||
|
||||
// ExecutionRefs links to downstream systems.
|
||||
@@ -174,22 +246,39 @@ type ExecutionRefs struct {
|
||||
FeeTransferRef string `bson:"feeTransferRef,omitempty" json:"feeTransferRef,omitempty"`
|
||||
}
|
||||
|
||||
// PaymentStep is an explicit action within a payment plan.
|
||||
type PaymentStep struct {
|
||||
Rail Rail `bson:"rail" json:"rail"`
|
||||
GatewayID string `bson:"gatewayId,omitempty" json:"gatewayId,omitempty"`
|
||||
Action RailOperation `bson:"action" json:"action"`
|
||||
Amount *paymenttypes.Money `bson:"amount,omitempty" json:"amount,omitempty"`
|
||||
Ref string `bson:"ref,omitempty" json:"ref,omitempty"`
|
||||
}
|
||||
|
||||
// PaymentPlan captures the ordered list of steps to execute a payment.
|
||||
type PaymentPlan struct {
|
||||
ID string `bson:"id,omitempty" json:"id,omitempty"`
|
||||
Steps []*PaymentStep `bson:"steps,omitempty" json:"steps,omitempty"`
|
||||
IdempotencyKey string `bson:"idempotencyKey,omitempty" json:"idempotencyKey,omitempty"`
|
||||
CreatedAt time.Time `bson:"createdAt,omitempty" json:"createdAt,omitempty"`
|
||||
}
|
||||
|
||||
// ExecutionStep describes a planned or executed payment step for reporting.
|
||||
type ExecutionStep struct {
|
||||
Code string `bson:"code,omitempty" json:"code,omitempty"`
|
||||
Description string `bson:"description,omitempty" json:"description,omitempty"`
|
||||
Amount *moneyv1.Money `bson:"amount,omitempty" json:"amount,omitempty"`
|
||||
NetworkFee *moneyv1.Money `bson:"networkFee,omitempty" json:"networkFee,omitempty"`
|
||||
SourceWalletRef string `bson:"sourceWalletRef,omitempty" json:"sourceWalletRef,omitempty"`
|
||||
DestinationRef string `bson:"destinationRef,omitempty" json:"destinationRef,omitempty"`
|
||||
TransferRef string `bson:"transferRef,omitempty" json:"transferRef,omitempty"`
|
||||
Metadata map[string]string `bson:"metadata,omitempty" json:"metadata,omitempty"`
|
||||
Code string `bson:"code,omitempty" json:"code,omitempty"`
|
||||
Description string `bson:"description,omitempty" json:"description,omitempty"`
|
||||
Amount *paymenttypes.Money `bson:"amount,omitempty" json:"amount,omitempty"`
|
||||
NetworkFee *paymenttypes.Money `bson:"networkFee,omitempty" json:"networkFee,omitempty"`
|
||||
SourceWalletRef string `bson:"sourceWalletRef,omitempty" json:"sourceWalletRef,omitempty"`
|
||||
DestinationRef string `bson:"destinationRef,omitempty" json:"destinationRef,omitempty"`
|
||||
TransferRef string `bson:"transferRef,omitempty" json:"transferRef,omitempty"`
|
||||
Metadata map[string]string `bson:"metadata,omitempty" json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// ExecutionPlan captures the ordered list of steps to execute a payment.
|
||||
type ExecutionPlan struct {
|
||||
Steps []*ExecutionStep `bson:"steps,omitempty" json:"steps,omitempty"`
|
||||
TotalNetworkFee *moneyv1.Money `bson:"totalNetworkFee,omitempty" json:"totalNetworkFee,omitempty"`
|
||||
Steps []*ExecutionStep `bson:"steps,omitempty" json:"steps,omitempty"`
|
||||
TotalNetworkFee *paymenttypes.Money `bson:"totalNetworkFee,omitempty" json:"totalNetworkFee,omitempty"`
|
||||
}
|
||||
|
||||
// Payment persists orchestrated payment lifecycle.
|
||||
@@ -206,6 +295,7 @@ type Payment struct {
|
||||
LastQuote *PaymentQuoteSnapshot `bson:"lastQuote,omitempty" json:"lastQuote,omitempty"`
|
||||
Execution *ExecutionRefs `bson:"execution,omitempty" json:"execution,omitempty"`
|
||||
ExecutionPlan *ExecutionPlan `bson:"executionPlan,omitempty" json:"executionPlan,omitempty"`
|
||||
PaymentPlan *PaymentPlan `bson:"paymentPlan,omitempty" json:"paymentPlan,omitempty"`
|
||||
Metadata map[string]string `bson:"metadata,omitempty" json:"metadata,omitempty"`
|
||||
CardPayout *CardPayout `bson:"cardPayout,omitempty" json:"cardPayout,omitempty"`
|
||||
}
|
||||
@@ -282,6 +372,19 @@ func (p *Payment) Normalize() {
|
||||
}
|
||||
}
|
||||
}
|
||||
if p.PaymentPlan != nil {
|
||||
p.PaymentPlan.ID = strings.TrimSpace(p.PaymentPlan.ID)
|
||||
p.PaymentPlan.IdempotencyKey = strings.TrimSpace(p.PaymentPlan.IdempotencyKey)
|
||||
for _, step := range p.PaymentPlan.Steps {
|
||||
if step == nil {
|
||||
continue
|
||||
}
|
||||
step.Rail = Rail(strings.TrimSpace(string(step.Rail)))
|
||||
step.GatewayID = strings.TrimSpace(step.GatewayID)
|
||||
step.Action = RailOperation(strings.TrimSpace(string(step.Action)))
|
||||
step.Ref = strings.TrimSpace(step.Ref)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeEndpoint(ep *PaymentEndpoint) {
|
||||
@@ -303,6 +406,7 @@ func normalizeEndpoint(ep *PaymentEndpoint) {
|
||||
if ep.ManagedWallet != nil {
|
||||
ep.ManagedWallet.ManagedWalletRef = strings.TrimSpace(ep.ManagedWallet.ManagedWalletRef)
|
||||
if ep.ManagedWallet.Asset != nil {
|
||||
ep.ManagedWallet.Asset.Chain = strings.TrimSpace(strings.ToUpper(ep.ManagedWallet.Asset.Chain))
|
||||
ep.ManagedWallet.Asset.TokenSymbol = strings.TrimSpace(strings.ToUpper(ep.ManagedWallet.Asset.TokenSymbol))
|
||||
ep.ManagedWallet.Asset.ContractAddress = strings.TrimSpace(strings.ToLower(ep.ManagedWallet.Asset.ContractAddress))
|
||||
}
|
||||
@@ -312,6 +416,7 @@ func normalizeEndpoint(ep *PaymentEndpoint) {
|
||||
ep.ExternalChain.Address = strings.TrimSpace(strings.ToLower(ep.ExternalChain.Address))
|
||||
ep.ExternalChain.Memo = strings.TrimSpace(ep.ExternalChain.Memo)
|
||||
if ep.ExternalChain.Asset != nil {
|
||||
ep.ExternalChain.Asset.Chain = strings.TrimSpace(strings.ToUpper(ep.ExternalChain.Asset.Chain))
|
||||
ep.ExternalChain.Asset.TokenSymbol = strings.TrimSpace(strings.ToUpper(ep.ExternalChain.Asset.TokenSymbol))
|
||||
ep.ExternalChain.Asset.ContractAddress = strings.TrimSpace(strings.ToLower(ep.ExternalChain.Asset.ContractAddress))
|
||||
}
|
||||
|
||||
47
api/payments/orchestrator/storage/model/route.go
Normal file
47
api/payments/orchestrator/storage/model/route.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/tech/sendico/pkg/db/storable"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
)
|
||||
|
||||
// PaymentRoute defines an allowed rail transition for orchestration.
|
||||
type PaymentRoute struct {
|
||||
storable.Base `bson:",inline" json:",inline"`
|
||||
|
||||
FromRail Rail `bson:"fromRail" json:"fromRail"`
|
||||
ToRail Rail `bson:"toRail" json:"toRail"`
|
||||
Network string `bson:"network,omitempty" json:"network,omitempty"`
|
||||
RequiresObserve bool `bson:"requiresObserve,omitempty" json:"requiresObserve,omitempty"`
|
||||
IsEnabled bool `bson:"isEnabled" json:"isEnabled"`
|
||||
}
|
||||
|
||||
// Collection implements storable.Storable.
|
||||
func (*PaymentRoute) Collection() string {
|
||||
return mservice.PaymentRoutes
|
||||
}
|
||||
|
||||
// Normalize standardizes route fields for consistent indexing and matching.
|
||||
func (r *PaymentRoute) Normalize() {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
r.FromRail = Rail(strings.ToUpper(strings.TrimSpace(string(r.FromRail))))
|
||||
r.ToRail = Rail(strings.ToUpper(strings.TrimSpace(string(r.ToRail))))
|
||||
r.Network = strings.ToUpper(strings.TrimSpace(r.Network))
|
||||
}
|
||||
|
||||
// PaymentRouteFilter selects routes for lookup.
|
||||
type PaymentRouteFilter struct {
|
||||
FromRail Rail
|
||||
ToRail Rail
|
||||
Network string
|
||||
IsEnabled *bool
|
||||
}
|
||||
|
||||
// PaymentRouteList holds route results.
|
||||
type PaymentRouteList struct {
|
||||
Items []*PaymentRoute
|
||||
}
|
||||
@@ -19,6 +19,7 @@ type Store struct {
|
||||
|
||||
payments storage.PaymentsStore
|
||||
quotes storage.QuotesStore
|
||||
routes storage.RoutesStore
|
||||
}
|
||||
|
||||
// New constructs a Mongo-backed payments repository from a Mongo connection.
|
||||
@@ -28,11 +29,12 @@ func New(logger mlogger.Logger, conn *db.MongoConnection) (*Store, error) {
|
||||
}
|
||||
paymentsRepo := repository.CreateMongoRepository(conn.Database(), (&model.Payment{}).Collection())
|
||||
quotesRepo := repository.CreateMongoRepository(conn.Database(), (&model.PaymentQuoteRecord{}).Collection())
|
||||
return NewWithRepository(logger, conn.Ping, paymentsRepo, quotesRepo)
|
||||
routesRepo := repository.CreateMongoRepository(conn.Database(), (&model.PaymentRoute{}).Collection())
|
||||
return NewWithRepository(logger, conn.Ping, paymentsRepo, quotesRepo, routesRepo)
|
||||
}
|
||||
|
||||
// NewWithRepository constructs a payments repository using the provided primitives.
|
||||
func NewWithRepository(logger mlogger.Logger, ping func(context.Context) error, paymentsRepo repository.Repository, quotesRepo repository.Repository) (*Store, error) {
|
||||
func NewWithRepository(logger mlogger.Logger, ping func(context.Context) error, paymentsRepo repository.Repository, quotesRepo repository.Repository, routesRepo repository.Repository) (*Store, error) {
|
||||
if ping == nil {
|
||||
return nil, merrors.InvalidArgument("payments.storage.mongo: ping func is nil")
|
||||
}
|
||||
@@ -42,6 +44,9 @@ func NewWithRepository(logger mlogger.Logger, ping func(context.Context) error,
|
||||
if quotesRepo == nil {
|
||||
return nil, merrors.InvalidArgument("payments.storage.mongo: quotes repository is nil")
|
||||
}
|
||||
if routesRepo == nil {
|
||||
return nil, merrors.InvalidArgument("payments.storage.mongo: routes repository is nil")
|
||||
}
|
||||
|
||||
childLogger := logger.Named("storage").Named("mongo")
|
||||
paymentsStore, err := store.NewPayments(childLogger, paymentsRepo)
|
||||
@@ -52,11 +57,16 @@ func NewWithRepository(logger mlogger.Logger, ping func(context.Context) error,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
routesStore, err := store.NewRoutes(childLogger, routesRepo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &Store{
|
||||
logger: childLogger,
|
||||
ping: ping,
|
||||
payments: paymentsStore,
|
||||
quotes: quotesStore,
|
||||
routes: routesStore,
|
||||
}
|
||||
|
||||
return result, nil
|
||||
@@ -80,4 +90,9 @@ func (s *Store) Quotes() storage.QuotesStore {
|
||||
return s.quotes
|
||||
}
|
||||
|
||||
// Routes returns the routing store.
|
||||
func (s *Store) Routes() storage.RoutesStore {
|
||||
return s.routes
|
||||
}
|
||||
|
||||
var _ storage.Repository = (*Store)(nil)
|
||||
|
||||
@@ -54,6 +54,9 @@ func NewPayments(logger mlogger.Logger, repo repository.Repository) (*Payments,
|
||||
{
|
||||
Keys: []ri.Key{{Field: "execution.chainTransferRef", Sort: ri.Asc}},
|
||||
},
|
||||
{
|
||||
Keys: []ri.Key{{Field: "executionPlan.steps.transferRef", Sort: ri.Asc}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, def := range indexes {
|
||||
@@ -160,7 +163,11 @@ func (p *Payments) GetByChainTransferRef(ctx context.Context, transferRef string
|
||||
return nil, merrors.InvalidArgument("paymentsStore: empty chain transfer reference")
|
||||
}
|
||||
entity := &model.Payment{}
|
||||
if err := p.repo.FindOneByFilter(ctx, repository.Filter("execution.chainTransferRef", transferRef), entity); err != nil {
|
||||
query := repository.Query().Or(
|
||||
repository.Filter("execution.chainTransferRef", transferRef),
|
||||
repository.Filter("executionPlan.steps.transferRef", transferRef),
|
||||
)
|
||||
if err := p.repo.FindOneByFilter(ctx, query, entity); err != nil {
|
||||
if errors.Is(err, merrors.ErrNoData) {
|
||||
return nil, storage.ErrPaymentNotFound
|
||||
}
|
||||
|
||||
165
api/payments/orchestrator/storage/mongo/store/routes.go
Normal file
165
api/payments/orchestrator/storage/mongo/store/routes.go
Normal file
@@ -0,0 +1,165 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/tech/sendico/payments/orchestrator/storage"
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
"github.com/tech/sendico/pkg/db/repository"
|
||||
ri "github.com/tech/sendico/pkg/db/repository/index"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type Routes struct {
|
||||
logger mlogger.Logger
|
||||
repo repository.Repository
|
||||
}
|
||||
|
||||
// NewRoutes constructs a Mongo-backed routes store.
|
||||
func NewRoutes(logger mlogger.Logger, repo repository.Repository) (*Routes, error) {
|
||||
if repo == nil {
|
||||
return nil, merrors.InvalidArgument("routesStore: repository is nil")
|
||||
}
|
||||
|
||||
indexes := []*ri.Definition{
|
||||
{
|
||||
Keys: []ri.Key{
|
||||
{Field: "fromRail", Sort: ri.Asc},
|
||||
{Field: "toRail", Sort: ri.Asc},
|
||||
{Field: "network", Sort: ri.Asc},
|
||||
},
|
||||
Unique: true,
|
||||
},
|
||||
{
|
||||
Keys: []ri.Key{{Field: "fromRail", Sort: ri.Asc}},
|
||||
},
|
||||
{
|
||||
Keys: []ri.Key{{Field: "toRail", Sort: ri.Asc}},
|
||||
},
|
||||
{
|
||||
Keys: []ri.Key{{Field: "isEnabled", Sort: ri.Asc}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, def := range indexes {
|
||||
if err := repo.CreateIndex(def); err != nil {
|
||||
logger.Error("failed to ensure routes index", zap.Error(err), zap.String("collection", repo.Collection()))
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &Routes{
|
||||
logger: logger.Named("routes"),
|
||||
repo: repo,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Routes) Create(ctx context.Context, route *model.PaymentRoute) error {
|
||||
if route == nil {
|
||||
return merrors.InvalidArgument("routesStore: nil route")
|
||||
}
|
||||
route.Normalize()
|
||||
if route.FromRail == "" || route.FromRail == model.RailUnspecified {
|
||||
return merrors.InvalidArgument("routesStore: from_rail is required")
|
||||
}
|
||||
if route.ToRail == "" || route.ToRail == model.RailUnspecified {
|
||||
return merrors.InvalidArgument("routesStore: to_rail is required")
|
||||
}
|
||||
if route.ID.IsZero() {
|
||||
route.SetID(primitive.NewObjectID())
|
||||
} else {
|
||||
route.Update()
|
||||
}
|
||||
|
||||
filter := repository.Filter("fromRail", route.FromRail).And(
|
||||
repository.Filter("toRail", route.ToRail),
|
||||
repository.Filter("network", route.Network),
|
||||
)
|
||||
|
||||
if err := r.repo.Insert(ctx, route, filter); err != nil {
|
||||
if errors.Is(err, merrors.ErrDataConflict) {
|
||||
return storage.ErrDuplicateRoute
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Routes) Update(ctx context.Context, route *model.PaymentRoute) error {
|
||||
if route == nil {
|
||||
return merrors.InvalidArgument("routesStore: nil route")
|
||||
}
|
||||
if route.ID.IsZero() {
|
||||
return merrors.InvalidArgument("routesStore: missing route id")
|
||||
}
|
||||
route.Normalize()
|
||||
route.Update()
|
||||
if err := r.repo.Update(ctx, route); err != nil {
|
||||
if errors.Is(err, merrors.ErrNoData) {
|
||||
return storage.ErrRouteNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Routes) GetByID(ctx context.Context, id primitive.ObjectID) (*model.PaymentRoute, error) {
|
||||
if id == primitive.NilObjectID {
|
||||
return nil, merrors.InvalidArgument("routesStore: route id is required")
|
||||
}
|
||||
entity := &model.PaymentRoute{}
|
||||
if err := r.repo.Get(ctx, id, entity); err != nil {
|
||||
if errors.Is(err, merrors.ErrNoData) {
|
||||
return nil, storage.ErrRouteNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return entity, nil
|
||||
}
|
||||
|
||||
func (r *Routes) List(ctx context.Context, filter *model.PaymentRouteFilter) (*model.PaymentRouteList, error) {
|
||||
if filter == nil {
|
||||
filter = &model.PaymentRouteFilter{}
|
||||
}
|
||||
|
||||
query := repository.Query()
|
||||
|
||||
if from := strings.ToUpper(strings.TrimSpace(string(filter.FromRail))); from != "" {
|
||||
query = query.Filter(repository.Field("fromRail"), from)
|
||||
}
|
||||
if to := strings.ToUpper(strings.TrimSpace(string(filter.ToRail))); to != "" {
|
||||
query = query.Filter(repository.Field("toRail"), to)
|
||||
}
|
||||
if network := strings.ToUpper(strings.TrimSpace(filter.Network)); network != "" {
|
||||
query = query.Filter(repository.Field("network"), network)
|
||||
}
|
||||
if filter.IsEnabled != nil {
|
||||
query = query.Filter(repository.Field("isEnabled"), *filter.IsEnabled)
|
||||
}
|
||||
|
||||
routes := make([]*model.PaymentRoute, 0)
|
||||
decoder := func(cur *mongo.Cursor) error {
|
||||
item := &model.PaymentRoute{}
|
||||
if err := cur.Decode(item); err != nil {
|
||||
return err
|
||||
}
|
||||
routes = append(routes, item)
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := r.repo.FindManyByFilter(ctx, query, decoder); err != nil && !errors.Is(err, merrors.ErrNoData) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &model.PaymentRouteList{
|
||||
Items: routes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
var _ storage.RoutesStore = (*Routes)(nil)
|
||||
@@ -22,6 +22,10 @@ var (
|
||||
ErrQuoteNotFound = storageError("payments.orchestrator.storage: quote not found")
|
||||
// ErrDuplicateQuote signals that a quote reference already exists.
|
||||
ErrDuplicateQuote = storageError("payments.orchestrator.storage: duplicate quote")
|
||||
// ErrRouteNotFound signals that a payment route record does not exist.
|
||||
ErrRouteNotFound = storageError("payments.orchestrator.storage: route not found")
|
||||
// ErrDuplicateRoute signals that a route already exists for the same transition.
|
||||
ErrDuplicateRoute = storageError("payments.orchestrator.storage: duplicate route")
|
||||
)
|
||||
|
||||
// Repository exposes persistence primitives for the orchestrator domain.
|
||||
@@ -29,6 +33,7 @@ type Repository interface {
|
||||
Ping(ctx context.Context) error
|
||||
Payments() PaymentsStore
|
||||
Quotes() QuotesStore
|
||||
Routes() RoutesStore
|
||||
}
|
||||
|
||||
// PaymentsStore manages payment lifecycle state.
|
||||
@@ -46,3 +51,11 @@ type QuotesStore interface {
|
||||
Create(ctx context.Context, quote *model.PaymentQuoteRecord) error
|
||||
GetByRef(ctx context.Context, orgRef primitive.ObjectID, quoteRef string) (*model.PaymentQuoteRecord, error)
|
||||
}
|
||||
|
||||
// RoutesStore manages allowed routing transitions.
|
||||
type RoutesStore interface {
|
||||
Create(ctx context.Context, route *model.PaymentRoute) error
|
||||
Update(ctx context.Context, route *model.PaymentRoute) error
|
||||
GetByID(ctx context.Context, id primitive.ObjectID) (*model.PaymentRoute, error)
|
||||
List(ctx context.Context, filter *model.PaymentRouteFilter) (*model.PaymentRouteList, error)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user