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,609 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "securerandom"
5
+ require "time"
6
+
7
+ require_relative "fineco_xls"
8
+ require_relative "proto/client_pb"
9
+ require_relative "transaction_identity"
10
+ require_relative "transaction_sync"
11
+ require_relative "transaction_types"
12
+
13
+ module PortfolioPerformanceApi
14
+ # Fineco row → Portfolio Performance transaction.
15
+ module FinecoImport
16
+ DEFAULT_SECURITY_SPEC = "/Compravendita Titoli\\s+(.+?)\\s+Qta/"
17
+ CROSS_ENTRY_TYPES = TransactionTypes::CROSS_ENTRY
18
+ SHARE_DIVISOR = 100_000_000
19
+ SHARE_MATCH_DAYS = 7
20
+ CASH_MATCH_DAYS = 1
21
+ ExistingTx = Struct.new(:id, :date, :cents, :security, :shares, keyword_init: true)
22
+ Skipped = Struct.new(:row, :reason, keyword_init: true)
23
+ Result = Struct.new(:excluded, :existing, :candidates, :skipped, keyword_init: true)
24
+
25
+ module_function
26
+
27
+ def prepare(client, account, rows, security_specs: [], offset_specs: [], exclude: nil)
28
+ excluded, kept = FinecoXls.partition_excluded(rows, exclude)
29
+ apply_matches!(kept, security_specs, offset_specs)
30
+ assign_types!(kept, account, client)
31
+ invalid, valid = partition_invalid(kept, account, client)
32
+ existing, candidates = partition_existing(valid, client, account)
33
+ skipped = skipped_rows(excluded, "matched --exclude") +
34
+ invalid +
35
+ skipped_rows(existing, "already in portfolio")
36
+ Result.new(excluded: excluded, existing: existing, candidates: candidates, skipped: skipped)
37
+ end
38
+
39
+ def append!(client, account, rows, at: Time.now.utc, skipped: nil)
40
+ list = Array(rows)
41
+ repair_cross_entries!(client, at: at)
42
+ source = import_source(at: at)
43
+ imported = 0
44
+ list.each do |row|
45
+ client.transactions << build_transaction(row, account, client: client, source: source)
46
+ imported += 1
47
+ rescue ArgumentError => error
48
+ raise unless skipped
49
+
50
+ skipped << Skipped.new(row: row, reason: error.message)
51
+ end
52
+ imported
53
+ end
54
+
55
+ # --- types -------------------------------------------------------------
56
+
57
+ def filled?(value)
58
+ !value.to_s.strip.empty?
59
+ end
60
+
61
+ def buy_sell?(type)
62
+ %w[PURCHASE SALE].include?(type.to_s)
63
+ end
64
+
65
+ def cross_entry?(type)
66
+ CROSS_ENTRY_TYPES.include?(type.to_s)
67
+ end
68
+
69
+ def portfolio_type(row, account: nil, client: nil)
70
+ security = filled?(row.security)
71
+ offset = filled?(row.offset_account)
72
+ inflow = row.type.to_s != "REMOVAL"
73
+
74
+ if security && offset
75
+ inflow ? :SALE : :PURCHASE
76
+ elsif security
77
+ :DEPOSIT
78
+ elsif offset
79
+ :CASH_TRANSFER
80
+ else
81
+ row.type
82
+ end
83
+ end
84
+
85
+ def assign_types!(rows, account, client)
86
+ Array(rows).each { |row| row.proto_type = portfolio_type(row, account: account, client: client) }
87
+ end
88
+
89
+ def effective_type(row, account: nil, client: nil)
90
+ row.proto_type || portfolio_type(row, account: account, client: client)
91
+ end
92
+
93
+ def preview_type(row, account: nil, client: nil)
94
+ type = effective_type(row, account: account, client: client)
95
+ (TransactionTypes.coerce(type, kind: :deposit) || type).to_s
96
+ end
97
+
98
+ # --- match specs -------------------------------------------------------
99
+
100
+ def parse_match_spec(spec, flag: "--match")
101
+ rule = Match.parse(spec, flag: flag)
102
+ [rule.regexp, rule.fixed]
103
+ end
104
+
105
+ def parse_offset_spec(spec)
106
+ parse_match_spec(spec, flag: "--match-offset-account")
107
+ end
108
+
109
+ def compile_regexp(pattern)
110
+ Match.compile(pattern)
111
+ end
112
+
113
+ def capturing?(regexp)
114
+ Match.new(regexp).capturing?
115
+ end
116
+
117
+ def value_from_cells(cells, regexp, fixed = "")
118
+ Match.new(regexp, fixed).extract(cells)
119
+ end
120
+
121
+ def extract_from_cells(cells, regexp)
122
+ value_from_cells(cells, regexp, "")
123
+ end
124
+
125
+ def apply_matches!(rows, security_specs, offset_specs)
126
+ securities = Array(security_specs).filter_map do |spec|
127
+ next if spec.to_s.strip.empty?
128
+
129
+ Match.parse(spec, flag: "--match-security")
130
+ end
131
+ offsets = Array(offset_specs).map { |spec| Match.parse(spec, flag: "--match-offset-account") }
132
+
133
+ Array(rows).each do |row|
134
+ cells = FinecoXls.row_cells(row)
135
+ row.security = first_match(cells, securities) unless filled?(row.security)
136
+ row.offset_account = first_match(cells, offsets) unless filled?(row.offset_account)
137
+ end
138
+ rows
139
+ end
140
+
141
+ def validate_matches!(client, rows, account: nil)
142
+ Array(rows).each do |row|
143
+ reason = match_skip_reason(row, client, account)
144
+ raise ArgumentError, reason if reason
145
+ end
146
+ end
147
+
148
+ def match_skip_reason(row, client, account = nil)
149
+ if filled?(row.security) && find_security(client, row.security).nil?
150
+ return "security not found: #{row.security}"
151
+ end
152
+ if filled?(row.offset_account) && find_vehicle(client, row.offset_account).nil?
153
+ return "offset account not found: #{row.offset_account}"
154
+ end
155
+ if filled?(row.security) && filled?(row.offset_account)
156
+ vehicle = find_vehicle(client, row.offset_account)
157
+ unless vehicle&.kind == :securities
158
+ return "buy/sell offset must be a securities account: #{row.offset_account}"
159
+ end
160
+ end
161
+
162
+ type = TransactionTypes.coerce(effective_type(row, account: account, client: client), kind: :deposit)
163
+ return "unsupported Portfolio Performance type: #{effective_type(row)}" if type.nil?
164
+
165
+ nil
166
+ end
167
+
168
+ def partition_invalid(rows, account, client)
169
+ invalid = []
170
+ valid = []
171
+ Array(rows).each do |row|
172
+ reason = match_skip_reason(row, client, account)
173
+ if reason
174
+ invalid << Skipped.new(row: row, reason: reason)
175
+ else
176
+ valid << row
177
+ end
178
+ end
179
+ [invalid, valid]
180
+ end
181
+
182
+ def skipped_rows(rows, reason)
183
+ Array(rows).map { |row| Skipped.new(row: row, reason: reason) }
184
+ end
185
+
186
+ # --- identity / already imported --------------------------------------
187
+
188
+ def identity_for(row, account, client: nil)
189
+ type = effective_type(row, account: account, client: client)
190
+ security = buy_sell?(type) ? row.security.to_s : ""
191
+ TransactionIdentity.id(
192
+ account.name,
193
+ row.date,
194
+ TransactionSync.signed_cents(type, row.amount_cents),
195
+ row.description,
196
+ row.offset_account.to_s,
197
+ security
198
+ )
199
+ end
200
+
201
+ def partition_existing(rows, client, account)
202
+ remaining = portfolio_existing(client, account)
203
+ existing = []
204
+ missing = []
205
+ Array(rows).each do |row|
206
+ index = take_existing_index(remaining, row, account, client: client)
207
+ if index
208
+ remaining.delete_at(index)
209
+ existing << row
210
+ else
211
+ missing << row
212
+ end
213
+ end
214
+ [existing, missing]
215
+ end
216
+
217
+ def portfolio_existing(client, account)
218
+ names = TransactionSync.uuid_names(client)
219
+ secs = TransactionSync.security_names(client)
220
+ client.transactions.filter_map do |tx|
221
+ rec = TransactionSync.from_proto(tx, account, names: names, security_names: secs)
222
+ next unless rec
223
+
224
+ security = ""
225
+ if tx.respond_to?(:has_security?) && tx.has_security?
226
+ security = secs[tx.security].to_s.strip
227
+ end
228
+ ExistingTx.new(
229
+ id: rec.id,
230
+ date: rec.date,
231
+ cents: amount_in_account_cents(tx, account),
232
+ security: security,
233
+ shares: tx.shares.to_i
234
+ )
235
+ end
236
+ end
237
+
238
+ def portfolio_identities(client, account)
239
+ portfolio_existing(client, account).map(&:id)
240
+ end
241
+
242
+ # --- write proto -------------------------------------------------------
243
+
244
+ def import_source(at: Time.now.utc)
245
+ "bdgtr import #{at.utc.strftime("%Y%m%dT%H%M%S")}"
246
+ end
247
+
248
+ def build_transaction(row, account, client: nil, source: nil, at: Time.now.utc)
249
+ now = at.utc
250
+ date = Time.utc(row.date.year, row.date.month, row.date.day)
251
+ type = TransactionTypes.coerce(effective_type(row, account: account, client: client), kind: :deposit)
252
+ raise ArgumentError, "unsupported Portfolio Performance type: #{effective_type(row)}" if type.nil?
253
+
254
+ tx = Proto::PTransaction.new(
255
+ uuid: SecureRandom.uuid,
256
+ type: type,
257
+ account: account.uuid,
258
+ date: Google::Protobuf::Timestamp.new(seconds: date.to_i),
259
+ currencyCode: account.currencyCode,
260
+ amount: row.amount_cents,
261
+ shares: buy_sell?(type) ? extract_shares(row) : 0,
262
+ note: row.description,
263
+ updatedAt: Google::Protobuf::Timestamp.new(seconds: now.to_i, nanos: now.nsec),
264
+ source: source || import_source(at: now)
265
+ )
266
+ assign_counterparts!(tx, row, account, client)
267
+ assert_pp_safe!(tx)
268
+ tx
269
+ end
270
+
271
+ def assert_pp_safe!(tx)
272
+ type = tx.type.to_s
273
+ unless TransactionTypes.proto?(type)
274
+ raise ArgumentError, "unsupported Portfolio Performance type: #{type}"
275
+ end
276
+ return if TransactionTypes.loadable?(tx)
277
+
278
+ raise ArgumentError, "transaction is not loadable by Portfolio Performance: #{type}"
279
+ end
280
+
281
+ def repair_cross_entries!(client, at: Time.now.utc)
282
+ stamped = 0
283
+ client.transactions.each do |tx|
284
+ next unless cross_entry?(tx.type)
285
+
286
+ missing = tx.otherUuid.to_s.empty? || !tx.has_otherUpdatedAt?
287
+ stamp_cross_entry!(tx, at: at)
288
+ stamped += 1 if missing
289
+ end
290
+ stamped
291
+ end
292
+
293
+ def extract_shares(row)
294
+ text = ([row.description] + FinecoXls.row_cells(row)).compact.join(" ")
295
+ match = text.match(%r{Qta/Val\.nom\.\s*([\d.,]+)}i)
296
+ return 0 unless match
297
+
298
+ (Float(italian_number(match[1])) * SHARE_DIVISOR).round
299
+ rescue ArgumentError
300
+ 0
301
+ end
302
+
303
+ def italian_number(value)
304
+ text = value.to_s.strip.gsub(/[€$£\s]/, "")
305
+ if text.include?(",") && text.include?(".")
306
+ text.delete(".").tr(",", ".")
307
+ elsif text.include?(",")
308
+ text.tr(",", ".")
309
+ else
310
+ text
311
+ end
312
+ end
313
+
314
+ # --- lookup ------------------------------------------------------------
315
+
316
+ def find_account(client, name)
317
+ find_named(client.accounts, name)
318
+ end
319
+
320
+ def find_security(client, name)
321
+ find_named(client.securities, name)
322
+ end
323
+
324
+ def find_vehicle(client, name, kind: nil)
325
+ text = name.to_s.strip
326
+ return if text.empty?
327
+
328
+ vehicles = TransactionSync.vehicles(client)
329
+ vehicles = vehicles.select { |item| item.kind == kind } if kind
330
+ vehicles.find { |item| item.name == text } ||
331
+ vehicles.find { |item| item.name.casecmp?(text) } ||
332
+ vehicles.find { |item| item.uuid == text }
333
+ end
334
+
335
+ def last_transaction_date(client, account_uuid)
336
+ client.transactions.filter_map do |tx|
337
+ next unless tx.has_account? && tx.account == account_uuid
338
+ next unless tx.has_date?
339
+
340
+ Time.at(tx.date.seconds).utc.to_date
341
+ end.max
342
+ end
343
+
344
+ # --- FX ----------------------------------------------------------------
345
+
346
+ def convert_cents(client, from_account, to_account, cents, date)
347
+ return cents if from_account.currencyCode.to_s == to_account.currencyCode.to_s
348
+
349
+ (Integer(cents) * fx_rate(client, from_account, to_account, date)).round
350
+ end
351
+
352
+ def encode_decimal(rate)
353
+ scale = 10
354
+ unscaled = (Float(rate) * (10**scale)).round
355
+ Proto::PDecimal.new(
356
+ scale: scale,
357
+ precision: unscaled.abs.to_s.length,
358
+ value: biginteger_bytes(unscaled)
359
+ )
360
+ end
361
+
362
+ def amount_in_account_cents(tx, account)
363
+ code = account.currencyCode.to_s
364
+ return tx.amount if tx.currencyCode.to_s == code
365
+
366
+ unit = tx.units.find do |item|
367
+ item.type.to_s == "GROSS_VALUE" &&
368
+ item.has_fxCurrencyCode? && item.fxCurrencyCode.to_s == code &&
369
+ item.has_fxAmount?
370
+ end
371
+ unit ? unit.fxAmount : tx.amount.abs
372
+ end
373
+
374
+ def rate_from_unit(unit, from_code, to_code)
375
+ if unit.currencyCode.to_s == from_code && unit.fxCurrencyCode.to_s == to_code
376
+ unit.fxAmount.to_f / unit.amount
377
+ elsif unit.currencyCode.to_s == to_code && unit.fxCurrencyCode.to_s == from_code
378
+ unit.amount.to_f / unit.fxAmount
379
+ else
380
+ raise ArgumentError,
381
+ "FX unit #{unit.currencyCode}/#{unit.fxCurrencyCode} does not match #{from_code}/#{to_code}"
382
+ end
383
+ end
384
+
385
+ class Match
386
+ attr_reader :regexp, :fixed
387
+
388
+ def initialize(regexp, fixed = "")
389
+ @regexp = regexp
390
+ @fixed = fixed.to_s.strip
391
+ end
392
+
393
+ def self.parse(spec, flag: "--match")
394
+ text = spec.to_s.strip
395
+ raise ArgumentError, "invalid #{flag} #{spec.inspect} (expected /REGEXP/ or /REGEXP/VALUE)" if text.empty?
396
+
397
+ text = "/#{text}/" unless text.start_with?("/")
398
+ match = text.match(%r{\A/(.*)/(.*)\z}m)
399
+ if match.nil? || match[1].empty?
400
+ raise ArgumentError, "invalid #{flag} #{spec.inspect} (expected /REGEXP/ or /REGEXP/VALUE)"
401
+ end
402
+
403
+ rule = new(compile(match[1]), match[2])
404
+ unless rule.capturing? || !rule.fixed.empty?
405
+ raise ArgumentError, "invalid #{flag} #{spec.inspect} (need a capture group or /REGEXP/VALUE)"
406
+ end
407
+
408
+ rule
409
+ end
410
+
411
+ def self.compile(pattern)
412
+ text = pattern.to_s.strip
413
+ raise ArgumentError, "empty regexp" if text.empty?
414
+
415
+ Regexp.new(text, Regexp::IGNORECASE)
416
+ end
417
+
418
+ def capturing?
419
+ return true unless regexp.names.empty?
420
+
421
+ unescaped = regexp.source.gsub(/\\./, "")
422
+ unescaped.match?(/\([^?]/) || unescaped.match?(/\(\?</)
423
+ end
424
+
425
+ def extract(cells)
426
+ Array(cells).each do |cell|
427
+ match = regexp.match(cell.to_s)
428
+ next unless match
429
+
430
+ captured = match.captures.find { |value| value && !value.strip.empty? }
431
+ return captured.strip if captured
432
+ return fixed unless fixed.empty?
433
+ end
434
+ nil
435
+ end
436
+ end
437
+
438
+ def first_match(cells, rules)
439
+ rules.each do |rule|
440
+ value = rule.extract(cells)
441
+ return value if value
442
+ end
443
+ nil
444
+ end
445
+
446
+ def find_named(collection, name)
447
+ text = name.to_s.strip
448
+ return if text.empty?
449
+
450
+ collection.find { |item| item.name == text } ||
451
+ collection.find { |item| item.name.casecmp?(text) } ||
452
+ collection.find { |item| item.uuid == text }
453
+ end
454
+
455
+ def take_existing_index(remaining, row, account, client:)
456
+ id = identity_for(row, account, client: client)
457
+ index = remaining.index { |slot| slot.id == id }
458
+ return index if index
459
+
460
+ shares = extract_shares(row)
461
+ security = row.security.to_s.strip
462
+ if filled?(security) && shares.positive?
463
+ index = remaining.index do |slot|
464
+ slot.shares == shares &&
465
+ filled?(slot.security) &&
466
+ slot.security.casecmp?(security) &&
467
+ (slot.date - row.date).abs <= SHARE_MATCH_DAYS
468
+ end
469
+ return index if index
470
+ end
471
+
472
+ remaining.index { |slot| (slot.date - row.date).abs <= CASH_MATCH_DAYS && slot.cents == row.amount_cents.abs }
473
+ end
474
+
475
+ def assign_counterparts!(tx, row, account, client)
476
+ type = tx.type.to_s
477
+ if buy_sell?(type)
478
+ assign_buy_sell!(tx, row, account, client)
479
+ return
480
+ end
481
+ return if row.offset_account.to_s.empty?
482
+ raise ArgumentError, "client required to resolve offset account" if client.nil?
483
+
484
+ if type == "CASH_TRANSFER"
485
+ assign_cash_transfer!(tx, row, account, client)
486
+ else
487
+ assign_offset!(tx, row.offset_account, client)
488
+ end
489
+ end
490
+
491
+ def assign_buy_sell!(tx, row, account, client)
492
+ raise ArgumentError, "client required to resolve buy/sell" if client.nil?
493
+ raise ArgumentError, "buy/sell needs an offset securities account" if row.offset_account.to_s.empty?
494
+
495
+ vehicle = find_vehicle(client, row.offset_account)
496
+ raise ArgumentError, "offset account not found: #{row.offset_account}" unless vehicle
497
+ unless vehicle.kind == :securities
498
+ raise ArgumentError, "buy/sell offset must be a securities account: #{row.offset_account}"
499
+ end
500
+
501
+ security = find_security(client, row.security)
502
+ raise ArgumentError, "security not found: #{row.security}" unless security
503
+
504
+ tx.account = account.uuid
505
+ tx.portfolio = vehicle.uuid
506
+ tx.security = security.uuid
507
+ stamp_cross_entry!(tx)
508
+ end
509
+
510
+ def assign_cash_transfer!(tx, row, account, client)
511
+ other = find_account(client, row.offset_account)
512
+ raise ArgumentError, "offset account not found: #{row.offset_account}" unless other
513
+
514
+ inbound = row.type.to_s != "REMOVAL"
515
+ source = inbound ? other : account
516
+ dest = inbound ? account : other
517
+ tx.account = source.uuid
518
+ tx.otherAccount = dest.uuid
519
+ tx.currencyCode = source.currencyCode
520
+ stamp_cross_entry!(tx)
521
+
522
+ source_cents, dest_cents = transfer_amounts(client, row, source, dest, inbound)
523
+ tx.amount = source_cents
524
+ return if source.currencyCode.to_s == dest.currencyCode.to_s
525
+
526
+ tx.units << Proto::PTransactionUnit.new(
527
+ type: :GROSS_VALUE,
528
+ amount: source_cents,
529
+ currencyCode: source.currencyCode,
530
+ fxAmount: dest_cents,
531
+ fxCurrencyCode: dest.currencyCode,
532
+ fxRateToBase: encode_decimal(source_cents.to_f / dest_cents)
533
+ )
534
+ end
535
+
536
+ def transfer_amounts(client, row, source, dest, inbound)
537
+ if source.currencyCode.to_s == dest.currencyCode.to_s
538
+ return [row.amount_cents, row.amount_cents]
539
+ end
540
+
541
+ if inbound
542
+ dest_cents = row.amount_cents
543
+ [convert_cents(client, dest, source, dest_cents, row.date), dest_cents]
544
+ else
545
+ source_cents = row.amount_cents
546
+ [source_cents, convert_cents(client, source, dest, source_cents, row.date)]
547
+ end
548
+ end
549
+
550
+ def assign_offset!(tx, name, client)
551
+ vehicle = find_vehicle(client, name)
552
+ raise ArgumentError, "offset account not found: #{name}" unless vehicle
553
+
554
+ if vehicle.kind == :securities
555
+ tx.portfolio = vehicle.uuid
556
+ else
557
+ tx.otherAccount = vehicle.uuid
558
+ end
559
+ end
560
+
561
+ def stamp_cross_entry!(tx, at: Time.now.utc)
562
+ now = at.utc
563
+ tx.otherUuid = SecureRandom.uuid if tx.otherUuid.to_s.empty?
564
+ return if tx.has_otherUpdatedAt?
565
+
566
+ tx.otherUpdatedAt = Google::Protobuf::Timestamp.new(seconds: now.to_i, nanos: now.nsec)
567
+ end
568
+
569
+ def fx_rate(client, from_account, to_account, date)
570
+ from = from_account.currencyCode.to_s
571
+ to = to_account.currencyCode.to_s
572
+ pair = [from_account.uuid, to_account.uuid]
573
+ candidates = client.transactions.select do |tx|
574
+ next false unless tx.type.to_s == "CASH_TRANSFER"
575
+ next false unless tx.has_account? && tx.has_otherAccount?
576
+ next false unless pair.include?(tx.account) && pair.include?(tx.otherAccount)
577
+
578
+ unit = gross_fx_unit(tx)
579
+ unit && unit.amount.positive? && unit.fxAmount.positive?
580
+ end
581
+ if candidates.empty?
582
+ raise ArgumentError,
583
+ "no FX rate between #{from_account.name} (#{from}) and #{to_account.name} (#{to})"
584
+ end
585
+
586
+ best = candidates.min_by do |tx|
587
+ tx_date = tx.has_date? ? Time.at(tx.date.seconds).utc.to_date : Date.new(1970, 1, 1)
588
+ (tx_date - date).abs
589
+ end
590
+ rate_from_unit(gross_fx_unit(best), from, to)
591
+ end
592
+
593
+ def gross_fx_unit(tx)
594
+ tx.units.find do |unit|
595
+ unit.type.to_s == "GROSS_VALUE" && unit.has_fxAmount? && unit.has_fxCurrencyCode?
596
+ end
597
+ end
598
+
599
+ def biginteger_bytes(value)
600
+ int = Integer(value)
601
+ raise ArgumentError, "FX rate must be positive" unless int.positive?
602
+
603
+ hex = int.to_s(16)
604
+ hex = "0#{hex}" if hex.length.odd?
605
+ bytes = [hex].pack("H*")
606
+ bytes.getbyte(0) >= 0x80 ? "\x00".b + bytes : bytes
607
+ end
608
+ end
609
+ end