amounts 0.2.0 → 0.3.1

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9a77f5a9506149f307e11d78c1063e9951c149302eaace9b35e924cf92ce4102
4
- data.tar.gz: ade0b4aca169538a4b9e17d3e4ab412f19cbe343aff7b540de6936b814373751
3
+ metadata.gz: 1b99d7bc88a17f234c114154f19398ecc56df1543f06d4761a3575b94cdd048e
4
+ data.tar.gz: 066f2619c934bcda1f006a0c4bed2bda6afb9aa995e9158eec34186d84570b06
5
5
  SHA512:
6
- metadata.gz: 0c9225c174016b40143bd049c8673312a0ceffcb32244b5ce9a613cdb2342d768faf67141ea0aeb30fe5c91d89bbf720860dae27fb77413e401d9e1877723b9b
7
- data.tar.gz: 1c0dd2ff180fc3589c4a722bd0789e37b9afb7d71599680c77fcd299b2e07366df31d439647c5927ff9a8f50d1d89c07ec8de1da05fae72d9570be78e8731020
6
+ metadata.gz: f4911f3bff7b8a5af9b7d946845a4d264bacf29736f841767d9453622f2c344e3dc24dd2762e1b13965817cadebc4ae4c341e042b15174e2982437fdb6c76be1
7
+ data.tar.gz: 38979ea9efb87717a922271cb0acf64f80a9998af17ae01e0139789ad4662b99f88f82d1816844786ac9a133f83f7b01487bc7c1a1e24a09f91d48427641b72b
data/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.1 - 2026-11-15
4
+
5
+ ### Added
6
+
7
+ - `sum_amount`, `minimum_amount`, `maximum_amount` and `average_amount` take
8
+ several `has_amount` attributes and aggregate them all in one query, returning
9
+ a Hash by attribute name (per group when grouped) in place of each Amount, as
10
+ Rails' `pluck` returns rows for several columns. A model with several amounts
11
+ on one table no longer pays one round trip per amount over the same rows.
12
+ Each attribute folds exactly as it would alone, with the same symbol rule. With
13
+ several attributes, a group appears when it has any row, and an attribute with
14
+ no amount in it gets the empty-set result (zero for a fixed-symbol sum, else
15
+ `nil`). A name given twice raises `ArgumentError`. With one attribute, nothing
16
+ changes.
17
+
18
+ ## 0.3.0 - 2026-11-15
19
+
20
+ ### Added
21
+
22
+ - `Amount.manifest(locales: [])` exports the registry as a JSON-ready Hash for
23
+ a client in another language to mirror: every type (with the
24
+ `Amount.register` option names), every default rate as an exact decimal
25
+ string, and for each requested locale every translation the core looks up,
26
+ already resolved. The new `@zarpay/amounts` JavaScript client is built from
27
+ it. Locales need I18n.
28
+ - `Amount::Registry#default_rates` returns every registered default rate,
29
+ keyed by `[from, to]`.
30
+ - `Amount::Compact.locale_format(locale)` is public.
31
+
32
+ ### Fixed
33
+
34
+ - **Breaking:** `ui` and `to_s` round negative amounts by magnitude, like
35
+ their positive. `direction: :floor` (the default) now rounds toward zero and
36
+ `:ceil` away from it; before, `:floor` rounded toward negative infinity, so
37
+ a negative displayed more than it was (`-1.234` showed as `$-1.24`, and
38
+ `-0.001` as `$-0.01`). It now shows `$-1.23` and `$0.00`, and a value that
39
+ rounds to zero has no sign. Compact notation follows (`-1_999_999` is
40
+ `-1.99M`, was `-2M`). Positive amounts are unchanged. This matches `*`, `/`,
41
+ `to`, `split` and `allocate`, which already truncate toward zero. Migration:
42
+ code or tests that expect the old output for an inexact negative amount
43
+ should expect its positive's digits; pass `direction: :ceil` for the
44
+ larger magnitude.
45
+
3
46
  ## 0.2.0 - 2026-11-14
4
47
 
5
48
  ### Added
data/README.md CHANGED
@@ -422,6 +422,26 @@ Amount.of_usdc("1.5").as_json # => "USDC|1.500000"
422
422
  { amount: Amount.of_usdc("1.5") }.to_json # => '{"amount":"USDC|1.500000"}'
423
423
  ```
424
424
 
425
+ ### JavaScript client
426
+
427
+ `Amount.manifest` exports the registry for the
428
+ [`@zarpay/amounts`](../client) JavaScript client, which mirrors the core on the
429
+ web and in React Native: the same parsing, math, conversions, serialization
430
+ and display, on `bigint` atomic values.
431
+
432
+ ```ruby
433
+ render json: Amount.manifest(locales: I18n.available_locales)
434
+ ```
435
+
436
+ ```ts
437
+ const amounts = Amounts.fromManifest(manifest);
438
+ amounts.parse("USDC|1.500000").add(amounts.of("USDC", "0.25")).ui(); // "$1.75"
439
+ ```
440
+
441
+ The manifest holds the types (with the `Amount.register` option names), the
442
+ default rates as exact decimal strings, and for each requested locale every
443
+ translation the core looks up. Locales need I18n.
444
+
425
445
  ## Registry API
426
446
 
427
447
  ```ruby
@@ -429,9 +449,11 @@ Amount.register(...)
429
449
  Amount.register_default_rate(:USD, :USDC, "1")
430
450
  Amount.registry.lookup(:USDC)
431
451
  Amount.registry.symbols
452
+ Amount.registry.default_rates
432
453
  Amount.registry.clear!
433
454
  Amount.registry.lock!
434
455
  Amount.registry.locked?
456
+ Amount.manifest(locales: %i[en de])
435
457
  ```
436
458
 
437
459
  ## ActiveRecord Integration
@@ -546,6 +568,14 @@ Holding.average_amount(:fee) # truncated toward zero, lik
546
568
  Holding.group(:amount_symbol).sum_amount(:amount) # => { "USDC" => #<Amount USDC ...>, "SOL" => ... }
547
569
  ```
548
570
 
571
+ Given several attributes, like `pluck`, each aggregate still runs one query and
572
+ returns a Hash by name:
573
+
574
+ ```ruby
575
+ Holding.sum_amount(:amount, :fee) # => { amount: #<Amount USDC ...>, fee: #<Amount SOL ...> }
576
+ Holding.group(:account_id).sum_amount(:amount, :fee) # => { 1 => { amount: ..., fee: ... }, ... }
577
+ ```
578
+
549
579
  Symbols never mix: a multi-symbol attribute with more than one symbol in scope
550
580
  (or in one group) raises `Amount::TypeMismatch`, so group by its symbol column for
551
581
  one Amount per symbol. A fixed-symbol sum over no rows is zero; otherwise an
@@ -654,14 +684,20 @@ bundle exec rspec
654
684
 
655
685
  ## Releases
656
686
 
657
- RubyGems publishing is intended to run from GitHub Releases using RubyGems trusted publishing.
687
+ The gem and the [`@zarpay/amounts`](../client) JavaScript client are versioned in lockstep and
688
+ released together from one GitHub Release, both through trusted publishing.
658
689
 
659
690
  Workflow:
660
691
 
661
- - create and push a version tag such as `v0.0.1`
692
+ - bump `Amount::VERSION` and `client/package.json` to the same version (CI fails when they
693
+ differ), and date both changelogs
694
+ - create and push a version tag such as `v0.3.0`
662
695
  - publish a GitHub Release for that tag
663
- - GitHub Actions runs `.github/workflows/release.yml`
664
- - the workflow verifies the test suite and publishes the gem to RubyGems.org
696
+ - GitHub Actions runs `.github/workflows/release.yml`, which verifies the test suite and
697
+ publishes the gem to RubyGems.org
698
+ - and `.github/workflows/publish-npm.yml`, which verifies the tag against both versions, runs
699
+ the client's checks and publishes `@zarpay/amounts` to npm with provenance (skipping a
700
+ version that's already on npm)
665
701
 
666
702
  RubyGems setup:
667
703
 
@@ -671,9 +707,18 @@ RubyGems setup:
671
707
  - workflow filename: `release.yml`
672
708
  - GitHub Actions environment: `release`
673
709
 
674
- This uses OIDC trusted publishing, so no RubyGems API token needs to be stored in GitHub Actions. See the official RubyGems trusted publishing guide:
710
+ npm setup:
711
+
712
+ - the first version of `@zarpay/amounts` is published once by hand (`npm publish --access public`
713
+ from `client/`), since npm can only attach a trusted publisher to a package that exists
714
+ - on npmjs.com, in the package's settings, add a trusted publisher: GitHub Actions, organization
715
+ `zarpay`, repository `amounts`, workflow filename `publish-npm.yml`, environment `release`
716
+
717
+ This uses OIDC trusted publishing on both registries, so no API token needs to be stored in
718
+ GitHub Actions. See the official guides:
675
719
 
676
720
  - https://guides.rubygems.org/trusted-publishing/
721
+ - https://docs.npmjs.com/trusted-publishers
677
722
 
678
723
  ## Compared to `money`
679
724
 
@@ -11,6 +11,13 @@ class Amount
11
11
  # Group by a column or SQL expression; grouping by an association name
12
12
  # raises `ArgumentError` (group by its foreign key instead).
13
13
  #
14
+ # Given several attributes, like Rails' `pluck`, each method still runs
15
+ # one query and returns a Hash keyed by attribute name in place of each
16
+ # Amount: `{ quantity: ..., cost: ... }`, or per group
17
+ # `{ "search" => { quantity: ..., cost: ... } }`. A group is in the result
18
+ # when it has any row; an attribute with no amount in that group gets the
19
+ # result of an empty set (zero for a fixed-symbol sum, else `nil`).
20
+ #
14
21
  # Amounts of different symbols never combine: a multi-symbol attribute
15
22
  # with more than one symbol in scope, or in one group, raises
16
23
  # {Amount::TypeMismatch}. Group by its symbol column for one Amount per
@@ -20,65 +27,83 @@ class Amount
20
27
  # UsageRecord.sum_amount(:cost) # => #<Amount USDP ...>
21
28
  # UsageRecord.group(:kind).sum_amount(:cost) # => { "search" => #<Amount USDP ...> }
22
29
  # UsageRecord.group(:quantity_symbol).sum_amount(:quantity)
30
+ #
31
+ # @example Several attributes, one query
32
+ # UsageRecord.group(:kind).sum_amount(:quantity, :cost)
33
+ # # => { "search" => { quantity: #<Amount SEARCHES 3>, cost: #<Amount USDP $0.30> } }
23
34
  module Calculations
24
35
  # A fixed-symbol sum over no rows is zero; a multi-symbol one is `nil`.
25
36
  #
26
- # @param name [Symbol, String] a `has_amount` attribute
27
- # @return [Amount, Hash, nil]
37
+ # @param names [Array<Symbol, String>] one or more `has_amount` attributes
38
+ # @return [Amount, Hash, nil] for several names, a Hash by name
28
39
  # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
29
- def sum_amount(name)
40
+ # @raise [ArgumentError] for no names, or a name given twice
41
+ def sum_amount(*names)
30
42
  # SQL's SUM is NULL over no rows, and `none` runs no query at all;
31
43
  # Rails' `sum` is zero for both. `deserialize(0)` is that zero for a
32
44
  # fixed symbol and `nil` for a multi-symbol attribute.
33
- zero = amount_attribute_definitions.fetch(name.to_sym).type.deserialize(0)
34
- aggregate_amount(name, :sum) { |sum| sum || zero } || zero
45
+ aggregate_amounts(names, :sum) { |definition, sum| sum || definition.type.deserialize(0) }
35
46
  end
36
47
 
37
- # @param name [Symbol, String] a `has_amount` attribute
38
- # @return [Amount, Hash, nil] `nil` over no rows
48
+ # @param names [Array<Symbol, String>] one or more `has_amount` attributes
49
+ # @return [Amount, Hash, nil] `nil` over no rows; for several names, a Hash by name
39
50
  # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
40
- def minimum_amount(name)
41
- aggregate_amount(name, :minimum) { |minimum| minimum }
51
+ # @raise [ArgumentError] for no names, or a name given twice
52
+ def minimum_amount(*names)
53
+ aggregate_amounts(names, :minimum) { |_definition, minimum| minimum }
42
54
  end
43
55
 
44
- # @param name [Symbol, String] a `has_amount` attribute
45
- # @return [Amount, Hash, nil] `nil` over no rows
56
+ # @param names [Array<Symbol, String>] one or more `has_amount` attributes
57
+ # @return [Amount, Hash, nil] `nil` over no rows; for several names, a Hash by name
46
58
  # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
47
- def maximum_amount(name)
48
- aggregate_amount(name, :maximum) { |maximum| maximum }
59
+ # @raise [ArgumentError] for no names, or a name given twice
60
+ def maximum_amount(*names)
61
+ aggregate_amounts(names, :maximum) { |_definition, maximum| maximum }
49
62
  end
50
63
 
51
64
  # The sum divided by the number of amounts, truncated toward zero to a
52
65
  # whole atomic unit, as `Amount#/` does. The sum and the count come from
53
66
  # the same query.
54
67
  #
55
- # @param name [Symbol, String] a `has_amount` attribute
56
- # @return [Amount, Hash, nil] `nil` over no rows
68
+ # @param names [Array<Symbol, String>] one or more `has_amount` attributes
69
+ # @return [Amount, Hash, nil] `nil` over no rows; for several names, a Hash by name
57
70
  # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
58
- def average_amount(name)
59
- aggregate_amount(name, :sum, :count) { |sum, count| sum / count unless count.zero? }
71
+ # @raise [ArgumentError] for no names, or a name given twice
72
+ def average_amount(*names)
73
+ aggregate_amounts(names, :sum, :count) { |_definition, sum, count| sum / count unless count.zero? }
60
74
  end
61
75
 
62
76
  private
63
77
 
64
- # Plucks the caller's groups, the symbol and the aggregates as
65
- # `[*groups, symbol, atomic, *rest]`, then yields each group's first
66
- # aggregate as an Amount, with the rest as they came.
67
- def aggregate_amount(name, *operations)
68
- definition = amount_attribute_definitions.fetch(name.to_sym)
78
+ # Plucks `[*groups, *columns]`, where each attribute contributes its
79
+ # symbol and one aggregate per operation, then folds each caller group's
80
+ # rows per attribute. A multi-symbol attribute is grouped by its symbol
81
+ # column too, so one caller group can span several rows.
82
+ def aggregate_amounts(names, *operations, &fold)
83
+ definitions = amount_definitions_for(names)
69
84
  groups = amount_group_values
70
- atomic = arel_table[definition.atomic_column]
85
+ rows = amount_aggregate_scope(definitions)
86
+ .pluck(*groups, *amount_aggregate_columns(definitions, operations))
87
+
88
+ fold_rows = lambda do |group_rows|
89
+ columns = group_rows.map { |row| row.drop(groups.size) }
90
+ results = amount_fold_group(definitions, operations, columns, &fold)
91
+ names.one? ? results.values.first : results
92
+ end
93
+
94
+ return fold_rows.call(rows) if groups.empty?
71
95
 
72
- rows = amount_aggregate_scope(definition)
73
- .pluck(*groups, amount_symbol_select(definition),
74
- *operations.map { |operation| atomic.public_send(operation) })
96
+ rows.group_by { |row| amount_group_key(row.first(groups.size)) }.transform_values(&fold_rows)
97
+ end
98
+
99
+ def amount_definitions_for(names)
100
+ raise ArgumentError, "pass at least one has_amount attribute" if names.empty?
75
101
 
76
- results = rows.group_by { |row| amount_group_key(row.first(groups.size)) }
77
- .transform_values do |group_rows|
78
- yield(*amount_group_values_of(definition, group_rows.map { |row| row.drop(groups.size) }))
79
- end
102
+ symbols = names.map(&:to_sym)
103
+ repeated = symbols.detect { |symbol| symbols.count(symbol) > 1 }
104
+ raise ArgumentError, "#{repeated} is given more than once" if repeated
80
105
 
81
- groups.empty? ? results[[]] : results
106
+ symbols.map { |symbol| amount_attribute_definitions.fetch(symbol) }
82
107
  end
83
108
 
84
109
  # The caller passed these to `group`, which takes raw SQL; `pluck` takes
@@ -95,12 +120,27 @@ class Amount
95
120
  end
96
121
  end
97
122
 
98
- # A multi-symbol attribute is grouped by its symbol too, so each row is
99
- # one symbol's aggregate. Rows without an amount are left out.
100
- def amount_aggregate_scope(definition)
101
- return all if definition.fixed_symbol?
123
+ # Each multi-symbol attribute is grouped by its symbol column, so each
124
+ # row holds one symbol per attribute. A single multi-symbol attribute
125
+ # also leaves out rows without an amount, so a group with no amount is
126
+ # absent rather than `nil`; with several attributes a row may have one
127
+ # amount and not another, and the fold skips each attribute's `NULL`s.
128
+ def amount_aggregate_scope(definitions)
129
+ multi_symbol = definitions.reject(&:fixed_symbol?)
130
+ scope = all
131
+ scope = scope.where.not(multi_symbol.first.symbol_column => nil) if definitions.one? && multi_symbol.one?
132
+
133
+ multi_symbol.reduce(scope) { |grouped, definition| grouped.group(definition.symbol_column) }
134
+ end
102
135
 
103
- where.not(definition.symbol_column => nil).group(definition.symbol_column)
136
+ # Per attribute: its symbol (a constant for a fixed symbol), then one
137
+ # aggregate of its atomic column per operation.
138
+ def amount_aggregate_columns(definitions, operations)
139
+ definitions.flat_map do |definition|
140
+ atomic = arel_table[definition.atomic_column]
141
+
142
+ [amount_symbol_select(definition), *operations.map { |operation| atomic.public_send(operation) }]
143
+ end
104
144
  end
105
145
 
106
146
  def amount_symbol_select(definition)
@@ -113,14 +153,47 @@ class Amount
113
153
  values.size == 1 ? values.first : values
114
154
  end
115
155
 
116
- def amount_group_values_of(definition, rows)
117
- unless rows.size == 1
118
- raise ::Amount::TypeMismatch,
119
- "#{definition.name} has more than one symbol in scope: #{rows.map(&:first).join(', ')}"
156
+ # One caller group's rows, folded per attribute, as `{ name => result }`.
157
+ def amount_fold_group(definitions, operations, rows, &fold)
158
+ width = operations.size + 1
159
+
160
+ definitions.each_with_index.to_h do |definition, index|
161
+ slices = rows.map { |row| row[index * width, width] }
162
+
163
+ [definition.name, amount_fold(definition, operations, slices, &fold)]
164
+ end
165
+ end
166
+
167
+ # One attribute's slices `[symbol, *aggregates]`, one per row: the rows
168
+ # without its amount are skipped, the rest must share one symbol, and
169
+ # each aggregate is combined across them before the fold sees it.
170
+ def amount_fold(definition, operations, slices)
171
+ present = slices.reject { |symbol, *| symbol.nil? }
172
+ symbols = present.map(&:first).uniq
173
+ if symbols.size > 1
174
+ raise ::Amount::TypeMismatch, "#{definition.name} has more than one symbol in scope: #{symbols.join(', ')}"
120
175
  end
121
176
 
122
- symbol, atomic, *rest = rows.first
123
- [definition.type.deserialize(atomic, symbol), *rest]
177
+ atomic, *rest = operations.each_with_index.map do |operation, index|
178
+ amount_combine(operation, present.map { |slice| slice[index + 1] })
179
+ end
180
+
181
+ yield(definition, definition.type.deserialize(atomic, symbols.first), *rest)
182
+ end
183
+
184
+ # Several rows' partial aggregates as one: sums and counts add up, and
185
+ # the minimum or maximum is that of the partials. Over no rows, a count
186
+ # is zero and everything else `nil`.
187
+ def amount_combine(operation, values)
188
+ values = values.compact
189
+ return values.sum if operation == :count
190
+ return if values.empty?
191
+
192
+ case operation
193
+ when :sum then values.sum
194
+ when :minimum then values.min
195
+ when :maximum then values.max
196
+ end
124
197
  end
125
198
  end
126
199
  end
@@ -117,6 +117,10 @@ class Amount
117
117
  Formattable.fill(locale_format(locale), number:, label: word)
118
118
  end
119
119
 
120
+ # The template joining a compacted number and its scale word in `locale`:
121
+ # `number.human.decimal_units.format` when it places `%n`, else `"%n %u"`.
122
+ # @param locale [Symbol, String]
123
+ # @return [String]
120
124
  def locale_format(locale)
121
125
  found = Locale.translate(LOCALE_FORMAT_KEY, locale, LOCALE_FORMAT)
122
126
  Formattable.valid_template?(found) ? found : LOCALE_FORMAT
@@ -132,6 +136,6 @@ class Amount
132
136
  raise ArgumentError, "compact: precision must be a positive Integer, got #{digits.inspect}"
133
137
  end
134
138
 
135
- private_class_method :round, :number, :join, :locale_format, :precision_from_hash
139
+ private_class_method :round, :number, :join, :precision_from_hash
136
140
  end
137
141
  end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ # Concern: exporting the registry for a client in another language to
5
+ # mirror. See {Manifest} for what the export holds.
6
+ module Exportable
7
+ def self.included(base)
8
+ base.extend(ClassMethods)
9
+ end
10
+
11
+ # Class-level methods extended onto any class that does `include Exportable`.
12
+ module ClassMethods
13
+ # The registry as a JSON-ready manifest: its types, its default rates,
14
+ # and for each locale in `locales` every translation the core looks up.
15
+ # The `@zarpay/amounts` JavaScript client is built from it.
16
+ #
17
+ # @param locales [Array<Symbol, String>] locales to resolve (needs I18n)
18
+ # @return [Hash{String=>Object}]
19
+ # @raise [ArgumentError] when locales are given without I18n loaded
20
+ # @example
21
+ # Amount.manifest["types"]["USDC"]["decimals"]
22
+ # # => 6
23
+ #
24
+ # @example Serving it from a Rails controller
25
+ # render json: Amount.manifest(locales: I18n.available_locales)
26
+ def manifest(locales: [])
27
+ Manifest.new(registry, locales:).to_h
28
+ end
29
+ end
30
+ end
31
+ end
@@ -6,16 +6,19 @@ class Amount
6
6
  # Formats amounts for UI output without changing their type.
7
7
  class Display
8
8
  # Rounds to `decimals` places (negative rounds to tens, hundreds, ...),
9
- # down with `:floor` and up with `:ceil`, like `ui`'s `direction:`.
9
+ # like `ui`'s `direction:`. The direction is by magnitude: `:floor` rounds
10
+ # toward zero and `:ceil` away from it, so a negative amount rounds like
11
+ # its positive and never displays more than it is. The rounded value is
12
+ # never negative zero.
10
13
  # @param value [BigDecimal]
11
14
  # @param decimals [Integer]
12
15
  # @param direction [Symbol]
13
16
  # @return [BigDecimal]
14
17
  def self.round(value, decimals, direction)
15
18
  factor = BigDecimal(10)**decimals
16
- scaled = value * factor
17
- truncated = direction == :ceil ? scaled.ceil : scaled.floor
18
- truncated / factor
19
+ scaled = value.abs * factor
20
+ magnitude = direction == :ceil ? scaled.ceil : scaled.floor
21
+ (value.negative? ? -magnitude : magnitude) / factor
19
22
  end
20
23
 
21
24
  # @param amount [Amount]
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Amount
4
+ # Writes a registry as a manifest: a JSON-ready Hash with everything the
5
+ # core reads at runtime, for a client in another language to mirror (the
6
+ # `@zarpay/amounts` JavaScript client reads it).
7
+ #
8
+ # Types are written with the `Amount.register` option names. Every I18n
9
+ # lookup the core makes is resolved for each requested locale, so a client
10
+ # needs neither I18n nor its key conventions. The fallbacks (a missing label
11
+ # to `display_symbol`, a missing format to the registered template) are left
12
+ # to the client, which applies them as the gem does.
13
+ #
14
+ # @example
15
+ # Amount::Manifest.new(Amount.registry, locales: [:de]).to_h["types"]["USD"]["decimals"]
16
+ # # => 2
17
+ class Manifest
18
+ VERSION = 1
19
+
20
+ # @param registry [Amount::Registry]
21
+ # @param locales [Array<Symbol, String>] locales to resolve (needs I18n)
22
+ # @raise [ArgumentError] when locales are given without I18n loaded
23
+ def initialize(registry, locales: [])
24
+ Locale.require_i18n! unless locales.empty?
25
+
26
+ @registry = registry
27
+ @locales = locales
28
+ end
29
+
30
+ # @return [Hash{String=>Object}]
31
+ def to_h
32
+ {
33
+ "v" => VERSION,
34
+ "types" => @registry.symbols.to_h { |symbol| [symbol.to_s, type(@registry.lookup(symbol))] },
35
+ "rates" => @registry.default_rates.map { |(from, to), rate| rate_row(from, to, rate) },
36
+ "locales" => @locales.to_h { |locale| [locale.to_s, locale_table(locale)] }
37
+ }
38
+ end
39
+
40
+ private
41
+
42
+ def type(entry)
43
+ {
44
+ "decimals" => entry.decimals,
45
+ "display_symbol" => label(entry.display_symbol),
46
+ "display_format" => entry.display_format,
47
+ "ui_decimals" => entry.ui_decimals,
48
+ "trim_zeros" => entry.trim_zeros ? true : false,
49
+ "display_units" => entry.display_units&.to_h { |unit, spec| [unit.to_s, display_unit(spec)] },
50
+ "default_display" => entry.default_display&.to_s
51
+ }
52
+ end
53
+
54
+ def display_unit(spec)
55
+ {
56
+ "scale" => Amount.coerce_decimal(spec[:scale]).to_s("F"),
57
+ "symbol" => label(spec[:symbol]),
58
+ "ui_decimals" => spec[:ui_decimals],
59
+ "format" => spec[:format] || (spec[:position] && Formattable.template_for(spec[:position])),
60
+ "trim_zeros" => unit_trim_zeros(spec)
61
+ }
62
+ end
63
+
64
+ # `nil` when the unit doesn't set it, so the client falls back to the type.
65
+ def unit_trim_zeros(spec)
66
+ return unless spec.key?(:trim_zeros)
67
+
68
+ spec[:trim_zeros] ? true : false
69
+ end
70
+
71
+ def rate_row(from, to, rate)
72
+ { "from" => from.to_s, "to" => to.to_s, "rate" => rate.to_s("F") }
73
+ end
74
+
75
+ def locale_table(locale)
76
+ {
77
+ "number" => Locale.number_format(locale).transform_keys(&:to_s),
78
+ "compact" => compact_table(locale),
79
+ "types" => @registry.symbols.to_h { |symbol| [symbol.to_s, type_table(@registry.lookup(symbol), locale)] }
80
+ }
81
+ end
82
+
83
+ def compact_table(locale)
84
+ units = Compact::SCALES.to_h do |_, key, _|
85
+ [key.to_s, label(lookup("#{Compact::LOCALE_UNITS_KEY}.#{key}", locale))]
86
+ end
87
+
88
+ { "format" => Compact.locale_format(locale), "units" => units }
89
+ end
90
+
91
+ def type_table(entry, locale)
92
+ downcased = entry.symbol.to_s.downcase
93
+ units = (entry.display_units || {}).to_h do |unit, spec|
94
+ [unit.to_s, unit_table(downcased, unit, spec, locale)]
95
+ end
96
+
97
+ {
98
+ "label" => label(lookup(entry.label_key || "amounts.units.#{downcased}", locale)),
99
+ "format" => template(lookup("amounts.formats.#{downcased}", locale)),
100
+ "units" => units
101
+ }
102
+ end
103
+
104
+ def unit_table(downcased, unit, spec, locale)
105
+ {
106
+ "label" => label(lookup(spec[:label_key] || "amounts.display_units.#{downcased}.#{unit}", locale)),
107
+ "format" => template(lookup("amounts.display_unit_formats.#{downcased}.#{unit}", locale))
108
+ }
109
+ end
110
+
111
+ def lookup(key, locale)
112
+ ::I18n.t(key.to_s, locale:, default: nil)
113
+ end
114
+
115
+ # A String, or a plural Hash with String keys. Anything else is not a
116
+ # label the core could display, so it is written as `nil`.
117
+ def label(value)
118
+ case value
119
+ when String then value
120
+ when Hash then value.select { |_, form| form.is_a?(String) }.transform_keys(&:to_s)
121
+ end
122
+ end
123
+
124
+ def template(value)
125
+ value if Formattable.valid_template?(value)
126
+ end
127
+ end
128
+ end
@@ -223,6 +223,15 @@ class Amount
223
223
  @lock.synchronize { @default_rates.key?([from.to_sym, to.to_sym]) }
224
224
  end
225
225
 
226
+ # @return [Hash{Array(Symbol, Symbol)=>BigDecimal}] every registered
227
+ # default rate, keyed by `[from, to]`. A frozen copy.
228
+ # @example
229
+ # Amount.registry.default_rates
230
+ # # => { [:USD, :USDC] => 0.1e1 }
231
+ def default_rates
232
+ @lock.synchronize { @default_rates.dup.freeze }
233
+ end
234
+
226
235
  # @return [void]
227
236
  # @example Locking the global registry after initialization
228
237
  # Amount.registry.lock!
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Amount
4
- VERSION = "0.2.0"
4
+ VERSION = "0.3.1"
5
5
  end
data/lib/amount.rb CHANGED
@@ -14,6 +14,7 @@ require_relative "amount/compact"
14
14
  require_relative "amount/display"
15
15
  require_relative "amount/parser"
16
16
  require_relative "amount/ui_parser"
17
+ require_relative "amount/manifest"
17
18
 
18
19
  # Concerns: modules mixed into Amount. Files live in amount/concerns/, but the
19
20
  # constants are Amount::<Name> (the folder is not a namespace).
@@ -28,6 +29,7 @@ require_relative "amount/concerns/orderable"
28
29
  require_relative "amount/concerns/convertible"
29
30
  require_relative "amount/concerns/serializable"
30
31
  require_relative "amount/concerns/formattable"
32
+ require_relative "amount/concerns/exportable"
31
33
 
32
34
  # Represents a precise quantity of a registered fungible type.
33
35
  #
@@ -53,6 +55,8 @@ require_relative "amount/concerns/formattable"
53
55
  # - {Serializable} — `to_h`, `as_json`, `Amount.load`
54
56
  # - {Formattable} — `display_format(unit:, locale:)`, where the number and
55
57
  # unit go
58
+ # - {Exportable} — `Amount.manifest(locales:)`, the registry for a client
59
+ # in another language
56
60
  #
57
61
  # New behavior belongs in a concern, not in this class. See
58
62
  # `.claude/rules/concerns.md` for the shape a concern takes.
@@ -78,6 +82,7 @@ class Amount
78
82
  include Convertible
79
83
  include Serializable
80
84
  include Formattable
85
+ include Exportable
81
86
 
82
87
  extend Forwardable
83
88
 
@@ -156,8 +156,128 @@ class AmountActiveRecordCalculationsTest < Minitest::Test
156
156
  assert_equal BigDecimal("150000000"), Holding.average(:fee_atomic)
157
157
  end
158
158
 
159
+ # Several attributes in one query
160
+
161
+ def test_sum_amount_of_several_attributes
162
+ assert_equal({ fee: Amount.new("0.3", :SOL), reserve: Amount.new("5", :USDC) },
163
+ Holding.sum_amount(:fee, :reserve))
164
+ end
165
+
166
+ def test_sum_amount_of_several_attributes_runs_one_query
167
+ assert_equal 1, queries_during { Holding.group(:amount_symbol).sum_amount(:amount, :fee, :reserve) }
168
+ end
169
+
170
+ def test_sum_amount_of_several_attributes_keys_by_name_given_as_strings
171
+ assert_equal %i[fee reserve], Holding.sum_amount("fee", "reserve").keys
172
+ end
173
+
174
+ def test_sum_amount_of_several_attributes_grouped
175
+ assert_equal(
176
+ {
177
+ nil => { amount: nil, fee: Amount.new(0, :SOL) },
178
+ "USD" => { amount: Amount.new("3", :USD), fee: Amount.new(0, :SOL) },
179
+ "USDC" => { amount: Amount.new("3.5", :USDC), fee: Amount.new("0.3", :SOL) }
180
+ },
181
+ Holding.group(:amount_symbol).sum_amount(:amount, :fee)
182
+ )
183
+ end
184
+
185
+ # Rows (USDC, USDC) and (NULL, USDC): amount sums only its own row, reserve
186
+ # adds both.
187
+ def test_sum_amount_of_several_multi_symbol_attributes_combines_rows
188
+ assert_equal({ amount: Amount.new("3.5", :USDC), reserve: Amount.new("3.75", :USDC) },
189
+ Holding.where(amount_symbol: ["USDC", nil]).sum_amount(:amount, :reserve))
190
+ end
191
+
192
+ def test_sum_amount_of_several_attributes_keeps_a_group_without_one_of_them
193
+ assert_equal({ amount: nil, reserve: Amount.new("1.25", :USDC) },
194
+ Holding.group(:amount_symbol).sum_amount(:amount, :reserve).fetch(nil))
195
+ end
196
+
197
+ def test_sum_amount_of_several_attributes_with_mixed_symbols_raises_type_mismatch
198
+ assert_raises(Amount::TypeMismatch) { Holding.sum_amount(:fee, :amount) }
199
+ end
200
+
201
+ def test_sum_amount_of_several_attributes_with_mixed_symbols_names_the_attribute
202
+ assert_match(/\Aamount has more than one symbol in scope/,
203
+ error_from(Amount::TypeMismatch) { Holding.sum_amount(:fee, :amount) }.message)
204
+ end
205
+
206
+ def test_sum_amount_of_several_attributes_over_no_rows
207
+ assert_equal({ fee: Amount.new(0, :SOL), amount: nil }, Holding.where(id: nil).sum_amount(:fee, :amount))
208
+ end
209
+
210
+ def test_sum_amount_of_several_attributes_on_none
211
+ assert_equal({ fee: Amount.new(0, :SOL), amount: nil }, Holding.none.sum_amount(:fee, :amount))
212
+ end
213
+
214
+ def test_sum_amount_of_several_attributes_grouped_on_none_is_empty
215
+ assert_empty Holding.none.group(:amount_symbol).sum_amount(:amount, :fee)
216
+ end
217
+
218
+ def test_sum_amount_of_several_attributes_grouped_by_two_columns_keys_by_array
219
+ assert_equal [["USDC", nil], %w[USDC USD], %w[USDC USDC]].to_set,
220
+ Holding.group(:reserve_symbol, :amount_symbol).sum_amount(:amount, :fee).keys.to_set
221
+ end
222
+
223
+ def test_sum_amount_with_a_name_given_twice_raises_argument_error
224
+ assert_raises(ArgumentError) { Holding.sum_amount(:fee, :fee) }
225
+ end
226
+
227
+ def test_sum_amount_without_names_raises_argument_error
228
+ assert_raises(ArgumentError) { Holding.sum_amount }
229
+ end
230
+
231
+ def test_sum_amount_of_an_unknown_name_raises_key_error
232
+ assert_raises(KeyError) { Holding.sum_amount(:fee, :nope) }
233
+ end
234
+
235
+ def test_minimum_amount_of_several_attributes
236
+ assert_equal({ fee: Amount.new("0.1", :SOL), reserve: Amount.new("1.25", :USDC) },
237
+ Holding.minimum_amount(:fee, :reserve))
238
+ end
239
+
240
+ def test_minimum_amount_of_several_multi_symbol_attributes_combines_rows
241
+ assert_equal({ amount: Amount.new("1.5", :USDC), reserve: Amount.new("1.25", :USDC) },
242
+ Holding.where(amount_symbol: ["USDC", nil]).minimum_amount(:amount, :reserve))
243
+ end
244
+
245
+ def test_maximum_amount_of_several_attributes_grouped
246
+ assert_equal({ amount: Amount.new("2", :USDC), fee: Amount.new("0.2", :SOL) },
247
+ Holding.group(:amount_symbol).maximum_amount(:amount, :fee).fetch("USDC"))
248
+ end
249
+
250
+ def test_average_amount_of_several_attributes
251
+ assert_equal({ fee: Amount.new("0.15", :SOL), reserve: Amount.new("1.25", :USDC) },
252
+ Holding.average_amount(:fee, :reserve))
253
+ end
254
+
255
+ def test_average_amount_of_several_multi_symbol_attributes_combines_rows
256
+ assert_equal({ amount: Amount.new("1.75", :USDC), reserve: Amount.new("1.25", :USDC) },
257
+ Holding.where(amount_symbol: ["USDC", nil]).average_amount(:amount, :reserve))
258
+ end
259
+
260
+ def test_average_amount_of_several_attributes_truncates_toward_zero
261
+ holdings_with_atomic_fees(1, 2)
262
+
263
+ assert_equal Amount.new(1, :SOL, from: :atomic), Holding.average_amount(:fee, :reserve).fetch(:fee)
264
+ end
265
+
266
+ def test_average_amount_of_several_attributes_is_nil_for_one_without_amounts
267
+ assert_equal({ amount: Amount.new("3", :USD), fee: nil },
268
+ Holding.group(:amount_symbol).average_amount(:amount, :fee).fetch("USD"))
269
+ end
270
+
159
271
  private
160
272
 
273
+ # How many SQL statements the block runs, schema queries aside.
274
+ def queries_during(&)
275
+ count = 0
276
+ counter = ->(*, payload) { count += 1 unless payload[:name] == "SCHEMA" }
277
+ ::ActiveSupport::Notifications.subscribed(counter, "sql.active_record", &)
278
+ count
279
+ end
280
+
161
281
  def holdings_with_atomic_fees(*atomics)
162
282
  Holding.delete_all
163
283
  atomics.each { |atomic| Holding.create!(fee: Amount.new(atomic, :SOL, from: :atomic)) }
@@ -123,22 +123,27 @@ class AmountCompactTest < Minitest::Test
123
123
  assert_equal "1T TOKENS", tokens(999_999_999_999).ui(compact: true, direction: :ceil)
124
124
  end
125
125
 
126
- # floor goes toward negative infinity, as `ui` does for any negative amount
126
+ # Rounding is by magnitude, as `ui` rounds any negative amount: a negative
127
+ # compacts like its positive, with a minus sign.
127
128
 
128
129
  def test_negative_exact_value
129
130
  assert_equal "-1.5M TOKENS", tokens(-1_500_000).ui(compact: true)
130
131
  end
131
132
 
132
- def test_negative_floor_rounds_away_from_zero
133
- assert_equal "-2M TOKENS", tokens(-1_999_999).ui(compact: true)
133
+ def test_negative_floor_rounds_toward_zero
134
+ assert_equal "-1.99M TOKENS", tokens(-1_999_999).ui(compact: true)
134
135
  end
135
136
 
136
- def test_negative_ceil_rounds_toward_zero
137
- assert_equal "-1.99M TOKENS", tokens(-1_999_999).ui(compact: true, direction: :ceil)
137
+ def test_negative_ceil_rounds_away_from_zero
138
+ assert_equal "-2M TOKENS", tokens(-1_999_999).ui(compact: true, direction: :ceil)
138
139
  end
139
140
 
140
- def test_negative_floor_rounds_into_the_next_scale
141
- assert_equal "-1M TOKENS", tokens(-999_999).ui(compact: true)
141
+ def test_negative_floor_stays_in_its_scale
142
+ assert_equal "-999K TOKENS", tokens(-999_999).ui(compact: true)
143
+ end
144
+
145
+ def test_negative_ceil_rounds_into_the_next_scale
146
+ assert_equal "-1M TOKENS", tokens(-999_999).ui(compact: true, direction: :ceil)
142
147
  end
143
148
 
144
149
  def test_negative_below_one_thousand_is_formatted_normally
@@ -336,6 +341,16 @@ class AmountCompactTest < Minitest::Test
336
341
  assert_equal "1,5 Tsd. TOKENS", tokens(1_500).ui(compact: true, locale: :de)
337
342
  end
338
343
 
344
+ def test_locale_format_reads_the_locale_template
345
+ store_decimal_units(:de, format: "%n%u", units: {})
346
+
347
+ assert_equal "%n%u", Amount::Compact.locale_format(:de)
348
+ end
349
+
350
+ def test_locale_format_defaults_without_a_template
351
+ assert_equal "%n %u", Amount::Compact.locale_format(:de)
352
+ end
353
+
339
354
  def test_compact_works_without_i18n
340
355
  without_i18n { assert_equal "50M TOKENS", tokens(50_000_000).ui(compact: true) }
341
356
  end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../test_helper"
4
+ require_relative "../../support/locale_test_setup"
5
+
6
+ class AmountExportableTest < Minitest::Test
7
+ include LocaleTestSetup
8
+
9
+ def test_manifest_exports_the_global_registry
10
+ assert_equal Amount::Manifest.new(Amount.registry).to_h, Amount.manifest
11
+ end
12
+
13
+ def test_manifest_resolves_the_given_locales
14
+ assert_equal Amount::Manifest.new(Amount.registry, locales: [:de]).to_h, Amount.manifest(locales: [:de])
15
+ end
16
+
17
+ def test_manifest_follows_a_swapped_registry
18
+ exported = Amount.with_registry(Amount::Registry.new) do
19
+ Amount.register :TEST, decimals: 2
20
+ Amount.manifest
21
+ end
22
+
23
+ assert_equal %w[TEST], exported["types"].keys
24
+ end
25
+ end
@@ -39,6 +39,48 @@ class AmountDisplayTest < Minitest::Test
39
39
  assert_equal "$1.57", Amount.new("1.561", :USDC).ui(direction: :ceil)
40
40
  end
41
41
 
42
+ # Negatives round by magnitude: like their positive, with a minus sign.
43
+
44
+ def test_ui_negative_floor_rounds_toward_zero
45
+ assert_equal "$-1.56", Amount.new("-1.567", :USDC).ui
46
+ end
47
+
48
+ def test_ui_negative_ceil_rounds_away_from_zero
49
+ assert_equal "$-1.57", Amount.new("-1.561", :USDC).ui(direction: :ceil)
50
+ end
51
+
52
+ def test_ui_negative_rounding_to_zero_has_no_sign
53
+ assert_equal "$0.00", Amount.new("-0.001", :USDC).ui
54
+ end
55
+
56
+ def test_ui_negative_ceil_shows_the_smallest_unit
57
+ assert_equal "$-0.01", Amount.new("-0.001", :USDC).ui(direction: :ceil)
58
+ end
59
+
60
+ def test_ui_negative_display_unit_rounds_toward_zero
61
+ assert_equal "-31.10 g", Amount.new("-1", :GOLD).ui(unit: :gram)
62
+ end
63
+
64
+ def test_to_s_negative_rounds_toward_zero
65
+ assert_equal "USDC|-1.56", Amount.new("-1.567", :USDC).to_s
66
+ end
67
+
68
+ def test_to_s_negative_rounding_to_zero_has_no_sign
69
+ assert_equal "USDC|0.00", Amount.new("-0.001", :USDC).to_s
70
+ end
71
+
72
+ def test_round_negative_floor_toward_zero
73
+ assert_equal BigDecimal("-1.56"), Amount::Display.round(BigDecimal("-1.567"), 2, :floor)
74
+ end
75
+
76
+ def test_round_negative_ceil_away_from_zero
77
+ assert_equal BigDecimal("-1.57"), Amount::Display.round(BigDecimal("-1.561"), 2, :ceil)
78
+ end
79
+
80
+ def test_round_negative_to_tens_toward_zero
81
+ assert_equal BigDecimal("-120"), Amount::Display.round(BigDecimal("-129"), -1, :floor)
82
+ end
83
+
42
84
  # name => [expected, value, symbol]
43
85
  {
44
86
  "usdc" => ["1.50", "1.5", :USDC],
@@ -0,0 +1,325 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../test_helper"
5
+ require_relative "../support/locale_test_setup"
6
+
7
+ class AmountManifestTest < Minitest::Test
8
+ include LocaleTestSetup
9
+
10
+ # Types
11
+
12
+ def test_version_is_one
13
+ assert_equal 1, manifest["v"]
14
+ end
15
+
16
+ def test_types_are_keyed_by_symbol
17
+ assert_equal %w[USDC USD SOL GOLD LOGS], manifest["types"].keys
18
+ end
19
+
20
+ def test_type_decimals
21
+ assert_equal 6, type("USDC")["decimals"]
22
+ end
23
+
24
+ def test_type_display_symbol
25
+ assert_equal "$", type("USDC")["display_symbol"]
26
+ end
27
+
28
+ def test_type_plural_display_symbol_has_string_keys
29
+ Amount.register :SEARCHES, decimals: 0, display_symbol: { one: "search", other: "searches" }
30
+
31
+ assert_equal({ "one" => "search", "other" => "searches" }, type("SEARCHES")["display_symbol"])
32
+ end
33
+
34
+ def test_type_display_format_is_the_resolved_template
35
+ assert_equal "%u%n", type("USDC")["display_format"]
36
+ end
37
+
38
+ def test_type_display_format_written_as_given
39
+ Amount.register :EUR, decimals: 2, display_symbol: "€", display_format: "%n %u"
40
+
41
+ assert_equal "%n %u", type("EUR")["display_format"]
42
+ end
43
+
44
+ def test_type_ui_decimals
45
+ assert_equal 2, type("USDC")["ui_decimals"]
46
+ end
47
+
48
+ def test_type_trim_zeros_defaults_to_false
49
+ assert_equal false, type("USDC")["trim_zeros"]
50
+ end
51
+
52
+ def test_type_trim_zeros_when_set
53
+ Amount.register :TOKENS, decimals: 0, trim_zeros: true
54
+
55
+ assert_equal true, type("TOKENS")["trim_zeros"]
56
+ end
57
+
58
+ def test_type_without_display_units
59
+ assert_nil type("USDC")["display_units"]
60
+ end
61
+
62
+ def test_type_default_display
63
+ assert_equal "oz_t", type("GOLD")["default_display"]
64
+ end
65
+
66
+ def test_type_without_default_display
67
+ assert_nil type("USDC")["default_display"]
68
+ end
69
+
70
+ # Display units
71
+
72
+ def test_display_units_are_keyed_by_unit
73
+ assert_equal %w[oz_t gram kg], type("GOLD")["display_units"].keys
74
+ end
75
+
76
+ def test_display_unit_scale_is_an_exact_string
77
+ assert_equal "31.1035", unit("GOLD", "gram")["scale"]
78
+ end
79
+
80
+ def test_display_unit_integer_scale
81
+ assert_equal "1.0", unit("GOLD", "oz_t")["scale"]
82
+ end
83
+
84
+ def test_display_unit_rational_scale_is_written_as_the_gem_uses_it
85
+ register_unit_type(third: { scale: Rational(1, 3) })
86
+
87
+ assert_equal "0.3333333333333333333", unit("UNITS", "third")["scale"]
88
+ end
89
+
90
+ def test_display_unit_symbol
91
+ assert_equal "g", unit("GOLD", "gram")["symbol"]
92
+ end
93
+
94
+ def test_display_unit_without_symbol
95
+ register_unit_type(plain: { scale: 1 })
96
+
97
+ assert_nil unit("UNITS", "plain")["symbol"]
98
+ end
99
+
100
+ def test_display_unit_ui_decimals
101
+ assert_equal 2, unit("GOLD", "gram")["ui_decimals"]
102
+ end
103
+
104
+ def test_display_unit_without_ui_decimals
105
+ register_unit_type(plain: { scale: 1 })
106
+
107
+ assert_nil unit("UNITS", "plain")["ui_decimals"]
108
+ end
109
+
110
+ def test_display_unit_format
111
+ register_unit_type(dozen: { scale: "0.083", format: "%n doz" })
112
+
113
+ assert_equal "%n doz", unit("UNITS", "dozen")["format"]
114
+ end
115
+
116
+ def test_display_unit_position_is_written_as_its_template
117
+ register_unit_type(dozen: { scale: "0.083", position: :prefix })
118
+
119
+ assert_equal "%u%n", unit("UNITS", "dozen")["format"]
120
+ end
121
+
122
+ def test_display_unit_without_format_or_position
123
+ assert_nil unit("GOLD", "gram")["format"]
124
+ end
125
+
126
+ def test_display_unit_trim_zeros_when_set
127
+ register_unit_type(plain: { scale: 1, trim_zeros: true })
128
+
129
+ assert_equal true, unit("UNITS", "plain")["trim_zeros"]
130
+ end
131
+
132
+ def test_display_unit_trim_zeros_set_to_false
133
+ register_unit_type(plain: { scale: 1, trim_zeros: false })
134
+
135
+ assert_equal false, unit("UNITS", "plain")["trim_zeros"]
136
+ end
137
+
138
+ def test_display_unit_without_trim_zeros
139
+ assert_nil unit("GOLD", "gram")["trim_zeros"]
140
+ end
141
+
142
+ # Rates
143
+
144
+ def test_without_rates
145
+ assert_empty manifest["rates"]
146
+ end
147
+
148
+ def test_rate_row
149
+ Amount.register_default_rate :USD, :USDC, "1"
150
+
151
+ assert_equal [{ "from" => "USD", "to" => "USDC", "rate" => "1.0" }], manifest["rates"]
152
+ end
153
+
154
+ def test_rational_rate_is_written_as_the_gem_uses_it
155
+ Amount.register_default_rate :USDC, :USD, Rational(1, 3)
156
+
157
+ assert_equal "0.3333333333333333333", manifest["rates"].first["rate"]
158
+ end
159
+
160
+ # Locales
161
+
162
+ def test_without_locales
163
+ assert_empty manifest["locales"]
164
+ end
165
+
166
+ def test_locales_are_keyed_by_locale
167
+ assert_equal %w[en de], manifest(locales: %i[en de])["locales"].keys
168
+ end
169
+
170
+ def test_locales_need_i18n
171
+ without_i18n do
172
+ assert_raises(ArgumentError) { manifest(locales: [:de]) }
173
+ end
174
+ end
175
+
176
+ def test_number_format
177
+ assert_equal({ "delimiter" => ".", "separator" => "," }, locale_table(:de)["number"])
178
+ end
179
+
180
+ def test_number_format_defaults
181
+ assert_equal({ "delimiter" => ",", "separator" => "." }, locale_table(:xx)["number"])
182
+ end
183
+
184
+ def test_compact_format_defaults
185
+ assert_equal "%n %u", locale_table(:de)["compact"]["format"]
186
+ end
187
+
188
+ def test_compact_format_translated
189
+ store(:de, number: { human: { decimal_units: { format: "%n%u" } } })
190
+
191
+ assert_equal "%n%u", locale_table(:de)["compact"]["format"]
192
+ end
193
+
194
+ def test_compact_format_without_number_falls_back
195
+ store(:de, number: { human: { decimal_units: { format: "%u" } } })
196
+
197
+ assert_equal "%n %u", locale_table(:de)["compact"]["format"]
198
+ end
199
+
200
+ def test_compact_units_list_every_scale
201
+ assert_equal %w[thousand million billion trillion quadrillion quintillion sextillion septillion
202
+ octillion nonillion decillion], locale_table(:de)["compact"]["units"].keys
203
+ end
204
+
205
+ def test_compact_unit_translated
206
+ store(:de, number: { human: { decimal_units: { units: { thousand: "Tsd." } } } })
207
+
208
+ assert_equal "Tsd.", locale_table(:de)["compact"]["units"]["thousand"]
209
+ end
210
+
211
+ def test_compact_unit_plural_forms
212
+ store(:de, number: { human: { decimal_units: { units: { million: { one: "Million", other: "Millionen" } } } } })
213
+
214
+ assert_equal({ "one" => "Million", "other" => "Millionen" }, locale_table(:de)["compact"]["units"]["million"])
215
+ end
216
+
217
+ def test_compact_unit_without_translation
218
+ assert_nil locale_table(:de)["compact"]["units"]["thousand"]
219
+ end
220
+
221
+ def test_type_label_without_translation
222
+ assert_nil locale_type(:de, "GOLD")["label"]
223
+ end
224
+
225
+ def test_type_label_translated
226
+ store(:de, amounts: { units: { gold: "Feinunze" } })
227
+
228
+ assert_equal "Feinunze", locale_type(:de, "GOLD")["label"]
229
+ end
230
+
231
+ def test_type_label_from_label_key
232
+ store(:de, coins: { searches: "Suchen" })
233
+ Amount.register :SEARCHES, decimals: 0, label_key: "coins.searches"
234
+
235
+ assert_equal "Suchen", locale_type(:de, "SEARCHES")["label"]
236
+ end
237
+
238
+ def test_type_label_plural_forms
239
+ store(:de, amounts: { units: { logs: { one: "Stamm", other: "Stämme" } } })
240
+
241
+ assert_equal({ "one" => "Stamm", "other" => "Stämme" }, locale_type(:de, "LOGS")["label"])
242
+ end
243
+
244
+ def test_type_format_translated
245
+ store(:de, amounts: { formats: { usd: "%n %u" } })
246
+
247
+ assert_equal "%n %u", locale_type(:de, "USD")["format"]
248
+ end
249
+
250
+ def test_type_format_without_number_is_ignored
251
+ store(:de, amounts: { formats: { usd: "%u" } })
252
+
253
+ assert_nil locale_type(:de, "USD")["format"]
254
+ end
255
+
256
+ def test_type_without_display_units_has_no_unit_tables
257
+ assert_empty locale_type(:de, "USD")["units"]
258
+ end
259
+
260
+ def test_unit_label_translated
261
+ store(:de, amounts: { display_units: { gold: { gram: "Gramm" } } })
262
+
263
+ assert_equal "Gramm", locale_type(:de, "GOLD")["units"]["gram"]["label"]
264
+ end
265
+
266
+ def test_unit_label_from_label_key
267
+ store(:de, metric: { gram: "Gramm" })
268
+ register_unit_type(gram: { scale: 1, label_key: "metric.gram" })
269
+
270
+ assert_equal "Gramm", locale_type(:de, "UNITS")["units"]["gram"]["label"]
271
+ end
272
+
273
+ def test_unit_label_without_translation
274
+ assert_nil locale_type(:de, "GOLD")["units"]["gram"]["label"]
275
+ end
276
+
277
+ def test_unit_format_translated
278
+ store(:de, amounts: { display_unit_formats: { gold: { gram: "%n %u" } } })
279
+
280
+ assert_equal "%n %u", locale_type(:de, "GOLD")["units"]["gram"]["format"]
281
+ end
282
+
283
+ def test_unit_format_without_translation
284
+ assert_nil locale_type(:de, "GOLD")["units"]["gram"]["format"]
285
+ end
286
+
287
+ # JSON
288
+
289
+ def test_survives_a_json_round_trip
290
+ Amount.register_default_rate :USD, :USDC, "1"
291
+ written = manifest(locales: [:de])
292
+
293
+ assert_equal written, JSON.parse(written.to_json)
294
+ end
295
+
296
+ private
297
+
298
+ def manifest(locales: [])
299
+ Amount::Manifest.new(Amount.registry, locales:).to_h
300
+ end
301
+
302
+ def type(symbol)
303
+ manifest["types"][symbol]
304
+ end
305
+
306
+ def unit(symbol, unit)
307
+ type(symbol)["display_units"][unit]
308
+ end
309
+
310
+ def locale_table(locale)
311
+ manifest(locales: [locale])["locales"][locale.to_s]
312
+ end
313
+
314
+ def locale_type(locale, symbol)
315
+ locale_table(locale)["types"][symbol]
316
+ end
317
+
318
+ def store(locale, translations)
319
+ I18n.backend.store_translations(locale, translations)
320
+ end
321
+
322
+ def register_unit_type(units)
323
+ Amount.register :UNITS, decimals: 2, display_units: units
324
+ end
325
+ end
@@ -79,6 +79,20 @@ class AmountRegistryTest < Minitest::Test
79
79
  assert_equal BigDecimal("0.5"), Amount.new("1", :USDC).to(:USD).decimal
80
80
  end
81
81
 
82
+ def test_default_rates_lists_each_rate_by_direction
83
+ Amount.register_default_rate :USD, :USDC, "1"
84
+
85
+ assert_equal({ %i[USD USDC] => BigDecimal("1") }, Amount.registry.default_rates)
86
+ end
87
+
88
+ def test_default_rates_is_empty_without_rates
89
+ assert_empty Amount.registry.default_rates
90
+ end
91
+
92
+ def test_default_rates_is_frozen
93
+ assert_predicate Amount.registry.default_rates, :frozen?
94
+ end
95
+
82
96
  def test_prefix_display_position_is_stored_as_its_template
83
97
  assert_equal "%u%n", Amount.registry.lookup(:USD).display_format
84
98
  end
@@ -95,6 +95,27 @@ class PostgreSQLIntegrationTest < Minitest::Test
95
95
  Holding.group(:amount_symbol).sum_amount(:amount))
96
96
  end
97
97
 
98
+ def test_postgresql_sum_amount_of_several_attributes_is_exact_past_64_bits
99
+ holdings_with_atomic_amounts(10**30, (10**30) + 1)
100
+
101
+ assert_equal({ amount: Amount.new((2 * (10**30)) + 1, :SOL, from: :atomic), fee: Amount.new(0, :SOL) },
102
+ Holding.sum_amount(:amount, :fee))
103
+ end
104
+
105
+ def test_postgresql_average_amount_of_several_attributes_is_exact_past_64_bits
106
+ holdings_with_atomic_amounts(10**30, (10**30) + 3)
107
+
108
+ assert_equal Amount.new((10**30) + 1, :SOL, from: :atomic),
109
+ Holding.average_amount(:amount, :reserve).fetch(:amount)
110
+ end
111
+
112
+ def test_postgresql_sum_amount_of_several_attributes_grouped
113
+ create_usdc_and_usd_holdings
114
+
115
+ assert_equal({ amount: Amount.new("1.5", :USDC), reserve: Amount.new("1.25", :USDC) },
116
+ Holding.group(:amount_symbol).sum_amount(:amount, :reserve).fetch("USDC"))
117
+ end
118
+
98
119
  private
99
120
 
100
121
  def holdings_with_atomic_amounts(*atomics)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: amounts
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Seb Scholl
@@ -64,6 +64,7 @@ files:
64
64
  - lib/amount/concerns/coercible.rb
65
65
  - lib/amount/concerns/constructible.rb
66
66
  - lib/amount/concerns/convertible.rb
67
+ - lib/amount/concerns/exportable.rb
67
68
  - lib/amount/concerns/formattable.rb
68
69
  - lib/amount/concerns/localizable.rb
69
70
  - lib/amount/concerns/orderable.rb
@@ -72,6 +73,7 @@ files:
72
73
  - lib/amount/concerns/serializable.rb
73
74
  - lib/amount/display.rb
74
75
  - lib/amount/locale.rb
76
+ - lib/amount/manifest.rb
75
77
  - lib/amount/parser.rb
76
78
  - lib/amount/registry.rb
77
79
  - lib/amount/registry/generated_constructors.rb
@@ -103,6 +105,7 @@ files:
103
105
  - test/amount/concerns/coercible_test.rb
104
106
  - test/amount/concerns/constructible_test.rb
105
107
  - test/amount/concerns/convertible_test.rb
108
+ - test/amount/concerns/exportable_test.rb
106
109
  - test/amount/concerns/formattable_test.rb
107
110
  - test/amount/concerns/localizable_test.rb
108
111
  - test/amount/concerns/orderable_test.rb
@@ -111,6 +114,7 @@ files:
111
114
  - test/amount/concerns/serializable_test.rb
112
115
  - test/amount/display_test.rb
113
116
  - test/amount/locale_test.rb
117
+ - test/amount/manifest_test.rb
114
118
  - test/amount/parser_test.rb
115
119
  - test/amount/registry/generated_constructors_test.rb
116
120
  - test/amount/registry_test.rb