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,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ class Loader
5
+ # @api private
6
+ # Reads one step entry (+{ "type": "percent", "name": "promo", "value": 10 }+) and builds it
7
+ # with the {Builder} method of the same name, so the DSL and data share every check.
8
+ class StepEntry
9
+ # Keys every step type except +base+ takes, besides its own.
10
+ COMMON = %i[type name if unless starts_at ends_at].freeze
11
+ # The keys each built-in step type takes.
12
+ KEYS = {
13
+ base: %i[type name value], override: COMMON + %i[value], percent: COMMON + %i[value],
14
+ surcharge: COMMON + %i[value], amount: COMMON + %i[value cap], tiered: COMMON + %i[tiers quantity],
15
+ rounding: COMMON + %i[mode to]
16
+ }.freeze
17
+ # The keys each built-in step type needs.
18
+ REQUIRED = {
19
+ base: %i[value], override: %i[name value], percent: %i[name value], surcharge: %i[name value],
20
+ amount: %i[name value], tiered: %i[name tiers quantity]
21
+ }.freeze
22
+
23
+ # @param builder [Builder] collects the built steps, with the shared sources, operators and clock
24
+ # @param registry [Registry] the custom step types the config may name
25
+ def initialize(builder, registry)
26
+ @builder = builder
27
+ @registry = registry
28
+ end
29
+
30
+ # @param entry [Object] one entry of +steps+
31
+ # @param at [String] its path, +steps[3]+
32
+ # @return [Symbol] its built-in or registered type
33
+ # @raise [ConfigurationError] if it is not a Hash, or its type is missing or unknown
34
+ def type!(entry, at)
35
+ unless entry.is_a?(Hash)
36
+ raise ConfigurationError, "#{at}: must be a Hash, got #{Conditions::Reason.show(entry)}"
37
+ end
38
+
39
+ type = entry.find { |key, _| key.to_s == "type" }&.last
40
+ raise ConfigurationError, "#{at}: missing type" if type.nil?
41
+
42
+ known(Registered.name_of(type, "#{at}.type").to_sym, at)
43
+ end
44
+
45
+ # @param type [Symbol] from {#type!}
46
+ # @return [Hash{Symbol => Object}] the entry's fields
47
+ # @raise [ConfigurationError] if a key is unknown or given twice, or a required one is missing
48
+ def fields!(entry, type, at)
49
+ fields = Keys.read(entry, allowed(type, entry), at)
50
+ missing = REQUIRED.fetch(type, []) - fields.keys
51
+ raise ConfigurationError, "#{at}: missing #{missing.join(", ")}" unless missing.empty?
52
+
53
+ fields
54
+ end
55
+
56
+ # @return [Steps::Step] the step, added to the builder
57
+ # @raise [ConfigurationError] if the step can't be built from the fields
58
+ def build(type, fields)
59
+ options = fields.slice(:if, :unless, :starts_at, :ends_at)
60
+ case type
61
+ when :base then @builder.base(base_name(fields), fields[:value])
62
+ when :tiered then @builder.tiered(fields[:name], fields[:tiers], quantity: fields[:quantity], **options)
63
+ when :rounding then rounding(fields, options)
64
+ when *Builder::VALUE_STEPS.keys
65
+ @builder.public_send(type, fields[:name], fields[:value], **options, **fields.slice(:cap))
66
+ else custom(type, fields, options)
67
+ end
68
+ end
69
+
70
+ private
71
+
72
+ def known(type, at)
73
+ return type if KEYS.key?(type) || @registry.steps.key?(type)
74
+
75
+ raise ConfigurationError, "#{at}.type: unknown step type #{type.to_s.inspect} (expected one of: " \
76
+ "#{(KEYS.keys + @registry.steps.keys).join(", ")})"
77
+ end
78
+
79
+ # A registered step type takes any other keys, as its params.
80
+ def allowed(type, entry)
81
+ KEYS.fetch(type) do
82
+ COMMON | entry.keys.grep(String).select(&:valid_encoding?).map(&:to_sym) | entry.keys.grep(Symbol)
83
+ end
84
+ end
85
+
86
+ # The name is checked and passed first, so a Symbol value (as YAML can give) is never read as it.
87
+ def base_name(fields) = StepName.check!(fields.fetch(:name, :base), ConfigurationError, "name")
88
+
89
+ def rounding(fields, options)
90
+ modes = fields.key?(:mode) ? [fields[:mode]] : []
91
+ @builder.rounding(*modes, name: fields.fetch(:name, :rounding), **options, **fields.slice(:to))
92
+ end
93
+
94
+ def custom(type, fields, options)
95
+ callable = @registry.steps.fetch(type)
96
+ params = frozen_copy(fields.except(*COMMON))
97
+ @builder.step(fields.fetch(:name, type), **options) do |cents, item, ctx|
98
+ callable.call(cents, item, ctx, params)
99
+ end
100
+ end
101
+
102
+ # @return [Object] +value+ with every Hash, Array and String in it copied and frozen, so a
103
+ # custom step's params can't change after loading
104
+ def frozen_copy(value)
105
+ case value
106
+ when Hash then value.to_h { |key, entry| [key, frozen_copy(entry)] }.freeze
107
+ when Array then value.map { |entry| frozen_copy(entry) }.freeze
108
+ when String then value.dup.freeze
109
+ else value
110
+ end
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # @api private
5
+ # Builds a pipeline from rules written as data: a Hash with +version+ and +steps+, as parsed
6
+ # from JSON or YAML or read from a database (see {PriceWaterfall.load}). Each step entry goes
7
+ # through the same {Builder} methods as the DSL ({StepEntry}), so both share every check.
8
+ #
9
+ # Every problem is collected with where it is (+steps[3].if.all[0]+), so {PriceWaterfall.validate}
10
+ # can list them all for an admin form; {PriceWaterfall.load} raises the first. Each step reports
11
+ # its first problem, as building it stops there.
12
+ class Loader
13
+ # @return [String, nil] the config's +version+
14
+ attr_reader :version
15
+
16
+ # @param config [Hash] +version+ (optional) and +steps+, with String or Symbol keys
17
+ # @param registry [Registry, nil] custom step types, sources and operators the config may name
18
+ # @param clock [#call, nil] clock for time-limited steps, already checked
19
+ # @raise [ConfigurationError] if +registry+ is not a {Registry}, or +clock+ is not a clock
20
+ def initialize(config, registry: nil, clock: nil)
21
+ @registry = Registry.check!(registry) || Registry.new
22
+ @problems = Problems.new
23
+ @built = {}
24
+ @types = []
25
+ fields = @problems.attempt("config") { Keys.read(hash!(config), %i[version steps], "config") }
26
+ read(fields, clock) if fields
27
+ end
28
+
29
+ # @return [Array<Problem>] everything wrong with the config, in the order found
30
+ def problems = @problems.to_a
31
+
32
+ # @param hide_values [Boolean] see {Pipeline#initialize}
33
+ # @return [Pipeline] frozen
34
+ # @raise [ConfigurationError] naming the first problem and where it is
35
+ def pipeline(hide_values: false)
36
+ @problems.raise_first!
37
+ Pipeline.new(@built.values, version:, hide_values:)
38
+ end
39
+
40
+ private
41
+
42
+ def read(fields, clock)
43
+ @version = @problems.attempt("version") { version!(fields[:version]) }
44
+ return @problems.add("steps", "missing") unless fields.key?(:steps)
45
+
46
+ builder = Builder.new(sources: @registry.sources, operators: @registry.operators, clock:)
47
+ read_steps(fields[:steps], StepEntry.new(builder, @registry))
48
+ end
49
+
50
+ def read_steps(steps, reader)
51
+ unless steps.is_a?(Array) && !steps.empty?
52
+ return @problems.add("steps", "must be a non-empty list of steps, got #{Conditions::Reason.show(steps)}")
53
+ end
54
+
55
+ steps.each_with_index { |entry, index| read_step(reader, entry, index) }
56
+ Order.check(@types, @built, @problems)
57
+ end
58
+
59
+ def read_step(reader, entry, index)
60
+ at = "steps[#{index}]"
61
+ type = @types[index] = @problems.attempt(at) { reader.type!(entry, at) }
62
+ fields = type && @problems.attempt(at) { reader.fields!(entry, type, at) }
63
+ step = fields && @problems.attempt(at) { reader.build(type, fields) }
64
+ @built[index] = step if step
65
+ end
66
+
67
+ def hash!(config)
68
+ return config if config.is_a?(Hash)
69
+
70
+ raise ConfigurationError, "config: must be a Hash, got #{Conditions::Reason.show(config)}"
71
+ end
72
+
73
+ def version!(version)
74
+ Result.version(version)
75
+ rescue ConfigurationError => e
76
+ raise ConfigurationError, e.message.delete_prefix("version ")
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Exact parsing of the numbers steps accept (percentages, quantities), shared so they all take
5
+ # the same forms and reject the same things.
6
+ module Number
7
+ # Numeric Strings accepted: "10", "12.5", ".5", "+3". No exponents, no thousands separators.
8
+ PATTERN = /\A[+-]?(?:\d+(?:\.\d+)?|\.\d+)\z/
9
+
10
+ # Most decimal places {format} writes exactly.
11
+ MAX_DECIMALS = 20
12
+ # Most digits {format} writes out; a bigger number is written approximately, so a huge value
13
+ # in request data can't make a note slow, and a long one isn't cut short in a note.
14
+ MAX_DIGITS = 36
15
+ # Most digits {parse} accepts in a BigDecimal or a numeric String, counted as the number is
16
+ # written out in decimal: +1e999+ and +12.5+ have 1000 and 3. Signs, spaces and the decimal
17
+ # point don't count; a String's leading zeros do (+"0.001"+ has 4). Converting a longer one
18
+ # exactly takes time that grows with its size (a BigDecimal of +1e100000000+ takes over half a
19
+ # minute), and these values can come from request data at pricing time, so they are rejected
20
+ # first. No price, percentage or quantity needs more.
21
+ MAX_PARSED_DIGITS = 1_000
22
+ # Smallest numerator or denominator that has more than {MAX_DIGITS} digits.
23
+ TOO_LONG = 10**MAX_DIGITS
24
+
25
+ module_function
26
+
27
+ # Converts +value+ to an exact Integer or Rational.
28
+ #
29
+ # Integers and Rationals are returned unchanged. Floats go through their decimal String form,
30
+ # so +12.5+ becomes exactly +25/2+. BigDecimals convert exactly.
31
+ #
32
+ # @param value [Integer, Rational, Float, BigDecimal, String]
33
+ # @param label [String] what the number is, for the error message
34
+ # @return [Integer, Rational]
35
+ # @raise [InvalidAmount] if +value+ is not a finite real number or a numeric String, or is a
36
+ # BigDecimal or String with more than {MAX_PARSED_DIGITS} digits
37
+ # @example
38
+ # Number.parse(12.5, "percentage") # => (25/2)
39
+ # Number.parse("12", "quantity") # => (12/1)
40
+ def parse(value, label)
41
+ case value
42
+ when Integer, Rational then value
43
+ when Numeric then from_number(value, label)
44
+ when String then from_string(value, label)
45
+ else invalid(value, label)
46
+ end
47
+ end
48
+
49
+ # Writes a parsed, non-negative number for trace notes: exact decimals as decimals ("12",
50
+ # "9.5", "0.0000001"), anything else as its nearest Float ("0.3333333333333333"). A number too
51
+ # big or too precise to write out (see {MAX_DIGITS}) is written approximately: "~1.0e+50",
52
+ # or "~1e1000000" beyond what a Float can hold.
53
+ #
54
+ # @param number [Integer, Rational] 0 or more
55
+ # @return [String]
56
+ # @example
57
+ # Number.format(Rational(19, 2)) # => "9.5"
58
+ def format(number)
59
+ return approximate(number) if huge?(number)
60
+
61
+ scale = decimal_places(number, MAX_DECIMALS)
62
+ return number.to_f.to_s if scale.nil?
63
+ return number.to_i.to_s if scale.zero?
64
+
65
+ whole, fraction = (number * (10**scale)).to_i.divmod(10**scale)
66
+ "#{whole}.#{fraction.to_s.rjust(scale, "0")}"
67
+ end
68
+
69
+ # Writes a non-negative BigDecimal like {format}, without turning a huge one into a huge
70
+ # Rational first.
71
+ #
72
+ # @param decimal [BigDecimal] finite, 0 or more
73
+ # @return [String]
74
+ # @example
75
+ # Number.format_decimal(BigDecimal("1e1000000")) # => "~1e1000000"
76
+ def format_decimal(decimal)
77
+ return format(decimal.to_r) if decimal.precision <= MAX_DIGITS
78
+
79
+ float = decimal.to_f
80
+ float.finite? && !float.zero? ? "~#{float}" : "~1e#{power_of_ten(decimal)}"
81
+ end
82
+
83
+ # @param number [Integer, Rational]
84
+ # @param max [Integer]
85
+ # @return [Integer, nil] how many decimal places write +number+ exactly, or +nil+ if more
86
+ # than +max+ would be needed
87
+ # @example
88
+ # Number.decimal_places(Rational(1, 8), 6) # => 3
89
+ def decimal_places(number, max) = (0..max).find { |n| (number * (10**n)).denominator == 1 }
90
+
91
+ # @api private
92
+ # Comparing with {TOO_LONG} looks at sizes first, so it is quick however big +number+ is.
93
+ def huge?(number) = number.numerator >= TOO_LONG || number.denominator >= TOO_LONG
94
+
95
+ # @api private
96
+ # A BigDecimal is 0.d1d2... * 10**exponent, so the power of ten nearest it is read from its
97
+ # leading digits, as {approximate} reads it from a Rational.
98
+ def power_of_ten(decimal)
99
+ lead = decimal.split[1][0, 17]
100
+ (Math.log10(Integer(lead, 10)) - lead.length + decimal.exponent).round
101
+ end
102
+
103
+ # @api private
104
+ # Beyond a Float, writes the power of ten nearest +number+ ({format_decimal} writes a BigDecimal
105
+ # the same way). +Math.log10+ reads an Integer of any size exactly and quickly.
106
+ def approximate(number)
107
+ float = number.to_f
108
+ return "~#{float}" if float.finite? && !float.zero?
109
+
110
+ "~1e#{(Math.log10(number.numerator.abs) - Math.log10(number.denominator)).round}"
111
+ end
112
+
113
+ # @api private
114
+ def from_number(value, label)
115
+ return invalid(value, label) unless value.real? && value.finite?
116
+ return too_long(value, label) if decimal_too_long?(value)
117
+
118
+ value.is_a?(Float) ? Rational(value.to_s) : value.to_r
119
+ end
120
+
121
+ # @api private
122
+ def from_string(value, label)
123
+ return invalid(value, label) unless value.valid_encoding? && value.strip.match?(PATTERN)
124
+ return too_long(value, label) if value.count("0-9") > MAX_PARSED_DIGITS
125
+
126
+ Rational(value.strip)
127
+ end
128
+
129
+ # @api private
130
+ # Read from the BigDecimal's size, without converting it. +precision+ is how many digits it
131
+ # has written out in decimal, the same count {format_decimal} uses.
132
+ def decimal_too_long?(value)
133
+ defined?(BigDecimal) && value.is_a?(BigDecimal) && value.precision > MAX_PARSED_DIGITS
134
+ end
135
+
136
+ # @api private
137
+ def too_long(value, label)
138
+ raise InvalidAmount, "#{label} must have at most #{MAX_PARSED_DIGITS} digits, got #{value.class} " \
139
+ "#{Conditions::Reason.show(value)}"
140
+ end
141
+
142
+ # @api private
143
+ def invalid(value, label)
144
+ raise InvalidAmount, "#{label} must be a number, got #{value.class} #{Conditions::Reason.show(value)}"
145
+ end
146
+ private_class_method :huge?, :approximate, :power_of_ten, :from_number, :from_string, :decimal_too_long?, :too_long,
147
+ :invalid
148
+ end
149
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Percentage parsing, maths and formatting shared by the percent, surcharge and tiered steps.
5
+ module Percentage
6
+ # Most decimal places {format} prints; longer decimals are rounded and marked with "~".
7
+ MAX_DECIMALS = 6
8
+
9
+ # Rounds a share of a price half up to whole cents.
10
+ HALF_UP = Rounding.rounder(:half_up)
11
+
12
+ module_function
13
+
14
+ # Converts a percentage to an exact Rational; see {Number.parse} for the accepted forms.
15
+ #
16
+ # @param value [Integer, Rational, Float, BigDecimal, String, nil]
17
+ # @param max [Integer, nil] upper bound; +nil+ for none (surcharges can exceed 100%)
18
+ # @return [Rational, nil] +nil+ when +value+ is +nil+
19
+ # @raise [InvalidAmount] if +value+ is not a finite real number, is negative or is above +max+
20
+ # @example
21
+ # Percentage.parse(12.5) # => (25/2)
22
+ # Percentage.parse("10") # => (10/1)
23
+ # Percentage.parse(150, max: nil) # => (150/1)
24
+ def parse(value, max: 100)
25
+ return nil if value.nil?
26
+
27
+ pct = Rational(Number.parse(value, "percentage"))
28
+ return pct unless pct.negative? || (max && pct > max)
29
+
30
+ range = max ? "between 0 and #{max}" : "0 or more"
31
+ raise InvalidAmount, "percentage must be #{range}, got #{Conditions::Reason.show(value)}"
32
+ end
33
+
34
+ # @param cents [Integer]
35
+ # @param pct [Rational]
36
+ # @return [Integer] +pct+ percent of +cents+, rounded half up to whole cents
37
+ # @example
38
+ # Percentage.of(4599, 10) # => 460
39
+ def of(cents, pct) = HALF_UP.call(Rational(cents) * pct / 100)
40
+
41
+ # Takes +pct+ percent off +cents+, or adds it, and builds the trace note.
42
+ #
43
+ # @param cents [Integer]
44
+ # @param pct [Rational] a percentage from {parse}
45
+ # @param increase [Boolean] true to add the share, false to subtract it
46
+ # @param suffix [String] appended inside the note's parentheses
47
+ # @return [Array(Integer, String)] new price and trace note; a share that rounds to 0 cents
48
+ # leaves the price unchanged with a "skipped" note
49
+ # @example
50
+ # Percentage.adjust(4599, 10) # => [4139, "-460 (10%)"]
51
+ # Percentage.adjust(4599, 5, increase: true) # => [4829, "+230 (5%)"]
52
+ def adjust(cents, pct, increase: false, suffix: "")
53
+ share = of(cents, pct)
54
+ return [cents, "skipped (#{format(pct)}%#{suffix} rounds to 0)"] if share.zero?
55
+
56
+ after = increase ? cents + share : cents - share
57
+ [after, "#{increase ? "+" : "-"}#{share} (#{format(pct)}%#{suffix})"]
58
+ end
59
+
60
+ # Formats a percentage for trace notes without the % sign.
61
+ #
62
+ # @param pct [Rational]
63
+ # @return [String] "10", "12.5", or for longer decimals the value rounded half up to
64
+ # {MAX_DECIMALS} places and marked with "~", such as "~33.333333"
65
+ # @example
66
+ # Percentage.format(Rational(25, 2)) # => "12.5"
67
+ # Percentage.format(Rational(1, 3)) # => "~0.333333"
68
+ def format(pct)
69
+ return Number.format(pct) if Number.decimal_places(pct, MAX_DECIMALS)
70
+
71
+ scale = 10**MAX_DECIMALS
72
+ rounded = Number.format(Rational(HALF_UP.call(pct * scale), scale))
73
+ # A huge percentage is already marked approximate by Number.format.
74
+ rounded.start_with?("~") ? rounded : "~#{rounded}"
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # An ordered list of steps that prices an item: the first step sets the starting price and each
5
+ # one after it changes the price the previous one left. Built by {PriceWaterfall.define} (or
6
+ # directly from steps), checked once when it is built, and frozen, so one pipeline can be kept
7
+ # in a constant and shared across threads.
8
+ #
9
+ # @example
10
+ # pipeline = PriceWaterfall::Pipeline.new([PriceWaterfall::Steps::Base.new(:base, 4599),
11
+ # PriceWaterfall::Steps::Percent.new(:promo, 10)])
12
+ # pipeline.call({}, {}).cents # => 4139
13
+ class Pipeline
14
+ # @return [Array<Steps::Step>] frozen, in the order they run
15
+ attr_reader :steps
16
+ # @return [String, nil] the rule set's version, copied into every {Result}
17
+ attr_reader :version
18
+ # @return [Boolean] whether condition reasons in notes leave out the values they read
19
+ attr_reader :hide_values
20
+
21
+ # @param steps [Array<Steps::Step>] a {Steps::Base} first, then the steps that change the price
22
+ # @param version [String, nil] the rule set's version (a date, git sha, database row id ...)
23
+ # @param hide_values [Boolean] write why a data condition skipped a step without the values it
24
+ # read (+item.qty < 10+ rather than +item.qty 4 < 10+), for results stored where they must not
25
+ # hold customer data; the values written in the rules themselves are still shown
26
+ # @raise [ConfigurationError] unless the steps form a valid pipeline: a {Steps::Base} first and
27
+ # only there, unique names, and the step named +:rounding+, if any, a {Steps::Round} and
28
+ # last; or +version+ is neither a String nor +nil+, or +hide_values+ is not true or false
29
+ def initialize(steps, version: nil, hide_values: false)
30
+ unless [true, false].include?(hide_values)
31
+ raise ConfigurationError, "hide_values: must be true or false, got #{Conditions::Reason.show(hide_values)}"
32
+ end
33
+
34
+ @hide_values = hide_values
35
+ @version = Result.version(version)
36
+ @steps = Pipeline.check!(steps).dup.freeze
37
+ freeze
38
+ end
39
+
40
+ # Prices one item.
41
+ #
42
+ # @param item [Object] the item being priced, passed to every step
43
+ # @param ctx [Object] the pricing context, passed to every step
44
+ # @param now [Time, nil] the moment to price at, for time-limited steps (an "as of" preview, a
45
+ # test); +nil+ asks the clock, once for the whole call, so every step sees the same moment
46
+ # @return [Result] the final price with one {Entry} per step
47
+ # @raise [InvalidAmount, StepError] from the step that failed, naming it
48
+ # @raise [InvalidAmount] if +now+ is not a Time
49
+ def call(item, ctx = {}, now: nil)
50
+ Run.start(now:, hide_values:) do
51
+ cents = 0
52
+ entries = steps.map do |step|
53
+ after, note, skipped = step.evaluate(cents, item, ctx)
54
+ Entry.new(step: step.name, before: cents, after:, note:, skipped:).tap { cents = after }
55
+ end
56
+ Result.new(entries:, version:)
57
+ end
58
+ end
59
+
60
+ # @return [Array<Symbol>] the steps' names, in order
61
+ def names = steps.map(&:name)
62
+
63
+ # @api private
64
+ # @return [Array<Steps::Step>] +steps+, checked
65
+ # @raise [ConfigurationError] naming the first problem
66
+ def self.check!(steps)
67
+ unless steps.is_a?(Array) && steps.all?(Steps::Step)
68
+ raise ConfigurationError, "steps must be an Array of steps, got #{Conditions::Reason.show(steps)}"
69
+ end
70
+
71
+ check_base!(steps)
72
+ check_names!(steps)
73
+ check_rounding!(steps)
74
+ steps
75
+ end
76
+
77
+ # @api private
78
+ def self.check_base!(steps)
79
+ raise ConfigurationError, "a pipeline needs a base step first" unless steps.first.is_a?(Steps::Base)
80
+
81
+ extra = steps.drop(1).find { |step| step.is_a?(Steps::Base) }
82
+ return unless extra
83
+
84
+ raise ConfigurationError.new("#{extra.name.inspect}: only the first step can be a base", step: extra.name)
85
+ end
86
+
87
+ # @api private
88
+ def self.check_names!(steps)
89
+ repeated, = steps.map(&:name).tally.find { |_, count| count > 1 }
90
+ raise ConfigurationError.new("#{repeated.inspect}: step names must be unique", step: repeated) if repeated
91
+ end
92
+
93
+ # @api private
94
+ # The unnamed rounding step rounds the final price, so nothing may change it afterwards; a
95
+ # pipeline that rounds earlier names that step (+rounding :floor, name: :pre_tax+). The name
96
+ # +:rounding+ is kept for it, so a trace's "rounding" line is always the final rounding.
97
+ def self.check_rounding!(steps)
98
+ index = steps.index { |step| step.name == :rounding }
99
+ return if index.nil?
100
+ unless steps[index].is_a?(Steps::Round)
101
+ raise ConfigurationError.new(":rounding: the name :rounding is kept for the rounding step; give this " \
102
+ "step another name", step: :rounding)
103
+ end
104
+ return if index == steps.size - 1
105
+
106
+ raise ConfigurationError.new(":rounding must be the last step; give an earlier rounding its own name " \
107
+ "(rounding :floor, name: :pre_tax)", step: :rounding)
108
+ end
109
+ private_class_method :check_base!, :check_names!, :check_rounding!
110
+ end
111
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Callables registered in Ruby and named in data: value sources (+{ source: "contract_price" }+)
5
+ # and condition operators (+op: "is_vip"+). They are passed in as a Hash of name => callable, so
6
+ # data can only use functions the app chose to expose.
7
+ module Registered
8
+ module_function
9
+
10
+ # Checks a Hash of registered callables as a whole: it must be a Hash, its names Strings or
11
+ # Symbols, and no name may be registered twice as a String and a Symbol (+"vip"+ and +:vip+).
12
+ #
13
+ # @param callables [Object] what was passed in
14
+ # @param label [String] what it is, for error messages (+"sources"+, +"operators"+)
15
+ # @return [Hash] a frozen copy
16
+ # @raise [ConfigurationError] if it is not a Hash, a name is not a String or Symbol, or a name
17
+ # is registered twice
18
+ def table(callables, label) = check!(callables, label).dup.freeze
19
+
20
+ # @api private
21
+ # Steps pass tables already checked by {table}; checking again is cheap, and keeps {find} safe
22
+ # for {Values::Source} and {Conditions::Custom} built directly.
23
+ def check!(callables, label)
24
+ unless callables.is_a?(Hash)
25
+ raise ConfigurationError, "#{label}: must be a Hash of name => callable, " \
26
+ "got #{Conditions::Reason.show(callables)}"
27
+ end
28
+
29
+ callables.keys.group_by { |name| name_of(name, label) }.each do |name, keys|
30
+ raise ConfigurationError, "#{label}: #{name.inspect} is registered more than once" if keys.size > 1
31
+ end
32
+ callables
33
+ end
34
+
35
+ # @api private
36
+ def name_of(name, label)
37
+ return name.to_s if (name.is_a?(String) && name.valid_encoding?) || name.is_a?(Symbol)
38
+
39
+ raise ConfigurationError, "#{label}: names must be Strings or Symbols with a valid encoding, " \
40
+ "got #{Conditions::Reason.show(name)}"
41
+ end
42
+
43
+ # Finds a registered callable by name and checks it can be called with +signature+.
44
+ #
45
+ # @param name [Object] the name given in data
46
+ # @param callables [Hash{Symbol, String => #call}] the registered callables
47
+ # @param kind [String] what is looked up, for error messages (+"source"+, +"operator"+)
48
+ # @param key [String] the data key holding the name, for error messages (+"source"+, +"op"+)
49
+ # @param signature [Array(Integer, String)] number of arguments and their description
50
+ # @param at [String] where the name is, for error messages
51
+ # @return [Array(Symbol, #call)] the registered name and its callable
52
+ # @raise [ConfigurationError] if +name+ is not a String or Symbol, is unknown or registered
53
+ # twice, or its callable can't take +signature+
54
+ # @example
55
+ # Registered.find("vip", { vip: ->(value, _arg) { value } }, kind: "operator", key: "op",
56
+ # signature: [2, "(value, arg)"], at: "condition") # => [:vip, #<Proc>]
57
+ def find(name, callables, kind:, key:, signature:, at:)
58
+ unless name.is_a?(String) || name.is_a?(Symbol)
59
+ raise ConfigurationError, "#{at}: #{key} must be a name, got #{Conditions::Reason.show(name)}"
60
+ end
61
+
62
+ registered, callable = lookup(name, check!(callables, "#{at}: #{kind}s"), kind, at)
63
+ check_arity(callable, signature, "#{at}: #{kind} #{registered.to_s.inspect}")
64
+ [registered.to_sym, callable]
65
+ end
66
+
67
+ # @api private
68
+ def lookup(name, callables, kind, at)
69
+ callables.find { |registered, _| registered.to_s == name.to_s } ||
70
+ raise(ConfigurationError, "#{at}: unknown #{kind} #{name.to_s.inspect}" \
71
+ "#{" (registered: #{callables.keys.join(", ")})" unless callables.empty?}")
72
+ end
73
+
74
+ # @api private
75
+ def check_arity(callable, (count, description), label)
76
+ shown = Conditions::Reason.show(callable)
77
+ raise ConfigurationError, "#{label} is not callable, got #{shown}" unless callable.respond_to?(:call)
78
+
79
+ begin
80
+ Resolver.check_arity!(callable, count, description)
81
+ rescue ConfigurationError => e
82
+ raise ConfigurationError, "#{label}: #{e.message}"
83
+ end
84
+ end
85
+ private_class_method :check!, :lookup, :check_arity
86
+ end
87
+ end