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,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ module Conditions
5
+ # Shared by {All} and {Any}: holds the conditions they combine, and stops at the first one
6
+ # whose result settles the group (a failure for {All}, a success for {Any}).
7
+ class Group
8
+ include Compiled
9
+
10
+ # @return [Array<#call>] the conditions as given
11
+ attr_reader :conditions
12
+
13
+ # @param conditions [Array<#call>] at least one condition; a plain callable runs as user code
14
+ # @raise [ConfigurationError] unless +conditions+ is a non-empty Array, so a group can't hold
15
+ # with nothing to say why
16
+ def initialize(conditions)
17
+ unless conditions.is_a?(Array)
18
+ raise ConfigurationError, "#{self.class::KEY} conditions must be an Array, got #{Reason.show(conditions)}"
19
+ end
20
+ raise ConfigurationError, "#{self.class::KEY} needs at least one condition" if conditions.empty?
21
+
22
+ @conditions = conditions.dup.freeze
23
+ @wrapped = conditions.map { |condition| Compiled.wrap(condition) }.freeze
24
+ freeze
25
+ end
26
+
27
+ # The first condition that settles the group gives the reason. Otherwise every condition's
28
+ # reason is a fact about it, so they are joined with "and".
29
+ #
30
+ # @param item [Object]
31
+ # @param ctx [Object]
32
+ # @return [Array(Boolean, String)] the group's result, and why
33
+ def check(item, ctx)
34
+ settles_on = self.class::SETTLES_ON
35
+ reasons = @wrapped.map do |condition|
36
+ held, why = Compiled.check(condition, item, ctx)
37
+ return [held, why] if held == settles_on
38
+
39
+ why
40
+ end
41
+ [!settles_on, Reason.join(reasons)]
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ module Conditions
5
+ # True when the condition is not: +{ not: {...} }+.
6
+ class Negation
7
+ include Compiled
8
+
9
+ # @return [#call] the condition as given
10
+ attr_reader :condition
11
+
12
+ # @param condition [#call] a plain callable runs as user code
13
+ def initialize(condition)
14
+ @condition = condition
15
+ @wrapped = Compiled.wrap(condition)
16
+ freeze
17
+ end
18
+
19
+ # @param item [Object]
20
+ # @param ctx [Object]
21
+ # @return [Boolean]
22
+ def call(item, ctx) = @wrapped.call(item, ctx) ? false : true
23
+
24
+ # The inner reason is already a fact (+item.qty 4 < 10+), true whichever way the negation
25
+ # went, so it is passed through unchanged.
26
+ #
27
+ # @param item [Object]
28
+ # @param ctx [Object]
29
+ # @return [Array(Boolean, String)] whether the condition does not hold, and why
30
+ def check(item, ctx)
31
+ held, why = Compiled.check(@wrapped, item, ctx)
32
+ [!held, why]
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,227 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ module Conditions
5
+ # Writes why a data condition held or not, for trace notes:
6
+ # +skipped (condition: item.qty 4 < 10)+. Every reason is written as a fact that is true, so
7
+ # +all+, +any+ and +not+ can pass reasons on without rewording them.
8
+ #
9
+ # Values are shortened so a long list can't swamp the note. In a run that hides values
10
+ # (+PriceWaterfall.define(hide_values: true)+), what a condition read is named rather than
11
+ # shown: +item.qty < 10+, +item.qty < ctx.min_qty+; values written in the rule itself still show.
12
+ # Lists and Hashes are written by the
13
+ # gem rather than by +inspect+, so a note reads the same on every Ruby version, and a Hash shows
14
+ # only its size, keeping customer data out of it.
15
+ module Reason
16
+ # Longest value written, in characters, before it is cut short with "...".
17
+ MAX_LENGTH = 40
18
+ # How many entries of a long list, or reasons of a group, are written before the rest are counted.
19
+ MAX_ENTRIES = 3
20
+ # How a comparison that held is written, by operator.
21
+ HELD = { eq: "==", not_eq: "!=", in: "in", not_in: "not in", gt: ">", gte: ">=", lt: "<", lte: "<=",
22
+ between: "between", present: "is present", blank: "is blank" }.freeze
23
+ # Written for a value that can't be shown safely.
24
+ UNPRINTABLE = "#<unprintable>"
25
+ # How a comparison that failed is written: the opposite test, so the note reads as a fact.
26
+ FAILED = { eq: "!=", not_eq: "==", in: "not in", not_in: "in", gt: "<=", gte: "<", lt: ">=", lte: ">",
27
+ between: "not between", present: "is not present", blank: "is not blank" }.freeze
28
+
29
+ module_function
30
+
31
+ # @param resolver [#call] what was read
32
+ # @param found [Object] the value read
33
+ # @param operator [Symbol] one of {Comparison::OPERATORS}
34
+ # @param compared [Array(#call, Object)] the operand's resolver and its value
35
+ # @param held [Boolean] whether the comparison held
36
+ # @param comparable [Boolean] whether the two could be compared at all
37
+ # @return [String] e.g. +item.qty 4 < 10+, +item.qty "12" can't be compared with 10+,
38
+ # +ctx.min_qty is missing+, +item.coupon and ctx.used are missing+
39
+ def comparison(resolver, found, operator, compared, held:, comparable:)
40
+ gaps = gaps([resolver, found], compared)
41
+ return missing(gaps + missing_entries(compared)) unless gaps.empty?
42
+
43
+ subject = subject(resolver, found)
44
+ unless comparable
45
+ entries = missing_entries(compared)
46
+ return entries.empty? ? not_comparable(subject, operator, compared) : missing(entries)
47
+ end
48
+
49
+ words = (held ? HELD : FAILED).fetch(operator)
50
+ %i[present blank].include?(operator) ? "#{subject} #{words}" : "#{subject} #{words} #{written(*compared)}"
51
+ end
52
+
53
+ # @param resolver [#call] what was read
54
+ # @param found [Object] the value read
55
+ # @param name [Symbol] the registered operator
56
+ # @param given [Array(#call, Object)] the argument's resolver and its value (+nil+ when none)
57
+ # @param held [Boolean] whether the operator returned a truthy value
58
+ # @return [String] e.g. +ctx.spend 150 is over 100+, +ctx.customer is missing+,
59
+ # +ctx.limit is missing+
60
+ def operator(resolver, found, name, given, held:)
61
+ gaps = gaps([resolver, found], given)
62
+ return missing(gaps) unless gaps.empty?
63
+
64
+ "#{subject(resolver, found)} #{held ? "is" : "is not"} #{name}#{" #{written(*given)}" unless given.last.nil?}"
65
+ end
66
+
67
+ # @api private
68
+ # +nil.equal?+ works for any value, even a BasicObject without +nil?+.
69
+ def missing?(resolver, value) = nil.equal?(value) && !resolver.is_a?(Values::Literal)
70
+
71
+ # @api private
72
+ # @return [Array<#call>] the resolvers, of +[resolver, value]+ pairs, whose value is missing
73
+ def gaps(*pairs) = pairs.select { |resolver, value| missing?(resolver, value) }.map(&:first)
74
+
75
+ # @api private
76
+ # @param resolvers [Array<#call>] one or more resolvers whose values are missing
77
+ def missing(resolvers)
78
+ labels = resolvers.map { |resolver| label(resolver) }.uniq
79
+ "#{labels.join(" and ")} #{labels.one? ? "is" : "are"} missing"
80
+ end
81
+
82
+ # @api private
83
+ # @return [Array<#call>] the missing entries of a list operand (+between: [{ ctx: "lo" }, 10]+),
84
+ # named so the item isn't blamed for them
85
+ def missing_entries((resolver, operand))
86
+ resolver.is_a?(Values::List) && operand.is_a?(Array) ? gaps(*resolver.entries.zip(operand)) : []
87
+ end
88
+
89
+ # @api private
90
+ def not_comparable(subject, operator, compared)
91
+ return "#{subject} can't be checked" if %i[present blank].include?(operator)
92
+
93
+ "#{subject} can't be compared with #{written(*compared)}"
94
+ end
95
+
96
+ # @param reasons [Array<String>] facts that all hold
97
+ # @return [String] the first few joined with "and", the rest counted
98
+ # @example
99
+ # Reason.join(%w[a b c d e]) # => "a and b and c and 2 more"
100
+ def join(reasons)
101
+ shown = reasons.first(MAX_ENTRIES)
102
+ shown << "#{reasons.size - MAX_ENTRIES} more" if reasons.size > MAX_ENTRIES
103
+ shown.join(" and ")
104
+ end
105
+
106
+ # @param resolver [#call] what a condition read
107
+ # @param found [Object] the value it gave
108
+ # @return [String] its label and value (+item.qty 4+), or just the value for a literal
109
+ def subject(resolver, found) = written(resolver, found, named: true)
110
+
111
+ # @api private
112
+ # @param named [Boolean] write the label before the value (+item.qty 4+)
113
+ # @return [String] a value a condition read, or in a run that hides values, what it was read
114
+ # from (+item.qty+); a value written in the rule itself always shows
115
+ def written(resolver, value, named: false)
116
+ return show(value) if resolver.is_a?(Values::Literal)
117
+ return label(resolver) if Run.hiding_values?
118
+
119
+ named ? "#{label(resolver)} #{show(value)}" : show(value)
120
+ end
121
+
122
+ # @param resolver [#call] what a condition reads (a {Values::Path}, {Values::Source} ...)
123
+ # @return [String] how a trace names it: +item.qty+, +ctx.price_list[item.sku]+, +source contract_price+
124
+ def label(resolver) = resolver.respond_to?(:label) ? resolver.label : "value"
125
+
126
+ # @param value [Object]
127
+ # @return [String] +value+ written briefly
128
+ # @example
129
+ # Reason.show(%w[A B C D E]) # => '["A", "B", "C", ... 2 more]'
130
+ # Reason.show({ vip: true }) # => "{1 key}"
131
+ def show(value) = brief(value, nested: false)
132
+
133
+ # @api private
134
+ # Only simple values are written out. Any other object is written as its class (+#<User>+),
135
+ # which is cheaper than +inspect+ and keeps a model's attributes, such as an email, out of the
136
+ # note, as a Hash's size does. A list is cut entry by entry, so the count of the rest always
137
+ # shows; a list inside a list is written as "[...]", so a list that contains itself can't
138
+ # recurse. Anything that can't be written safely becomes {UNPRINTABLE}. The +when+ tests call
139
+ # the classes, not the value; only +is_a?+ is asked of other objects, so a time that stands in
140
+ # for Time (+ActiveSupport::TimeWithZone+) is written as a time.
141
+ def brief(value, nested:)
142
+ case value
143
+ when Array, Set, Hash then collection(value, nested)
144
+ when String then string(value)
145
+ when Numeric then cut(number(value))
146
+ when Time then time(value)
147
+ when Symbol, true, false, nil then cut(value.inspect)
148
+ else object(value)
149
+ end
150
+ rescue StandardError
151
+ UNPRINTABLE
152
+ end
153
+
154
+ # @api private
155
+ # @return [String] an Integer, Rational or BigDecimal (as conditions parse numbers to) written
156
+ # as a decimal with {Number.format}, the way step notes write numbers: +12.5+, not +(25/2)+
157
+ # or +0.125e2+. A huge number is written approximately, signed inside the tilde: +~-1e300000+.
158
+ def number(value)
159
+ return value.inspect unless value.is_a?(Integer) || value.is_a?(Rational) || big_decimal?(value)
160
+
161
+ text = big_decimal?(value) ? Number.format_decimal(value.abs) : Number.format(value.abs.to_r)
162
+ return text unless value.negative?
163
+
164
+ text.start_with?("~") ? "~-#{text[1..]}" : "-#{text}"
165
+ end
166
+
167
+ # @api private
168
+ def big_decimal?(value) = defined?(BigDecimal) && value.is_a?(BigDecimal) && value.finite?
169
+
170
+ # @api private
171
+ # @return [String] ISO-8601, as time window notes write times, with milliseconds when the
172
+ # time has a fraction of a second
173
+ def time(value) = value.iso8601(value.subsec.zero? ? 0 : 3)
174
+
175
+ # @api private
176
+ # @return [String] a time (see {.time}), or the class of any other object (+#<User>+); a
177
+ # BasicObject, which has no +is_a?+, is written by its class too
178
+ def object(value)
179
+ klass = Kernel.instance_method(:class).bind_call(value)
180
+ return time(value) if klass.method_defined?(:is_a?) && value.is_a?(Time)
181
+
182
+ "#<#{klass.name || "anonymous"}>"
183
+ end
184
+
185
+ # @api private
186
+ def collection(value, nested)
187
+ return "{#{value.size} key#{"s" unless value.size == 1}}" if value.is_a?(Hash)
188
+
189
+ nested ? "[...]" : list(value)
190
+ end
191
+
192
+ # @api private
193
+ # A long String is cut before +inspect+, so a huge one isn't written out first, and keeps
194
+ # its closing quote even when +inspect+ adds escapes for quotes or backslashes. A String that
195
+ # isn't ASCII-compatible (UTF-16) is converted to UTF-8 (see {Result.utf8}), so it can be cut
196
+ # and reads the same whatever its length; any other keeps its bytes, so invalid ones show as
197
+ # +\\xFF+ however long the String.
198
+ def string(value)
199
+ text = head(value).inspect if value.length <= MAX_LENGTH
200
+ return text if text && text.length <= MAX_LENGTH
201
+
202
+ head = head(value)
203
+ length = [head.length, MAX_LENGTH - 5].min
204
+ length -= 1 while length.positive? && "#{head[0, length]}...".inspect.length > MAX_LENGTH
205
+ "#{head[0, length]}...".inspect
206
+ end
207
+
208
+ # @api private
209
+ def head(value)
210
+ head = value[0, MAX_LENGTH]
211
+ head.encoding.ascii_compatible? ? head : Result.utf8(head)
212
+ end
213
+
214
+ # @api private
215
+ def cut(text) = text.length > MAX_LENGTH ? "#{text[0, MAX_LENGTH - 3]}..." : text
216
+
217
+ # @api private
218
+ def list(value)
219
+ shown = value.first(MAX_ENTRIES).map { |entry| brief(entry, nested: true) }
220
+ shown << "... #{value.size - MAX_ENTRIES} more" if value.size > MAX_ENTRIES
221
+ "[#{shown.join(", ")}]"
222
+ end
223
+ private_class_method :missing?, :gaps, :missing, :missing_entries, :not_comparable, :written, :brief, :number,
224
+ :head, :big_decimal?, :time, :object, :collection, :string, :cut, :list
225
+ end
226
+ end
227
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Raised when configuration is invalid, e.g. an unknown rounding mode, a duplicate step name or a
5
+ # first step that is not +base+. Pipelines raise it at define time; calling {Rounding.apply}
6
+ # directly with a bad mode or +to:+ raises it at call time.
7
+ class ConfigurationError < Error; end
8
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # One line of a price's trace: which step ran, the price before and after it, and the step's note
5
+ # (+"-460 (10%)"+, +"skipped (qty 4 below 10)"+). Frozen, so a {Result} can be shared and stored.
6
+ # The step name (see {StepName}) and note are kept in UTF-8, so {Result#to_h} can always be
7
+ # written as JSON.
8
+ #
9
+ # @!attribute [r] step
10
+ # @return [Symbol] the step's name
11
+ # @!attribute [r] before
12
+ # @return [Integer] price going into the step, in cents
13
+ # @!attribute [r] after
14
+ # @return [Integer] price coming out of the step, in cents
15
+ # @!attribute [r] note
16
+ # @return [String] the step's frozen trace note
17
+ # @!attribute [r] skipped
18
+ # @return [Boolean] whether the step was skipped (see {#skipped?})
19
+ Entry = Data.define(:step, :before, :after, :note, :skipped) do
20
+ # @param step [Symbol, String] the step's name
21
+ # @param before [Integer] price going in, in cents
22
+ # @param after [Integer] price coming out, in cents
23
+ # @param note [String] the step's trace note
24
+ # @param delta [Integer, nil] optional, as {#to_h} writes it; checked to be +after - before+, so
25
+ # a stored entry can be read back and a changed one is caught
26
+ # @param skipped [Boolean] whether the step was skipped; a skipped step leaves the price as it was
27
+ # @raise [InvalidAmount] if a price is not a non-negative Integer, +step+ / +note+ is invalid,
28
+ # +delta+ is not an Integer or doesn't match, or +skipped+ is not true or false, or is true
29
+ # while the price changed
30
+ def initialize(step:, before:, after:, note:, delta: nil, skipped: false)
31
+ raise InvalidAmount, "entry note must be a String, got #{Conditions::Reason.show(note)}" unless note.is_a?(String)
32
+
33
+ step = StepName.check!(step, InvalidAmount, "entry step")
34
+ super(step:, before: Steps::Cents.check!(before, "entry before"),
35
+ after: Steps::Cents.check!(after, "entry after"), note: -Result.utf8(note), skipped:)
36
+ Entry.check_delta!(step, delta, after - before) unless delta.nil?
37
+ Entry.check_skipped!(step, skipped, after - before)
38
+ end
39
+
40
+ # @api private
41
+ # @raise [InvalidAmount] unless +skipped+ is true or false, and false when the price changed
42
+ def self.check_skipped!(step, skipped, change)
43
+ unless [true, false].include?(skipped)
44
+ raise InvalidAmount, "entry #{step.inspect} skipped must be true or false, got #{Conditions::Reason.show(skipped)}"
45
+ end
46
+ return unless skipped && !change.zero?
47
+
48
+ raise InvalidAmount, "entry #{step.inspect} is skipped but changed the price by #{change}"
49
+ end
50
+
51
+ # @api private
52
+ # @raise [InvalidAmount] unless +delta+ is an Integer equal to +change+
53
+ def self.check_delta!(step, delta, change)
54
+ unless delta.is_a?(Integer)
55
+ raise InvalidAmount, "entry #{step.inspect} delta must be an Integer, got #{Conditions::Reason.show(delta)}"
56
+ end
57
+ return if delta == change
58
+
59
+ raise InvalidAmount, "entry #{step.inspect} delta #{delta} doesn't match after - before (#{change})"
60
+ end
61
+
62
+ # Reads an entry back from {#to_h}, with Symbol or String keys (as JSON gives them).
63
+ #
64
+ # @param data [Hash] +step+, +before+, +after+, +note+, and optionally +delta+ and +skipped+
65
+ # (+false+ when missing)
66
+ # @param at [String] where the entry is, for error messages
67
+ # @return [Entry]
68
+ # @raise [InvalidAmount] if +data+ is not such a Hash, or its values are invalid
69
+ # @example
70
+ # Entry.from_h({ "step" => "base", "before" => 0, "after" => 4599, "delta" => 4599, "note" => "base" })
71
+ def self.from_h(data, at: "entry")
72
+ fields = Result.fields(data, %i[step before after delta note skipped], at)
73
+ missing = %i[step before after note] - fields.keys
74
+ raise InvalidAmount, "#{at}: missing #{missing.join(", ")}" unless missing.empty?
75
+
76
+ new(**fields)
77
+ end
78
+
79
+ # Ruby 3.2's +Data#with+ skips +initialize+; build through +new+ so it is validated too.
80
+ #
81
+ # @param changes [Hash] new values for any of +step+, +before+, +after+, +note+ and +skipped+
82
+ # @return [Entry]
83
+ # @raise [InvalidAmount] if the result is invalid, or +changes+ names anything else (+delta+ is
84
+ # worked out from +before+ and +after+). A skipped entry stays skipped, so changing its price
85
+ # also needs +skipped: false+
86
+ def with(**changes)
87
+ unknown = changes.keys - Entry.members
88
+ unless unknown.empty?
89
+ raise InvalidAmount, "entry can't change #{unknown.join(", ")}; change step, before, after, note or skipped"
90
+ end
91
+
92
+ self.class.new(step:, before:, after:, note:, skipped:, **changes)
93
+ end
94
+
95
+ # Whether the step was skipped and left the price as it was: by its time window, +condition:+
96
+ # or +skip_if:+, or because it had nothing to apply (no value, a share that rounds to 0 cents,
97
+ # an override with no price). Recorded by the step, so it never depends on the note's wording.
98
+ #
99
+ # @return [Boolean]
100
+ def skipped? = skipped
101
+
102
+ # @return [Integer] +after - before+: negative for a discount, positive for a surcharge
103
+ def delta = after - before
104
+
105
+ # @yieldparam key [Symbol]
106
+ # @yieldparam value [Object]
107
+ # @return [Hash{Symbol => Object}] +step+, +before+, +after+, +delta+, +note+ and +skipped+,
108
+ # mapped by the block like +Hash#to_h+ when one is given
109
+ def to_h(&) = { step:, before:, after:, delta:, note:, skipped: }.to_h(&)
110
+ end
111
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Base class for every error raised by the gem, so callers can rescue them all at once.
5
+ # Errors raised by or inside a step carry the step's name in {#step}.
6
+ #
7
+ # @example
8
+ # begin
9
+ # pricing.call(item, ctx)
10
+ # rescue PriceWaterfall::Error => e
11
+ # logger.warn("#{e.step}: #{e.message}")
12
+ # end
13
+ class Error < StandardError
14
+ # @return [Symbol, nil] name of the step the error belongs to, if any
15
+ attr_reader :step
16
+
17
+ # @param message [String, nil]
18
+ # @param step [Symbol, nil] name of the step the error belongs to
19
+ def initialize(message = nil, step: nil)
20
+ @step = step
21
+ super(message)
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Raised at call time when a step produces or receives an amount that is not allowed,
5
+ # e.g. a Float instead of Integer cents, a negative price or a percentage outside 0..100.
6
+ class InvalidAmount < Error; end
7
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Reads the keys of a data description ({ "item" => "qty" } or { item: "qty" }), so configs work
5
+ # with String or Symbol keys alike and typos are caught instead of ignored.
6
+ module Keys
7
+ module_function
8
+
9
+ # @param hash [Hash] the description, with String or Symbol keys
10
+ # @param allowed [Array<Symbol>] the keys it may have
11
+ # @param at [String] where the description is, for error messages (e.g. "condition.all[0]")
12
+ # @return [Hash{Symbol => Object}] the same entries with Symbol keys
13
+ # @raise [ConfigurationError] on an unknown key, a key given twice ("item" and :item), or a key
14
+ # that is not a String or Symbol
15
+ # @example
16
+ # Keys.read({ "ctx" => "tier" }, %i[item ctx], "value") # => { ctx: "tier" }
17
+ def read(hash, allowed, at)
18
+ hash.each_with_object({}) do |(key, value), read|
19
+ name = name_for(key, allowed, at)
20
+ raise ConfigurationError, "#{at}: key #{name.name.inspect} is given twice" if read.key?(name)
21
+
22
+ read[name] = value
23
+ end
24
+ end
25
+
26
+ # @api private
27
+ def name_for(key, allowed, at)
28
+ unless key.is_a?(Symbol) || key.is_a?(String)
29
+ raise ConfigurationError, "#{at}: keys must be Strings or Symbols, got #{Conditions::Reason.show(key)}"
30
+ end
31
+
32
+ allowed.find { |name| name.name == key.to_s } ||
33
+ raise(ConfigurationError, "#{at}: unknown key #{Conditions::Reason.show(key.to_s)} " \
34
+ "(expected one of: #{allowed.join(", ")})")
35
+ end
36
+ private_class_method :name_for
37
+ end
38
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ class Loader
5
+ # @api private
6
+ # The pipeline's rules about its steps, checked with the path of each step at fault: the first
7
+ # step is a base and only it; names are unique; the step named +:rounding+ is a rounding step
8
+ # and last ({Pipeline.check!} raises only the first). Types come from the config, so a step that
9
+ # failed to build doesn't cause more problems.
10
+ module Order
11
+ module_function
12
+
13
+ # @param types [Array<Symbol, nil>] each entry's type, +nil+ where it couldn't be read
14
+ # @param built [Hash{Integer => Steps::Step}] the steps that were built, by position
15
+ # @param problems [Problems]
16
+ # @return [void]
17
+ def check(types, built, problems)
18
+ problems.add("steps[0]", "the first step must be a base") unless [:base, nil].include?(types.first)
19
+ types.each_with_index.drop(1).each do |type, index|
20
+ problems.add("steps[#{index}]", "only the first step can be a base") if type == :base
21
+ end
22
+ names(built, problems)
23
+ rounding(built, types.size, problems)
24
+ end
25
+
26
+ # @api private
27
+ def names(built, problems)
28
+ seen = {}
29
+ built.each do |index, step|
30
+ first = seen[step.name]
31
+ problems.add("steps[#{index}]", "step name #{step.name.inspect} is already used by steps[#{first}]") if first
32
+ seen[step.name] ||= index
33
+ end
34
+ end
35
+
36
+ # @api private
37
+ def rounding(built, count, problems)
38
+ index, step = built.find { |_, found| found.name == :rounding }
39
+ return unless step
40
+
41
+ if !step.is_a?(Steps::Round)
42
+ problems.add("steps[#{index}]",
43
+ "the name :rounding is kept for the rounding step; give this step another name")
44
+ elsif index != count - 1
45
+ problems.add("steps[#{index}]", "the rounding step must be last; give an earlier rounding its own name")
46
+ end
47
+ end
48
+ private_class_method :names, :rounding
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ class Loader
5
+ # One problem with a config: where it is and what is wrong.
6
+ #
7
+ # @!attribute [r] path
8
+ # @return [String] where it is: +steps[3].if.all[0]+
9
+ # @!attribute [r] message
10
+ # @return [String] what is wrong, without the path
11
+ Problem = Data.define(:path, :message) do
12
+ # @return [String] +path: message+
13
+ def to_s = "#{path}: #{message}"
14
+ end
15
+
16
+ # @api private
17
+ # Collects the problems found while reading a config, each with its path, so checking goes on
18
+ # after the first. Errors from the steps name the field they are about (+condition.all[0]: ...+);
19
+ # the path takes that field under the name data gives it (+steps[3].if.all[0]+).
20
+ class Problems
21
+ # Fields a step's own errors start with, and how data names them.
22
+ FIELDS = { condition: "if", skip_if: "unless", value: "value", quantity: "quantity", cap: "cap" }.freeze
23
+ # A step error about one field: +condition.all[0]: unknown key "equals"+.
24
+ FIELD_ERROR = /\A(#{FIELDS.keys.join("|")})((?:\.\w+|\[\d+\])*): (.*)\z/m
25
+
26
+ def initialize
27
+ @list = []
28
+ @steps = {}.compare_by_identity
29
+ end
30
+
31
+ # @return [Array<Problem>] in the order found
32
+ def to_a = @list.dup
33
+
34
+ # @return [Boolean]
35
+ def empty? = @list.empty?
36
+
37
+ # @raise [ConfigurationError] with the first problem, naming its step, if there is one
38
+ def raise_first!
39
+ first = @list.first
40
+ raise ConfigurationError.new(first.to_s, step: @steps[first]) if first
41
+ end
42
+
43
+ # @return [Problem]
44
+ def add(path, message, step: nil)
45
+ Problem.new(path:, message:).tap do |problem|
46
+ @list << problem
47
+ @steps[problem] = step
48
+ end
49
+ end
50
+
51
+ # Runs a check, recording what it raises at +at+ (or deeper, where the error says).
52
+ # @return [Object, nil] what the block returns, or +nil+ when it raised
53
+ def attempt(at)
54
+ yield
55
+ rescue ConfigurationError => e
56
+ add(*located(e, at), step: e.step)
57
+ nil
58
+ end
59
+
60
+ private
61
+
62
+ # @return [Array(String, String)] the path and the message without it
63
+ def located(error, at)
64
+ found = /\A(#{Regexp.escape(at)}(?:\.\w+|\[\d+\])*): (.*)\z/m.match(error.message)
65
+ at, message = found ? found.captures : [at, error.message]
66
+ message = message.delete_prefix("step #{error.step.inspect}: ") if error.step
67
+ field = FIELD_ERROR.match(message)
68
+ field ? ["#{at}.#{FIELDS.fetch(field[1].to_sym)}#{field[2]}", field[3]] : [at, message]
69
+ end
70
+ end
71
+ end
72
+ end