price_waterfall 0.1.0

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 (58) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +186 -0
  3. data/LICENSE.txt +21 -0
  4. data/README.md +582 -0
  5. data/lib/price_waterfall/builder/arguments.rb +86 -0
  6. data/lib/price_waterfall/builder.rb +192 -0
  7. data/lib/price_waterfall/conditions/all.rb +18 -0
  8. data/lib/price_waterfall/conditions/any.rb +18 -0
  9. data/lib/price_waterfall/conditions/comparison.rb +142 -0
  10. data/lib/price_waterfall/conditions/compiled.rb +32 -0
  11. data/lib/price_waterfall/conditions/compiler.rb +182 -0
  12. data/lib/price_waterfall/conditions/custom.rb +59 -0
  13. data/lib/price_waterfall/conditions/group.rb +45 -0
  14. data/lib/price_waterfall/conditions/negation.rb +36 -0
  15. data/lib/price_waterfall/conditions/reason.rb +227 -0
  16. data/lib/price_waterfall/configuration_error.rb +8 -0
  17. data/lib/price_waterfall/entry.rb +111 -0
  18. data/lib/price_waterfall/error.rb +24 -0
  19. data/lib/price_waterfall/invalid_amount.rb +7 -0
  20. data/lib/price_waterfall/keys.rb +38 -0
  21. data/lib/price_waterfall/loader/order.rb +51 -0
  22. data/lib/price_waterfall/loader/problems.rb +72 -0
  23. data/lib/price_waterfall/loader/step_entry.rb +114 -0
  24. data/lib/price_waterfall/loader.rb +79 -0
  25. data/lib/price_waterfall/number.rb +149 -0
  26. data/lib/price_waterfall/percentage.rb +77 -0
  27. data/lib/price_waterfall/pipeline.rb +111 -0
  28. data/lib/price_waterfall/registered.rb +87 -0
  29. data/lib/price_waterfall/registry.rb +127 -0
  30. data/lib/price_waterfall/resolver.rb +148 -0
  31. data/lib/price_waterfall/result.rb +200 -0
  32. data/lib/price_waterfall/rounding.rb +119 -0
  33. data/lib/price_waterfall/run.rb +113 -0
  34. data/lib/price_waterfall/step_error.rb +9 -0
  35. data/lib/price_waterfall/step_name.rb +56 -0
  36. data/lib/price_waterfall/steps/amount.rb +50 -0
  37. data/lib/price_waterfall/steps/base.rb +40 -0
  38. data/lib/price_waterfall/steps/callable.rb +48 -0
  39. data/lib/price_waterfall/steps/cents.rb +35 -0
  40. data/lib/price_waterfall/steps/custom.rb +50 -0
  41. data/lib/price_waterfall/steps/override.rb +23 -0
  42. data/lib/price_waterfall/steps/percent.rb +17 -0
  43. data/lib/price_waterfall/steps/percentage_change.rb +26 -0
  44. data/lib/price_waterfall/steps/round.rb +46 -0
  45. data/lib/price_waterfall/steps/skipping.rb +43 -0
  46. data/lib/price_waterfall/steps/step.rb +200 -0
  47. data/lib/price_waterfall/steps/surcharge.rb +17 -0
  48. data/lib/price_waterfall/steps/tiered.rb +95 -0
  49. data/lib/price_waterfall/time_window.rb +93 -0
  50. data/lib/price_waterfall/timestamp.rb +58 -0
  51. data/lib/price_waterfall/user_code.rb +72 -0
  52. data/lib/price_waterfall/values/list.rb +28 -0
  53. data/lib/price_waterfall/values/literal.rb +28 -0
  54. data/lib/price_waterfall/values/path.rb +106 -0
  55. data/lib/price_waterfall/values/source.rb +44 -0
  56. data/lib/price_waterfall/version.rb +6 -0
  57. data/lib/price_waterfall.rb +126 -0
  58. metadata +103 -0
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # What rules written as data may use beyond the built-ins: custom step types, value sources and
5
+ # condition operators, each a callable registered in Ruby by name. Data can only name what is
6
+ # registered here, so a config edited in an admin form can't run any other code.
7
+ #
8
+ # There is no global registry: pass one to {PriceWaterfall.load} (or {PriceWaterfall.define}), so
9
+ # apps, tenants and tests never affect each other. It is frozen once a pipeline is built from it.
10
+ #
11
+ # @example
12
+ # registry = PriceWaterfall::Registry.new
13
+ # registry.step(:min_margin) { |cents, item, _ctx, _params| [[cents, item[:cost_cents]].max, "floor at cost"] }
14
+ # registry.operator(:is_vip) { |customer, _arg| customer[:vip] }
15
+ # registry.source(:contract_price) { |item, ctx| ctx.dig(:contracts, item[:sku]) }
16
+ class Registry
17
+ # Step types data can name without registering them.
18
+ BUILT_IN_STEPS = %i[base override percent surcharge amount tiered rounding].freeze
19
+ # Condition keys data uses for the built-in tests, which a registered operator can't share.
20
+ BUILT_IN_OPERATORS = (Conditions::Comparison::OPERATORS + %i[all any not]).freeze
21
+ # For each kind: the names it can't use and the arguments its callables take.
22
+ KINDS = {
23
+ step: [BUILT_IN_STEPS, 4, "(cents, item, ctx, params)"], source: [[], 2, "(item, ctx)"],
24
+ operator: [BUILT_IN_OPERATORS, 2, "(value, arg)"]
25
+ }.freeze
26
+
27
+ def initialize
28
+ @tables = { step: {}, source: {}, operator: {} }
29
+ end
30
+
31
+ # @api private
32
+ # @param registry [Object] a +registry:+ argument
33
+ # @return [Registry, nil] +registry+
34
+ # @raise [ConfigurationError] unless it is a Registry or +nil+
35
+ def self.check!(registry)
36
+ return registry if registry.nil? || registry.is_a?(Registry)
37
+
38
+ raise ConfigurationError, "registry: must be a PriceWaterfall::Registry, got #{Conditions::Reason.show(registry)}"
39
+ end
40
+
41
+ # A copy has tables of its own, unfrozen, so it can be added to without changing the original.
42
+ def initialize_copy(original)
43
+ super
44
+ @tables = @tables.transform_values(&:dup)
45
+ end
46
+
47
+ # Registers a step type, named in data as +{ "type": "min_margin" }+. The entry's other keys
48
+ # (beyond +type+, +name+, +if+, +unless+, +starts_at+ and +ends_at+) are passed as +params+, a
49
+ # frozen Hash with Symbol keys.
50
+ #
51
+ # @param name [Symbol, String]
52
+ # @param callable [#call, nil] taking +(cents, item, ctx, params)+ and returning
53
+ # +[new_cents, note]+; or give a block
54
+ # @return [self]
55
+ # @raise [ConfigurationError] if the name is invalid, built in or already registered, the
56
+ # callable can't take those arguments, or the registry is frozen
57
+ def step(name, callable = nil, &) = add(:step, name, callable, &)
58
+
59
+ # Registers a value source, named in data as +{ "source": "contract_price" }+.
60
+ #
61
+ # @param name [Symbol, String]
62
+ # @param callable [#call, nil] taking +(item, ctx)+; or give a block
63
+ # @return [self]
64
+ # @raise (see #step)
65
+ def source(name, callable = nil, &) = add(:source, name, callable, &)
66
+
67
+ # Registers a condition operator, named in data as +{ "ctx": "customer", "op": "is_vip" }+.
68
+ #
69
+ # @param name [Symbol, String]
70
+ # @param callable [#call, nil] taking +(value, arg)+; or give a block
71
+ # @return [self]
72
+ # @raise (see #step)
73
+ def operator(name, callable = nil, &) = add(:operator, name, callable, &)
74
+
75
+ # @return [Hash{Symbol => #call}] the registered step types, frozen
76
+ def steps = @tables[:step].dup.freeze
77
+ # @return [Hash{Symbol => #call}] the registered value sources, frozen
78
+ def sources = @tables[:source].dup.freeze
79
+ # @return [Hash{Symbol => #call}] the registered operators, frozen
80
+ def operators = @tables[:operator].dup.freeze
81
+
82
+ # Freezes the registry and what it holds, so a built pipeline can't change under it.
83
+ # @return [self]
84
+ def freeze
85
+ @tables.each_value(&:freeze).freeze
86
+ super
87
+ end
88
+
89
+ private
90
+
91
+ def add(kind, name, callable, &block)
92
+ built_in, count, signature = KINDS.fetch(kind)
93
+ key = key!(kind, name)
94
+ callable = one_callable(kind, key, callable, block)
95
+ raise ConfigurationError, "#{kind} #{key.inspect} is built in" if built_in.include?(key)
96
+ raise ConfigurationError, "#{kind} #{key.inspect} is already registered" if @tables[kind].key?(key)
97
+
98
+ checked(kind, key, callable, count, signature)
99
+ @tables[kind][key] = callable
100
+ self
101
+ end
102
+
103
+ def key!(kind, name)
104
+ raise ConfigurationError, "#{kind} #{Conditions::Reason.show(name)}: the registry is frozen" if frozen?
105
+
106
+ return StepName.check!(name, ConfigurationError, "step name") if kind == :step
107
+
108
+ Registered.name_of(name, "#{kind}s").to_sym
109
+ end
110
+
111
+ def one_callable(kind, key, callable, block)
112
+ raise ConfigurationError, "#{kind} #{key.inspect}: takes a callable or a block, not both" if callable && block
113
+
114
+ callable ||= block
115
+ return callable if callable.respond_to?(:call)
116
+
117
+ raise ConfigurationError, "#{kind} #{key.inspect}: needs a callable or a block, got " \
118
+ "#{Conditions::Reason.show(callable)}"
119
+ end
120
+
121
+ def checked(kind, key, callable, count, signature)
122
+ Resolver.check_arity!(callable, count, signature)
123
+ rescue ConfigurationError => e
124
+ raise ConfigurationError, "#{kind} #{key.inspect}: #{e.message}"
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,148 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Turns any step input into an object that responds to +call(item, ctx)+, so steps never care
5
+ # whether they were given a Ruby callable, a plain value or a value described in data.
6
+ module Resolver
7
+ # Keys of a value description: +item:+ or +ctx:+ (with optional +key:+), +source:+ or +value:+.
8
+ VALUE_KEYS = %i[item ctx key source value].freeze
9
+ # How deeply descriptions may nest through +key:+, so a deep or cyclic config can't exhaust the stack.
10
+ MAX_DEPTH = 32
11
+
12
+ module_function
13
+
14
+ # @param input [#call, Hash, Object] a callable taking +(item, ctx)+, a value description
15
+ # (see {describe}) or a literal value
16
+ # @param sources [Hash{Symbol, String => #call}] registered value sources, for +{ source: ... }+
17
+ # @param at [String] where the input is, for error messages
18
+ # @return [#call] the callable itself, a {Values::Path} / {Values::Source} / {Values::Literal}
19
+ # for a description, or a {Values::Literal}
20
+ # @raise [ConfigurationError] if a callable cannot take +(item, ctx)+ or a description is malformed
21
+ # @example
22
+ # Resolver.build(->(item, _ctx) { item[:qty] }) # => the lambda
23
+ # Resolver.build(10).call(item, ctx) # => 10
24
+ # Resolver.build({ "item" => "qty" }).call({ qty: 3 }, {}) # => 3
25
+ def build(input, sources: {}, at: "value") = build_at(input, sources, at, 0)
26
+
27
+ # Builds a resolver from a value description, with String or Symbol keys:
28
+ #
29
+ # - +{ item: "qty" }+, +{ ctx: "customer.group" }+: a dotted path into the item or context
30
+ # - +{ ctx: "price_list", key: { item: "sku" } }+: the same, then a lookup by +key:+ (a literal
31
+ # or another description)
32
+ # - +{ source: "contract_price" }+: a registered value source
33
+ # - +{ value: { min: 1, max: 5 } }+: a literal, taken as it is; the way to pass a Hash, which
34
+ # would otherwise be read as a description
35
+ #
36
+ # @param data [Hash]
37
+ # @param sources [Hash{Symbol, String => #call}] registered value sources
38
+ # @param at [String] where the description is, for error messages
39
+ # @return [Values::Path, Values::Source, Values::Literal]
40
+ # @raise [ConfigurationError] if the description is malformed or +key:+ nests more than
41
+ # {MAX_DEPTH} levels deep, naming where
42
+ def describe(data, sources: {}, at: "value") = describe_at(data, sources, at, 0)
43
+
44
+ # @api private
45
+ # Like {build}, for a value inside a description or a condition. There a Ruby callable runs
46
+ # inside the gem's own code, so it is wrapped to keep what it raises reported as user code.
47
+ #
48
+ # @return [#call] a resolver that is always {Builtin}
49
+ def nested(input, sources: {}, at: "value") = nested_at(input, sources, at, 0)
50
+
51
+ # @api private
52
+ def build_at(input, sources, at, depth)
53
+ return describe_at(input, sources, at, depth) if input.is_a?(Hash)
54
+ return Values::Literal.new(input) unless input.respond_to?(:call)
55
+
56
+ check_arity!(input, 2, "(item, ctx)")
57
+ input
58
+ end
59
+
60
+ # @api private
61
+ def describe_at(data, sources, at, depth)
62
+ raise ConfigurationError, "#{at}: key: lookups nest more than #{MAX_DEPTH} levels deep" if depth > MAX_DEPTH
63
+
64
+ keys = Keys.read(data, VALUE_KEYS, at)
65
+ roots = keys.keys - [:key]
66
+ unless roots.size == 1
67
+ raise ConfigurationError,
68
+ "#{at}: needs exactly one of item, ctx, source or value, got #{roots.empty? ? "none" : roots.join(", ")}"
69
+ end
70
+
71
+ root = roots.first
72
+ return unkeyed(root, keys, sources, at) unless %i[item ctx].include?(root)
73
+
74
+ Values::Path.new(root, keys[root], key: lookup_key(keys, sources, at, depth), at:)
75
+ end
76
+
77
+ # Checks that a callable can be called with +count+ arguments. Procs from blocks accept any
78
+ # number of arguments, so only lambdas, methods and +call+ methods are checked.
79
+ #
80
+ # @param callable [#call]
81
+ # @param count [Integer] number of arguments it will be called with
82
+ # @param signature [String] the expected arguments, for the error message
83
+ # @return [void]
84
+ # @raise [ConfigurationError] if +callable+ cannot take +count+ arguments
85
+ # @example
86
+ # Resolver.check_arity!(-> { 10 }, 2, "(item, ctx)") # raises ConfigurationError
87
+ def check_arity!(callable, count, signature)
88
+ types = parameters_of(callable)&.map(&:first)
89
+ return if types.nil? || accepts?(types, count)
90
+
91
+ raise ConfigurationError, "callable must take #{signature}, but it takes #{describe_arity(types)}"
92
+ end
93
+
94
+ # @api private
95
+ def nested_at(input, sources, at, depth)
96
+ resolver = build_at(input, sources, at, depth)
97
+ resolver.is_a?(Builtin) ? resolver : UserCode::Callable.new(resolver)
98
+ end
99
+
100
+ # @api private
101
+ def lookup_key(keys, sources, at, depth)
102
+ keys.key?(:key) ? nested_at(keys[:key], sources, "#{at}.key", depth + 1) : nil
103
+ end
104
+
105
+ # @api private
106
+ def unkeyed(root, keys, sources, at)
107
+ raise ConfigurationError, "#{at}: key only works with item or ctx" if keys.key?(:key)
108
+
109
+ root == :value ? Values::Literal.new(keys[:value]) : Values::Source.new(keys[:source], sources, at:)
110
+ end
111
+
112
+ # @api private
113
+ # @return [Array<Array(Symbol, Symbol)>, nil] +nil+ when the parameters can't be read or any
114
+ # number of arguments is accepted (a proc from a block)
115
+ def parameters_of(callable)
116
+ return callable.lambda? ? callable.parameters : nil if callable.is_a?(Proc)
117
+ return callable.parameters if callable.is_a?(Method)
118
+
119
+ Object.instance_method(:method).bind_call(callable, :call).parameters
120
+ rescue NameError, TypeError => e
121
+ # No readable #call method (e.g. it is answered by method_missing): skip the check. A
122
+ # NoMethodError, though, is a bug in the callable itself and must not be hidden.
123
+ raise if e.is_a?(NoMethodError)
124
+
125
+ nil
126
+ end
127
+
128
+ # @api private
129
+ def accepts?(types, count)
130
+ return false if types.include?(:keyreq) || count < types.count(:req)
131
+
132
+ types.include?(:rest) || count <= types.count(:req) + types.count(:opt)
133
+ end
134
+
135
+ # @api private
136
+ def describe_arity(types)
137
+ min = types.count(:req)
138
+ max = min + types.count(:opt)
139
+ text = if types.include?(:rest) then "#{min} or more arguments"
140
+ elsif max > min then "#{min} to #{max} arguments"
141
+ else "#{min} argument#{"s" unless min == 1}"
142
+ end
143
+ types.include?(:keyreq) ? "#{text} and required keywords" : text
144
+ end
145
+ private_class_method :build_at, :describe_at, :nested_at, :lookup_key, :unkeyed, :parameters_of, :accepts?,
146
+ :describe_arity
147
+ end
148
+ end
@@ -0,0 +1,200 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # A price with its full trace: the final {#cents}, one {Entry} per step, and the +version+ of the
5
+ # rules that produced it, so a stored price can be explained later. Frozen.
6
+ #
7
+ # @example
8
+ # result.cents # => 4140
9
+ # puts result.explain
10
+ # # base 4599 base
11
+ # # customer_tier 4139 -460 (10%)
12
+ # # rounding 4140 half_up to 5
13
+ #
14
+ # @!attribute [r] entries
15
+ # @return [Array<Entry>] frozen, in the order the steps ran
16
+ # @!attribute [r] version
17
+ # @return [String, nil] the rule set's version (a date, git sha, database row id ...)
18
+ Result = Data.define(:entries, :version) do
19
+ # @param entries [Array<Entry>] in the order the steps ran; each starts where the previous one ended
20
+ # @param version [String, nil] the rule set's version, kept in UTF-8 so {#to_h} can be written
21
+ # as JSON
22
+ # @raise [InvalidAmount] if +entries+ is not an Array of {Entry} whose prices follow on
23
+ # @raise [ConfigurationError] if +version+ is neither a String nor +nil+
24
+ def initialize(entries:, version: nil)
25
+ super(entries: Result.chain!(entries), version: Result.version(version))
26
+ end
27
+
28
+ # Ruby 3.2's +Data#with+ skips +initialize+; build through +new+ so it is validated too.
29
+ #
30
+ # @param changes [Hash] new +entries:+ and/or +version:+
31
+ # @return [Result]
32
+ # @raise [InvalidAmount, ConfigurationError] if the result is invalid
33
+ # @raise [InvalidAmount] if +changes+ names anything else (+cents+ comes from the entries)
34
+ def with(**changes)
35
+ unknown = changes.keys - Result.members
36
+ raise InvalidAmount, "result can't change #{unknown.join(", ")}; change entries or version" unless unknown.empty?
37
+
38
+ self.class.new(entries:, version:, **changes)
39
+ end
40
+
41
+ # @return [Integer] the final price in cents: the last entry's +after+, or 0 when there are none
42
+ def cents = entries.empty? ? 0 : entries.last.after
43
+
44
+ # One line per step: the name, left-aligned to the longest name; the price after the step,
45
+ # right-aligned; and the note, with control characters escaped (+\\n+, +\\t+, +\\e+) so each step
46
+ # stays on one line and a note can't send escape codes to a terminal or log.
47
+ #
48
+ # @return [String] the lines joined with newlines, without a trailing one
49
+ def explain
50
+ names = entries.map { |entry| Result.escape(entry.step.name) }
51
+ width = names.map(&:length).max
52
+ entries.zip(names).map { |entry, name| Result.line(entry, name.ljust(width)) }.join("\n")
53
+ end
54
+
55
+ alias_method :to_s, :explain
56
+
57
+ # @yieldparam key [Symbol]
58
+ # @yieldparam value [Object]
59
+ # @return [Hash{Symbol => Object}] +cents+, +version+ and +entries+ (each as {Entry#to_h}), ready
60
+ # to store as JSON for an audit trail; mapped by the block like +Hash#to_h+ when one is given
61
+ def to_h(&) = { cents:, version:, entries: entries.map(&:to_h) }.to_h(&)
62
+
63
+ # Reads a result back from {#to_h}, with Symbol or String keys (as JSON gives them), so a stored
64
+ # price can be explained again. +cents+, when given, must match the entries, so a changed row
65
+ # is caught.
66
+ #
67
+ # @param data [Hash] +entries+ (each as {Entry#to_h}), and optionally +cents+ and +version+
68
+ # @return [Result]
69
+ # @raise [InvalidAmount] if +data+ is not such a Hash, or its values (including +version+) are
70
+ # invalid or don't match, so one rescue catches every bad stored row
71
+ # @example
72
+ # Result.from_h(JSON.parse(stored)).explain
73
+ def self.from_h(data)
74
+ fields = Result.fields(data, %i[cents version entries], "result")
75
+ raise InvalidAmount, "result: missing entries" unless fields.key?(:entries)
76
+
77
+ result = new(entries: Result.stored_entries(fields[:entries]), version: Result.stored_version(fields[:version]))
78
+ fields.key?(:cents) ? Result.check_cents!(result, fields[:cents]) : result
79
+ end
80
+
81
+ # @api private
82
+ # Shared with {Pipeline}, which keeps its version the same way.
83
+ # @return [String, nil] +version+ in UTF-8, frozen
84
+ # @raise [ConfigurationError] unless +version+ is a String or +nil+
85
+ def self.version(version)
86
+ return version && -Result.utf8(version) if version.nil? || version.is_a?(String)
87
+
88
+ raise ConfigurationError, "version must be a String or nil, got #{Conditions::Reason.show(version)}"
89
+ end
90
+
91
+ # @api private
92
+ # @return [String, nil] +version+
93
+ # @raise [InvalidAmount] unless it is a String or +nil+, so a bad stored row raises the same
94
+ # error as any other bad value
95
+ def self.stored_version(version)
96
+ return version if version.nil? || version.is_a?(String)
97
+
98
+ raise InvalidAmount, "result: version must be a String or nil, got #{Conditions::Reason.show(version)}"
99
+ end
100
+
101
+ # @api private
102
+ # @return [Result] +result+
103
+ # @raise [InvalidAmount] unless +cents+ is Integer cents matching +result+'s entries
104
+ def self.check_cents!(result, cents)
105
+ return result if Steps::Cents.check!(cents, "result cents") == result.cents
106
+
107
+ raise InvalidAmount, "result cents #{cents} doesn't match its entries (#{result.cents})"
108
+ end
109
+
110
+ # @api private
111
+ # @return [Array<Entry>] the stored entries, each read with {Entry.from_h}
112
+ def self.stored_entries(entries)
113
+ unless entries.is_a?(Array)
114
+ raise InvalidAmount, "result: entries must be an Array, got #{Conditions::Reason.show(entries)}"
115
+ end
116
+
117
+ entries.each_with_index.map { |entry, index| Result.stored_entry(entry, "result.entries[#{index}]") }
118
+ end
119
+
120
+ # @api private
121
+ # @return [Entry] +entry+ read with {Entry.from_h}
122
+ # @raise [InvalidAmount] naming +at+, so a bad value in a long trace can be found
123
+ def self.stored_entry(entry, at)
124
+ Entry.from_h(entry, at:)
125
+ rescue InvalidAmount => e
126
+ raise if e.message.start_with?("#{at}:")
127
+
128
+ raise InvalidAmount, "#{at}: #{e.message}"
129
+ end
130
+
131
+ # @api private
132
+ # @return [String] one line of {#explain}, for an already escaped and padded name
133
+ def self.line(entry, name) = "#{name} #{entry.after.to_s.rjust(Result::PRICE_WIDTH)} #{escape(entry.note)}"
134
+
135
+ # @api private
136
+ # @return [Hash{Symbol => Object}] +data+'s entries with Symbol keys
137
+ # @raise [InvalidAmount] unless +data+ is a Hash with only the +allowed+ keys
138
+ def self.fields(data, allowed, at)
139
+ raise InvalidAmount, "#{at}: must be a Hash, got #{Conditions::Reason.show(data)}" unless data.is_a?(Hash)
140
+
141
+ Keys.read(data, allowed, at)
142
+ rescue ConfigurationError => e
143
+ raise InvalidAmount, e.message
144
+ end
145
+
146
+ # @api private
147
+ # @return [String] +text+ as UTF-8 (see {.utf8}), with the characters in {ESCAPED} written as
148
+ # escapes (+\\t+, +\\u202E+), so each step stays on one line and a note can't reorder or
149
+ # colour a terminal or hide text. Backslashes are kept as they are, so a value a condition
150
+ # reason wrote with +inspect+ (+"5\\" screen"+) isn't escaped twice.
151
+ def self.escape(text) = utf8(text).gsub(Result::ESCAPED) { |char| Result.escaped(char) }
152
+
153
+ # @api private
154
+ # @return [String] +text+ in valid UTF-8, replacing what can't be converted, so it can be
155
+ # stored as JSON and +explain+ can't raise on mixed encodings. Binary text, and text in an
156
+ # encoding Ruby has no converter for (UTF-7, ISO-2022-JP-2), is read as UTF-8 bytes.
157
+ def self.utf8(text)
158
+ return text.b.force_encoding(Encoding::UTF_8).scrub if Result::AS_BYTES.include?(text.encoding)
159
+
160
+ text.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
161
+ rescue EncodingError
162
+ text.b.force_encoding(Encoding::UTF_8).scrub
163
+ end
164
+
165
+ # @api private
166
+ # @return [String] +char+ written as an escape: its +dump+ form for ASCII (+\\t+, +\\e+),
167
+ # +\\uXXXX+ otherwise, or +\\u{XXXXX}+ above U+FFFF so it can't be misread
168
+ def self.escaped(char)
169
+ return char.dump[1..-2] if char.ascii_only?
170
+
171
+ char.ord > 0xFFFF ? format("\\u{%X}", char.ord) : format("\\u%04X", char.ord)
172
+ end
173
+
174
+ # @api private
175
+ # @return [Array<Entry>] +entries+ as a frozen Array, checked to follow on from each other
176
+ def self.chain!(entries)
177
+ unless entries.is_a?(Array) && entries.all?(Entry)
178
+ raise InvalidAmount, "entries must be an Array of PriceWaterfall::Entry, got #{Conditions::Reason.show(entries)}"
179
+ end
180
+
181
+ entries.each_cons(2) do |previous, entry|
182
+ next if entry.before == previous.after
183
+
184
+ raise InvalidAmount, "entry #{entry.step.inspect} starts at #{entry.before}, " \
185
+ "but #{previous.step.inspect} ended at #{previous.after}"
186
+ end
187
+ entries.dup.freeze
188
+ end
189
+ end
190
+
191
+ # Width the price column is right-aligned to in {Result#explain}.
192
+ Result::PRICE_WIDTH = 8
193
+ # Encodings whose bytes {Result.utf8} reads as UTF-8 rather than converting.
194
+ Result::AS_BYTES = [Encoding::UTF_8, Encoding::BINARY].freeze
195
+ # Characters {Result#explain} writes as escapes: control characters, line and paragraph
196
+ # separators, and every invisible format character (bidirectional controls,
197
+ # zero-width spaces, tag characters ...) except the three that text needs: the zero-width
198
+ # joiner and non-joiner (emoji, Indic scripts) and the soft hyphen.
199
+ Result::ESCAPED = /[[:cntrl:]\p{Cf}\p{Zl}\p{Zp}&&[^\u00AD\u200C\u200D]]/
200
+ end
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Exact rounding of Integer / Rational amounts to a multiple of +to+ cents.
5
+ # All maths is done with Rational, never Float.
6
+ module Rounding
7
+ # +half_up+ rounds halves away from zero (2.5 -> 3, -2.5 -> -3), like BigDecimal::ROUND_HALF_UP.
8
+ # +bankers+ rounds halves to the even neighbour (BigDecimal::ROUND_HALF_EVEN).
9
+ # +ceiling+ / +floor+ round towards positive / negative infinity (BigDecimal::ROUND_CEILING / ROUND_FLOOR).
10
+ ROUNDERS = {
11
+ half_up: ->(units) { units.round(half: :up) },
12
+ bankers: ->(units) { units.round(half: :even) },
13
+ ceiling: lambda(&:ceil),
14
+ floor: lambda(&:floor)
15
+ }.freeze
16
+
17
+ # Supported rounding modes.
18
+ MODES = ROUNDERS.keys.freeze
19
+
20
+ module_function
21
+
22
+ # Looks up a rounding mode by Symbol or String name, so modes read from JSON or YAML work.
23
+ # Only the known names match; arbitrary Strings are never turned into Symbols.
24
+ #
25
+ # @param mode [Symbol, String]
26
+ # @return [Symbol, nil] the matching entry of {MODES}, or +nil+ if there is none
27
+ # @example
28
+ # Rounding.normalize_mode("half_up") # => :half_up
29
+ def normalize_mode(mode) = MODES.find { |known| known == mode || known.name == mode }
30
+
31
+ # Checks a rounding configuration without rounding anything.
32
+ #
33
+ # @param mode [Symbol, String] one of {MODES}
34
+ # @param to [Integer] round to a multiple of this many cents
35
+ # @return [Symbol] the mode as an entry of {MODES}
36
+ # @raise [ConfigurationError] if +mode+ is unknown or +to+ is not a positive Integer
37
+ def validate!(mode, to)
38
+ normalized = normalize_mode(mode)
39
+ unless normalized
40
+ raise ConfigurationError,
41
+ "unknown rounding mode #{Conditions::Reason.show(mode)} (expected one of: #{MODES.join(", ")})"
42
+ end
43
+ return normalized if to.is_a?(Integer) && to.positive?
44
+
45
+ raise ConfigurationError, "rounding to: must be a positive Integer, got #{Conditions::Reason.show(to)}"
46
+ end
47
+
48
+ # Rounds +value+ to a multiple of +to+ using +mode+.
49
+ #
50
+ # @param value [Integer, Rational] amount in cents; Floats and other types are rejected
51
+ # @param mode [Symbol, String] one of {MODES}
52
+ # @param to [Integer] round to a multiple of this many cents
53
+ # @return [Integer] rounded amount in cents
54
+ # @raise [ConfigurationError] if +mode+ or +to+ is invalid (re-checked on every direct call)
55
+ # @raise [InvalidAmount] if +value+ is not an Integer or Rational
56
+ # @example
57
+ # Rounding.apply(Rational(5, 2), mode: :bankers) # => 2
58
+ # Rounding.apply(4139, mode: :half_up, to: 5) # => 4140
59
+ def apply(value, mode:, to: 1) = round(value, validate!(mode, to), to)
60
+
61
+ # Checks the configuration once and returns a {Rounder} for it, for callers that round many
62
+ # amounts the same way.
63
+ #
64
+ # @param mode [Symbol, String] one of {MODES}
65
+ # @param to [Integer] round to a multiple of this many cents
66
+ # @return [Rounder]
67
+ # @raise [ConfigurationError] if +mode+ or +to+ is invalid
68
+ # @example
69
+ # to_five = Rounding.rounder(:half_up, to: 5)
70
+ # to_five.call(4139) # => 4140
71
+ def rounder(mode, to: 1) = Rounder.new(mode:, to:)
72
+
73
+ # Rounds with an already validated configuration; use {apply} or a {Rounder} instead.
74
+ # Private, since it skips validation.
75
+ #
76
+ # @param value [Integer, Rational]
77
+ # @param mode [Symbol] an entry of {MODES}
78
+ # @param to [Integer] a positive Integer
79
+ # @return [Integer]
80
+ # @raise [InvalidAmount] if +value+ is not an Integer or Rational
81
+ def round(value, mode, to)
82
+ unless value.is_a?(Integer) || value.is_a?(Rational)
83
+ raise InvalidAmount, "amount must be Integer cents or a Rational, got #{value.class} #{Conditions::Reason.show(value)}"
84
+ end
85
+
86
+ ROUNDERS.fetch(mode).call(Rational(value) / to) * to
87
+ end
88
+
89
+ # A checked rounding configuration. Every way of building one ({Rounding.rounder}, +new+,
90
+ # +with+) validates +mode+ and +to+ and normalizes a String mode. Frozen, so it can be shared.
91
+ #
92
+ # @!attribute [r] mode
93
+ # @return [Symbol] one of {MODES}
94
+ # @!attribute [r] to
95
+ # @return [Integer] round to a multiple of this many cents
96
+ Rounder = Data.define(:mode, :to) do
97
+ # @param mode [Symbol, String] one of {MODES}
98
+ # @param to [Integer] round to a multiple of this many cents
99
+ # @raise [ConfigurationError] if +mode+ or +to+ is invalid
100
+ def initialize(mode:, to: 1)
101
+ super(mode: Rounding.validate!(mode, to), to:)
102
+ end
103
+
104
+ # Ruby 3.2's +Data#with+ skips +initialize+; build through +new+ so it is validated too.
105
+ #
106
+ # @param changes [Hash] new +mode:+ and/or +to:+
107
+ # @return [Rounder]
108
+ # @raise [ConfigurationError] if the result is invalid
109
+ def with(**changes) = self.class.new(**to_h, **changes)
110
+
111
+ # @param value [Integer, Rational] amount in cents
112
+ # @return [Integer] +value+ rounded to a multiple of {#to} using {#mode}
113
+ # @raise [InvalidAmount] if +value+ is not an Integer or Rational
114
+ # +Rounding.round+ is private because it skips validation; a Rounder is already validated.
115
+ def call(value) = Rounding.send(:round, value, mode, to)
116
+ end
117
+ private_class_method :round
118
+ end
119
+ end