bdgtr-cli 0.2 → 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 (87) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +1 -1
  3. data/bin/bdgtr +26 -5
  4. data/lib/bdgtr/cli/config.rb +188 -0
  5. data/lib/bdgtr/cli/config.sample.yml +15 -0
  6. data/lib/bdgtr/cli/help.rb +168 -0
  7. data/lib/bdgtr/cli/ledger_sync.rb +102 -0
  8. data/lib/bdgtr/cli/prompt.rb +47 -0
  9. data/lib/bdgtr/cli/psd2.rb +530 -0
  10. data/lib/bdgtr/cli/rows.rb +38 -0
  11. data/lib/bdgtr/cli/runtime.rb +88 -0
  12. data/lib/bdgtr/cli/table.rb +458 -0
  13. data/lib/bdgtr/cli.rb +126 -0
  14. data/lib/bdgtr/core/binder.rb +79 -0
  15. data/lib/bdgtr/core/exchange.rb +66 -0
  16. data/lib/bdgtr/core/models/account.rb +177 -0
  17. data/lib/bdgtr/core/models/account_requisition.rb +12 -0
  18. data/lib/bdgtr/core/models/account_sync.rb +12 -0
  19. data/lib/bdgtr/core/models/import.rb +12 -0
  20. data/lib/bdgtr/core/models/ledger.rb +10 -0
  21. data/lib/bdgtr/core/models/requisition.rb +27 -0
  22. data/lib/bdgtr/core/models/transaction.rb +98 -0
  23. data/lib/bdgtr/core/models/transaction_category.rb +12 -0
  24. data/lib/bdgtr/core/record.rb +11 -0
  25. data/lib/bdgtr/core/schema.rb +290 -0
  26. data/lib/bdgtr/core/session.rb +76 -0
  27. data/lib/bdgtr/core/syncable.rb +272 -0
  28. data/lib/bdgtr/core/transfer.rb +90 -0
  29. data/lib/bdgtr/core.rb +18 -0
  30. data/lib/bdgtr/portfolio/Rakefile +20 -0
  31. data/lib/bdgtr/portfolio/cli/LICENSE +21 -0
  32. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/app.rb +77 -0
  33. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/import.rb +30 -0
  34. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/spreadsheet.rb +25 -0
  35. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli.rb +52 -0
  36. data/lib/bdgtr/portfolio/exe/bdgtr +7 -0
  37. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/accounts_csv.rb +67 -0
  38. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/app.rb +104 -0
  39. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/auth.rb +52 -0
  40. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/balances.rb +157 -0
  41. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/cache.rb +46 -0
  42. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/checkbox_menu.rb +90 -0
  43. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/checkbox_selection.rb +68 -0
  44. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/config.rb +138 -0
  45. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/decryptor.rb +70 -0
  46. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/drive_client.rb +182 -0
  47. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/errors.rb +10 -0
  48. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/file_reader.rb +80 -0
  49. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/fineco_import.rb +609 -0
  50. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/fineco_xls.rb +235 -0
  51. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/import/fineco.rb +243 -0
  52. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/import.rb +85 -0
  53. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/parser.rb +254 -0
  54. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/portfolio_source.rb +30 -0
  55. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/portfolio_store.rb +124 -0
  56. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/preview_window.rb +98 -0
  57. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/proto/client_pb.rb +29 -0
  58. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/row_preview.rb +174 -0
  59. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sheets_client.rb +272 -0
  60. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/snapshot.rb +27 -0
  61. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sync.rb +247 -0
  62. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sync_preview.rb +63 -0
  63. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_identity.rb +49 -0
  64. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_sync.rb +948 -0
  65. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_types.rb +142 -0
  66. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/version.rb +5 -0
  67. data/lib/bdgtr/portfolio/lib/portfolio_performance_api.rb +42 -0
  68. data/lib/bdgtr/portfolio/proto/client.proto +114 -0
  69. data/lib/bdgtr/psd2/account.rb +24 -0
  70. data/lib/bdgtr/psd2/account_snapshot.rb +96 -0
  71. data/lib/bdgtr/psd2/callback.rb +49 -0
  72. data/lib/bdgtr/psd2/connect.rb +75 -0
  73. data/lib/bdgtr/psd2/enable_banking.rb +250 -0
  74. data/lib/bdgtr/psd2/go_cardless.rb +133 -0
  75. data/lib/bdgtr/psd2/institution.rb +17 -0
  76. data/lib/bdgtr/psd2/platform.rb +37 -0
  77. data/lib/bdgtr/psd2/requisition.rb +21 -0
  78. data/lib/bdgtr/psd2/transaction.rb +29 -0
  79. data/lib/bdgtr/psd2.rb +25 -0
  80. data/lib/bdgtr/sync/importer.rb +125 -0
  81. data/lib/bdgtr/sync/library.rb +18 -0
  82. data/lib/bdgtr/sync/portfolio.rb +14 -0
  83. data/lib/bdgtr/sync/projection.rb +38 -0
  84. data/lib/bdgtr/sync/spreadsheet.rb +23 -0
  85. data/lib/bdgtr/sync.rb +25 -0
  86. data/lib/bdgtr/version.rb +1 -1
  87. metadata +353 -30
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ module Core
5
+ # Copies the ledger tables between the connection that is current when the
6
+ # method runs. capture reads. write! inserts, keeping ids.
7
+ class Transfer
8
+ def self.capture(workspace)
9
+ account_ids = Account.where(workspace_id: workspace.id).pluck(:id)
10
+ transaction_ids = Transaction.where(account_id: account_ids).pluck(:id)
11
+ taggings = ActsAsTaggableOn::Tagging.where(taggable_type: "Transaction", taggable_id: transaction_ids).to_a
12
+ tag_ids = taggings.map(&:tag_id)
13
+ requisition_ids = AccountRequisition.where(account_id: account_ids).distinct.pluck(:requisition_id)
14
+ {
15
+ "transaction_categories" => rows(TransactionCategory.where(workspace_id: workspace.id)),
16
+ "accounts" => rows(Account.where(workspace_id: workspace.id)),
17
+ "requisitions" => rows(Requisition.where(id: requisition_ids)),
18
+ "account_requisitions" => rows(AccountRequisition.where(account_id: account_ids)),
19
+ "imports" => rows(Import.where(workspace_id: workspace.id)),
20
+ "transactions" => rows(Transaction.where(id: transaction_ids)),
21
+ "account_syncs" => rows(AccountSync.where(account_id: account_ids)),
22
+ "tags" => rows(ActsAsTaggableOn::Tag.where(id: tag_ids)),
23
+ "taggings" => taggings.map { |row| row.attributes.slice(*ActsAsTaggableOn::Tagging.column_names) }
24
+ }
25
+ end
26
+
27
+ TABLES = %w[transaction_categories accounts requisitions account_requisitions imports transactions account_syncs tags taggings].freeze
28
+
29
+ def self.write!(snapshot)
30
+ snapshot = snapshot.merge("accounts" => Array(snapshot["accounts"]).map { |attrs| fold_account_sync_data(attrs) })
31
+ Record.connection.disable_referential_integrity do
32
+ TABLES.each do |table|
33
+ payload = Array(snapshot[table])
34
+ next if payload.empty?
35
+
36
+ # Tags live on their own class. Insert them through the ledger
37
+ # connection so they join the same transaction as the other rows.
38
+ model = insert_model(table)
39
+ model.insert_all(payload)
40
+ reset_sequence(model)
41
+ end
42
+ end
43
+ end
44
+
45
+ def self.insert_model(table)
46
+ model = model_for(table)
47
+ return model if model < Record
48
+
49
+ klass = Class.new(Record)
50
+ klass.table_name = table
51
+ klass.reset_column_information
52
+ klass
53
+ end
54
+
55
+ def self.fold_account_sync_data(attrs)
56
+ legacy = attrs["data"]
57
+ attrs = attrs.except("data")
58
+ return attrs if legacy.blank? || attrs["sync_data"].present?
59
+
60
+ attrs.merge("sync_data" => legacy)
61
+ end
62
+
63
+ def self.rows(relation)
64
+ columns = relation.klass.column_names
65
+ relation.order(:id).map { |row| row.attributes.slice(*columns) }
66
+ end
67
+
68
+ def self.model_for(table)
69
+ case table
70
+ when "transaction_categories" then TransactionCategory
71
+ when "accounts" then Account
72
+ when "requisitions" then Requisition
73
+ when "account_requisitions" then AccountRequisition
74
+ when "imports" then Import
75
+ when "transactions" then Transaction
76
+ when "account_syncs" then AccountSync
77
+ when "tags" then ActsAsTaggableOn::Tag
78
+ when "taggings" then ActsAsTaggableOn::Tagging
79
+ else raise ArgumentError, "unknown ledger table #{table}"
80
+ end
81
+ end
82
+
83
+ def self.reset_sequence(model)
84
+ return unless model.connection.respond_to?(:reset_pk_sequence!)
85
+
86
+ model.connection.reset_pk_sequence!(model.table_name)
87
+ end
88
+ end
89
+ end
90
+ end
data/lib/bdgtr/core.rb ADDED
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ # Ledger access. Opens one SQLite ledger and uses the same table names as Postgres.
5
+ module Core
6
+ def self.open(path, &block)
7
+ Session.open(path, &block)
8
+ end
9
+
10
+ def self.bind!(workspace, path: nil)
11
+ Binder.bind!(workspace, path: path)
12
+ end
13
+
14
+ def self.export!(workspace, path: nil)
15
+ Binder.export!(workspace, path: path)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/setup"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/*_test.rb"]
10
+ t.warning = false
11
+ end
12
+
13
+ task default: :test
14
+
15
+ namespace :proto do
16
+ desc "Regenerate Ruby protobuf bindings from proto/client.proto"
17
+ task :generate do
18
+ sh "protoc --proto_path=proto --proto_path=/opt/homebrew/include --ruby_out=lib/portfolio_performance_api/proto proto/client.proto"
19
+ end
20
+ end
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bdgtr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "thor"
4
+ require_relative "spreadsheet"
5
+ require_relative "import"
6
+
7
+ module PortfolioPerformanceApi
8
+ module Cli
9
+ class App < Thor
10
+ package_name "bdgtr"
11
+
12
+ def self.exit_on_failure?
13
+ true
14
+ end
15
+
16
+ desc "spreadsheet SUBCOMMAND", "Spreadsheet commands (dump, cleanup)"
17
+ subcommand "spreadsheet", Spreadsheet
18
+
19
+ desc "import SUBCOMMAND", "Import commands (xls)"
20
+ subcommand "import", Import
21
+
22
+ desc "version", "Show the bdgtr version of the portfolio tools"
23
+ def version
24
+ require "portfolio_performance_api/version"
25
+ puts "bdgtr #{PortfolioPerformanceApi::VERSION}"
26
+ end
27
+ map %w[--version -v] => :version
28
+
29
+ desc "help [COMMAND]", "Describe available commands or one specific command"
30
+ def help(command = nil, subcommand = false)
31
+ if command.to_s.empty?
32
+ print_colon_help
33
+ elsif command.include?(":")
34
+ namespace, name = command.split(":", 2)
35
+ klass = self.class.subcommand_classes[namespace]
36
+ if klass && name
37
+ klass.command_help(shell, name)
38
+ else
39
+ super
40
+ end
41
+ else
42
+ super
43
+ end
44
+ end
45
+
46
+ default_task :help
47
+
48
+ no_commands do
49
+ def print_colon_help
50
+ shell.print_table(colon_help_rows)
51
+ end
52
+
53
+ def colon_help_rows
54
+ rows = []
55
+ self.class.commands.each_value do |command|
56
+ next if command.hidden?
57
+ next if self.class.subcommands.include?(command.name)
58
+
59
+ rows << help_row(command.usage, command.description)
60
+ end
61
+ self.class.subcommand_classes.each do |namespace, klass|
62
+ klass.commands.each_value do |command|
63
+ next if command.hidden? || command.name == "help"
64
+
65
+ rows << help_row("#{namespace}:#{command.usage}", command.description)
66
+ end
67
+ end
68
+ rows.sort_by(&:first)
69
+ end
70
+
71
+ def help_row(usage, description)
72
+ [usage, description.to_s.empty? ? "" : "# #{description}"]
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "thor"
4
+
5
+ module PortfolioPerformanceApi
6
+ module Cli
7
+ class Import < Thor
8
+ def self.banner(command, _namespace = nil, _subcommand = false)
9
+ "import:#{command.usage}"
10
+ end
11
+
12
+ def self.check_unknown_options?(*)
13
+ false
14
+ end
15
+
16
+ desc "xls PROVIDER ACCOUNT [XLS]", "Import an Excel export into the Drive .portfolio"
17
+ long_desc <<~LONGDESC
18
+ Import a provider Excel export into the Drive .portfolio.
19
+
20
+ Examples:
21
+ import:xls fineco EUR010069756 ./movements.xlsx
22
+ import:xls fineco EUR010069756 --file ~/Desktop/movements.xlsx --exclude "Compravendita"
23
+ LONGDESC
24
+ def xls(*_args)
25
+ require "portfolio_performance_api/import"
26
+ PortfolioPerformanceApi::Import.run(Cli.arguments_after("import", "xls"))
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "thor"
4
+
5
+ module PortfolioPerformanceApi
6
+ module Cli
7
+ class Spreadsheet < Thor
8
+ def self.banner(command, _namespace = nil, _subcommand = false)
9
+ "spreadsheet:#{command.usage}"
10
+ end
11
+
12
+ desc "dump", "Align the Drive .portfolio with the Google spreadsheet"
13
+ def dump
14
+ require "portfolio_performance_api/sync"
15
+ PortfolioPerformanceApi::Sync.new.run
16
+ end
17
+
18
+ desc "cleanup", "Clear spreadsheet tabs one at a time"
19
+ def cleanup
20
+ require "portfolio_performance_api/sync"
21
+ PortfolioPerformanceApi::Sync.new.cleanup
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dotenv"
4
+ require "thor"
5
+
6
+ require_relative "cli/app"
7
+
8
+ module PortfolioPerformanceApi
9
+ module Cli
10
+ COMMAND_SEPARATOR = ":"
11
+
12
+ class << self
13
+ attr_accessor :raw_argv
14
+
15
+ def start(argv = ARGV)
16
+ self.raw_argv = Array(argv)
17
+ App.start(split_namespaced(raw_argv))
18
+ end
19
+
20
+ def load_environment!
21
+ paths = [File.expand_path(".env", Dir.pwd)]
22
+ root = ENV["BDGTR_ROOT"].to_s
23
+ paths << File.join(root, ".env") unless root.empty?
24
+ Dotenv.load(*paths.uniq)
25
+ end
26
+
27
+ def split_namespaced(argv)
28
+ args = Array(argv).dup
29
+ token = args[0].to_s
30
+ return args if token.empty? || token.start_with?("-") || !token.include?(COMMAND_SEPARATOR)
31
+
32
+ namespace, command = token.split(COMMAND_SEPARATOR, 2)
33
+ return args if namespace.empty? || command.empty?
34
+ return args unless namespace.match?(/\A[a-z][a-z0-9_]*\z/i) && command.match?(/\A[a-z][a-z0-9_]*\z/i)
35
+
36
+ [namespace, command, *args[1..]]
37
+ end
38
+
39
+ def arguments_after(*tokens)
40
+ argv = Array(raw_argv)
41
+ joined = tokens.join(COMMAND_SEPARATOR)
42
+ index = argv.index(joined)
43
+ return argv[(index + 1)..] if index
44
+
45
+ argv.each_cons(tokens.size).with_index do |window, i|
46
+ return argv[(i + tokens.size)..] if window == tokens
47
+ end
48
+ argv
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "portfolio_performance_api/cli"
5
+
6
+ PortfolioPerformanceApi::Cli.load_environment!
7
+ PortfolioPerformanceApi::Cli.start(ARGV)
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "csv"
4
+
5
+ module PortfolioPerformanceApi
6
+ module AccountsCsv
7
+ HEADERS = %w[uuid kind name currency retired balance balance_cents reference_account_uuid].freeze
8
+
9
+ module_function
10
+
11
+ def generate(payload, locale: "en")
12
+ locale = normalize_locale(locale)
13
+ accounts = Array(payload[:accounts] || payload["accounts"])
14
+ CSV.generate(**csv_options) do |csv|
15
+ csv << HEADERS
16
+ accounts.each do |row|
17
+ csv << serialize_row(row, locale)
18
+ end
19
+ end
20
+ end
21
+
22
+ def csv_options
23
+ {
24
+ encoding: Encoding::UTF_8,
25
+ col_sep: ";",
26
+ row_sep: "\r\n",
27
+ force_quotes: false
28
+ }
29
+ end
30
+
31
+ def serialize_row(row, locale)
32
+ row = stringify_keys(row)
33
+ [
34
+ row["uuid"],
35
+ row["kind"],
36
+ row["name"],
37
+ row["currency"],
38
+ boolean(row["retired"]),
39
+ decimal(row["balance"], locale),
40
+ row["balance_cents"],
41
+ row["reference_account_uuid"]
42
+ ]
43
+ end
44
+
45
+ def stringify_keys(row)
46
+ row.to_h { |key, value| [key.to_s, value] }
47
+ end
48
+
49
+ def boolean(value)
50
+ value ? "TRUE" : "FALSE"
51
+ end
52
+
53
+ def decimal(value, locale)
54
+ formatted = format("%.2f", Float(value))
55
+ return formatted unless locale == "it"
56
+
57
+ formatted.tr(".", ",")
58
+ end
59
+
60
+ def normalize_locale(value)
61
+ code = value.to_s.strip.downcase.split(/[-_]/, 2).first
62
+ code == "it" ? "it" : "en"
63
+ end
64
+
65
+ private_class_method :csv_options, :serialize_row, :stringify_keys, :boolean, :decimal
66
+ end
67
+ end
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "sinatra/base"
5
+
6
+ module PortfolioPerformanceApi
7
+ class App < Sinatra::Base
8
+ configure do
9
+ set :show_exceptions, false
10
+ set :raise_errors, false
11
+ set :dump_errors, ENV["RACK_ENV"] != "test"
12
+ set :logging, ENV["RACK_ENV"] != "test"
13
+ disable :static
14
+ end
15
+
16
+ configure :development do
17
+ require "sinatra/reloader"
18
+ register Sinatra::Reloader
19
+ Dir[File.expand_path("**/*.rb", __dir__)].each do |path|
20
+ also_reload path
21
+ end
22
+ end
23
+
24
+ error Unauthorized do
25
+ error_json 401, "unauthorized"
26
+ end
27
+
28
+ error NotConfigured do
29
+ error_json 500, "not_configured"
30
+ end
31
+
32
+ error IncorrectPassword, NotAPortfolioFile do
33
+ error_json 422, "portfolio_error"
34
+ end
35
+
36
+ error DriveError do
37
+ error_json 502, "drive_error"
38
+ end
39
+
40
+ error do
41
+ error_json 500, "internal_error"
42
+ end
43
+
44
+ get "/health" do
45
+ json(status: "ok", version: VERSION)
46
+ end
47
+
48
+ get "/accounts.csv" do
49
+ payload = accounts_payload
50
+ lang = AccountsCsv.normalize_locale(params["locale"])
51
+ content_type "text/csv", charset: "utf-8"
52
+ headers["Content-Language"] = lang
53
+ headers["Cache-Control"] = "private, no-store"
54
+ headers["Content-Disposition"] = %(inline; filename="accounts-#{lang}.csv")
55
+ AccountsCsv.generate(payload, locale: lang)
56
+ end
57
+
58
+ get "/accounts.json" do
59
+ json(accounts_payload)
60
+ end
61
+
62
+ get "/accounts" do
63
+ json(accounts_payload)
64
+ end
65
+
66
+ get "/" do
67
+ json(accounts_payload)
68
+ end
69
+
70
+ helpers do
71
+ def accounts_payload
72
+ Auth.require!(env)
73
+ snapshot.accounts(nocache: nocache?)
74
+ end
75
+
76
+ def snapshot
77
+ self.class.snapshot
78
+ end
79
+
80
+ def nocache?
81
+ params.key?("nocache")
82
+ end
83
+
84
+ def json(object = nil, **fields)
85
+ payload = object.nil? ? fields : object
86
+ content_type "application/json"
87
+ JSON.generate(payload)
88
+ end
89
+
90
+ def error_json(status_code, name)
91
+ status status_code
92
+ json(error: name, message: env["sinatra.error"].message)
93
+ end
94
+ end
95
+
96
+ def self.snapshot
97
+ PortfolioPerformanceApi.snapshot
98
+ end
99
+
100
+ def self.snapshot=(value)
101
+ PortfolioPerformanceApi.snapshot = value
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "rack/utils"
5
+
6
+ module PortfolioPerformanceApi
7
+ module Auth
8
+ module_function
9
+
10
+ def require!(env)
11
+ provided = api_key_from(env)
12
+ raise Unauthorized, "missing API key" if provided.nil? || provided.empty?
13
+ raise Unauthorized, "invalid API key" unless secure_compare(provided, Config.api_key)
14
+ end
15
+
16
+ def api_key_from(env)
17
+ from_header(env) || from_authorization(env) || from_query(env)
18
+ end
19
+
20
+ def from_header(env)
21
+ header = Config.api_key_header
22
+ rack_name = "HTTP_#{header.upcase.tr("-", "_")}"
23
+ value = env[rack_name]
24
+ present(value)
25
+ end
26
+
27
+ def from_authorization(env)
28
+ authorization = env["HTTP_AUTHORIZATION"].to_s
29
+ return if authorization.empty?
30
+ return authorization.sub(/\ABearer\s+/i, "") if authorization.match?(/\ABearer\s+/i)
31
+
32
+ authorization
33
+ end
34
+
35
+ def from_query(env)
36
+ query = Rack::Utils.parse_query(env["QUERY_STRING"].to_s)
37
+ value = query["apikey"]
38
+ value = value.first if value.is_a?(Array)
39
+ present(value)
40
+ end
41
+
42
+ def present(value)
43
+ return if value.nil? || value.empty?
44
+
45
+ value
46
+ end
47
+
48
+ def secure_compare(a, b)
49
+ Rack::Utils.secure_compare(Digest::SHA256.hexdigest(a), Digest::SHA256.hexdigest(b))
50
+ end
51
+ end
52
+ end