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,458 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+ require "tty-cursor"
5
+ require "tty-reader"
6
+ require "tty-screen"
7
+ require "unicode/display_width/string_ext"
8
+
9
+ module Bdgtr
10
+ class Cli
11
+ # A terminal table. Ten data rows are visible. Arrow keys scroll and the
12
+ # header stays put. A column is as wide as its longest value. Columns are
13
+ # separated by two spaces. Search, when enabled, filters every cell.
14
+ class Table
15
+ PAGE = 10
16
+ GAP = " "
17
+ SEARCH_HINT = "write to search, ctrl+u prev page, +v next page"
18
+ UNDERLINE = [ "write to search", "ctrl+u", "+v" ].freeze
19
+
20
+ def self.show(headers, rows, on_select: nil, search: false, summary: nil)
21
+ table = new(headers, rows, on_select: on_select, search: search, summary: summary)
22
+ if $stdout.tty? && $stdin.tty?
23
+ table.interact
24
+ else
25
+ rows.each { |row| puts Array(row).join("\t") }
26
+ end
27
+ end
28
+
29
+ def self.width_of(text)
30
+ text.to_s.display_width
31
+ end
32
+
33
+ def self.ellipsize(text, limit)
34
+ value = text.to_s
35
+ return value if width_of(value) <= limit
36
+
37
+ mark = "…"
38
+ budget = limit - width_of(mark)
39
+ kept = +""
40
+ used = 0
41
+ value.each_grapheme_cluster do |cluster|
42
+ cluster_width = width_of(cluster)
43
+ break if used + cluster_width > budget
44
+
45
+ kept << cluster
46
+ used += cluster_width
47
+ end
48
+ "#{kept}#{mark}"
49
+ end
50
+
51
+ def initialize(headers, rows, on_select: nil, search: false, summary: nil)
52
+ @headers = headers.map(&:to_s)
53
+ @rows = rows.map { |row| Array(row).map { |value| value.to_s } }
54
+ @on_select = on_select
55
+ @selectable = !on_select.nil?
56
+ @search = search
57
+ @summary_column = summary&.to_s
58
+ @query = +""
59
+ @selected = 0
60
+ @row_offset = 0
61
+ @column_offset = 0
62
+ @detail_lines = []
63
+ @detail_offset = 0
64
+ end
65
+
66
+ def interact
67
+ reader = TTY::Reader.new(interrupt: :noop)
68
+ drawn = 0
69
+ mode = :list
70
+ $stdout.print(TTY::Cursor.hide)
71
+ loop do
72
+ lines = case mode
73
+ when :detail then detail_frame
74
+ when :confirm then frame + [ "Exit? [Y/n]" ]
75
+ else frame
76
+ end
77
+ drawn = paint(lines, drawn)
78
+ key = keypress(reader)
79
+ if mode == :confirm
80
+ case exit_decision(key)
81
+ when :yes then break
82
+ when :no then mode = :list
83
+ end
84
+ next
85
+ end
86
+ case handle_key(mode, key)
87
+ when :quit
88
+ break if [ :ctrl_c, :ctrl_d ].include?(key)
89
+
90
+ mode = :confirm
91
+ when :back then mode = :list
92
+ when :open then mode = :detail if open_detail
93
+ when :detail then scroll_detail(key)
94
+ end
95
+ end
96
+ $stdout.puts
97
+ ensure
98
+ $stdout.print(TTY::Cursor.show)
99
+ end
100
+
101
+ def move(key)
102
+ if @selectable
103
+ move_selection(key)
104
+ else
105
+ move_window(key)
106
+ end
107
+ end
108
+
109
+ def frame
110
+ width = screen_width
111
+ indexes = matching_indexes
112
+ lines = []
113
+ lines << search_line(width) if @search
114
+ lines << slice(summary_line, width) if @summary_column
115
+ lines << slice(render(@headers), width)
116
+ PAGE.times do |index|
117
+ row_index = @row_offset + index
118
+ source = indexes[row_index]
119
+ row = source.nil? ? nil : @rows[source]
120
+ line = row.nil? ? "" : slice(render(row), width)
121
+ selected = @selectable && row && row_index == @selected
122
+ line = mark_matches(line, selected: selected)
123
+ lines << line
124
+ end
125
+ shown = indexes.size
126
+ last = [ @row_offset + PAGE, shown ].min
127
+ status = if @selectable
128
+ position = shown.zero? ? 0 : @selected + 1
129
+ "#{position}/#{shown} arrows move enter opens q quits"
130
+ else
131
+ "#{shown.zero? ? 0 : @row_offset + 1}-#{last}/#{shown} arrows scroll q quits"
132
+ end
133
+ lines << slice(status, width)
134
+ lines
135
+ end
136
+
137
+ def type_query(text)
138
+ @query << text.to_s
139
+ reset_view
140
+ end
141
+
142
+ def clear_query
143
+ @query.clear
144
+ reset_view
145
+ end
146
+
147
+ private
148
+
149
+ def exit_decision(key)
150
+ return :yes if [ :return, :enter, "y", "Y", "q", "Q", :ctrl_c, :ctrl_d ].include?(key)
151
+ return :no if [ "n", "N", :escape ].include?(key)
152
+
153
+ :stay
154
+ end
155
+
156
+ def handle_key(mode, key)
157
+ if mode == :detail
158
+ return :back if [ :escape, "q", "Q" ].include?(key)
159
+ return :quit if [ :ctrl_c, :ctrl_d ].include?(key)
160
+ if @search && key == :ctrl_u
161
+ scroll_detail(:page_up)
162
+ return :stay
163
+ elsif @search && key == :ctrl_v
164
+ scroll_detail(:page_down)
165
+ return :stay
166
+ end
167
+
168
+ :detail
169
+ elsif key == :escape && @search && @query.present?
170
+ clear_query
171
+ :stay
172
+ elsif %w[q Q].include?(key) || [ :escape, :ctrl_c, :ctrl_d ].include?(key)
173
+ :quit
174
+ elsif [ :return, :enter ].include?(key)
175
+ :open
176
+ elsif @search && [ :backspace, :ctrl_h, :delete ].include?(key)
177
+ pop_query
178
+ :stay
179
+ elsif @search && key == :ctrl_u
180
+ move(:page_up)
181
+ :stay
182
+ elsif @search && key == :ctrl_v
183
+ move(:page_down)
184
+ :stay
185
+ elsif @search && (key == :space || searchable_character?(key))
186
+ type_query(key == :space ? " " : key)
187
+ :stay
188
+ else
189
+ move(key)
190
+ :stay
191
+ end
192
+ end
193
+
194
+ def move_window(key)
195
+ case key
196
+ when :up then @row_offset -= 1
197
+ when :down then @row_offset += 1
198
+ when :page_up then @row_offset -= PAGE
199
+ when :page_down then @row_offset += PAGE
200
+ when :left then @column_offset -= 4
201
+ when :right then @column_offset += 4
202
+ when :home then @row_offset = 0
203
+ when :end then @row_offset = max_row_offset
204
+ else
205
+ return
206
+ end
207
+ @row_offset = @row_offset.clamp(0, max_row_offset)
208
+ @column_offset = @column_offset.clamp(0, max_column_offset)
209
+ end
210
+
211
+ def move_selection(key)
212
+ case key
213
+ when :up then @selected -= 1
214
+ when :down then @selected += 1
215
+ when :page_up then @selected -= PAGE
216
+ when :page_down then @selected += PAGE
217
+ when :home then @selected = 0
218
+ when :end then @selected = @rows.size - 1
219
+ when :left then @column_offset -= 4
220
+ when :right then @column_offset += 4
221
+ else
222
+ return
223
+ end
224
+ @selected = @selected.clamp(0, [ matching_indexes.size - 1, 0 ].max)
225
+ follow_selection
226
+ @column_offset = @column_offset.clamp(0, max_column_offset)
227
+ end
228
+
229
+ def follow_selection
230
+ if @selected < @row_offset
231
+ @row_offset = @selected
232
+ elsif @selected >= @row_offset + PAGE
233
+ @row_offset = @selected - PAGE + 1
234
+ end
235
+ @row_offset = @row_offset.clamp(0, max_row_offset)
236
+ end
237
+
238
+ def open_detail
239
+ source = matching_indexes[@selected]
240
+ return false unless @selectable && source
241
+
242
+ @detail_lines = Array(@on_select.call(source)).map(&:to_s)
243
+ @detail_offset = 0
244
+ true
245
+ end
246
+
247
+ def scroll_detail(key)
248
+ case key
249
+ when :up then @detail_offset -= 1
250
+ when :down then @detail_offset += 1
251
+ when :page_up then @detail_offset -= detail_height
252
+ when :page_down then @detail_offset += detail_height
253
+ when :home then @detail_offset = 0
254
+ when :end then @detail_offset = max_detail_offset
255
+ else
256
+ return false
257
+ end
258
+ @detail_offset = @detail_offset.clamp(0, max_detail_offset)
259
+ true
260
+ end
261
+
262
+ def detail_frame
263
+ height = detail_height
264
+ visible = @detail_lines.slice(@detail_offset, height) || []
265
+ visible << "" while visible.size < height
266
+ visible << "esc back"
267
+ visible
268
+ end
269
+
270
+ def detail_height
271
+ height = TTY::Screen.height.to_i
272
+ height = 24 if height < 5
273
+ height - 2
274
+ end
275
+
276
+ def max_detail_offset
277
+ [ @detail_lines.size - detail_height, 0 ].max
278
+ end
279
+
280
+ def paint(lines, drawn)
281
+ $stdout.print(TTY::Cursor.up(drawn) + TTY::Cursor.column(1)) if drawn.positive?
282
+ lines.each { |line| $stdout.print(TTY::Cursor.clear_line + line + "\n") }
283
+ extra = drawn - lines.size
284
+ if extra.positive?
285
+ extra.times { $stdout.print(TTY::Cursor.clear_line + "\n") }
286
+ $stdout.print(TTY::Cursor.up(extra))
287
+ end
288
+ lines.size
289
+ end
290
+
291
+ def keypress(reader)
292
+ char = reader.read_keypress(echo: false)
293
+ reader.console.keys[char] || char
294
+ end
295
+
296
+ def highlight(line)
297
+ "\e[7m#{line}\e[0m"
298
+ end
299
+
300
+ def render(values)
301
+ @headers.each_index.map { |index| pad(values[index].to_s, widths[index]) }.join(GAP)
302
+ end
303
+
304
+ def pad(text, width)
305
+ gap = width - self.class.width_of(text)
306
+ gap.positive? ? text + (" " * gap) : text
307
+ end
308
+
309
+ def widths
310
+ @widths ||= @headers.each_index.map do |index|
311
+ samples = [ @headers[index], *@rows.map { |row| row[index].to_s } ]
312
+ samples << amount_width_sample if index == summary_index
313
+ samples.map { |value| self.class.width_of(value) }.max
314
+ end
315
+ end
316
+
317
+ def slice(line, width)
318
+ return line if self.class.width_of(line) <= width
319
+
320
+ kept = +""
321
+ used = 0
322
+ skipped = 0
323
+ line.each_grapheme_cluster do |cluster|
324
+ cluster_width = self.class.width_of(cluster)
325
+ if skipped < @column_offset
326
+ skipped += cluster_width
327
+ next
328
+ end
329
+ break if used + cluster_width > width
330
+
331
+ kept << cluster
332
+ used += cluster_width
333
+ end
334
+ pad(kept, width)
335
+ end
336
+
337
+ def screen_width
338
+ [ TTY::Screen.width - 1, 20 ].max
339
+ end
340
+
341
+ def matching_indexes
342
+ return (0...@rows.size).to_a if !@search || @query.empty?
343
+
344
+ needle = @query.downcase
345
+ @rows.each_index.select do |index|
346
+ @rows[index].any? { |value| value.downcase.include?(needle) }
347
+ end
348
+ end
349
+
350
+ def search_line(width)
351
+ text = @query.empty? ? SEARCH_HINT : @query
352
+ fitted = fit_tail(text, width)
353
+ return underline_hint(fitted) if @query.empty? && fitted == SEARCH_HINT
354
+
355
+ fitted
356
+ end
357
+
358
+ def underline_hint(text)
359
+ UNDERLINE.reduce(text.dup) do |line, part|
360
+ line.sub(part) { "\e[4m#{part}\e[24m" }
361
+ end
362
+ end
363
+
364
+ def fit_tail(text, width)
365
+ return text if self.class.width_of(text) <= width
366
+
367
+ kept = +""
368
+ used = 0
369
+ text.each_grapheme_cluster.reverse_each do |cluster|
370
+ cluster_width = self.class.width_of(cluster)
371
+ break if used + cluster_width > width
372
+
373
+ kept.prepend(cluster)
374
+ used += cluster_width
375
+ end
376
+ kept
377
+ end
378
+
379
+ def summary_line
380
+ indexes = matching_indexes
381
+ label = "#{indexes.size} row of #{@rows.size}"
382
+ index = summary_index
383
+ return label unless index
384
+
385
+ total = format_amount(indexes.sum(BigDecimal(0)) { |row_index| decimal_at(@rows[row_index], index) })
386
+ start = column_start(index)
387
+ label_width = self.class.width_of(label)
388
+ if label_width < start
389
+ label + (" " * (start - label_width)) + total
390
+ else
391
+ label + GAP + total
392
+ end
393
+ end
394
+
395
+ def summary_index
396
+ return nil if @summary_column.nil?
397
+
398
+ @headers.index(@summary_column)
399
+ end
400
+
401
+ def column_start(index)
402
+ widths.take(index).sum + (GAP.length * index)
403
+ end
404
+
405
+ def decimal_at(row, index)
406
+ text = row[index].to_s
407
+ text.empty? ? BigDecimal(0) : BigDecimal(text)
408
+ end
409
+
410
+ def format_amount(value)
411
+ format("%.2f", value)
412
+ end
413
+
414
+ def amount_width_sample
415
+ index = summary_index
416
+ return nil unless index
417
+
418
+ bound = @rows.sum(BigDecimal(0)) { |row| decimal_at(row, index).abs }
419
+ format_amount(-bound)
420
+ end
421
+
422
+ def mark_matches(line, selected:)
423
+ colored = if @search && @query.present?
424
+ pattern = Regexp.new(Regexp.escape(@query), Regexp::IGNORECASE)
425
+ line.gsub(pattern) { |match| "\e[33m#{match}\e[39m" }
426
+ else
427
+ line
428
+ end
429
+ selected ? highlight(colored) : colored
430
+ end
431
+
432
+ def pop_query
433
+ parts = []
434
+ @query.each_grapheme_cluster { |cluster| parts << cluster }
435
+ parts.pop
436
+ @query = parts.join
437
+ reset_view
438
+ end
439
+
440
+ def reset_view
441
+ @selected = 0
442
+ @row_offset = 0
443
+ end
444
+
445
+ def searchable_character?(key)
446
+ key.is_a?(String) && key.match?(/\A[[:print:]]\z/)
447
+ end
448
+
449
+ def max_row_offset
450
+ [ matching_indexes.size - PAGE, 0 ].max
451
+ end
452
+
453
+ def max_column_offset
454
+ [ self.class.width_of(render(@headers)) - screen_width, 0 ].max
455
+ end
456
+ end
457
+ end
458
+ end
data/lib/bdgtr/cli.rb ADDED
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ gem_home = File.expand_path("../../bdgtr_cli/lib/bdgtr/cli/gem_home.rb", __dir__)
4
+ gem_home = File.expand_path("cli/gem_home.rb", __dir__) unless File.file?(gem_home)
5
+ require gem_home
6
+
7
+ module Bdgtr
8
+ # Shell entry. Ledger, account, and transaction commands use ~/.bdgtr.
9
+ # The other commands are the Portfolio Performance tools
10
+ # (spreadsheet:dump, spreadsheet:cleanup, import:xls).
11
+ class Cli
12
+ def self.start(argv = ARGV)
13
+ command = Array(argv)[0].to_s
14
+ Config.ensure!
15
+ require_workspace! if requires_workspace?(command)
16
+ if requires_workspace?(command)
17
+ Config.during_ledger { dispatch(command, argv) }
18
+ else
19
+ dispatch(command, argv)
20
+ end
21
+ rescue Interrupt
22
+ warn "Aborted."
23
+ exit 130
24
+ end
25
+
26
+ def self.dispatch(command, argv)
27
+ if command == "config"
28
+ show_config
29
+ elsif command == "workspace:set"
30
+ set_workspace(argv[1])
31
+ elsif command == "ledger:reset"
32
+ GemHome.reset_with_confirmation!
33
+ elsif command.start_with?("ledger:")
34
+ start_ledger(command, argv[1])
35
+ elsif command.start_with?("account:", "transaction:")
36
+ Cli::Psd2.start(argv)
37
+ else
38
+ Sync::Library.load!
39
+ require "portfolio_performance_api/cli"
40
+ PortfolioPerformanceApi::Cli.start(argv)
41
+ end
42
+ end
43
+
44
+ def self.requires_workspace?(command)
45
+ return false if command == "ledger:reset"
46
+
47
+ command.start_with?("ledger:", "account:", "transaction:")
48
+ end
49
+
50
+ def self.require_workspace!
51
+ return if Config.workspace_id.present?
52
+
53
+ warn "Set a workspace first: bdgtr workspace:set WORKSPACE_ID"
54
+ exit 1
55
+ end
56
+
57
+ def self.set_workspace(id)
58
+ if id.blank?
59
+ warn "Usage: bdgtr workspace:set WORKSPACE_ID"
60
+ exit 1
61
+ end
62
+
63
+ number = Integer(id, exception: false)
64
+ if number.nil? || number <= 0
65
+ warn "workspace #{id} is not an id"
66
+ exit 1
67
+ end
68
+
69
+ Config.workspace_id = number
70
+ puts "workspace #{number}"
71
+ end
72
+
73
+ def self.show_config
74
+ puts Config.display
75
+ case Prompt.confirm("Edit config?", default: :no)
76
+ when :yes
77
+ edit_config
78
+ when :abort
79
+ warn "Aborted."
80
+ exit 1
81
+ end
82
+ end
83
+
84
+ def self.edit_config
85
+ editor = ENV["VISUAL"].presence || ENV["EDITOR"].presence || "vi"
86
+ exit 1 unless system(editor, Config.path)
87
+ end
88
+
89
+ def self.start_ledger(command, workspace_id)
90
+ case command
91
+ when "ledger:push"
92
+ LedgerSync.push
93
+ when "ledger:pull"
94
+ LedgerSync.pull
95
+ when "ledger:export", "ledger:import", "ledger:project"
96
+ copy_postgres(command, workspace_id)
97
+ else
98
+ warn "unknown command #{command}"
99
+ exit 1
100
+ end
101
+ end
102
+
103
+ # Copies rows between Postgres and the ledger file. The web app owns that copy.
104
+ def self.copy_postgres(command, workspace_id)
105
+ workspace = Workspace.find_by(id: workspace_id.presence || Config.workspace_id)
106
+ unless workspace
107
+ warn "workspace #{workspace_id.presence || Config.workspace_id} not found"
108
+ exit 1
109
+ end
110
+
111
+ case command
112
+ when "ledger:export"
113
+ puts Core.export!(workspace, path: Config.ledger)
114
+ when "ledger:import"
115
+ Sync.import!(workspace)
116
+ puts "imported workspace #{workspace.id}"
117
+ when "ledger:project"
118
+ Sync.project!(workspace)
119
+ puts "projected workspace #{workspace.id}"
120
+ else
121
+ warn "unknown command #{command}"
122
+ exit 1
123
+ end
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ module Core
5
+ class Binder
6
+ def self.bind!(workspace, path: nil)
7
+ write_ledger!(workspace, path)
8
+ end
9
+
10
+ # Copies the workspace rows into the ledger file, links it, then removes
11
+ # those rows from Postgres. Tags are global, so a tag is removed only
12
+ # when nothing else still uses it.
13
+ def self.export!(workspace, path: nil)
14
+ path = destination(workspace, path)
15
+ snapshot = Transfer.capture(workspace)
16
+ if empty?(snapshot) && File.exist?(path)
17
+ workspace.update!(ledger_path: path)
18
+ return path
19
+ end
20
+
21
+ write_ledger!(workspace, path, snapshot)
22
+ purge!(snapshot)
23
+ path
24
+ end
25
+
26
+ def self.write_ledger!(workspace, path, snapshot = nil)
27
+ path = destination(workspace, path)
28
+ snapshot ||= Transfer.capture(workspace)
29
+ store = Exchange.physical_path(path)
30
+ FileUtils.mkdir_p(File.dirname(store))
31
+ FileUtils.rm_f(store)
32
+ Session.open(store) { Transfer.write!(snapshot) }
33
+ workspace.update!(ledger_path: path)
34
+ path
35
+ end
36
+
37
+ def self.destination(workspace, path)
38
+ path.presence || Rails.root.join("storage/ledgers", "#{workspace.id}.sqlite").to_s
39
+ end
40
+
41
+ def self.empty?(snapshot)
42
+ Transfer::TABLES.all? { |table| Array(snapshot[table]).empty? }
43
+ end
44
+
45
+ def self.purge!(snapshot)
46
+ account_ids = ids(snapshot, "accounts")
47
+ transaction_ids = ids(snapshot, "transactions")
48
+ tag_ids = ids(snapshot, "tags")
49
+ Account.transaction do
50
+ ActsAsTaggableOn::Tagging.where(taggable_type: "Transaction", taggable_id: transaction_ids).delete_all
51
+ AccountSync.where(id: ids(snapshot, "account_syncs")).delete_all
52
+ Transaction.where(id: transaction_ids).delete_all
53
+ Import.where(id: ids(snapshot, "imports")).delete_all
54
+ AccountRequisition.where(id: ids(snapshot, "account_requisitions")).delete_all
55
+ Requisition.where(id: ids(snapshot, "requisitions")).delete_all
56
+ Account.where(id: account_ids).delete_all
57
+ TransactionCategory.where(id: ids(snapshot, "transaction_categories")).delete_all
58
+ delete_unused_tags!(tag_ids)
59
+ end
60
+ end
61
+
62
+ def self.ids(snapshot, table)
63
+ Array(snapshot[table]).map { |row| row["id"] }
64
+ end
65
+
66
+ def self.delete_unused_tags!(tag_ids)
67
+ ActsAsTaggableOn::Tag.where(id: tag_ids).find_each do |tag|
68
+ count = ActsAsTaggableOn::Tagging.where(tag_id: tag.id).count
69
+ if count.zero?
70
+ tag.delete
71
+ else
72
+ tag.update_column(:taggings_count, count)
73
+ end
74
+ end
75
+ end
76
+ private_class_method :write_ledger!, :destination, :empty?, :purge!, :ids, :delete_unused_tags!
77
+ end
78
+ end
79
+ end