Files
sendico/api/gateway/mntx/internal/service/gateway/card_processor.go
2026-02-26 02:39:48 +01:00

609 lines
19 KiB
Go

package gateway
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"github.com/shopspring/decimal"
gatewayoutbox "github.com/tech/sendico/gateway/common/outbox"
"github.com/tech/sendico/gateway/mntx/internal/service/monetix"
"github.com/tech/sendico/gateway/mntx/storage"
"github.com/tech/sendico/gateway/mntx/storage/model"
clockpkg "github.com/tech/sendico/pkg/clock"
"github.com/tech/sendico/pkg/db/storable"
"github.com/tech/sendico/pkg/merrors"
msg "github.com/tech/sendico/pkg/messaging"
"github.com/tech/sendico/pkg/mlogger"
pmodel "github.com/tech/sendico/pkg/model"
gatewayv1 "github.com/tech/sendico/pkg/proto/common/gateway/v1"
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
"go.mongodb.org/mongo-driver/v2/bson"
"go.uber.org/zap"
)
type cardPayoutProcessor struct {
logger mlogger.Logger
config monetix.Config
clock clockpkg.Clock
store storage.Repository
httpClient *http.Client
producer msg.Producer
msgCfg pmodel.SettingsT
outbox *gatewayoutbox.ReliableRuntime
perTxMinAmountMinor int64
perTxMinAmountMinorByCurrency map[string]int64
}
func mergePayoutStateWithExisting(state, existing *model.CardPayout) {
if state == nil || existing == nil {
return
}
state.ID = existing.ID // preserve ID for upsert
if !existing.CreatedAt.IsZero() {
state.CreatedAt = existing.CreatedAt
}
if state.OperationRef == "" {
state.OperationRef = existing.OperationRef
}
if state.IdempotencyKey == "" {
state.IdempotencyKey = existing.IdempotencyKey
}
if state.IntentRef == "" {
state.IntentRef = existing.IntentRef
}
}
func (p *cardPayoutProcessor) findAndMergePayoutState(ctx context.Context, state *model.CardPayout) (*model.CardPayout, error) {
if p == nil || state == nil {
return nil, nil
}
existing, err := p.store.Payouts().FindByPaymentID(ctx, state.PaymentRef)
if err != nil {
return nil, err
}
mergePayoutStateWithExisting(state, existing)
return existing, nil
}
func (p *cardPayoutProcessor) resolveProjectID(requestProjectID int64, logFieldKey, logFieldValue string) (int64, error) {
projectID := requestProjectID
if projectID == 0 {
projectID = p.config.ProjectID
}
if projectID == 0 {
p.logger.Warn("Monetix project_id is not configured", zap.String(logFieldKey, logFieldValue))
return 0, merrors.Internal("mcards project_id is not configured")
}
return projectID, nil
}
func applyCardPayoutSendResult(state *model.CardPayout, result *monetix.CardPayoutSendResult) {
if state == nil || result == nil {
return
}
state.ProviderPaymentID = strings.TrimSpace(result.ProviderRequestID)
if result.Accepted {
state.Status = model.PayoutStatusWaiting
return
}
state.Status = model.PayoutStatusFailed
state.ProviderCode = strings.TrimSpace(result.ErrorCode)
state.ProviderMessage = strings.TrimSpace(result.ErrorMessage)
}
func payoutStateLogFields(state *model.CardPayout) []zap.Field {
if state == nil {
return nil
}
return []zap.Field{
zap.String("payment_ref", state.PaymentRef),
zap.String("customer_id", state.CustomerID),
zap.String("operation_ref", state.OperationRef),
zap.String("idempotency_key", state.IdempotencyKey),
zap.String("intent_ref", state.IntentRef),
}
}
func newCardPayoutProcessor(
logger mlogger.Logger,
cfg monetix.Config,
clock clockpkg.Clock,
store storage.Repository,
client *http.Client,
producer msg.Producer,
) *cardPayoutProcessor {
return &cardPayoutProcessor{
logger: logger.Named("card_payout_processor"),
config: cfg,
clock: clock,
store: store,
httpClient: client,
producer: producer,
}
}
func (p *cardPayoutProcessor) applyGatewayDescriptor(descriptor *gatewayv1.GatewayInstanceDescriptor) {
if p == nil {
return
}
minAmountMinor, perCurrency := perTxMinAmountPolicy(descriptor)
p.perTxMinAmountMinor = minAmountMinor
p.perTxMinAmountMinorByCurrency = perCurrency
}
func perTxMinAmountPolicy(descriptor *gatewayv1.GatewayInstanceDescriptor) (int64, map[string]int64) {
if descriptor == nil || descriptor.GetLimits() == nil {
return 0, nil
}
limits := descriptor.GetLimits()
globalMin, _ := decimalAmountToMinor(firstNonEmpty(limits.GetPerTxMinAmount(), limits.GetMinAmount()))
perCurrency := map[string]int64{}
for currency, override := range limits.GetCurrencyLimits() {
if override == nil {
continue
}
minor, ok := decimalAmountToMinor(override.GetMinAmount())
if !ok {
continue
}
code := strings.ToUpper(strings.TrimSpace(currency))
if code == "" {
continue
}
perCurrency[code] = minor
}
if len(perCurrency) == 0 {
perCurrency = nil
}
return globalMin, perCurrency
}
func decimalAmountToMinor(raw string) (int64, bool) {
raw = strings.TrimSpace(raw)
if raw == "" {
return 0, false
}
value, err := decimal.NewFromString(raw)
if err != nil || !value.IsPositive() {
return 0, false
}
minor := value.Mul(decimal.NewFromInt(100)).Ceil().IntPart()
if minor <= 0 {
return 0, false
}
return minor, true
}
func (p *cardPayoutProcessor) validatePerTxMinimum(amountMinor int64, currency string) error {
if p == nil {
return nil
}
minAmountMinor := p.perTxMinimum(currency)
if minAmountMinor <= 0 || amountMinor >= minAmountMinor {
return nil
}
return newPayoutError("amount_below_minimum", merrors.InvalidArgument(
fmt.Sprintf("amount_minor must be at least %d", minAmountMinor),
"amount_minor",
))
}
func (p *cardPayoutProcessor) perTxMinimum(currency string) int64 {
if p == nil {
return 0
}
minAmountMinor := p.perTxMinAmountMinor
if len(p.perTxMinAmountMinorByCurrency) == 0 {
return minAmountMinor
}
code := strings.ToUpper(strings.TrimSpace(currency))
if code == "" {
return minAmountMinor
}
if override, ok := p.perTxMinAmountMinorByCurrency[code]; ok && override > 0 {
return override
}
return minAmountMinor
}
func (p *cardPayoutProcessor) Submit(ctx context.Context, req *mntxv1.CardPayoutRequest) (*mntxv1.CardPayoutResponse, error) {
if p == nil {
return nil, merrors.Internal("card payout processor not initialised")
}
req = sanitizeCardPayoutRequest(req)
p.logger.Info("Submitting card payout",
zap.String("payout_id", strings.TrimSpace(req.GetPayoutId())),
zap.String("customer_id", strings.TrimSpace(req.GetCustomerId())),
zap.Int64("amount_minor", req.GetAmountMinor()),
zap.String("currency", strings.ToUpper(strings.TrimSpace(req.GetCurrency()))),
zap.String("operation_ref", strings.TrimSpace(req.GetOperationRef())),
zap.String("idempotency_key", strings.TrimSpace(req.GetIdempotencyKey())),
)
if strings.TrimSpace(p.config.BaseURL) == "" || strings.TrimSpace(p.config.SecretKey) == "" {
p.logger.Warn("Monetix configuration is incomplete for payout submission")
return nil, merrors.Internal("monetix configuration is incomplete")
}
if err := validateCardPayoutRequest(req, p.config); err != nil {
p.logger.Warn("Card payout validation failed",
zap.String("payout_id", req.GetPayoutId()),
zap.String("customer_id", req.GetCustomerId()),
zap.Error(err),
)
return nil, err
}
if err := p.validatePerTxMinimum(req.GetAmountMinor(), req.GetCurrency()); err != nil {
p.logger.Warn("Card payout amount below configured minimum",
zap.String("payout_id", req.GetPayoutId()),
zap.String("customer_id", req.GetCustomerId()),
zap.Int64("amount_minor", req.GetAmountMinor()),
zap.String("currency", strings.ToUpper(strings.TrimSpace(req.GetCurrency()))),
zap.Int64("configured_min_amount_minor", p.perTxMinimum(req.GetCurrency())),
zap.Error(err),
)
return nil, err
}
projectID, err := p.resolveProjectID(req.GetProjectId(), "payout_id", req.GetPayoutId())
if err != nil {
return nil, err
}
now := p.clock.Now()
state := &model.CardPayout{
Base: storable.Base{
ID: bson.NilObjectID,
},
PaymentRef: strings.TrimSpace(req.GetPayoutId()),
OperationRef: strings.TrimSpace(req.GetOperationRef()),
IdempotencyKey: strings.TrimSpace(req.GetIdempotencyKey()),
IntentRef: strings.TrimSpace(req.GetIntentRef()),
ProjectID: projectID,
CustomerID: strings.TrimSpace(req.GetCustomerId()),
AmountMinor: req.GetAmountMinor(),
Currency: strings.ToUpper(strings.TrimSpace(req.GetCurrency())),
Status: model.PayoutStatusWaiting,
CreatedAt: now,
UpdatedAt: now,
}
// Keep CreatedAt/refs if record already exists.
_, _ = p.findAndMergePayoutState(ctx, state)
client := monetix.NewClient(p.config, p.httpClient, p.logger)
apiReq := buildCardPayoutRequest(projectID, req)
result, err := client.CreateCardPayout(ctx, apiReq)
if err != nil {
state.Status = model.PayoutStatusFailed
state.ProviderMessage = err.Error()
state.UpdatedAt = p.clock.Now()
if e := p.updatePayoutStatus(ctx, state); e != nil {
fields := append([]zap.Field{zap.Error(e)}, payoutStateLogFields(state)...)
p.logger.Warn("Failed to update payout status", fields...)
}
fields := append([]zap.Field{zap.Error(err)}, payoutStateLogFields(state)...)
p.logger.Warn("Monetix payout submission failed", fields...)
return nil, err
}
// Provider request id is the provider-side payment id in your model.
applyCardPayoutSendResult(state, result)
state.UpdatedAt = p.clock.Now()
if err := p.updatePayoutStatus(ctx, state); err != nil {
p.logger.Warn("Failed to store payout",
zap.Error(err),
zap.String("payment_ref", state.PaymentRef),
zap.String("customer_id", state.CustomerID),
zap.String("operation_ref", state.OperationRef),
zap.String("idempotency_key", state.IdempotencyKey),
)
// do not fail request here: provider already answered and client expects response
}
resp := &mntxv1.CardPayoutResponse{
Payout: StateToProto(state),
Accepted: result.Accepted,
ProviderRequestId: result.ProviderRequestID,
ErrorCode: result.ErrorCode,
ErrorMessage: result.ErrorMessage,
}
p.logger.Info("Card payout submission stored",
zap.String("payment_ref", state.PaymentRef),
zap.String("status", string(state.Status)),
zap.Bool("accepted", result.Accepted),
zap.String("provider_request_id", result.ProviderRequestID),
)
return resp, nil
}
func (p *cardPayoutProcessor) SubmitToken(ctx context.Context, req *mntxv1.CardTokenPayoutRequest) (*mntxv1.CardTokenPayoutResponse, error) {
if p == nil {
return nil, merrors.Internal("card payout processor not initialised")
}
req = sanitizeCardTokenPayoutRequest(req)
p.logger.Info("Submitting card token payout",
zap.String("payout_id", strings.TrimSpace(req.GetPayoutId())),
zap.String("customer_id", strings.TrimSpace(req.GetCustomerId())),
zap.Int64("amount_minor", req.GetAmountMinor()),
zap.String("currency", strings.ToUpper(strings.TrimSpace(req.GetCurrency()))),
zap.String("operation_ref", strings.TrimSpace(req.GetOperationRef())),
zap.String("idempotency_key", strings.TrimSpace(req.GetIdempotencyKey())),
)
if strings.TrimSpace(p.config.BaseURL) == "" || strings.TrimSpace(p.config.SecretKey) == "" {
p.logger.Warn("Monetix configuration is incomplete for token payout submission")
return nil, merrors.Internal("monetix configuration is incomplete")
}
if err := validateCardTokenPayoutRequest(req, p.config); err != nil {
p.logger.Warn("Card token payout validation failed",
zap.String("payout_id", req.GetPayoutId()),
zap.String("customer_id", req.GetCustomerId()),
zap.Error(err),
)
return nil, err
}
if err := p.validatePerTxMinimum(req.GetAmountMinor(), req.GetCurrency()); err != nil {
p.logger.Warn("Card token payout amount below configured minimum",
zap.String("payout_id", req.GetPayoutId()),
zap.String("customer_id", req.GetCustomerId()),
zap.Int64("amount_minor", req.GetAmountMinor()),
zap.String("currency", strings.ToUpper(strings.TrimSpace(req.GetCurrency()))),
zap.Int64("configured_min_amount_minor", p.perTxMinimum(req.GetCurrency())),
zap.Error(err),
)
return nil, err
}
projectID, err := p.resolveProjectID(req.GetProjectId(), "payout_id", req.GetPayoutId())
if err != nil {
return nil, err
}
now := p.clock.Now()
state := &model.CardPayout{
PaymentRef: strings.TrimSpace(req.GetPayoutId()),
OperationRef: strings.TrimSpace(req.GetOperationRef()),
IdempotencyKey: strings.TrimSpace(req.GetIdempotencyKey()),
ProjectID: projectID,
CustomerID: strings.TrimSpace(req.GetCustomerId()),
AmountMinor: req.GetAmountMinor(),
Currency: strings.ToUpper(strings.TrimSpace(req.GetCurrency())),
Status: model.PayoutStatusWaiting,
CreatedAt: now,
UpdatedAt: now,
}
_, _ = p.findAndMergePayoutState(ctx, state)
client := monetix.NewClient(p.config, p.httpClient, p.logger)
apiReq := buildCardTokenPayoutRequest(projectID, req)
result, err := client.CreateCardTokenPayout(ctx, apiReq)
if err != nil {
state.Status = model.PayoutStatusFailed
state.ProviderMessage = err.Error()
state.UpdatedAt = p.clock.Now()
_ = p.updatePayoutStatus(ctx, state)
p.logger.Warn("Monetix token payout submission failed",
zap.String("payment_ref", state.PaymentRef),
zap.String("customer_id", state.CustomerID),
zap.Error(err),
)
return nil, err
}
applyCardPayoutSendResult(state, result)
state.UpdatedAt = p.clock.Now()
if err := p.updatePayoutStatus(ctx, state); err != nil {
p.logger.Warn("Failed to update payout status", zap.Error(err))
return nil, err
}
resp := &mntxv1.CardTokenPayoutResponse{
Payout: StateToProto(state),
Accepted: result.Accepted,
ProviderRequestId: result.ProviderRequestID,
ErrorCode: result.ErrorCode,
ErrorMessage: result.ErrorMessage,
}
p.logger.Info("Card token payout submission stored",
zap.String("payment_ref", state.PaymentRef),
zap.String("status", string(state.Status)),
zap.Bool("accepted", result.Accepted),
zap.String("provider_request_id", result.ProviderRequestID),
)
return resp, nil
}
func (p *cardPayoutProcessor) Tokenize(ctx context.Context, req *mntxv1.CardTokenizeRequest) (*mntxv1.CardTokenizeResponse, error) {
if p == nil {
return nil, merrors.Internal("card payout processor not initialised")
}
p.logger.Info("Submitting card tokenization",
zap.String("request_id", strings.TrimSpace(req.GetRequestId())),
zap.String("customer_id", strings.TrimSpace(req.GetCustomerId())),
)
cardInput, err := validateCardTokenizeRequest(req, p.config)
if err != nil {
p.logger.Warn("Card tokenization validation failed",
zap.String("request_id", req.GetRequestId()),
zap.String("customer_id", req.GetCustomerId()),
zap.Error(err),
)
return nil, err
}
projectID, err := p.resolveProjectID(req.GetProjectId(), "request_id", req.GetRequestId())
if err != nil {
return nil, err
}
req = sanitizeCardTokenizeRequest(req)
cardInput = extractTokenizeCard(req)
client := monetix.NewClient(p.config, p.httpClient, p.logger)
apiReq := buildCardTokenizeRequest(projectID, req, cardInput)
result, err := client.CreateCardTokenization(ctx, apiReq)
if err != nil {
p.logger.Warn("Monetix tokenization request failed",
zap.String("request_id", req.GetRequestId()),
zap.String("customer_id", req.GetCustomerId()),
zap.Error(err),
)
return nil, err
}
resp := &mntxv1.CardTokenizeResponse{
RequestId: req.GetRequestId(),
Success: result.Accepted,
ErrorCode: result.ErrorCode,
ErrorMessage: result.ErrorMessage,
}
resp.Token = result.Token
resp.MaskedPan = result.MaskedPAN
resp.ExpiryMonth = result.ExpiryMonth
resp.ExpiryYear = result.ExpiryYear
resp.CardBrand = result.CardBrand
p.logger.Info("Card tokenization completed",
zap.String("request_id", resp.GetRequestId()),
zap.Bool("success", resp.GetSuccess()),
zap.String("provider_request_id", result.ProviderRequestID),
)
return resp, nil
}
func (p *cardPayoutProcessor) Status(ctx context.Context, payoutID string) (*mntxv1.CardPayoutState, error) {
if p == nil {
return nil, merrors.Internal("card payout processor not initialised")
}
id := strings.TrimSpace(payoutID)
p.logger.Info("Card payout status requested", zap.String("payout_id", id))
if id == "" {
p.logger.Warn("Payout status requested with empty payout_id")
return nil, merrors.InvalidArgument("payout_id is required", "payout_id")
}
state, err := p.store.Payouts().FindByPaymentID(ctx, id)
if err != nil || state == nil {
p.logger.Warn("Payout status not found", zap.String("payout_id", id), zap.Error(err))
return nil, merrors.NoData("payout not found")
}
p.logger.Info("Card payout status resolved",
zap.String("payment_ref", state.PaymentRef),
zap.String("status", string(state.Status)),
)
return StateToProto(state), nil
}
func (p *cardPayoutProcessor) ProcessCallback(ctx context.Context, payload []byte) (int, error) {
if p == nil {
return http.StatusInternalServerError, merrors.Internal("card payout processor not initialised")
}
p.logger.Debug("Processing Monetix callback", zap.Int("payload_bytes", len(payload)))
if len(payload) == 0 {
p.logger.Warn("Received empty Monetix callback payload")
return http.StatusBadRequest, merrors.InvalidArgument("callback body is empty")
}
if strings.TrimSpace(p.config.SecretKey) == "" {
p.logger.Warn("Monetix secret key is not configured; cannot verify callback")
return http.StatusInternalServerError, merrors.Internal("monetix secret key is not configured")
}
var cb monetixCallback
if err := json.Unmarshal(payload, &cb); err != nil {
p.logger.Warn("Failed to unmarshal Monetix callback", zap.Error(err))
return http.StatusBadRequest, err
}
signature, err := verifyCallbackSignature(payload, p.config.SecretKey)
if err != nil {
status := http.StatusBadRequest
if errors.Is(err, merrors.ErrDataConflict) {
status = http.StatusForbidden
}
p.logger.Warn("Monetix callback signature check failed",
zap.String("payout_id", cb.Payment.ID),
zap.String("signature", signature),
zap.String("payload", string(payload)),
zap.Error(err),
)
return status, err
}
// mapCallbackToState currently returns proto-state in your code.
// Convert it to mongo model and preserve internal refs if record exists.
pbState, statusLabel := mapCallbackToState(p.clock, p.config, cb)
// Convert proto -> mongo (operationRef/idempotencyKey are internal; keep empty for now)
state := CardPayoutStateFromProto(p.clock, pbState)
// Preserve CreatedAt + internal keys from existing record if present.
existing, err := p.findAndMergePayoutState(ctx, state)
if err != nil {
p.logger.Warn("Failed to fetch payout state while processing callback",
zap.Error(err),
zap.String("payment_ref", state.PaymentRef),
)
return http.StatusInternalServerError, err
}
if existing != nil {
// keep failure reason if you want, or override depending on callback semantics
if state.FailureReason == "" {
state.FailureReason = existing.FailureReason
}
}
if err := p.updatePayoutStatus(ctx, state); err != nil {
p.logger.Warn("Failed to update payout state while processing callback", zap.Error(err))
}
monetix.ObserveCallback(statusLabel)
p.logger.Info("Monetix payout callback processed",
zap.String("payment_ref", state.PaymentRef),
zap.String("status", statusLabel),
zap.String("provider_code", state.ProviderCode),
zap.String("provider_message", state.ProviderMessage),
zap.String("masked_account", cb.Account.Number),
)
return http.StatusOK, nil
}