2021-02-05 12:19:05 +01:00
|
|
|
class BankAccountInformationImporter
|
|
|
|
def initialize(bank_account)
|
|
|
|
@bank_account = bank_account
|
|
|
|
end
|
|
|
|
|
|
|
|
def import!(content)
|
|
|
|
return nil if content.empty?
|
2021-03-01 15:27:26 +01:00
|
|
|
|
2022-05-27 19:52:56 +02:00
|
|
|
import_data! JSON.parse(content, symbolize_names: true)
|
|
|
|
end
|
2021-02-05 12:19:05 +01:00
|
|
|
|
2022-05-27 19:52:56 +02:00
|
|
|
def import_data!(data)
|
2021-02-05 12:19:05 +01:00
|
|
|
return 0 if data.empty?
|
2021-03-01 15:27:26 +01:00
|
|
|
|
2021-02-05 12:19:05 +01:00
|
|
|
booked = data.fetch(:transactions, {}).fetch(:booked, [])
|
|
|
|
|
|
|
|
ret = 0
|
|
|
|
booked.each do |t|
|
|
|
|
amount = parse_account_information_amount t[:transactionAmount]
|
|
|
|
entityName = amount < 0 ? t[:creditorName] : t[:debtorName]
|
|
|
|
entityAccount = amount < 0 ? t[:creditorAccount] : t[:debtorAccount]
|
2022-05-27 19:52:56 +02:00
|
|
|
reference = [t[:endToEndId], t[:remittanceInformationUnstructured]].join("\n").strip
|
2021-02-05 12:19:05 +01:00
|
|
|
|
|
|
|
@bank_account.bank_transactions.where(external_id: t[:transactionId]).first_or_create.update({
|
2021-03-01 15:27:26 +01:00
|
|
|
date: t[:bookingDate],
|
|
|
|
amount: amount,
|
|
|
|
iban: entityAccount && entityAccount[:iban],
|
2022-05-27 19:52:56 +02:00
|
|
|
reference: reference,
|
2021-03-01 15:27:26 +01:00
|
|
|
text: entityName,
|
2022-05-27 19:52:56 +02:00
|
|
|
receipt: t[:additionalInformation]
|
2021-03-01 15:27:26 +01:00
|
|
|
})
|
2021-02-05 12:19:05 +01:00
|
|
|
ret += 1
|
|
|
|
end
|
|
|
|
|
2022-05-27 19:52:56 +02:00
|
|
|
balances = (data[:balances] ? data[:balances].map { |b| [b[:balanceType], b[:balanceAmount]] } : []).to_h
|
2021-02-05 12:19:05 +01:00
|
|
|
balance = balances.values.first
|
|
|
|
%w(closingBooked expected authorised openingBooked interimAvailable forwardAvailable nonInvoiced).each do |type|
|
|
|
|
value = balances[type]
|
2022-05-27 19:52:56 +02:00
|
|
|
if value
|
2021-02-05 12:19:05 +01:00
|
|
|
balance = value
|
|
|
|
break
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
@bank_account.balance = parse_account_information_amount(balance) || @bank_account.bank_transactions.sum(:amount)
|
2022-05-27 19:52:56 +02:00
|
|
|
@bank_account.import_continuation_point = booked.first&.fetch(:entryReference, nil) unless booked.empty?
|
2021-02-05 12:19:05 +01:00
|
|
|
@bank_account.last_import = Time.now
|
|
|
|
@bank_account.save!
|
|
|
|
|
|
|
|
ret
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def parse_account_information_amount(value)
|
|
|
|
value && value[:amount].to_f
|
|
|
|
end
|
|
|
|
end
|