Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(monobank): currencyCode is the operation currency, not the account's (#3495)

Yaroslav Shparuk5e578f6e33c2
diff --git a/app/models/monobank_entry/processor.rb b/app/models/monobank_entry/processor.rb
index 5816e2cb5f..9fce7916aa 100644
--- a/app/models/monobank_entry/processor.rb
+++ b/app/models/monobank_entry/processor.rb
@@ -148,13 +148,16 @@ class MonobankEntry::Processor
-(minor_units(data[:amount]) / account_minor_unit_divisor)
end
- # Entries are recorded in the account currency, which is what `amount` is expressed
- # in. Monobank's `currencyCode` on a statement item is documented as the *account*
- # currency ("Код валюти рахунку"), so it is preferred here and the stored account
- # currency is the fallback.
+ # Entries are recorded in the account currency, which is what `amount` is expressed in.
+ #
+ # `currencyCode` is NOT the account currency: it varies between items on a single
+ # account, and the account's own currency cannot. Transferring UAH from a hryvnia card
+ # to fund a euro one reports 978 on the hryvnia card's item, while `amount` on that
+ # same item stays in UAH. Pairing the two labelled an account-currency figure with a
+ # foreign code, so 500 UAH was stored as 500 EUR. The operation currency is recorded
+ # as `fx_from` instead.
def currency
- parse_currency(alpha_currency_code(data[:currencyCode])) ||
- parse_currency(monobank_account.currency) ||
+ parse_currency(monobank_account.currency) ||
account&.currency ||
"UAH"
end
@@ -205,6 +208,8 @@ class MonobankEntry::Processor
"commission_amount" => major_amount(data[:commissionRate]),
"balance_after" => major_amount(data[:balance]),
"operation_amount" => foreign_operation_amount,
+ "fx_from" => fx_from,
+ "fx_amount" => fx_amount,
"counter_name" => data[:counterName],
"counter_iban" => data[:counterIban],
"counter_edrpou" => data[:counterEdrpou],
@@ -219,12 +224,9 @@ class MonobankEntry::Processor
self.class.pending?(data)
end
- # Monobank's `operationAmount` is the amount in the currency the transaction was
- # actually made in, but the statement never reports *which* currency that was — only
- # the account currency is given. So an FX purchase can be detected (the two amounts
- # differ) without being described: the raw operation amount is recorded for
- # reference and Sure's fx_from/fx_amount convention is deliberately left unset
- # rather than filled in with a guessed currency.
+ # `operationAmount` is the amount in the currency the operation was actually made in,
+ # which `currencyCode` names. Kept in raw minor units for reference — `fx_amount`
+ # carries the same figure in major units once the currency resolves.
def foreign_operation_amount
operation_amount = data[:operationAmount]
return nil if operation_amount.blank?
@@ -233,6 +235,67 @@ class MonobankEntry::Processor
operation_amount
end
+ # The currency the operation was made in, per `currencyCode`.
+ def operation_currency
+ return @operation_currency if defined?(@operation_currency)
+
+ @operation_currency = parse_currency(alpha_currency_code(data[:currencyCode]))
+ end
+
+ # True for an operation in a currency other than the account's, which is what makes
+ # `operationAmount` worth recording separately from `amount`.
+ def foreign_operation?
+ operation_currency.present? && operation_currency != currency
+ end
+
+ # fx_from/fx_amount follow the convention UpEntry::Processor uses: the currency the
+ # operation was made in, and the amount expressed in that currency.
+ #
+ # Both are set only for a *recognized foreign* operation — one whose `currencyCode`
+ # maps to a known currency that differs from the account's. `fx_amount` additionally
+ # needs an `operationAmount` that is present and parseable. An operation in the
+ # account's own currency, or one whose code Sure does not know, leaves both unset while
+ # `operation_amount` still carries the raw figure whenever it differs from `amount`.
+ def fx_from
+ operation_currency if foreign_operation?
+ end
+
+ def fx_amount
+ return nil unless foreign_operation?
+
+ value = data[:operationAmount]
+ return nil if value.blank?
+
+ divisor = BigDecimal(minor_unit_divisor(operation_currency).to_s)
+ (minor_units(value) / divisor).to_s("F")
+ rescue ArgumentError
+ report_unparseable_operation_amount(value)
+ nil
+ end
+
+ # A foreign operation whose amount will not parse leaves partial FX metadata behind:
+ # `fx_from` names a currency that no `fx_amount` accompanies. `minor_units` only writes
+ # to the Rails log, which support cannot see, so record the incident where provider
+ # diagnostics are surfaced.
+ def report_unparseable_operation_amount(value)
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "Monobank operationAmount could not be parsed; fx_amount left unset",
+ source: self.class.name,
+ provider_key: "monobank",
+ family: account&.family,
+ account: account,
+ account_provider: monobank_account.account_provider,
+ metadata: {
+ external_id: external_id,
+ operation_currency: operation_currency,
+ operation_amount: value.to_s,
+ monobank_account_id: monobank_account.id
+ }
+ )
+ end
+
# Minor units of the account currency per major unit (100 for UAH).
def account_minor_unit_divisor
@account_minor_unit_divisor ||= BigDecimal(minor_unit_divisor(monobank_account.currency).to_s)
diff --git a/docs/llm-guides/providers.md b/docs/llm-guides/providers.md
index 52b46dcef4..1b5fe566d9 100644
--- a/docs/llm-guides/providers.md
+++ b/docs/llm-guides/providers.md
@@ -33,7 +33,7 @@ metadata produces no badge; manual/CSV imports have no pending concept.
| SimpleFIN | [`SimplefinEntry::Processor.pending?`](../../app/models/simplefin_entry/processor.rb) accepts an explicitly truthy `pending` flag, or `posted` equal to numeric `0` or string `"0"` with a present, positive `transacted_at` timestamp. A blank/missing `posted` value does **not** imply pending. Writes `extra["simplefin"]["pending"]` as true or false so a posted update clears stale pending metadata. |
| Plaid | [`PlaidEntry::Processor`](../../app/models/plaid_entry/processor.rb) stores bank/credit transaction `pending` and `pending_transaction_id` under `extra["plaid"]`; the linking ID supports pending-to-posted reconciliation. The investment transaction processor does not store pending metadata. |
| Lunchflow | [`LunchflowEntry::Processor`](../../app/models/lunchflow_entry/processor.rb) stores the boolean-cast `isPending` value under `extra["lunchflow"]["pending"]` when the upstream key is present. |
-| Monobank | [`MonobankEntry::Processor`](../../app/models/monobank_entry/processor.rb) treats a `hold: true` statement item as pending and writes `extra["monobank"]["pending"]`. Monobank may settle a hold under a *different* id, so the settled record reconciles onto the pending entry through [`Account::ProviderImportAdapter`](../../app/models/account/provider_import_adapter.rb)'s amount/date lookup. A hold that simply disappears is pruned, but only when the statement request actually covered its date range, and never when the entry is `protected_from_sync?` — those only lose the pending flag. No FX metadata: the statement reports `operationAmount` without the operation currency, so `operation_amount` is stored raw and `fx_from`/`fx_amount` are left unset. |
+| Monobank | [`MonobankEntry::Processor`](../../app/models/monobank_entry/processor.rb) treats a `hold: true` statement item as pending and writes `extra["monobank"]["pending"]`. Monobank may settle a hold under a *different* id, so the settled record reconciles onto the pending entry through [`Account::ProviderImportAdapter`](../../app/models/account/provider_import_adapter.rb)'s amount/date lookup. A hold that simply disappears is pruned, but only when the statement request actually covered its date range, and never when the entry is `protected_from_sync?` — those only lose the pending flag. `currencyCode` on a statement item is the **operation** currency, not the account's — it varies between items on one account — so entries take their currency from `MonobankAccount#currency` and `currencyCode`/`operationAmount` populate `fx_from`/`fx_amount`. Those two are emitted only for a recognized foreign operation — a known `currencyCode` differing from the account currency, and for `fx_amount` a parseable `operationAmount`, whose failure is captured as a `provider_sync_error`. Independently of that, `operation_amount` keeps the raw minor-unit figure whenever it differs from `amount`. |
SimpleFIN additionally stores `extra["simplefin"]["fx_from"]` when transaction and
account currencies differ, and `fx_date` from the transacted date with posted-date
diff --git a/test/models/monobank_entry/processor_test.rb b/test/models/monobank_entry/processor_test.rb
index b91b8add35..8c5ca0438c 100644
--- a/test/models/monobank_entry/processor_test.rb
+++ b/test/models/monobank_entry/processor_test.rb
@@ -74,14 +74,68 @@ class MonobankEntry::ProcessorTest < ActiveSupport::TestCase
assert_equal true, entry.entryable.extra.dig("monobank", "pending")
end
- # The operation currency is not reported by Monobank, so only the raw operation amount
- # is recorded — fx_from/fx_amount are deliberately left unset.
- test "records the operation amount for a foreign-currency purchase" do
- entry = process(id: "tx_fx", time: MIDDAY_UNIX, description: "Steam", amount: -41_500, operationAmount: -1_000, currencyCode: 980, hold: false)
+ test "records the operation currency and amount for a foreign-currency purchase" do
+ # A UAH card paying in EUR: `amount` is the UAH charge, `operationAmount` the EUR
+ # figure, and `currencyCode` names the euro — not the account's hryvnia.
+ entry = process(id: "tx_fx", time: MIDDAY_UNIX, description: "Steam", amount: -41_500, operationAmount: -1_000, currencyCode: 978, hold: false)
+
+ assert_equal "UAH", entry.currency, "the entry stays in the account currency"
+ assert_equal BigDecimal("415"), entry.amount
extra = entry.entryable.extra["monobank"]
assert_equal(-1_000, extra["operation_amount"])
+ assert_equal "EUR", extra["fx_from"]
+ assert_equal "-10.0", extra["fx_amount"]
+ end
+
+ test "does not treat an account-currency operation as foreign" do
+ entry = process(id: "tx_local", time: MIDDAY_UNIX, description: "Silpo", amount: -41_500, operationAmount: -41_500, currencyCode: 980, hold: false)
+
+ extra = entry.entryable.extra["monobank"]
+ assert_equal "UAH", entry.currency
+ assert_nil extra["fx_from"]
+ assert_nil extra["fx_amount"]
+ assert_nil extra["operation_amount"]
+ end
+
+ test "keeps the account currency when currencyCode names another one" do
+ # The regression this replaces: 500 UAH leaving a hryvnia card to fund a euro card
+ # was stored as 500 EUR, because `currencyCode` reports the operation currency.
+ entry = process(id: "tx_transfer", time: MIDDAY_UNIX, description: "Card transfer", amount: -50_000, operationAmount: -960, currencyCode: 978, hold: false)
+
+ assert_equal "UAH", entry.currency
+ assert_equal BigDecimal("500"), entry.amount
+ assert_equal "EUR", entry.entryable.extra.dig("monobank", "fx_from")
+ assert_equal "-9.6", entry.entryable.extra.dig("monobank", "fx_amount")
+ end
+
+ test "captures a diagnostic when a foreign operation amount will not parse" do
+ entry = nil
+
+ assert_difference "DebugLogEntry.count", 1 do
+ entry = process(id: "tx_bad_op", time: MIDDAY_UNIX, description: "Steam", amount: -41_500, operationAmount: "not-a-number", currencyCode: 978, hold: false)
+ end
+
+ extra = entry.entryable.extra["monobank"]
+ assert_equal "EUR", extra["fx_from"], "the currency is still known"
+ assert_nil extra["fx_amount"]
+
+ log = DebugLogEntry.order(:created_at).last
+ assert_equal "provider_sync_error", log.category
+ assert_equal "warn", log.level
+ assert_equal "monobank", log.provider_key
+ assert_equal "monobank_tx_bad_op", log.metadata["external_id"]
+ assert_equal "EUR", log.metadata["operation_currency"]
+ end
+
+ test "leaves fx metadata unset when currencyCode is unrecognized" do
+ entry = process(id: "tx_bad_cur", time: MIDDAY_UNIX, description: "Unknown", amount: -1_000, operationAmount: -500, currencyCode: 1, hold: false)
+
+ extra = entry.entryable.extra["monobank"]
+ assert_equal "UAH", entry.currency
assert_nil extra["fx_from"]
+ assert_nil extra["fx_amount"]
+ assert_equal(-500, extra["operation_amount"], "the raw figure is still kept for reference")
end
test "stores counterparty details for business account transfers" do