bdgtr-cli 0.1.0 → 0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +3 -3
  3. data/bin/bdgtr +26 -10
  4. data/data/bdgtr.sqlite +0 -0
  5. data/lib/bdgtr/cli/config.rb +188 -0
  6. data/lib/bdgtr/cli/config.sample.yml +15 -0
  7. data/lib/bdgtr/cli/gem_home.rb +0 -25
  8. data/lib/bdgtr/cli/help.rb +168 -0
  9. data/lib/bdgtr/cli/ledger_sync.rb +102 -0
  10. data/lib/bdgtr/cli/prompt.rb +47 -0
  11. data/lib/bdgtr/cli/psd2.rb +530 -0
  12. data/lib/bdgtr/cli/rows.rb +38 -0
  13. data/lib/bdgtr/cli/runtime.rb +88 -0
  14. data/lib/bdgtr/cli/table.rb +458 -0
  15. data/lib/bdgtr/cli.rb +126 -0
  16. data/lib/bdgtr/core/binder.rb +79 -0
  17. data/lib/bdgtr/core/exchange.rb +66 -0
  18. data/lib/bdgtr/core/models/account.rb +177 -0
  19. data/lib/bdgtr/core/models/account_requisition.rb +12 -0
  20. data/lib/bdgtr/core/models/account_sync.rb +12 -0
  21. data/lib/bdgtr/core/models/import.rb +12 -0
  22. data/lib/bdgtr/core/models/ledger.rb +10 -0
  23. data/lib/bdgtr/core/models/requisition.rb +27 -0
  24. data/lib/bdgtr/core/models/transaction.rb +98 -0
  25. data/lib/bdgtr/core/models/transaction_category.rb +12 -0
  26. data/lib/bdgtr/core/record.rb +11 -0
  27. data/lib/bdgtr/core/schema.rb +290 -0
  28. data/lib/bdgtr/core/session.rb +76 -0
  29. data/lib/bdgtr/core/syncable.rb +272 -0
  30. data/lib/bdgtr/core/transfer.rb +90 -0
  31. data/lib/bdgtr/core.rb +18 -0
  32. data/lib/bdgtr/portfolio/Rakefile +20 -0
  33. data/lib/bdgtr/portfolio/cli/LICENSE +21 -0
  34. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/app.rb +77 -0
  35. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/import.rb +30 -0
  36. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/spreadsheet.rb +25 -0
  37. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli.rb +52 -0
  38. data/lib/bdgtr/portfolio/exe/bdgtr +7 -0
  39. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/accounts_csv.rb +67 -0
  40. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/app.rb +104 -0
  41. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/auth.rb +52 -0
  42. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/balances.rb +157 -0
  43. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/cache.rb +46 -0
  44. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/checkbox_menu.rb +90 -0
  45. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/checkbox_selection.rb +68 -0
  46. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/config.rb +138 -0
  47. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/decryptor.rb +70 -0
  48. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/drive_client.rb +182 -0
  49. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/errors.rb +10 -0
  50. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/file_reader.rb +80 -0
  51. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/fineco_import.rb +609 -0
  52. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/fineco_xls.rb +235 -0
  53. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/import/fineco.rb +243 -0
  54. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/import.rb +85 -0
  55. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/parser.rb +254 -0
  56. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/portfolio_source.rb +30 -0
  57. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/portfolio_store.rb +124 -0
  58. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/preview_window.rb +98 -0
  59. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/proto/client_pb.rb +29 -0
  60. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/row_preview.rb +174 -0
  61. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sheets_client.rb +272 -0
  62. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/snapshot.rb +27 -0
  63. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sync.rb +247 -0
  64. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sync_preview.rb +63 -0
  65. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_identity.rb +49 -0
  66. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_sync.rb +948 -0
  67. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_types.rb +142 -0
  68. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/version.rb +5 -0
  69. data/lib/bdgtr/portfolio/lib/portfolio_performance_api.rb +42 -0
  70. data/lib/bdgtr/portfolio/proto/client.proto +114 -0
  71. data/lib/bdgtr/psd2/account.rb +24 -0
  72. data/lib/bdgtr/psd2/account_snapshot.rb +96 -0
  73. data/lib/bdgtr/psd2/callback.rb +49 -0
  74. data/lib/bdgtr/psd2/connect.rb +75 -0
  75. data/lib/bdgtr/psd2/enable_banking.rb +250 -0
  76. data/lib/bdgtr/psd2/go_cardless.rb +133 -0
  77. data/lib/bdgtr/psd2/institution.rb +17 -0
  78. data/lib/bdgtr/psd2/platform.rb +37 -0
  79. data/lib/bdgtr/psd2/requisition.rb +21 -0
  80. data/lib/bdgtr/psd2/transaction.rb +29 -0
  81. data/lib/bdgtr/psd2.rb +25 -0
  82. data/lib/bdgtr/sync/importer.rb +125 -0
  83. data/lib/bdgtr/sync/library.rb +18 -0
  84. data/lib/bdgtr/sync/portfolio.rb +14 -0
  85. data/lib/bdgtr/sync/projection.rb +38 -0
  86. data/lib/bdgtr/sync/spreadsheet.rb +23 -0
  87. data/lib/bdgtr/sync.rb +25 -0
  88. data/lib/bdgtr/version.rb +1 -1
  89. metadata +353 -30
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "sqlite3"
5
+ require "stringio"
6
+
7
+ module Bdgtr
8
+ module Core
9
+ # Download and replace a closed ledger file.
10
+ class Exchange
11
+ HEADER = "SQLite format 3"
12
+
13
+ def self.checkpoint!(path)
14
+ return path unless File.exist?(path)
15
+
16
+ database = SQLite3::Database.new(path)
17
+ database.busy_timeout = 200
18
+ database.execute("PRAGMA wal_checkpoint(TRUNCATE)")
19
+ path
20
+ ensure
21
+ database&.close
22
+ end
23
+
24
+ def self.install!(io, path)
25
+ bytes = io.read
26
+ raise ArgumentError, "not a sqlite file" unless bytes.to_s.start_with?(HEADER)
27
+
28
+ destination = path.to_s
29
+ raise ArgumentError, "ledger path is missing" if destination.empty?
30
+
31
+ store = physical_path(destination)
32
+ raise ArgumentError, "ledger is open" if File.exist?(store) && !writable?(store)
33
+
34
+ FileUtils.mkdir_p(File.dirname(store))
35
+ temporary = "#{store}.upload"
36
+ File.binwrite(temporary, bytes)
37
+ File.rename(temporary, store)
38
+ destination
39
+ end
40
+
41
+ def self.replace!(workspace, io, path: nil)
42
+ destination = path.presence || workspace.ledger_path.presence || Rails.root.join("storage/ledgers", "#{workspace.id}.sqlite").to_s
43
+ install!(StringIO.new(io.read.to_s), destination)
44
+ workspace.update!(ledger_path: destination)
45
+ destination
46
+ end
47
+
48
+ # A symlink stays in place. The bytes are written to the file it names.
49
+ def self.physical_path(path)
50
+ File.symlink?(path) ? File.realpath(path) : path
51
+ end
52
+
53
+ def self.writable?(path)
54
+ database = SQLite3::Database.new(path)
55
+ database.busy_timeout = 200
56
+ database.execute("BEGIN EXCLUSIVE")
57
+ database.execute("ROLLBACK")
58
+ true
59
+ rescue SQLite3::BusyException
60
+ false
61
+ ensure
62
+ database&.close
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,177 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ module Core
5
+ module Models
6
+ # Ledger account. The web app subclasses this and adds bookmarks, users,
7
+ # and JSON export. The CLI uses this class directly.
8
+ class Account < Record
9
+ self.abstract_class = true
10
+ self.table_name = "accounts"
11
+
12
+ OPEN_SYNC_STATES = %w[created syncing parsing].freeze
13
+
14
+ scope :visible, -> { where(visible: true) }
15
+ scope :with_external_account_id, ->(external_id) {
16
+ where(id: link_model(:AccountRequisition).where(external_account_id: external_id).select(:account_id))
17
+ }
18
+
19
+ validates :ord, numericality: { only_integer: true }
20
+
21
+ attr_accessor :provider_payload
22
+
23
+ before_validation :assign_default_nickname, on: :create
24
+
25
+ def self.normalize_iban(value)
26
+ text = value.to_s.gsub(/\s+/, "").upcase
27
+ text.presence
28
+ end
29
+
30
+ def self.iban_for_bank_account(service, external_id)
31
+ bank_account_identity(service, external_id).first
32
+ end
33
+
34
+ def self.bank_account_identity(service, external_id)
35
+ details = service.get_account(external_id).get_details
36
+ account = details.is_a?(Hash) ? details["account"] : nil
37
+ account = {} unless account.is_a?(Hash)
38
+ iban = normalize_iban(account["iban"] || details&.dig("account_id", "iban"))
39
+ currency = account["currency"].to_s.strip.upcase.presence
40
+ [ iban, currency ]
41
+ end
42
+
43
+ def self.connection_key(iban, currency)
44
+ normalized = normalize_iban(iban)
45
+ code = currency.to_s.strip.upcase.presence
46
+ return if normalized.blank? || code.blank?
47
+
48
+ "#{normalized}-#{code}"
49
+ end
50
+
51
+ def self.locate_for_connection(scope, external_id:, iban:, currency:)
52
+ found = scope.with_external_account_id(external_id).first
53
+ return found if found
54
+
55
+ key = connection_key(iban, currency)
56
+ return if key.blank?
57
+
58
+ scope.where(iban: normalize_iban(iban)).order(:id).find do |account|
59
+ connection_key(account.iban, account.currency) == key
60
+ end
61
+ end
62
+
63
+ def self.link_model(name)
64
+ return Object.const_get(name) if Object.const_defined?(name, false)
65
+
66
+ const_get(name)
67
+ end
68
+
69
+ def latest_account_requisition
70
+ ids = account_requisitions.pluck(:requisition_id)
71
+ return if ids.empty?
72
+
73
+ requisition = self.class.link_model(:Requisition).where(id: ids).order(created_at: :desc, id: :desc).first
74
+ return if requisition.nil?
75
+
76
+ account_requisitions.find_by(requisition_id: requisition.id)
77
+ end
78
+
79
+ def linked_requisitions
80
+ ids = account_requisitions.pluck(:requisition_id)
81
+ self.class.link_model(:Requisition).where(id: ids).order(created_at: :desc, id: :desc)
82
+ end
83
+
84
+ def requisition
85
+ latest_account_requisition&.requisition
86
+ end
87
+
88
+ def external_account_id
89
+ latest_account_requisition&.external_account_id
90
+ end
91
+
92
+ def bank_institution_id
93
+ account_syncs.order(id: :desc).limit(20).each do |sync|
94
+ institution_id = sync.data&.dig("metadata", "institution_id")
95
+ return institution_id if institution_id.present?
96
+ end
97
+ nil
98
+ end
99
+
100
+ def remember_iban!(details)
101
+ incoming = self.class.normalize_iban(details&.dig("account", "iban") || details&.dig("account_id", "iban"))
102
+ return if incoming.blank?
103
+ return if iban.present? && iban != incoming
104
+
105
+ self.iban = incoming
106
+ end
107
+
108
+ def name
109
+ nickname.presence || read_attribute("name").presence || "account #{id}"
110
+ end
111
+
112
+ def balance_amount
113
+ balance_entry&.dig("balanceAmount", "amount")
114
+ end
115
+
116
+ def balance_currency
117
+ balance_entry&.dig("balanceAmount", "currency")
118
+ end
119
+
120
+ def currency
121
+ raw = sync_data&.dig("details", "account", "currency").presence || balance_currency
122
+ raw.to_s.strip.upcase.presence
123
+ end
124
+
125
+ def ledger_currency
126
+ currency.presence || "EUR"
127
+ end
128
+
129
+ def ledger_balance(currency = ledger_currency)
130
+ transactions.where(currency: currency).sum(:amount).to_d
131
+ end
132
+
133
+ def next_sync_at
134
+ return unless do_sync?
135
+
136
+ open = if association(:account_syncs).loaded?
137
+ states = self.class.link_model(:AccountSync).const_defined?(:OPEN_STATES) ? self.class.link_model(:AccountSync)::OPEN_STATES : OPEN_SYNC_STATES
138
+ account_syncs.select { |sync| states.include?(sync.state) }
139
+ else
140
+ account_syncs.open
141
+ end
142
+ open.filter_map(&:planned_at).min
143
+ end
144
+
145
+ def day_before_first_transaction
146
+ first = transactions.pick(Arel.sql("MIN(COALESCE(date_value, date_booking))"))
147
+ first&.to_date&.prev_day
148
+ end
149
+
150
+ def reset_balance!
151
+ payload = sync_data.deep_dup
152
+ entries = payload&.dig("balances", "balances")
153
+ return unless entries.is_a?(Array)
154
+
155
+ entries.each do |entry|
156
+ amount = entry["balanceAmount"] if entry.is_a?(Hash)
157
+ amount["amount"] = "0.00" if amount.is_a?(Hash)
158
+ end
159
+ update!(sync_data: payload)
160
+ end
161
+
162
+ private
163
+
164
+ def assign_default_nickname
165
+ self.nickname = read_attribute("name") if nickname.blank?
166
+ end
167
+
168
+ def balance_entry
169
+ entries = sync_data&.dig("balances", "balances")
170
+ return unless entries.is_a?(Array)
171
+
172
+ entries.find { |entry| entry["balanceType"] == "interimAvailable" } || entries.first
173
+ end
174
+ end
175
+ end
176
+ end
177
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ module Core
5
+ module Models
6
+ class AccountRequisition < Record
7
+ self.abstract_class = true
8
+ self.table_name = "account_requisitions"
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ module Core
5
+ module Models
6
+ class AccountSync < Record
7
+ self.abstract_class = true
8
+ self.table_name = "account_syncs"
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ module Core
5
+ module Models
6
+ class Import < Record
7
+ self.abstract_class = true
8
+ self.table_name = "imports"
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ module Core
5
+ module Models
6
+ # The id stored in ~/.bdgtr/config.yml. Not the web Workspace record.
7
+ Ledger = Struct.new(:id, :user, keyword_init: true)
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ module Core
5
+ module Models
6
+ # Bank consent stored in the ledger file. The web Requisition inherits this.
7
+ class Requisition < Record
8
+ ACCESS_VALID_FOR_DAYS = 90
9
+ RENEWAL_REMINDER_INTERVAL = 7.days
10
+
11
+ self.table_name = "requisitions"
12
+
13
+ validates :requisition_id, presence: true
14
+
15
+ alias_attribute :expires_at, :access_valid_until
16
+
17
+ def needs_renewal?
18
+ status == "EX" || (access_valid_until.present? && access_valid_until <= Time.current)
19
+ end
20
+
21
+ def renewal_recently_notified?
22
+ renewal_notified_at.present? && renewal_notified_at > RENEWAL_REMINDER_INTERVAL.ago
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+ require "digest"
5
+
6
+ module Bdgtr
7
+ module Core
8
+ module Models
9
+ # Ledger transaction. The web app subclasses this and adds categories
10
+ # automation and the tag gem. The CLI reads the same rows.
11
+ class Transaction < Record
12
+ self.abstract_class = true
13
+ self.table_name = "transactions"
14
+
15
+ SOURCES = %w[manual sync import].freeze
16
+
17
+ validates :amount, presence: true, numericality: true
18
+ validates :source, inclusion: { in: SOURCES }, allow_blank: true
19
+
20
+ before_save :assign_entry_hash
21
+
22
+ def self.without_categorization
23
+ yield
24
+ end
25
+
26
+ def self.categorize_transactions(_transactions)
27
+ end
28
+
29
+ def self.entry_hash_for(account_id:, date_booking:, date_value:, amount:, currency:, description:)
30
+ Digest::SHA256.hexdigest([
31
+ account_id.to_s,
32
+ date_booking&.to_date&.iso8601,
33
+ date_value&.to_date&.iso8601,
34
+ canonical_amount(amount),
35
+ currency.to_s.strip.upcase,
36
+ description.to_s.strip
37
+ ].join("|"))
38
+ end
39
+
40
+ def self.canonical_amount(amount)
41
+ return "" if amount.blank?
42
+
43
+ format("%.2f", BigDecimal(amount.to_s))
44
+ end
45
+
46
+ def assign_source(value)
47
+ self.source = value if source.blank? && value.present?
48
+ end
49
+
50
+ def reconcile!
51
+ self.reconciled = true
52
+ self.reconciled_at = Time.now
53
+ save(validate: false)
54
+ end
55
+
56
+ def category_name
57
+ if self.class.reflect_on_association(:transaction_category)
58
+ return transaction_category&.name.to_s
59
+ end
60
+ return "" if transaction_category_id.blank?
61
+
62
+ self.class.connection.select_value(
63
+ "SELECT name FROM transaction_categories WHERE id = #{transaction_category_id.to_i}"
64
+ ).to_s
65
+ end
66
+
67
+ def tag_names
68
+ if self.class.reflect_on_association(:tags)
69
+ return tags.map(&:name)
70
+ end
71
+ return [] if id.blank?
72
+
73
+ self.class.connection.select_values(<<~SQL)
74
+ SELECT tags.name FROM tags
75
+ INNER JOIN taggings ON taggings.tag_id = tags.id
76
+ WHERE taggings.taggable_id = #{id.to_i}
77
+ AND taggings.taggable_type = 'Transaction'
78
+ AND taggings.context = 'tags'
79
+ ORDER BY tags.name
80
+ SQL
81
+ end
82
+
83
+ private
84
+
85
+ def assign_entry_hash
86
+ self.entry_hash = self.class.entry_hash_for(
87
+ account_id: account_id,
88
+ date_booking: date_booking,
89
+ date_value: date_value,
90
+ amount: amount,
91
+ currency: currency,
92
+ description: description
93
+ )
94
+ end
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ module Core
5
+ module Models
6
+ class TransactionCategory < Record
7
+ self.abstract_class = true
8
+ self.table_name = "transaction_categories"
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ module Core
5
+ # Connection shared by the ledger models. Defaults to the primary database
6
+ # and is pointed at a SQLite file for the duration of Session.open.
7
+ class Record < ActiveRecord::Base
8
+ self.abstract_class = true
9
+ end
10
+ end
11
+ end