Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions internal/connectors/plugins/public/increase/payments.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package increase
import (
"context"
"encoding/json"
"math"
"math/big"
"sort"
"time"
Expand Down Expand Up @@ -212,7 +211,7 @@ func (p *Plugin) mapPayment(transaction *client.Transaction, status models.Payme
CreatedAt: createdTime,
Asset: *pointer.For(currency.FormatAsset(supportedCurrenciesWithDecimal, transaction.Currency)),
Status: paymentStatus,
Amount: big.NewInt(int64(math.Abs(float64(transaction.Amount)))),
Amount: new(big.Int).Abs(big.NewInt(transaction.Amount)),
Type: mapTransactionType(transaction),
Raw: raw,
Metadata: map[string]string{
Expand Down
44 changes: 44 additions & 0 deletions internal/connectors/plugins/public/increase/payments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"math/big"
"time"

"github.com/formancehq/payments/internal/connectors/plugins/public/increase/client"
Expand Down Expand Up @@ -628,3 +629,46 @@ var _ = Describe("Increase Plugin Payments", func() {
})
})
})

var _ = Describe("Increase Plugin Payments - amount conversion", func() {
var plg *Plugin

BeforeEach(func() {
plg = &Plugin{}
})

// Regression for M-CON5: amounts must be converted via big.Int, never round-tripped
// through float64 (which loses precision above 2^53 and overflows on MinInt64).
It("preserves amounts larger than 2^53 exactly", func() {
const amount int64 = 9007199254740993 // 2^53 + 1, not representable as float64
tx := &client.Transaction{
ID: "big",
AccountID: "account_1",
Amount: amount,
CreatedAt: time.Now().UTC().Format(time.RFC3339),
Currency: "USD",
Source: client.Source{Category: "inbound_ach_transfer"},
}

payment, err := plg.mapPayment(tx, models.PAYMENT_STATUS_SUCCEEDED)
Expect(err).To(BeNil())
Expect(payment.Amount.Cmp(big.NewInt(amount))).To(Equal(0))
})

It("returns the exact absolute value of large negative amounts", func() {
const amount int64 = -9007199254740993
tx := &client.Transaction{
ID: "big_neg",
AccountID: "account_1",
Amount: amount,
CreatedAt: time.Now().UTC().Format(time.RFC3339),
Currency: "USD",
Source: client.Source{Category: "inbound_ach_transfer"},
}

payment, err := plg.mapPayment(tx, models.PAYMENT_STATUS_SUCCEEDED)
Expect(err).To(BeNil())
Expect(payment.Amount.Cmp(big.NewInt(9007199254740993))).To(Equal(0))
Expect(payment.Amount.Sign()).To(Equal(1))
})
})
7 changes: 7 additions & 0 deletions internal/connectors/plugins/public/moneycorp/balances.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package moneycorp
import (
"context"
"encoding/json"
"errors"
"time"

"github.com/formancehq/go-libs/v5/pkg/types/currency"
Expand All @@ -27,6 +28,12 @@ func (p *Plugin) fetchNextBalances(ctx context.Context, req models.FetchNextBala
for _, balance := range balances {
precision, err := currency.GetPrecision(supportedCurrenciesWithDecimal, balance.Attributes.CurrencyCode)
if err != nil {
if errors.Is(err, currency.ErrMissingCurrencies) {
// Skip unsupported currencies rather than failing: a retryable
// error here would freeze balance ingestion for the account.
p.logger.WithField("currency", balance.Attributes.CurrencyCode).Info("skipping balance with unsupported currency")
continue
}
return models.FetchNextBalancesResponse{}, err
}

Expand Down
25 changes: 24 additions & 1 deletion internal/connectors/plugins/public/moneycorp/balances_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"math/big"
"strings"

"github.com/formancehq/go-libs/v5/pkg/observe/log"
"github.com/formancehq/payments/internal/connectors/plugins/public/moneycorp/client"
"github.com/formancehq/payments/pkg/domain/models"
. "github.com/onsi/ginkgo/v2"
Expand All @@ -31,7 +32,7 @@ var _ = Describe("Moneycorp *Plugin Balances", func() {
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
m = client.NewMockClient(ctrl)
plg = &Plugin{client: m}
plg = &Plugin{client: m, logger: logging.NewDefaultLogger(GinkgoWriter, true, false, false)}

accRef = "abc"
expectedAmount = big.NewInt(309900)
Expand Down Expand Up @@ -64,5 +65,27 @@ var _ = Describe("Moneycorp *Plugin Balances", func() {
Expect(res.Balances[0].Amount).To(BeEquivalentTo(expectedAmount))
Expect(res.Balances[0].Asset).To(HavePrefix(strings.ToUpper(sampleBalance.Attributes.CurrencyCode)))
})

It("skips balances with unsupported currencies", func(ctx SpecContext) {
req := models.FetchNextBalancesRequest{
FromPayload: json.RawMessage(fmt.Sprintf(`{"reference": "%s"}`, accRef)),
State: json.RawMessage(`{}`),
}
unsupported := &client.Balance{
Attributes: client.Attributes{
CurrencyCode: "ZZZ",
AvailableBalance: json.Number("100"),
},
}
m.EXPECT().GetAccountBalances(gomock.Any(), accRef).Return(
[]*client.Balance{unsupported, sampleBalance},
nil,
)
res, err := plg.FetchNextBalances(ctx, req)
Expect(err).To(BeNil())
// Only the supported balance is returned; the unsupported one is skipped.
Expect(res.Balances).To(HaveLen(1))
Expect(res.Balances[0].Asset).To(HavePrefix(strings.ToUpper(sampleBalance.Attributes.CurrencyCode)))
})
})
})
13 changes: 12 additions & 1 deletion internal/connectors/plugins/public/moneycorp/payments.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@ package moneycorp
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"time"

"github.com/formancehq/go-libs/v5/pkg/types/pointer"
"github.com/formancehq/go-libs/v5/pkg/types/currency"
"github.com/formancehq/go-libs/v5/pkg/types/pointer"
"github.com/formancehq/payments/internal/connectors/plugins/public/moneycorp/client"
"github.com/formancehq/payments/pkg/domain/models"
"github.com/formancehq/payments/pkg/domain/pagination"
"github.com/formancehq/payments/pkg/domain/plugins"
)

type paymentsState struct {
Expand Down Expand Up @@ -98,6 +100,12 @@ func (p *Plugin) toPSPPayments(

payment, err := p.transactionToPayment(ctx, transaction)
if err != nil {
if errors.Is(err, plugins.ErrCurrencyNotSupported) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 [major] Wrap unsupported currencies from Moneycorp transfer payments

When a Moneycorp transaction is a debit Transfer, transactionToPayment returns through fetchAndTranslateTransfer, whose transferToPayment still returns the bare currency.ErrMissingCurrencies for an unsupported TransferCurrency. This new skip branch only catches plugins.ErrCurrencyNotSupported, so those transfer rows still fail FetchNextPayments and keep retrying instead of being skipped.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 [major] Transfer path does not normalize unsupported-currency errors to plugins.ErrCurrencyNotSupported
reported by NumaryBot, coderabbitai

When a Moneycorp transaction is a debit Transfer, transactionToPayment delegates to fetchAndTranslateTransfer, which calls currency.GetPrecision in transfers.go. Unlike the payment path, this helper returns the raw currency.ErrMissingCurrencies without wrapping it into plugins.ErrCurrencyNotSupported. The new skip branch at line 103–108 only catches plugins.ErrCurrencyNotSupported, so Transfer rows with unsupported currencies still cause FetchNextPayments to fail and retry instead of being silently skipped.

Suggestion: In the transfer path (e.g., transferToPayment or its call site), wrap currency.ErrMissingCurrencies into plugins.ErrCurrencyNotSupported (using errors.Is/fmt.Errorf with the appropriate sentinel), so the skip branch at the payments level catches all unsupported-currency cases uniformly regardless of transaction type.

// Skip unsupported currencies rather than failing: a retryable
// error here would freeze ingestion for the whole account.
p.logger.WithField("transaction_id", transaction.ID).Info("skipping transaction with unsupported currency")
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 [major] Pagination watermark not advanced when all new rows are skipped due to unsupported currency

When the only new Moneycorp transactions (or the newest tail) all have unsupported currencies, the continue drops them from the returned payments slice. The caller advances LastCreatedAt based on payments[len(payments)-1], so the watermark remains unchanged. On the next poll, the same skipped rows are refetched and logged again, creating a permanent polling loop rather than truly skipping past those rows.

Suggestion: Track the timestamp/ID of the last-seen row (supported or not) separately from the list of returned payments, and always advance the watermark to the latest processed row even when all are skipped due to unsupported currencies.

}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return payments, err
}
if payment == nil {
Expand Down Expand Up @@ -138,6 +146,9 @@ func (p *Plugin) transactionToPayment(ctx context.Context, transaction *client.T

c, err := currency.GetPrecision(supportedCurrenciesWithDecimal, transaction.Attributes.Currency)
if err != nil {
if errors.Is(err, currency.ErrMissingCurrencies) {
return nil, fmt.Errorf("%w: %w", plugins.ErrCurrencyNotSupported, err)
}
return nil, err
}

Expand Down
60 changes: 55 additions & 5 deletions internal/connectors/plugins/public/moneycorp/payments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"strings"
"time"

"github.com/formancehq/go-libs/v5/pkg/types/currency"
"github.com/formancehq/go-libs/v5/pkg/observe/log"
"github.com/formancehq/payments/internal/connectors/plugins/public/moneycorp/client"
"github.com/formancehq/payments/pkg/domain/models"
. "github.com/onsi/ginkgo/v2"
Expand All @@ -35,7 +35,7 @@ var _ = Describe("Moneycorp *Plugin Payments - check types and minor conversion"
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
m = client.NewMockClient(ctrl)
plg = &Plugin{client: m}
plg = &Plugin{client: m, logger: logging.NewDefaultLogger(GinkgoWriter, true, false, false)}

pageSize = 5
accRef = 3796
Expand Down Expand Up @@ -136,7 +136,7 @@ var _ = Describe("Moneycorp *Plugin Payments - check types and minor conversion"
ctrl.Finish()
})

It("fails when payments contain unsupported currencies", func(ctx SpecContext) {
It("skips payments with unsupported currencies", func(ctx SpecContext) {
req := models.FetchNextPaymentsRequest{
FromPayload: json.RawMessage(fmt.Sprintf(`{"reference": "%d"}`, accRef)),
State: json.RawMessage(`{}`),
Expand All @@ -160,7 +160,8 @@ var _ = Describe("Moneycorp *Plugin Payments - check types and minor conversion"
)

res, err := plg.FetchNextPayments(ctx, req)
Expect(err).To(MatchError(currency.ErrMissingCurrencies))
Expect(err).To(BeNil())
Expect(res.Payments).To(BeEmpty())
Expect(res.HasMore).To(BeFalse())
})

Expand Down Expand Up @@ -218,6 +219,55 @@ var _ = Describe("Moneycorp *Plugin Payments - check types and minor conversion"
Expect(res.Payments[4].Amount).To(Equal(big.NewInt(expectedAmount * 100))) // after conversion to minors

})

It("skips transfer payments with unsupported currency", func(ctx SpecContext) {
req := models.FetchNextPaymentsRequest{
FromPayload: json.RawMessage(fmt.Sprintf(`{"reference": "%d"}`, accRef)),
State: json.RawMessage(`{}`),
PageSize: pageSize,
}

unsupportedTransfer := &client.TransferResponse{
ID: "transfer-zzz",
Attributes: client.TransferAttributes{
SendingAccountID: 1234,
ReceivingAccountID: 4321,
CreatedAt: strings.TrimSuffix(time.Now().UTC().Format(time.RFC3339Nano), "Z"),
TransferAmount: json.Number("65"),
TransferCurrency: "ZZZ", // unsupported
TransferStatus: "Cleared",
},
}
txns := []*client.Transaction{
{
ID: "transfer-unsupported",
Attributes: client.TransactionAttributes{
AccountID: accRef,
Type: "Transfer",
Direction: "Debit",
Currency: "EUR",
Amount: json.Number("65"),
CreatedAt: strings.TrimSuffix(time.Now().UTC().Format(time.RFC3339Nano), "Z"),
},
Relationships: client.RelationShips{
Data: client.Data{ID: unsupportedTransfer.ID},
},
},
}

m.EXPECT().GetTransactions(gomock.Any(), "3796", gomock.Any(), pageSize, gomock.Any()).Return(
txns,
nil,
)
m.EXPECT().GetTransfer(gomock.Any(), "3796", unsupportedTransfer.ID).Return(
unsupportedTransfer,
nil,
)

res, err := plg.FetchNextPayments(ctx, req)
Expect(err).To(BeNil())
Expect(res.Payments).To(BeEmpty())
})
})
})

Expand All @@ -239,7 +289,7 @@ var _ = Describe("Moneycorp *Plugin Payments - check pagination", func() {
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
m = client.NewMockClient(ctrl)
plg = &Plugin{client: m}
plg = &Plugin{client: m, logger: logging.NewDefaultLogger(GinkgoWriter, true, false, false)}
accRef = 3796
now = time.Now().UTC()

Expand Down
12 changes: 10 additions & 2 deletions internal/connectors/plugins/public/moneycorp/transfers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ package moneycorp
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"

"github.com/formancehq/go-libs/v5/pkg/types/pointer"
"github.com/formancehq/go-libs/v5/pkg/types/currency"
"github.com/formancehq/go-libs/v5/pkg/types/pointer"
"github.com/formancehq/payments/internal/connectors/plugins/public/moneycorp/client"
"github.com/formancehq/payments/pkg/domain/models"
errorsutils "github.com/formancehq/payments/pkg/domain/errors"
"github.com/formancehq/payments/pkg/domain/models"
"github.com/formancehq/payments/pkg/domain/plugins"
)

func (p *Plugin) createTransfer(ctx context.Context, pi models.PSPPaymentInitiation) (*models.PSPPayment, error) {
Expand Down Expand Up @@ -73,6 +75,12 @@ func transferToPayment(transfer *client.TransferResponse) (*models.PSPPayment, e

c, err := currency.GetPrecision(supportedCurrenciesWithDecimal, transfer.Attributes.TransferCurrency)
if err != nil {
if errors.Is(err, currency.ErrMissingCurrencies) {
// Wrap so the fetch loop (toPSPPayments) skips the transfer instead of
// freezing ingestion. transferToPayment is on the fetch path via
// fetchAndTranslateTransfer, not only the create path.
return nil, fmt.Errorf("%w: %w", plugins.ErrCurrencyNotSupported, err)
}
return nil, err
}

Expand Down
8 changes: 8 additions & 0 deletions internal/connectors/plugins/public/plaid/balances.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package plaid
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"

"github.com/formancehq/payments/internal/connectors/plugins/public/plaid/client"
"github.com/formancehq/payments/pkg/domain/models"
"github.com/formancehq/payments/pkg/domain/plugins"
"github.com/plaid/plaid-go/v34/plaid"
)

Expand All @@ -19,6 +21,12 @@ func (p *Plugin) fetchNextBalances(ctx context.Context, req models.FetchNextBala

pspBalance, err := toPSPBalance(pspAccount)
if err != nil {
if errors.Is(err, plugins.ErrCurrencyNotSupported) {
// Skip unsupported currencies rather than failing: a retryable
// error here would freeze balance ingestion for the account.
p.logger.WithField("reference", pspAccount.Reference).Info("skipping balance with unsupported currency")
return models.FetchNextBalancesResponse{}, nil
}
return models.FetchNextBalancesResponse{}, err
}

Expand Down
25 changes: 24 additions & 1 deletion internal/connectors/plugins/public/plaid/balances_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"math/big"
"time"

"github.com/formancehq/go-libs/v5/pkg/observe/log"
"github.com/formancehq/payments/pkg/domain/models"
"github.com/google/uuid"
. "github.com/onsi/ginkgo/v2"
Expand All @@ -19,7 +20,29 @@ var _ = Describe("Plaid *Plugin Balances", func() {
)

BeforeEach(func() {
plg = &Plugin{}
plg = &Plugin{logger: logging.NewDefaultLogger(GinkgoWriter, true, false, false)}
})

It("should skip balances with unsupported currencies", func(ctx SpecContext) {
account := plaid.NewAccountBaseWithDefaults()
account.SetAccountId("acc")

balance := plaid.NewAccountBalanceWithDefaults()
balance.SetCurrent(1000.0)
balance.SetIsoCurrencyCode("ZZZ")
account.SetBalances(*balance)

accountBytes, err := json.Marshal(account)
Expect(err).To(BeNil())

pspAccount := models.PSPAccount{Raw: accountBytes}
fromPayload, err := json.Marshal(pspAccount)
Expect(err).To(BeNil())

p := &Plugin{logger: logging.NewDefaultLogger(GinkgoWriter, true, false, false)}
res, err := p.fetchNextBalances(ctx, models.FetchNextBalancesRequest{FromPayload: fromPayload})
Expect(err).To(BeNil())
Expect(res.Balances).To(BeEmpty())
})

It("should fetch balances successfully", func(ctx SpecContext) {
Expand Down
Loading
Loading