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,948 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "digest"
5
+ require "securerandom"
6
+ require "time"
7
+
8
+ require_relative "proto/client_pb"
9
+ require_relative "transaction_identity"
10
+ require_relative "transaction_types"
11
+
12
+ module PortfolioPerformanceApi
13
+ module TransactionSync
14
+ HEADERS = %w[date type amount currency description destination uuid].freeze
15
+ DEPOSIT_EXTRA_COLUMNS = ["security", "shares", "per share", "offset account", "note", "source"].freeze
16
+ SECURITIES_EXTRA_COLUMNS = ["symbol", "isin", "shares", "quote", "fees", "taxes", "net transaction value"].freeze
17
+ DEPOSIT_EXTRA_KEYS = %i[security shares per_share offset_account note source].freeze
18
+ SECURITIES_EXTRA_KEYS = %i[symbol isin shares quote fees taxes net].freeze
19
+ DERIVED_EXTRA_KEYS = %i[per_share quote net].freeze
20
+ SECURITY_REF_KEYS = %i[security symbol isin].freeze
21
+ SHARE_SCALE = 100_000_000
22
+ EXTRA_HEADERS = {
23
+ security: [/\Asecurity\z/, /\Atitolo\z/],
24
+ shares: [/\Ashares\z/],
25
+ per_share: [/per[_\s-]*share/],
26
+ offset_account: [/offset[_\s-]*account/],
27
+ note: [/\Anote\z/],
28
+ source: [/\Asource\z/],
29
+ symbol: [/\Asymbol\z/, /\Aticker\z/],
30
+ isin: [/\Aisin\z/],
31
+ quote: [/\Aquote\z/],
32
+ fees: [/\Afees?\z/],
33
+ taxes: [/\Ataxes?\z/],
34
+ net: [/net[_\s-]*(transaction[_\s-]*)?value/]
35
+ }.freeze
36
+ OUTFLOW_TYPES = %w[
37
+ PURCHASE SALE OUTBOUND_DELIVERY REMOVAL INTEREST_CHARGE TAX FEE
38
+ ].freeze
39
+ TYPE_ALIASES = TransactionTypes::ALIASES
40
+ PROTO_TYPES = TransactionTypes::PROTO
41
+ DEFAULT_COLUMNS = {
42
+ date: 0,
43
+ type: 1,
44
+ amount: 2,
45
+ currency: 3,
46
+ description: 4,
47
+ destination: 5,
48
+ uuid: 6
49
+ }.freeze
50
+
51
+ Vehicle = Struct.new(:kind, :name, :uuid, :currency, keyword_init: true)
52
+ Record = Struct.new(
53
+ :id, :account_name, :date, :type, :signed_cents, :currency, :description, :destination, :uuid, :row_number,
54
+ :extras,
55
+ keyword_init: true
56
+ )
57
+ Plan = Struct.new(:create_sheet, :create_portfolio, :update_sheet, :update_portfolio, keyword_init: true)
58
+ Result = Struct.new(:created_sheet, :created_portfolio, :updated_sheet, :updated_portfolio, keyword_init: true)
59
+
60
+ module_function
61
+
62
+ def identity_id(account_name, date, signed_cents, description, destination = "", security = "")
63
+ TransactionIdentity.id(account_name, date, signed_cents, description, destination, security)
64
+ end
65
+
66
+ def signed_cents(type, amount_cents)
67
+ cents = Integer(amount_cents).abs
68
+ outflow?(type) ? -cents : cents
69
+ end
70
+
71
+ def outflow?(type)
72
+ OUTFLOW_TYPES.include?(type.to_s)
73
+ end
74
+
75
+ def normalize_description(value)
76
+ TransactionIdentity.normalize_description(value)
77
+ end
78
+
79
+ def normalize_type(value, signed_cents = nil, kind: nil)
80
+ type = TransactionTypes.normalize(value, signed_cents, kind: kind)
81
+ return type if kind.nil?
82
+
83
+ TransactionTypes.coerce(type, kind: kind)
84
+ end
85
+
86
+ def vehicles(client)
87
+ currencies = client.accounts.to_h { |account| [account.uuid, account.currencyCode] }
88
+ deposits = client.accounts.map do |account|
89
+ Vehicle.new(kind: :deposit, name: account.name, uuid: account.uuid, currency: account.currencyCode)
90
+ end
91
+ securities = client.portfolios.map do |portfolio|
92
+ reference = portfolio.has_referenceAccount? ? currencies[portfolio.referenceAccount] : nil
93
+ currency = reference.to_s.empty? ? client.baseCurrency : reference
94
+ currency = "EUR" if currency.to_s.empty?
95
+ Vehicle.new(kind: :securities, name: portfolio.name, uuid: portfolio.uuid, currency: currency)
96
+ end
97
+ deposits + securities
98
+ end
99
+
100
+ def uuid_names(client)
101
+ vehicles(client).to_h { |vehicle| [vehicle.uuid, vehicle.name] }
102
+ end
103
+
104
+ def security_names(client)
105
+ Array(client.securities).to_h { |security| [security.uuid, security.name.to_s] }
106
+ end
107
+
108
+ def name_index(client)
109
+ vehicles(client).each_with_object({}) do |vehicle, index|
110
+ index[vehicle.name] ||= vehicle
111
+ index[vehicle.name.downcase] ||= vehicle
112
+ end
113
+ end
114
+
115
+ def lookup_name(index, name)
116
+ text = name.to_s.strip
117
+ return if text.empty?
118
+
119
+ index[text] || index[text.downcase]
120
+ end
121
+
122
+ def from_proto(tx, vehicle, names: {}, security_names: {}, securities: {})
123
+ vehicle = wrap_vehicle(vehicle)
124
+ return unless belongs?(tx, vehicle)
125
+ return unless tx.has_date?
126
+
127
+ date = Time.at(tx.date.seconds).utc.to_date
128
+ description = tx.has_note? ? normalize_description(tx.note) : ""
129
+ destination = destination_name(tx, vehicle, names)
130
+ security = security_name(tx, security_names)
131
+ cents = signed_cents(tx.type, tx.amount)
132
+ Record.new(
133
+ id: identity_id(vehicle.name, date, cents, description, destination, security),
134
+ account_name: vehicle.name,
135
+ date: date,
136
+ type: tx.type.to_s,
137
+ signed_cents: cents,
138
+ currency: tx.currencyCode.to_s.empty? ? vehicle.currency : tx.currencyCode,
139
+ description: description,
140
+ destination: destination,
141
+ uuid: tx.uuid,
142
+ extras: extras_from_proto(tx, destination, security_names, securities)
143
+ )
144
+ end
145
+
146
+ def extra_columns_for(kind)
147
+ kind.to_s == "securities" ? SECURITIES_EXTRA_COLUMNS : DEPOSIT_EXTRA_COLUMNS
148
+ end
149
+
150
+ def extra_keys_for(kind)
151
+ kind.to_s == "securities" ? SECURITIES_EXTRA_KEYS : DEPOSIT_EXTRA_KEYS
152
+ end
153
+
154
+ def headers_for(kind)
155
+ HEADERS + extra_columns_for(kind)
156
+ end
157
+
158
+ def parse_sheet(raw_rows, account_name, currency:, skip_rows: 0, kind: :deposit)
159
+ rows = Array(raw_rows)
160
+ mapping = column_mapping(ensure_headers(rows[skip_rows], kind))
161
+ rows.each_with_index.filter_map do |row, index|
162
+ next if index < skip_rows
163
+ next if header_row?(row)
164
+
165
+ record = from_sheet_row(row, account_name, currency: currency, mapping: mapping, kind: kind)
166
+ next unless record
167
+
168
+ record.row_number = index + 1
169
+ record
170
+ end
171
+ end
172
+
173
+ def from_sheet_row(row, account_name, currency:, mapping: DEFAULT_COLUMNS, kind: :deposit)
174
+ cells = Array(row)
175
+ return if header_row?(cells)
176
+
177
+ date = parse_date(cells[mapping[:date]])
178
+ amount = parse_signed_cents(cells[mapping[:amount]])
179
+ description = normalize_description(cells[mapping[:description]])
180
+ return if date.nil? || amount.nil?
181
+
182
+ type = normalize_type(cells[mapping[:type]], amount, kind: kind)
183
+ return if type.nil?
184
+
185
+ extras = extras_from_sheet(cells, mapping)
186
+ destination = mapping[:destination] ? cells[mapping[:destination]].to_s.strip : ""
187
+ destination = extras[:offset_account].to_s.strip if destination.empty?
188
+ cents = signed_cents(type, amount)
189
+ uuid = cells[mapping[:uuid]].to_s.strip
190
+ currency_cell = cells[mapping[:currency]].to_s.strip
191
+ Record.new(
192
+ id: identity_id(account_name, date, cents, description, destination),
193
+ account_name: account_name,
194
+ date: date,
195
+ type: type,
196
+ signed_cents: cents,
197
+ currency: currency_cell.empty? ? currency : currency_cell,
198
+ description: description,
199
+ destination: destination,
200
+ uuid: uuid.empty? ? nil : uuid,
201
+ extras: extras
202
+ )
203
+ end
204
+
205
+ def find_sheet_row(sheet_records, identity)
206
+ Array(sheet_records).find { |record| record.id == identity }
207
+ end
208
+
209
+ def take_sheet_row!(remaining, proto)
210
+ if proto.uuid.to_s != ""
211
+ index = remaining.find_index { |row| row.uuid.to_s == proto.uuid.to_s }
212
+ return remaining.delete_at(index) if index
213
+ end
214
+
215
+ index = remaining.find_index { |row| row.id == proto.id }
216
+ remaining.delete_at(index) if index
217
+ end
218
+
219
+ def to_sheet_row(record, header: nil, existing: nil)
220
+ mapping = header ? column_mapping(header) : DEFAULT_COLUMNS.merge(extras: {})
221
+ cells = existing ? Array(existing).dup : []
222
+ write_cell(cells, mapping[:date], record.date.strftime("%Y-%m-%d"))
223
+ write_cell(cells, mapping[:type], record.type)
224
+ write_cell(cells, mapping[:amount], (record.signed_cents / 100.0).round(2))
225
+ write_cell(cells, mapping[:currency], record.currency)
226
+ write_cell(cells, mapping[:description], record.description)
227
+ write_cell(cells, mapping[:destination], record.destination.to_s)
228
+ write_cell(cells, mapping[:uuid], record.uuid.to_s)
229
+ mapping.fetch(:extras, {}).each do |key, index|
230
+ write_cell(cells, index, extra_cell(key, record))
231
+ end
232
+ cells
233
+ end
234
+
235
+ def account_plan(client, vehicle, raw_rows, names: uuid_names(client), skip_rows: 0)
236
+ secs = security_names(client)
237
+ securities = securities_by_uuid(client)
238
+ portfolio_records = client.transactions.filter_map do |tx|
239
+ from_proto(tx, vehicle, names: names, security_names: secs, securities: securities)
240
+ end
241
+ sheet_records = parse_sheet(
242
+ raw_rows, vehicle.name, currency: vehicle.currency, skip_rows: skip_rows, kind: vehicle.kind
243
+ )
244
+ plan(
245
+ portfolio_records,
246
+ sheet_records,
247
+ names_index: name_index(client),
248
+ extra_keys: extra_keys_for(vehicle.kind),
249
+ securities: Array(client.securities)
250
+ )
251
+ end
252
+
253
+ def split_plan(plan)
254
+ [
255
+ Plan.new(
256
+ create_sheet: plan.create_sheet,
257
+ update_sheet: plan.update_sheet,
258
+ create_portfolio: [],
259
+ update_portfolio: []
260
+ ),
261
+ Plan.new(
262
+ create_sheet: [],
263
+ update_sheet: [],
264
+ create_portfolio: plan.create_portfolio,
265
+ update_portfolio: plan.update_portfolio
266
+ )
267
+ ]
268
+ end
269
+
270
+ def plan(portfolio_records, sheet_records, names_index: {}, extra_keys: [], securities: [])
271
+ create_sheet = []
272
+ create_portfolio = []
273
+ update_sheet = []
274
+ update_portfolio = []
275
+ remaining = Array(sheet_records).dup
276
+
277
+ Array(portfolio_records).each do |proto|
278
+ row = take_sheet_row!(remaining, proto)
279
+ if row.nil?
280
+ create_sheet << proto
281
+ else
282
+ merged = merge(proto, row, names_index, extra_keys: extra_keys)
283
+ unless same_row?(row, merged)
284
+ merged.row_number = row.row_number
285
+ update_sheet << merged
286
+ end
287
+ update_portfolio << merged unless same_proto?(
288
+ proto, merged, names_index: names_index, securities: securities
289
+ )
290
+ end
291
+ end
292
+
293
+ Plan.new(
294
+ create_sheet: create_sheet,
295
+ create_portfolio: remaining,
296
+ update_sheet: update_sheet,
297
+ update_portfolio: update_portfolio
298
+ )
299
+ end
300
+
301
+ def apply_portfolio!(client, vehicle, records)
302
+ vehicle = wrap_vehicle(vehicle)
303
+ names = name_index(client)
304
+ changed = 0
305
+ records.each do |record|
306
+ next unless TransactionTypes.coerce(record.type, kind: vehicle.kind)
307
+
308
+ existing = find_transaction(client, vehicle, record, names: uuid_names(client))
309
+ if existing
310
+ changed += 1 if update_transaction!(existing, record, vehicle, names, client)
311
+ else
312
+ tx = build_transaction(vehicle, record, names, client)
313
+ next unless TransactionTypes.loadable?(tx)
314
+
315
+ client.transactions << tx
316
+ changed += 1
317
+ end
318
+ end
319
+ changed
320
+ end
321
+
322
+ def apply_sheet(sheets, title, plan, skip_rows: 0, chunk_size: 100, raw_rows: nil, kind: :deposit)
323
+ grid = materialize_sheet(
324
+ raw_rows || sheets.read_rows(title), plan, skip_rows: skip_rows, kind: kind
325
+ )
326
+ return [plan.create_sheet.size, plan.update_sheet.size] if grid.size <= skip_rows
327
+
328
+ sheets.write_chunks(title, grid, start_row: skip_rows + 1, chunk_size: chunk_size)
329
+ [plan.create_sheet.size, plan.update_sheet.size]
330
+ end
331
+
332
+ def materialize_sheet(raw_rows, plan, skip_rows: 0, kind: :deposit)
333
+ source = Array(raw_rows)
334
+ grid = Array.new([source.size, skip_rows + 1].max) { |index| Array(source[index]).dup }
335
+ grid[skip_rows] = ensure_headers(grid[skip_rows], kind)
336
+ header = grid[skip_rows]
337
+
338
+ Array(plan.update_sheet).each do |record|
339
+ index = record.row_number.to_i - 1
340
+ next if index.negative?
341
+
342
+ grid << [] while grid.size <= index
343
+ grid[index] = to_sheet_row(record, header: header, existing: grid[index])
344
+ end
345
+ Array(plan.create_sheet).each do |record|
346
+ grid << to_sheet_row(record, header: header)
347
+ end
348
+ grid
349
+ end
350
+
351
+ def sheet_chunks(grid, start_row:, chunk_size:)
352
+ data = Array(grid)[(start_row - 1)..]
353
+ return [] if data.nil? || data.empty?
354
+
355
+ size = [Integer(chunk_size), 1].max
356
+ data.each_slice(size).map.with_index do |slice, index|
357
+ first = start_row + (index * size)
358
+ { start_row: first, end_row: first + slice.size - 1, values: slice }
359
+ end
360
+ end
361
+
362
+ def column_mapping(header)
363
+ labels = Array(header).map { |cell| cell.to_s.strip.downcase }
364
+ return DEFAULT_COLUMNS.merge(extras: {}) unless header_row?(labels)
365
+
366
+ {
367
+ date: labels.index("date") || DEFAULT_COLUMNS[:date],
368
+ type: labels.index("type") || DEFAULT_COLUMNS[:type],
369
+ amount: labels.index("amount") || DEFAULT_COLUMNS[:amount],
370
+ currency: labels.index("currency") || DEFAULT_COLUMNS[:currency],
371
+ description: labels.index("description") || DEFAULT_COLUMNS[:description],
372
+ destination: destination_column(labels),
373
+ uuid: labels.index("uuid") || DEFAULT_COLUMNS[:uuid],
374
+ extras: extra_columns(labels)
375
+ }
376
+ end
377
+
378
+ def parse_date(value)
379
+ return value.to_date if value.respond_to?(:to_date) && !value.is_a?(String)
380
+
381
+ text = value.to_s.strip
382
+ return if text.empty?
383
+
384
+ Date.iso8601(text)
385
+ rescue ArgumentError
386
+ begin
387
+ Date.strptime(text, "%d/%m/%Y")
388
+ rescue ArgumentError
389
+ Date.parse(text)
390
+ end
391
+ rescue ArgumentError, TypeError
392
+ nil
393
+ end
394
+
395
+ def header_row?(cells)
396
+ labels = Array(cells).map { |cell| cell.to_s.strip.downcase }
397
+ labels.include?("date") && (labels.include?("amount") || labels.include?("type"))
398
+ end
399
+
400
+ def parse_signed_cents(value)
401
+ return if value.nil? || value.to_s.strip.empty?
402
+ return (value.to_f * 100).round if value.is_a?(Numeric)
403
+
404
+ text = value.to_s.strip.gsub(/[€$£\s]/, "")
405
+ last_comma = text.rindex(",")
406
+ last_dot = text.rindex(".")
407
+ text = if last_comma && last_dot
408
+ if last_comma > last_dot
409
+ text.delete(".").tr(",", ".")
410
+ else
411
+ text.delete(",")
412
+ end
413
+ elsif text.count(",") > 1
414
+ text.delete(",")
415
+ elsif text.include?(",")
416
+ text.tr(",", ".")
417
+ else
418
+ text
419
+ end
420
+ (Float(text) * 100).round
421
+ rescue ArgumentError
422
+ nil
423
+ end
424
+
425
+ def wrap_vehicle(vehicle)
426
+ return vehicle if vehicle.is_a?(Vehicle)
427
+ return vehicle if vehicle.respond_to?(:kind) && vehicle.respond_to?(:currency)
428
+
429
+ if vehicle.respond_to?(:currencyCode)
430
+ Vehicle.new(kind: :deposit, name: vehicle.name, uuid: vehicle.uuid, currency: vehicle.currencyCode)
431
+ else
432
+ Vehicle.new(kind: :securities, name: vehicle.name, uuid: vehicle.uuid, currency: "EUR")
433
+ end
434
+ end
435
+
436
+ def belongs?(tx, vehicle)
437
+ if vehicle.kind == :securities
438
+ (tx.has_portfolio? && tx.portfolio == vehicle.uuid) ||
439
+ (tx.has_otherPortfolio? && tx.otherPortfolio == vehicle.uuid)
440
+ else
441
+ (tx.has_account? && tx.account == vehicle.uuid) ||
442
+ (tx.has_otherAccount? && tx.otherAccount == vehicle.uuid)
443
+ end
444
+ end
445
+
446
+ def security_name(tx, names)
447
+ uuid = tx.respond_to?(:has_security?) && !tx.has_security? ? nil : tx.security
448
+ return "" if uuid.to_s.empty?
449
+
450
+ names[uuid].to_s.strip
451
+ end
452
+
453
+ def destination_name(tx, vehicle, names)
454
+ other_uuid =
455
+ if vehicle.uuid == (tx.has_account? ? tx.account : nil)
456
+ (tx.has_otherAccount? && tx.otherAccount) ||
457
+ (tx.has_otherPortfolio? && tx.otherPortfolio) ||
458
+ (tx.has_portfolio? && tx.portfolio)
459
+ elsif vehicle.uuid == (tx.has_otherAccount? ? tx.otherAccount : nil)
460
+ tx.has_account? ? tx.account : nil
461
+ elsif vehicle.uuid == (tx.has_portfolio? ? tx.portfolio : nil)
462
+ (tx.has_otherPortfolio? && tx.otherPortfolio) ||
463
+ (tx.has_otherAccount? && tx.otherAccount) ||
464
+ (tx.has_account? && tx.account)
465
+ elsif vehicle.uuid == (tx.has_otherPortfolio? ? tx.otherPortfolio : nil)
466
+ tx.has_portfolio? ? tx.portfolio : nil
467
+ end
468
+ names[other_uuid].to_s
469
+ end
470
+
471
+ def destination_column(labels)
472
+ labels.index("destination") ||
473
+ labels.index { |label| label.match?(/destinat|offset|other/) }
474
+ end
475
+
476
+ def merge(proto, row, names_index = {}, extra_keys: [])
477
+ destination = pick_destination(proto, row, names_index)
478
+ Record.new(
479
+ id: proto.id,
480
+ account_name: proto.account_name,
481
+ date: proto.date,
482
+ type: row.type || proto.type,
483
+ signed_cents: proto.signed_cents,
484
+ currency: proto.currency,
485
+ description: proto.description,
486
+ destination: destination,
487
+ uuid: proto.uuid.to_s.empty? ? row.uuid : proto.uuid,
488
+ row_number: row.row_number,
489
+ extras: merge_extras(proto, row, destination, extra_keys)
490
+ )
491
+ end
492
+
493
+ def pick_destination(proto, row, names_index)
494
+ sheet_dest = row.destination.to_s.strip
495
+ proto_dest = proto.destination.to_s.strip
496
+ return proto_dest if sheet_dest.empty?
497
+ return sheet_dest if proto_dest.empty? || sheet_dest == proto_dest
498
+
499
+ sheet_hit = lookup_name(names_index, sheet_dest)
500
+ proto_hit = lookup_name(names_index, proto_dest)
501
+ if proto_hit && (sheet_hit.nil? || sheet_hit.uuid == proto_hit.uuid ||
502
+ sheet_hit.name == proto.account_name)
503
+ proto_dest
504
+ else
505
+ sheet_dest
506
+ end
507
+ end
508
+
509
+ def same_row?(row, merged)
510
+ row.type == merged.type &&
511
+ row.currency == merged.currency &&
512
+ row.uuid.to_s == merged.uuid.to_s &&
513
+ row.description == merged.description &&
514
+ row.destination.to_s == merged.destination.to_s &&
515
+ row.signed_cents == merged.signed_cents &&
516
+ row.date == merged.date &&
517
+ same_extras?(row.extras, merged.extras, merged.extras.to_h.keys)
518
+ end
519
+
520
+ def same_proto?(proto, merged, names_index: {}, securities: [])
521
+ keys = merged.extras.to_h.keys - DERIVED_EXTRA_KEYS - SECURITY_REF_KEYS - %i[offset_account]
522
+ proto.type == merged.type &&
523
+ proto.uuid.to_s == merged.uuid.to_s &&
524
+ same_destination?(proto.destination, merged.destination, names_index) &&
525
+ same_extras?(proto.extras, merged.extras, keys) &&
526
+ same_security_ref?(proto, merged, securities)
527
+ end
528
+
529
+ def same_destination?(proto_dest, merged_dest, names_index)
530
+ return true if proto_dest.to_s.strip == merged_dest.to_s.strip
531
+
532
+ merged_hit = lookup_name(names_index, merged_dest)
533
+ return true unless merged_hit
534
+
535
+ proto_hit = lookup_name(names_index, proto_dest)
536
+ proto_hit&.uuid == merged_hit.uuid
537
+ end
538
+
539
+ def same_security_ref?(proto, merged, securities)
540
+ extras = merged.extras.to_h
541
+ return true unless extras.keys.any? { |key| SECURITY_REF_KEYS.include?(key) }
542
+
543
+ merged_sec = lookup_security_list(securities, extras)
544
+ return true unless merged_sec
545
+
546
+ proto_sec = lookup_security_list(securities, proto.extras.to_h)
547
+ proto_sec&.uuid == merged_sec.uuid
548
+ end
549
+
550
+ def find_transaction(client, vehicle, record, names: {})
551
+ if record.uuid.to_s != ""
552
+ found = client.transactions.find { |tx| tx.uuid == record.uuid }
553
+ return found if found
554
+ end
555
+
556
+ client.transactions.find do |tx|
557
+ mapped = from_proto(
558
+ tx, vehicle,
559
+ names: names,
560
+ security_names: security_names(client),
561
+ securities: securities_by_uuid(client)
562
+ )
563
+ mapped && mapped.id == record.id
564
+ end
565
+ end
566
+
567
+ def update_transaction!(tx, record, vehicle, names, client = nil)
568
+ type = TransactionTypes.coerce(record.type, kind: vehicle.kind)
569
+ return false if type.nil?
570
+
571
+ snapshot = Proto::PTransaction.encode(tx)
572
+ changed = false
573
+ if tx.type.to_s != type
574
+ tx.type = type
575
+ changed = true
576
+ end
577
+ amount = record.signed_cents.abs
578
+ if tx.amount != amount
579
+ tx.amount = amount
580
+ changed = true
581
+ end
582
+ if record.uuid.to_s != "" && tx.uuid != record.uuid
583
+ tx.uuid = record.uuid
584
+ changed = true
585
+ end
586
+ counterpart = assign_counterpart!(tx, vehicle, record, names)
587
+ extras = apply_extras!(tx, record, client)
588
+ stamped = stamp_cross_entry!(tx)
589
+ if TransactionTypes.loadable?(tx)
590
+ return changed || counterpart || extras || stamped
591
+ end
592
+
593
+ restore_transaction!(client, tx, snapshot)
594
+ false
595
+ end
596
+
597
+ def build_transaction(vehicle, record, names, client = nil)
598
+ type = TransactionTypes.coerce(record.type, kind: vehicle.kind)
599
+ raise ArgumentError, "unsupported transaction type for #{vehicle.kind}: #{record.type}" if type.nil?
600
+
601
+ now = Time.now.utc
602
+ date = Time.utc(record.date.year, record.date.month, record.date.day)
603
+ extras = record.extras.to_h
604
+ note = extra_present?(extras[:note]) ? extras[:note].to_s : record.description
605
+ tx = Proto::PTransaction.new(
606
+ uuid: record.uuid.to_s.empty? ? SecureRandom.uuid : record.uuid,
607
+ type: type,
608
+ date: Google::Protobuf::Timestamp.new(seconds: date.to_i),
609
+ currencyCode: record.currency.to_s.empty? ? vehicle.currency : record.currency,
610
+ amount: record.signed_cents.abs,
611
+ shares: extras[:shares].to_i,
612
+ note: note,
613
+ updatedAt: Google::Protobuf::Timestamp.new(seconds: now.to_i, nanos: now.nsec)
614
+ )
615
+ tx.source = extras[:source].to_s if extra_present?(extras[:source])
616
+ if vehicle.kind == :securities
617
+ tx.portfolio = vehicle.uuid
618
+ else
619
+ tx.account = vehicle.uuid
620
+ end
621
+ assign_counterpart!(tx, vehicle, record, names)
622
+ apply_extras!(tx, record, client)
623
+ stamp_cross_entry!(tx)
624
+ tx
625
+ end
626
+
627
+ def stamp_cross_entry!(tx, at: Time.now.utc)
628
+ return false unless TransactionTypes::CROSS_ENTRY.include?(tx.type.to_s)
629
+
630
+ changed = false
631
+ if tx.otherUuid.to_s.empty?
632
+ tx.otherUuid = SecureRandom.uuid
633
+ changed = true
634
+ end
635
+ unless tx.has_otherUpdatedAt?
636
+ now = at.utc
637
+ tx.otherUpdatedAt = Google::Protobuf::Timestamp.new(seconds: now.to_i, nanos: now.nsec)
638
+ changed = true
639
+ end
640
+ changed
641
+ end
642
+
643
+ def restore_transaction!(client, tx, snapshot)
644
+ return unless client
645
+
646
+ index = client.transactions.find_index { |item| item.equal?(tx) }
647
+ return unless index
648
+
649
+ client.transactions[index] = Proto::PTransaction.decode(snapshot)
650
+ end
651
+
652
+ def assign_counterpart!(tx, vehicle, record, names)
653
+ dest = lookup_name(names, record.destination)
654
+ return false unless dest
655
+
656
+ before = [tx.has_account? && tx.account, tx.has_otherAccount? && tx.otherAccount,
657
+ tx.has_portfolio? && tx.portfolio, tx.has_otherPortfolio? && tx.otherPortfolio]
658
+ if vehicle.kind == :deposit && dest.kind == :deposit
659
+ tx.otherAccount = dest.uuid
660
+ elsif vehicle.kind == :deposit && dest.kind == :securities
661
+ tx.portfolio = dest.uuid
662
+ elsif vehicle.kind == :securities && dest.kind == :securities
663
+ tx.otherPortfolio = dest.uuid
664
+ elsif vehicle.kind == :securities && dest.kind == :deposit
665
+ tx.account = dest.uuid
666
+ end
667
+ after = [tx.has_account? && tx.account, tx.has_otherAccount? && tx.otherAccount,
668
+ tx.has_portfolio? && tx.portfolio, tx.has_otherPortfolio? && tx.otherPortfolio]
669
+ before != after
670
+ end
671
+
672
+ def securities_by_uuid(client)
673
+ Array(client.securities).to_h { |security| [security.uuid, security] }
674
+ end
675
+
676
+ def extra_columns(labels)
677
+ used = [
678
+ labels.index("date"),
679
+ labels.index("type"),
680
+ labels.index("amount"),
681
+ labels.index("currency"),
682
+ labels.index("description"),
683
+ destination_column(labels),
684
+ labels.index("uuid")
685
+ ].compact
686
+ EXTRA_HEADERS.each_with_object({}) do |(key, patterns), extras|
687
+ index = labels.index { |label| patterns.any? { |pattern| label.match?(pattern) } }
688
+ next if index.nil? || used.include?(index)
689
+
690
+ extras[key] = index
691
+ end
692
+ end
693
+
694
+ def extras_from_proto(tx, destination, security_names, securities)
695
+ security = tx.respond_to?(:has_security?) && tx.has_security? ? securities[tx.security] : nil
696
+ shares = tx.respond_to?(:has_shares?) && tx.has_shares? ? tx.shares.to_i : 0
697
+ amount = tx.amount.to_i
698
+ per_share = per_share_value(amount, shares)
699
+ {
700
+ security: security_name(tx, security_names),
701
+ shares: shares.positive? ? shares : nil,
702
+ per_share: per_share,
703
+ offset_account: destination.to_s,
704
+ note: tx.has_note? ? tx.note.to_s : "",
705
+ source: tx.respond_to?(:has_source?) && tx.has_source? ? tx.source.to_s : "",
706
+ symbol: security_attr(security, :tickerSymbol),
707
+ isin: security_attr(security, :isin),
708
+ quote: per_share,
709
+ fees: unit_cents(tx, "FEE"),
710
+ taxes: unit_cents(tx, "TAX"),
711
+ net: amount
712
+ }
713
+ end
714
+
715
+ def extras_from_sheet(cells, mapping)
716
+ mapping.fetch(:extras, {}).each_with_object({}) do |(key, index), extras|
717
+ extras[key] = parse_extra(key, cells[index])
718
+ end
719
+ end
720
+
721
+ def parse_extra(key, value)
722
+ case key
723
+ when :shares
724
+ number = parse_decimal(value)
725
+ number && (number * SHARE_SCALE).round
726
+ when :fees, :taxes, :net
727
+ parse_signed_cents(value)&.abs
728
+ when :per_share, :quote
729
+ parse_decimal(value)
730
+ else
731
+ value.to_s.strip
732
+ end
733
+ end
734
+
735
+ def parse_extra_number(value)
736
+ cents = parse_signed_cents(value)
737
+ cents && cents / 100.0
738
+ end
739
+
740
+ def parse_decimal(value)
741
+ return if value.nil? || value.to_s.strip.empty?
742
+ return value.to_f if value.is_a?(Numeric)
743
+
744
+ text = value.to_s.strip.gsub(/[\u20ac$\u00a3\s]/, "")
745
+ last_comma = text.rindex(",")
746
+ last_dot = text.rindex(".")
747
+ text = if last_comma && last_dot
748
+ if last_comma > last_dot
749
+ text.delete(".").tr(",", ".")
750
+ else
751
+ text.delete(",")
752
+ end
753
+ elsif text.count(",") > 1
754
+ text.delete(",")
755
+ elsif text.include?(",")
756
+ text.tr(",", ".")
757
+ else
758
+ text
759
+ end
760
+ Float(text)
761
+ rescue ArgumentError
762
+ nil
763
+ end
764
+
765
+ def per_share_value(amount_cents, shares)
766
+ return if shares.to_i <= 0
767
+
768
+ (amount_cents.to_f / 100.0) / (shares.to_f / SHARE_SCALE)
769
+ end
770
+
771
+ def unit_cents(tx, type)
772
+ unit = Array(tx.units).find { |item| item.type.to_s == type }
773
+ unit&.amount
774
+ end
775
+
776
+ def security_attr(security, name)
777
+ return "" unless security
778
+ return "" unless security.respond_to?(name)
779
+
780
+ optional = "has_#{name}?"
781
+ return "" if security.respond_to?(optional) && !security.public_send(optional)
782
+
783
+ security.public_send(name).to_s
784
+ end
785
+
786
+ def ensure_headers(header, kind)
787
+ extras = extra_columns_for(kind)
788
+ labels = Array(header).map { |cell| cell.to_s }
789
+ return HEADERS + extras unless header_row?(labels)
790
+
791
+ extras.each do |name|
792
+ labels << name unless extra_header_present?(labels, name)
793
+ end
794
+ labels
795
+ end
796
+
797
+ def extra_header_present?(labels, name)
798
+ key = extra_key_for_label(name)
799
+ Array(labels).any? do |label|
800
+ text = label.to_s.strip.downcase
801
+ next true if text == name.downcase
802
+ next false unless key
803
+
804
+ EXTRA_HEADERS[key].any? { |pattern| text.match?(pattern) }
805
+ end
806
+ end
807
+
808
+ def extra_key_for_label(name)
809
+ text = name.to_s.strip.downcase
810
+ EXTRA_HEADERS.find { |_key, patterns| patterns.any? { |pattern| text.match?(pattern) } }&.first
811
+ end
812
+
813
+ def merge_extras(proto, row, destination, extra_keys = [])
814
+ keys = Array(extra_keys)
815
+ keys = row.extras.to_h.keys if keys.empty?
816
+ keys.each_with_object({}) do |key, merged|
817
+ sheet_val = row.extras[key]
818
+ proto_val = proto.extras.to_h[key]
819
+ proto_val = destination if key == :offset_account && !extra_present?(proto_val)
820
+ merged[key] = extra_present?(sheet_val) ? sheet_val : proto_val
821
+ merged[key] = destination if key == :offset_account && !extra_present?(merged[key])
822
+ end
823
+ end
824
+
825
+ def same_extras?(left, right, keys)
826
+ keys.all? { |key| extra_equal?(key, left.to_h[key], right.to_h[key]) }
827
+ end
828
+
829
+ def extra_equal?(key, left, right)
830
+ return left.to_s.strip == right.to_s.strip unless %i[shares fees taxes net per_share quote].include?(key)
831
+ return true unless extra_present?(left) || extra_present?(right)
832
+ return false unless extra_present?(left) && extra_present?(right)
833
+
834
+ l = left.to_f
835
+ r = right.to_f
836
+ (l - r).abs <= [l.abs, r.abs, 1.0].max * 1e-9
837
+ end
838
+
839
+ def extra_present?(value)
840
+ return false if value.nil?
841
+ return false if value.is_a?(String) && value.strip.empty?
842
+
843
+ true
844
+ end
845
+
846
+ def extra_cell(key, record)
847
+ value = record.extras.to_h[key]
848
+ value = record.destination if key == :offset_account && !extra_present?(value)
849
+ format_extra(key, value)
850
+ end
851
+
852
+ def format_extra(key, value)
853
+ return "" unless extra_present?(value)
854
+
855
+ case key
856
+ when :shares
857
+ value.to_f / SHARE_SCALE
858
+ when :fees, :taxes, :net
859
+ value.to_f / 100.0
860
+ when :per_share, :quote
861
+ value.to_f
862
+ else
863
+ value.to_s
864
+ end
865
+ end
866
+
867
+ def write_cell(cells, index, value)
868
+ return if index.nil?
869
+
870
+ cells << nil while cells.size <= index
871
+ cells[index] = value
872
+ end
873
+
874
+ def apply_extras!(tx, record, client)
875
+ extras = record.extras.to_h
876
+ return false if extras.empty?
877
+
878
+ changed = false
879
+ if extras.key?(:note) && extra_present?(extras[:note]) && tx.note.to_s != extras[:note].to_s
880
+ tx.note = extras[:note].to_s
881
+ changed = true
882
+ end
883
+ if extras.key?(:source) && tx.source.to_s != extras[:source].to_s
884
+ tx.source = extras[:source].to_s
885
+ changed = true
886
+ end
887
+ if extras.key?(:shares) && extra_present?(extras[:shares]) && tx.shares.to_i != extras[:shares].to_i
888
+ tx.shares = extras[:shares].to_i
889
+ changed = true
890
+ end
891
+ security = lookup_security(client, extras)
892
+ if security && tx.security.to_s != security.uuid
893
+ tx.security = security.uuid
894
+ changed = true
895
+ end
896
+ changed | apply_units!(tx, extras)
897
+ end
898
+
899
+ def lookup_security(client, extras)
900
+ lookup_security_list(Array(client&.securities), extras)
901
+ end
902
+
903
+ def lookup_security_list(securities, extras)
904
+ extras = extras.to_h
905
+ isin = extras[:isin].to_s.strip
906
+ symbol = extras[:symbol].to_s.strip
907
+ name = extras[:security].to_s.strip
908
+ found = Array(securities).find { |item| !isin.empty? && security_attr(item, :isin).casecmp?(isin) }
909
+ found ||= Array(securities).find { |item| !symbol.empty? && security_attr(item, :tickerSymbol).casecmp?(symbol) }
910
+ found ||= Array(securities).find { |item| !name.empty? && item.name == name }
911
+ found || Array(securities).find { |item| !name.empty? && item.name.casecmp?(name) }
912
+ end
913
+
914
+ def apply_units!(tx, extras)
915
+ changed = false
916
+ { fees: :FEE, taxes: :TAX }.each do |key, type|
917
+ next unless extras.key?(key) && extra_present?(extras[key])
918
+
919
+ cents = extras[key].to_i
920
+ unit = tx.units.find { |item| item.type.to_s == type.to_s }
921
+ if unit.nil?
922
+ tx.units << Proto::PTransactionUnit.new(
923
+ type: type,
924
+ amount: cents,
925
+ currencyCode: tx.currencyCode
926
+ )
927
+ changed = true
928
+ elsif unit.amount != cents
929
+ unit.amount = cents
930
+ changed = true
931
+ end
932
+ end
933
+ changed
934
+ end
935
+
936
+ private_class_method :merge, :same_row?, :same_proto?, :find_transaction,
937
+ :update_transaction!, :build_transaction, :wrap_vehicle, :belongs?,
938
+ :destination_name, :security_name, :destination_column, :assign_counterpart!,
939
+ :lookup_name, :take_sheet_row!, :pick_destination, :securities_by_uuid,
940
+ :extra_columns, :extras_from_proto, :extras_from_sheet, :parse_extra,
941
+ :parse_extra_number, :parse_decimal, :per_share_value, :unit_cents, :security_attr,
942
+ :merge_extras, :same_extras?, :extra_equal?, :extra_present?, :extra_cell,
943
+ :format_extra, :write_cell, :apply_extras!, :lookup_security, :lookup_security_list,
944
+ :apply_units!, :same_destination?, :same_security_ref?,
945
+ :ensure_headers, :extra_header_present?, :extra_key_for_label,
946
+ :stamp_cross_entry!, :restore_transaction!
947
+ end
948
+ end