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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +186 -0
- data/LICENSE.txt +21 -0
- data/README.md +582 -0
- data/lib/price_waterfall/builder/arguments.rb +86 -0
- data/lib/price_waterfall/builder.rb +192 -0
- data/lib/price_waterfall/conditions/all.rb +18 -0
- data/lib/price_waterfall/conditions/any.rb +18 -0
- data/lib/price_waterfall/conditions/comparison.rb +142 -0
- data/lib/price_waterfall/conditions/compiled.rb +32 -0
- data/lib/price_waterfall/conditions/compiler.rb +182 -0
- data/lib/price_waterfall/conditions/custom.rb +59 -0
- data/lib/price_waterfall/conditions/group.rb +45 -0
- data/lib/price_waterfall/conditions/negation.rb +36 -0
- data/lib/price_waterfall/conditions/reason.rb +227 -0
- data/lib/price_waterfall/configuration_error.rb +8 -0
- data/lib/price_waterfall/entry.rb +111 -0
- data/lib/price_waterfall/error.rb +24 -0
- data/lib/price_waterfall/invalid_amount.rb +7 -0
- data/lib/price_waterfall/keys.rb +38 -0
- data/lib/price_waterfall/loader/order.rb +51 -0
- data/lib/price_waterfall/loader/problems.rb +72 -0
- data/lib/price_waterfall/loader/step_entry.rb +114 -0
- data/lib/price_waterfall/loader.rb +79 -0
- data/lib/price_waterfall/number.rb +149 -0
- data/lib/price_waterfall/percentage.rb +77 -0
- data/lib/price_waterfall/pipeline.rb +111 -0
- data/lib/price_waterfall/registered.rb +87 -0
- data/lib/price_waterfall/registry.rb +127 -0
- data/lib/price_waterfall/resolver.rb +148 -0
- data/lib/price_waterfall/result.rb +200 -0
- data/lib/price_waterfall/rounding.rb +119 -0
- data/lib/price_waterfall/run.rb +113 -0
- data/lib/price_waterfall/step_error.rb +9 -0
- data/lib/price_waterfall/step_name.rb +56 -0
- data/lib/price_waterfall/steps/amount.rb +50 -0
- data/lib/price_waterfall/steps/base.rb +40 -0
- data/lib/price_waterfall/steps/callable.rb +48 -0
- data/lib/price_waterfall/steps/cents.rb +35 -0
- data/lib/price_waterfall/steps/custom.rb +50 -0
- data/lib/price_waterfall/steps/override.rb +23 -0
- data/lib/price_waterfall/steps/percent.rb +17 -0
- data/lib/price_waterfall/steps/percentage_change.rb +26 -0
- data/lib/price_waterfall/steps/round.rb +46 -0
- data/lib/price_waterfall/steps/skipping.rb +43 -0
- data/lib/price_waterfall/steps/step.rb +200 -0
- data/lib/price_waterfall/steps/surcharge.rb +17 -0
- data/lib/price_waterfall/steps/tiered.rb +95 -0
- data/lib/price_waterfall/time_window.rb +93 -0
- data/lib/price_waterfall/timestamp.rb +58 -0
- data/lib/price_waterfall/user_code.rb +72 -0
- data/lib/price_waterfall/values/list.rb +28 -0
- data/lib/price_waterfall/values/literal.rb +28 -0
- data/lib/price_waterfall/values/path.rb +106 -0
- data/lib/price_waterfall/values/source.rb +44 -0
- data/lib/price_waterfall/version.rb +6 -0
- data/lib/price_waterfall.rb +126 -0
- metadata +103 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PriceWaterfall
|
|
4
|
+
# The DSL behind {PriceWaterfall.define}: one method per step type, each adding a step in the
|
|
5
|
+
# order it is called. +if:+ / +unless:+ become the steps' +condition:+ / +skip_if:+, and the
|
|
6
|
+
# +sources:+, +operators:+ and +clock:+ given to {PriceWaterfall.define} are passed to every
|
|
7
|
+
# step, so data inputs and conditions can use them. A step's own +sources:+ or +operators:+ are
|
|
8
|
+
# added to the shared ones, replacing any with the same name.
|
|
9
|
+
#
|
|
10
|
+
# Every mistake in a call, such as a missing value, an unknown keyword or a wrong number of
|
|
11
|
+
# arguments, raises a {ConfigurationError} naming the step.
|
|
12
|
+
#
|
|
13
|
+
# Inside a block with no parameters, +self+ is the builder; give the block a parameter
|
|
14
|
+
# (+define do |p|+, or any other) to keep the caller's +self+, its methods and instance variables.
|
|
15
|
+
class Builder
|
|
16
|
+
include Arguments
|
|
17
|
+
|
|
18
|
+
# Step options the DSL renames, so it reads like Ruby's own +if+ / +unless+.
|
|
19
|
+
RENAMED = { if: :condition, unless: :skip_if }.freeze
|
|
20
|
+
# The steps driven by one value, given as an argument or a block, by DSL method.
|
|
21
|
+
VALUE_STEPS = {
|
|
22
|
+
override: Steps::Override, percent: Steps::Percent, surcharge: Steps::Surcharge, amount: Steps::Amount
|
|
23
|
+
}.freeze
|
|
24
|
+
# Options every step takes, in the DSL's spelling and the steps' own.
|
|
25
|
+
STEP_OPTIONS = %i[if unless condition skip_if starts_at ends_at clock sources operators].freeze
|
|
26
|
+
# Said of a lambda given to {PriceWaterfall.define} that can't take exactly one argument.
|
|
27
|
+
LAMBDA_PROBLEM = "define's lambda must take one argument, the builder"
|
|
28
|
+
# Step settings for which +nil+ means not set, so the shared one is kept: settings passed along
|
|
29
|
+
# (+clock: opts[:clock]+) can be +nil+.
|
|
30
|
+
UNSET_IF_NIL = %i[clock sources operators].freeze
|
|
31
|
+
# Settings a step's own Hash is added to, rather than replacing the shared one.
|
|
32
|
+
MERGED = %i[sources operators].freeze
|
|
33
|
+
|
|
34
|
+
# @param sources [Hash{Symbol, String => #call}] value sources for every step
|
|
35
|
+
# @param operators [Hash{Symbol, String => #call}] operators for every step's data conditions
|
|
36
|
+
# @param clock [#call, nil] clock for every time-limited step
|
|
37
|
+
# @raise [ConfigurationError] if +sources:+ or +operators:+ is not a Hash of named callables,
|
|
38
|
+
# or +clock:+ is not a callable taking no arguments, even when no step would use it
|
|
39
|
+
def initialize(sources: {}, operators: {}, clock: nil)
|
|
40
|
+
@shared = { sources: Registered.table(sources, "sources"), operators: Registered.table(operators, "operators") }
|
|
41
|
+
@clock = TimeWindow.check_clock!(clock)
|
|
42
|
+
@steps = []
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# @api private
|
|
46
|
+
# Checks {PriceWaterfall.define}'s block. A block with no parameters runs with the builder as
|
|
47
|
+
# +self+; any other gets the builder as its first argument, so it must take one positionally.
|
|
48
|
+
# @raise [ConfigurationError] if there is no block, it has parameters but none positional, it
|
|
49
|
+
# has a required keyword, or it is a lambda that can't take exactly one argument
|
|
50
|
+
def self.check_block!(block)
|
|
51
|
+
raise ConfigurationError, "define needs a block of steps" unless block
|
|
52
|
+
|
|
53
|
+
problem = block_problem(block.parameters.map(&:first), block.lambda?)
|
|
54
|
+
raise ConfigurationError, problem if problem
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# @api private
|
|
58
|
+
# @param types [Array<Symbol>] the block's parameter types, as +Proc#parameters+ gives them
|
|
59
|
+
# @param lambda [Boolean]
|
|
60
|
+
# @return [String, nil] what is wrong with the block, or +nil+ when it is fine
|
|
61
|
+
def self.block_problem(types, lambda)
|
|
62
|
+
return LAMBDA_PROBLEM if lambda && (types.empty? || types.count(:req) > 1)
|
|
63
|
+
return if types.empty?
|
|
64
|
+
if types.include?(:keyreq)
|
|
65
|
+
return "define's block can't have required keywords; it gets the builder as its one argument"
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
"define's block must take the builder as its first parameter" unless types.intersect?(%i[req opt rest])
|
|
69
|
+
end
|
|
70
|
+
private_class_method :block_problem
|
|
71
|
+
|
|
72
|
+
# @return [Array<Steps::Step>] the steps added so far, in order
|
|
73
|
+
def steps = @steps.dup
|
|
74
|
+
|
|
75
|
+
# @api private
|
|
76
|
+
# @param registry [Registry, nil]
|
|
77
|
+
# @return [Hash] +sources:+ and +operators:+, the registry's with the ones given added, a name
|
|
78
|
+
# given replacing the registry's in either its String or Symbol form
|
|
79
|
+
# @raise [ConfigurationError] if +sources+ or +operators+ is not a valid table
|
|
80
|
+
def self.with_registry(registry, sources:, operators:)
|
|
81
|
+
given = { sources: Registered.table(sources, "sources"), operators: Registered.table(operators, "operators") }
|
|
82
|
+
return given unless registry
|
|
83
|
+
|
|
84
|
+
given.to_h { |key, own| [key, Builder.merge(registry.public_send(key), own)] }
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# @api private
|
|
88
|
+
# @return [Hash] +shared+ with +own+ added, +own+ replacing an entry in either name form
|
|
89
|
+
def self.merge(shared, own) = shared.reject { |key, _| own.key?(key.to_s) || own.key?(key.to_sym) }.merge(own)
|
|
90
|
+
|
|
91
|
+
# Starting price; see {Steps::Base}. Takes a value or a block, not both, and is named +:base+
|
|
92
|
+
# unless a Symbol comes first (+base :msrp do ... end+) or +name:+ is given. Takes +sources:+
|
|
93
|
+
# too; it can't be conditional or time-limited.
|
|
94
|
+
#
|
|
95
|
+
# @overload base(input = nil, name: :base, **options, &block)
|
|
96
|
+
# @param input [#call, Hash, Integer, nil] callable +(item, ctx)+, value description or cents
|
|
97
|
+
# @param name [Symbol, String]
|
|
98
|
+
# @overload base(name, input = nil, **options, &block)
|
|
99
|
+
# @param name [Symbol]
|
|
100
|
+
# @param input [#call, Hash, Integer, nil]
|
|
101
|
+
# @yieldparam item [Object]
|
|
102
|
+
# @yieldparam ctx [Object]
|
|
103
|
+
# @return [Steps::Base]
|
|
104
|
+
# @raise [ConfigurationError] naming the step
|
|
105
|
+
def base(*args, name: nil, **options, &block)
|
|
106
|
+
args = base_args(args, name)
|
|
107
|
+
name = step_name!("base", args)
|
|
108
|
+
input = one_input("base", name, args.drop(1), block, options)
|
|
109
|
+
add(Steps::Base.new(name, input, sources: @shared[:sources], **own_options(name, options)))
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# @!method override(name, input = nil, **options, &block)
|
|
113
|
+
# Replaces the price when the value is not +nil+; see {Steps::Override}.
|
|
114
|
+
# @return [Steps::Override]
|
|
115
|
+
# @!method percent(name, input = nil, **options, &block)
|
|
116
|
+
# Percentage discount; see {Steps::Percent}.
|
|
117
|
+
# @return [Steps::Percent]
|
|
118
|
+
# @!method surcharge(name, input = nil, **options, &block)
|
|
119
|
+
# Percentage increase; see {Steps::Surcharge}.
|
|
120
|
+
# @return [Steps::Surcharge]
|
|
121
|
+
# @!method amount(name, input = nil, **options, &block)
|
|
122
|
+
# Fixed discount in cents; see {Steps::Amount}.
|
|
123
|
+
# @return [Steps::Amount]
|
|
124
|
+
VALUE_STEPS.each do |method, klass|
|
|
125
|
+
define_method(method) do |*args, **options, &block|
|
|
126
|
+
name = step_name!(method, args)
|
|
127
|
+
input = one_input(method, name, args.drop(1), block, options)
|
|
128
|
+
add(klass.new(name, input, **step_options(name, options)))
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
# Percentage discount picked by quantity; see {Steps::Tiered}. Write the tiers in braces
|
|
133
|
+
# (+tiered :volume, { 10 => 5 }, quantity: ...+), or Ruby reads them as keywords.
|
|
134
|
+
# @return [Steps::Tiered]
|
|
135
|
+
def tiered(*args, **options, &block)
|
|
136
|
+
name = step_name!("tiered", args)
|
|
137
|
+
no_block!("tiered", name, block)
|
|
138
|
+
if args.size == 1 && !(options.keys - STEP_OPTIONS - [:quantity]).empty?
|
|
139
|
+
raise ConfigurationError.new("step #{name.inspect}: needs its tiers; #{TIERS_HINT}", step: name)
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
add(Steps::Tiered.new(name, *args.drop(1), **step_options(name, options)))
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# Custom step: the callable or block gets +(cents, item, ctx)+ and returns +[new_cents, note]+;
|
|
146
|
+
# see {Steps::Custom}.
|
|
147
|
+
# @return [Steps::Custom]
|
|
148
|
+
def step(*args, **options, &)
|
|
149
|
+
name = step_name!("step", args)
|
|
150
|
+
add(Steps::Custom.new(name, *args.drop(1), **step_options(name, options), &))
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# Rounds to a multiple of +to:+ cents; see {Steps::Round}. Named +:rounding+, which must be the
|
|
154
|
+
# last step; give an earlier rounding its own +name:+.
|
|
155
|
+
#
|
|
156
|
+
# @overload rounding(mode = nil, name: :rounding, **options)
|
|
157
|
+
# @param mode [Symbol, String, nil] one of {Rounding::MODES}; +nil+ means +:half_up+
|
|
158
|
+
# @param name [Symbol, String]
|
|
159
|
+
# @return [Steps::Round]
|
|
160
|
+
def rounding(*modes, name: :rounding, **options, &block)
|
|
161
|
+
name = step_name!("rounding", [name])
|
|
162
|
+
no_block!("rounding", name, block)
|
|
163
|
+
problem = if modes.size > 1 then "takes one rounding mode, got #{modes.size}"
|
|
164
|
+
elsif !modes.empty? && options.key?(:mode) then "give the mode once, as rounding :floor or mode: :floor"
|
|
165
|
+
end
|
|
166
|
+
raise ConfigurationError.new("step #{name.inspect}: #{problem}", step: name) if problem
|
|
167
|
+
|
|
168
|
+
add(Steps::Round.new(name, mode: modes.first, **step_options(name, options)))
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
private
|
|
172
|
+
|
|
173
|
+
def add(step)
|
|
174
|
+
@steps << step
|
|
175
|
+
step
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
# The shared settings, then the step's own.
|
|
179
|
+
def step_options(name, options) = { **@shared, clock: @clock, **own_options(name, options) }
|
|
180
|
+
|
|
181
|
+
# The step's own options, with +if:+ / +unless:+ renamed, {UNSET_IF_NIL} settings that are +nil+
|
|
182
|
+
# left out, and its +sources:+ / +operators:+ added to the shared ones.
|
|
183
|
+
def own_options(name, options)
|
|
184
|
+
check_options!(name, options)
|
|
185
|
+
options = options.transform_keys(RENAMED).reject { |key, value| value.nil? && UNSET_IF_NIL.include?(key) }
|
|
186
|
+
MERGED.each do |key|
|
|
187
|
+
options[key] = Builder.merge(@shared[key], options[key]) if options[key].is_a?(Hash)
|
|
188
|
+
end
|
|
189
|
+
options
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
end
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PriceWaterfall
|
|
4
|
+
module Conditions
|
|
5
|
+
# True when every condition is: +{ all: [{...}, {...}] }+.
|
|
6
|
+
class All < Group
|
|
7
|
+
# The first condition that fails settles an +all+.
|
|
8
|
+
SETTLES_ON = false
|
|
9
|
+
# How the group is named in data and in errors.
|
|
10
|
+
KEY = "all"
|
|
11
|
+
|
|
12
|
+
# @param item [Object]
|
|
13
|
+
# @param ctx [Object]
|
|
14
|
+
# @return [Boolean]
|
|
15
|
+
def call(item, ctx) = @wrapped.all? { |condition| condition.call(item, ctx) }
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
end
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PriceWaterfall
|
|
4
|
+
module Conditions
|
|
5
|
+
# True when at least one condition is: +{ any: [{...}, {...}] }+.
|
|
6
|
+
class Any < Group
|
|
7
|
+
# The first condition that holds settles an +any+.
|
|
8
|
+
SETTLES_ON = true
|
|
9
|
+
# How the group is named in data and in errors.
|
|
10
|
+
KEY = "any"
|
|
11
|
+
|
|
12
|
+
# @param item [Object]
|
|
13
|
+
# @param ctx [Object]
|
|
14
|
+
# @return [Boolean]
|
|
15
|
+
def call(item, ctx) = @wrapped.any? { |condition| condition.call(item, ctx) }
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
end
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PriceWaterfall
|
|
4
|
+
# Conditions described in data, compiled by {Conditions::Compiler}. Each responds to
|
|
5
|
+
# +call(item, ctx)+ and returns +true+ or +false+.
|
|
6
|
+
module Conditions
|
|
7
|
+
# Compares a value from the item or context with an operand:
|
|
8
|
+
# +{ item: "qty", gte: 10 }+, +{ item: "category", in: ["apparel", "shoes"] }+.
|
|
9
|
+
#
|
|
10
|
+
# Values are compared as they are, without converting types: +"10"+ is not +10+. Ordering
|
|
11
|
+
# (+gt+, +gte+, +lt+, +lte+, +between+) only compares two numbers or two Times, so Strings are
|
|
12
|
+
# never ordered alphabetically (+"9" > "10"+). A comparison that can't be made (+nil >= 10+,
|
|
13
|
+
# +"12" >= 10+) is false rather than an error.
|
|
14
|
+
#
|
|
15
|
+
# The bounds for +between+ must be an Array of exactly two; anything else can't be compared. The
|
|
16
|
+
# list for +in+ / +not_in+ is an Array or a Set; a missing (+nil+) list is empty, so
|
|
17
|
+
# +not_in+ a missing exclusion list is true. Any other operand can't be compared, so both are false.
|
|
18
|
+
class Comparison
|
|
19
|
+
include Compiled
|
|
20
|
+
|
|
21
|
+
# The list a missing +in+ / +not_in+ operand stands for.
|
|
22
|
+
EMPTY = [].freeze
|
|
23
|
+
|
|
24
|
+
# Operators that compare with an operand.
|
|
25
|
+
TESTS = {
|
|
26
|
+
eq: ->(value, operand) { value == operand },
|
|
27
|
+
not_eq: ->(value, operand) { value != operand },
|
|
28
|
+
in: ->(value, operand) { Comparison.list(operand)&.include?(value) || false },
|
|
29
|
+
not_in: ->(value, operand) { Comparison.list(operand)&.include?(value) == false },
|
|
30
|
+
gt: ->(value, operand) { Comparison.order(value, operand)&.positive? || false },
|
|
31
|
+
gte: ->(value, operand) { Comparison.order(value, operand)&.>=(0) || false },
|
|
32
|
+
lt: ->(value, operand) { Comparison.order(value, operand)&.negative? || false },
|
|
33
|
+
lte: ->(value, operand) { Comparison.order(value, operand)&.<=(0) || false },
|
|
34
|
+
between: lambda do |value, bounds|
|
|
35
|
+
next false unless bounds.is_a?(Array) && bounds.size == 2
|
|
36
|
+
|
|
37
|
+
(Comparison.order(value, bounds[0])&.>=(0) && Comparison.order(value, bounds[1])&.<=(0)) || false
|
|
38
|
+
end,
|
|
39
|
+
present: ->(value, _operand) { Comparison.present?(value) },
|
|
40
|
+
blank: ->(value, _operand) { !Comparison.present?(value) }
|
|
41
|
+
}.freeze
|
|
42
|
+
|
|
43
|
+
# Every operator name, in the order they are documented.
|
|
44
|
+
OPERATORS = TESTS.keys.freeze
|
|
45
|
+
|
|
46
|
+
# @return [#call] resolver for the value being tested
|
|
47
|
+
attr_reader :value
|
|
48
|
+
# @return [Symbol] one of {OPERATORS}
|
|
49
|
+
attr_reader :operator
|
|
50
|
+
# @return [#call] resolver for the operand
|
|
51
|
+
attr_reader :operand
|
|
52
|
+
|
|
53
|
+
# @param value [#call] resolver for the value being tested
|
|
54
|
+
# @param operator [Symbol] one of {OPERATORS}
|
|
55
|
+
# @param operand [#call] resolver for the operand
|
|
56
|
+
def initialize(value, operator, operand)
|
|
57
|
+
@value = value
|
|
58
|
+
@operator = operator
|
|
59
|
+
@operand = operand
|
|
60
|
+
@test = TESTS.fetch(operator)
|
|
61
|
+
freeze
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# @param item [Object]
|
|
65
|
+
# @param ctx [Object]
|
|
66
|
+
# @return [Boolean]
|
|
67
|
+
def call(item, ctx) = test(value.call(item, ctx), operand.call(item, ctx))
|
|
68
|
+
|
|
69
|
+
# @param item [Object]
|
|
70
|
+
# @param ctx [Object]
|
|
71
|
+
# @return [Array(Boolean, String)] whether the comparison holds, and why
|
|
72
|
+
def check(item, ctx)
|
|
73
|
+
found = value.call(item, ctx)
|
|
74
|
+
against = operand.call(item, ctx)
|
|
75
|
+
held, comparable = evaluate(found, against)
|
|
76
|
+
[held, Reason.comparison(value, found, operator, [operand, against], held:, comparable:)]
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# @api private
|
|
80
|
+
# @return [Boolean] whether +value+ and +operand+ are of kinds the operator can compare
|
|
81
|
+
def self.comparable?(operator, value, operand)
|
|
82
|
+
case operator
|
|
83
|
+
when :gt, :gte, :lt, :lte then !order(value, operand).nil?
|
|
84
|
+
when :between
|
|
85
|
+
operand.is_a?(Array) && operand.size == 2 && operand.none? { |bound| order(value, bound).nil? }
|
|
86
|
+
when :in, :not_in then !list(operand).nil?
|
|
87
|
+
else true
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# @api private
|
|
92
|
+
# @return [Integer, nil] +left <=> right+ for two real numbers or two Times, otherwise +nil+
|
|
93
|
+
def self.order(left, right)
|
|
94
|
+
return left <=> right if left.is_a?(Time) && right.is_a?(Time)
|
|
95
|
+
return nil unless left.is_a?(Numeric) && right.is_a?(Numeric) && left.real? && right.real?
|
|
96
|
+
|
|
97
|
+
left <=> right
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# @api private
|
|
101
|
+
# @return [Array, Set, nil] the operand of +in+ / +not_in+ as a list (+nil+ is empty), or
|
|
102
|
+
# +nil+ when it isn't one
|
|
103
|
+
def self.list(operand)
|
|
104
|
+
return EMPTY if operand.nil?
|
|
105
|
+
|
|
106
|
+
operand if operand.is_a?(Array) || operand.is_a?(Set)
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# @api private
|
|
110
|
+
# @return [Boolean] false for +nil+, +false+, and empty or whitespace-only values (a String
|
|
111
|
+
# with an invalid encoding is only checked for emptiness)
|
|
112
|
+
def self.present?(value)
|
|
113
|
+
return false if value.nil? || value == false
|
|
114
|
+
return !(value.valid_encoding? ? value.strip : value).empty? if value.is_a?(String)
|
|
115
|
+
|
|
116
|
+
!(value.respond_to?(:empty?) && value.empty?)
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
private
|
|
120
|
+
|
|
121
|
+
# An object from the item or context whose +==+ or +<=>+ raises can't be compared, so the
|
|
122
|
+
# comparison is false. Errors while reading the value or operand (from a registered source,
|
|
123
|
+
# or a context that isn't a Hash) are raised before this.
|
|
124
|
+
# Always +true+ or +false+: +eq+ would otherwise return whatever the value's +==+ returns.
|
|
125
|
+
def test(value, operand)
|
|
126
|
+
@test.call(value, operand) ? true : false
|
|
127
|
+
rescue StandardError
|
|
128
|
+
false
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# {#test}, and whether the two could be compared at all, for a reason; {#call} skips the
|
|
132
|
+
# second part. A test that raised is false and can't be compared, so a value whose +==+ or
|
|
133
|
+
# +<=>+ raises reads "can't be compared".
|
|
134
|
+
def evaluate(value, operand)
|
|
135
|
+
held = @test.call(value, operand) ? true : false
|
|
136
|
+
[held, held || Comparison.comparable?(operator, value, operand)]
|
|
137
|
+
rescue StandardError
|
|
138
|
+
[false, false]
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
end
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PriceWaterfall
|
|
4
|
+
module Conditions
|
|
5
|
+
# @api private
|
|
6
|
+
# Marks the conditions {Compiler} builds, so a step accepts one as +condition:+ while still
|
|
7
|
+
# rejecting the gem's value resolvers there (+Values::List.new([])+ would always be truthy).
|
|
8
|
+
#
|
|
9
|
+
# Each compiled condition implements +call(item, ctx)+, returning +true+ or +false+ with no
|
|
10
|
+
# extra work, and +check(item, ctx)+, returning the same result with the reason as a String.
|
|
11
|
+
# A step uses +check+ only for a note, after +call+ has skipped it.
|
|
12
|
+
module Compiled
|
|
13
|
+
include Builtin
|
|
14
|
+
|
|
15
|
+
# @param condition [#call] a condition to combine in a group or negation
|
|
16
|
+
# @return [#call] +condition+, or a plain callable wrapped so what it raises is user code
|
|
17
|
+
def self.wrap(condition) = condition.is_a?(Builtin) ? condition : UserCode::Callable.new(condition)
|
|
18
|
+
|
|
19
|
+
# @param condition [#call] a condition inside a group or negation
|
|
20
|
+
# @param item [Object]
|
|
21
|
+
# @param ctx [Object]
|
|
22
|
+
# @return [Array(Boolean, String)] the condition's {#check}, or for one without a reason (a
|
|
23
|
+
# callable, a literal), its result and a fact about it: +callable did not hold+
|
|
24
|
+
def self.check(condition, item, ctx)
|
|
25
|
+
return condition.check(item, ctx) if condition.respond_to?(:check)
|
|
26
|
+
|
|
27
|
+
held = condition.call(item, ctx) ? true : false
|
|
28
|
+
[held, "#{Reason.label(condition)} #{held ? "held" : "did not hold"}"]
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PriceWaterfall
|
|
4
|
+
module Conditions
|
|
5
|
+
# Turns a condition described in data into an object responding to +call(item, ctx)+ that
|
|
6
|
+
# returns +true+ or +false+. Every problem is reported with where it is, e.g.
|
|
7
|
+
# +condition.all[0]: unknown key "equals"+.
|
|
8
|
+
#
|
|
9
|
+
# Forms:
|
|
10
|
+
# - comparison: a value (+item:+ / +ctx:+ with optional +key:+, or +source:+) and exactly one
|
|
11
|
+
# operator from {Comparison::OPERATORS}: +{ item: "qty", gte: 10 }+
|
|
12
|
+
# - registered operator: a value and +op:+ (optional +arg:+): +{ ctx: "customer", op: "is_vip" }+
|
|
13
|
+
# - +{ all: [...] }+, +{ any: [...] }+ (non-empty lists), +{ not: {...} }+
|
|
14
|
+
#
|
|
15
|
+
# Operands may be literals or value descriptions (+{ item: "qty", gte: { ctx: "min_qty" } }+).
|
|
16
|
+
# Literal operands of ordering operators (+gt+, +gte+, +lt+, +lte+, +between+) must be numbers or
|
|
17
|
+
# Times. Strings are read as numbers (+"gte": "10"+ from a form) or, when they start like a
|
|
18
|
+
# date, as times with a zone (+"lt": "2026-01-01T00:00:00Z"+, parsed like {TimeWindow}
|
|
19
|
+
# timestamps); anything else, such as +nil+ or a Date, is rejected. Values from the item and
|
|
20
|
+
# context, and literals given as +{ value: ... }+, are never converted, so a time in the context
|
|
21
|
+
# must be a Time to compare with a time operand.
|
|
22
|
+
#
|
|
23
|
+
# Conditions nest at most {MAX_DEPTH} levels deep.
|
|
24
|
+
module Compiler
|
|
25
|
+
# Keys that combine other conditions.
|
|
26
|
+
GROUPS = %i[all any not].freeze
|
|
27
|
+
# Operators that order values; their number-looking String operands are read as numbers.
|
|
28
|
+
ORDERING = %i[gt gte lt lte between].freeze
|
|
29
|
+
# How deeply conditions may nest (+all+ / +any+ / +not+), so a hostile config can't exhaust the stack.
|
|
30
|
+
MAX_DEPTH = Resolver::MAX_DEPTH
|
|
31
|
+
# Every key a condition may have.
|
|
32
|
+
KEYS = (Resolver::VALUE_KEYS + Comparison::OPERATORS + GROUPS + %i[op arg]).freeze
|
|
33
|
+
|
|
34
|
+
module_function
|
|
35
|
+
|
|
36
|
+
# @param data [Hash] the condition, with String or Symbol keys
|
|
37
|
+
# @param at [String] where it is, for error messages
|
|
38
|
+
# @param sources [Hash{Symbol, String => #call}] registered value sources
|
|
39
|
+
# @param operators [Hash{Symbol, String => #call}] registered operators
|
|
40
|
+
# @return [#call] the compiled condition
|
|
41
|
+
# @raise [ConfigurationError] if the condition is malformed, naming where
|
|
42
|
+
# @example
|
|
43
|
+
# condition = Compiler.compile({ "item" => "qty", "gte" => 10 }, at: "condition")
|
|
44
|
+
# condition.call({ qty: 12 }, {}) # => true
|
|
45
|
+
def compile(data, at:, sources: {}, operators: {}) = compile_at(data, at, sources, operators, 0)
|
|
46
|
+
|
|
47
|
+
# @api private
|
|
48
|
+
def compile_at(data, at, sources, operators, depth)
|
|
49
|
+
raise ConfigurationError, "#{at}: must be a Hash, got #{Reason.show(data)}" unless data.is_a?(Hash)
|
|
50
|
+
raise ConfigurationError, "#{at}: conditions nest more than #{MAX_DEPTH} levels deep" if depth > MAX_DEPTH
|
|
51
|
+
|
|
52
|
+
keys = Keys.read(data, KEYS, at)
|
|
53
|
+
group = keys.keys & GROUPS
|
|
54
|
+
return compile_group(group.first, keys, at, depth + 1, sources:, operators:) unless group.empty?
|
|
55
|
+
|
|
56
|
+
compile_test(keys, at, sources:, operators:)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# @api private
|
|
60
|
+
def compile_group(group, keys, at, depth, sources:, operators:)
|
|
61
|
+
raise ConfigurationError, "#{at}: #{group} can't be combined with other keys" unless keys.size == 1
|
|
62
|
+
|
|
63
|
+
inner = keys[group]
|
|
64
|
+
return Negation.new(compile_at(inner, "#{at}.not", sources, operators, depth)) if group == :not
|
|
65
|
+
|
|
66
|
+
conditions = compile_list(inner, "#{at}.#{group}", depth, sources:, operators:)
|
|
67
|
+
(group == :all ? All : Any).new(conditions)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# @api private
|
|
71
|
+
def compile_list(list, at, depth, sources:, operators:)
|
|
72
|
+
unless list.is_a?(Array) && !list.empty?
|
|
73
|
+
raise ConfigurationError, "#{at}: must be a non-empty list of conditions, got #{Reason.show(list)}"
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
list.each_with_index.map do |condition, index|
|
|
77
|
+
compile_at(condition, "#{at}[#{index}]", sources, operators, depth)
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# @api private
|
|
82
|
+
def compile_test(keys, at, sources:, operators:)
|
|
83
|
+
operator = single_operator(keys, at)
|
|
84
|
+
value = Resolver.describe(keys.slice(*Resolver::VALUE_KEYS), sources:, at:)
|
|
85
|
+
if operator == :op
|
|
86
|
+
arg = Resolver.nested(keys[:arg], sources:, at: "#{at}.arg")
|
|
87
|
+
return Custom.new(value, keys[:op], arg, operators, at:)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
Comparison.new(value, operator, operand(operator, keys[operator], "#{at}.#{operator}", sources))
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# @api private
|
|
94
|
+
def single_operator(keys, at)
|
|
95
|
+
operators = keys.keys & (Comparison::OPERATORS + [:op])
|
|
96
|
+
unless operators.size == 1
|
|
97
|
+
raise ConfigurationError, "#{at}: needs exactly one operator (#{Comparison::OPERATORS.join(", ")} or op), " \
|
|
98
|
+
"got #{operators.empty? ? "none" : operators.join(", ")}"
|
|
99
|
+
end
|
|
100
|
+
raise ConfigurationError, "#{at}: arg only works with op" if keys.key?(:arg) && operators.first != :op
|
|
101
|
+
|
|
102
|
+
operators.first
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# @api private
|
|
106
|
+
def operand(operator, data, at, sources)
|
|
107
|
+
case operator
|
|
108
|
+
when :present, :blank
|
|
109
|
+
raise ConfigurationError, "#{at}: must be true, got #{Reason.show(data)}" unless data == true
|
|
110
|
+
|
|
111
|
+
Values::Literal.new(true)
|
|
112
|
+
when :in, :not_in then list(operator, data, at, sources, size: nil)
|
|
113
|
+
when :between then range(list(operator, data, at, sources, size: 2), data, at)
|
|
114
|
+
else entry(operator, data, at, sources)
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# @api private
|
|
119
|
+
# A list given as a value description or a callable is resolved when the condition runs.
|
|
120
|
+
def list(operator, data, at, sources, size:)
|
|
121
|
+
return Resolver.nested(data, sources:, at:) if data.is_a?(Hash) || data.respond_to?(:call)
|
|
122
|
+
|
|
123
|
+
entries = listed(data, at, size).each_with_index.map do |value, index|
|
|
124
|
+
entry(operator, value, "#{at}[#{index}]", sources)
|
|
125
|
+
end
|
|
126
|
+
return Values::List.new(entries) unless entries.all?(Values::Literal)
|
|
127
|
+
|
|
128
|
+
literal_list(entries.map(&:value), size)
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# @api private
|
|
132
|
+
# A list of literals is built once. Strings (SKUs, categories) for +in+ / +not_in+ become a
|
|
133
|
+
# Set, so matching is a lookup rather than a scan; anything else stays an Array, keeping +==+
|
|
134
|
+
# semantics (a Set would not match +10+ with +10.0+).
|
|
135
|
+
def literal_list(values, size)
|
|
136
|
+
strings = size.nil? && values.all?(String)
|
|
137
|
+
Values::Literal.new(strings ? Set.new(values).freeze : values.freeze)
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# @api private
|
|
141
|
+
# +in+ / +not_in+ take an Array or a Set; +between+ takes an Array of +size+.
|
|
142
|
+
def listed(data, at, size)
|
|
143
|
+
return data.to_a if data.is_a?(Set) && size.nil?
|
|
144
|
+
return data if data.is_a?(Array) && (size.nil? || data.size == size)
|
|
145
|
+
|
|
146
|
+
raise ConfigurationError, "#{at}: must be a list#{" of #{size} values" if size}, got #{Reason.show(data)}"
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# @api private
|
|
150
|
+
# A +between+ whose bounds are both literals must have them in order, or it could never match.
|
|
151
|
+
def range(bounds, data, at)
|
|
152
|
+
return bounds unless bounds.is_a?(Values::Literal) && bounds.value.is_a?(Array)
|
|
153
|
+
return bounds if Comparison.order(*bounds.value)&.<=(0)
|
|
154
|
+
|
|
155
|
+
raise ConfigurationError, "#{at}: must be [low, high], two numbers or two times with low <= high, " \
|
|
156
|
+
"got #{Reason.show(data)}"
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# @api private
|
|
160
|
+
# Ordering only compares numbers or Times, so a literal operand that is neither (+nil+, a
|
|
161
|
+
# list, a Date from YAML) could never match: it is a mistake in the config.
|
|
162
|
+
def entry(operator, data, at, sources)
|
|
163
|
+
literal = !data.is_a?(Hash) && !data.respond_to?(:call)
|
|
164
|
+
return Resolver.nested(data, sources:, at:) unless ORDERING.include?(operator) && literal
|
|
165
|
+
|
|
166
|
+
Values::Literal.new(ordered(data, at))
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# @api private
|
|
170
|
+
def ordered(data, at)
|
|
171
|
+
return data if data.is_a?(Time)
|
|
172
|
+
|
|
173
|
+
Timestamp.date_like?(data) ? Timestamp.parse(data) : Number.parse(data, at)
|
|
174
|
+
rescue ArgumentError, InvalidAmount
|
|
175
|
+
raise ConfigurationError, "#{at}: must be a number, a Time or #{Timestamp::FORMAT}, got #{Reason.show(data)}" \
|
|
176
|
+
"#{Timestamp.hint(data)}"
|
|
177
|
+
end
|
|
178
|
+
private_class_method :compile_at, :compile_group, :compile_list, :compile_test, :single_operator,
|
|
179
|
+
:operand, :list, :literal_list, :listed, :range, :entry, :ordered
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
end
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PriceWaterfall
|
|
4
|
+
module Conditions
|
|
5
|
+
# A test registered in Ruby and named in data: +{ ctx: "customer", op: "is_vip" }+, optionally
|
|
6
|
+
# with +arg:+. Operators are passed in as a Hash of name => callable +(value, arg)+.
|
|
7
|
+
class Custom
|
|
8
|
+
include Compiled
|
|
9
|
+
|
|
10
|
+
# @return [#call] resolver for the value being tested
|
|
11
|
+
attr_reader :value
|
|
12
|
+
# @return [Symbol] the operator's name
|
|
13
|
+
attr_reader :name
|
|
14
|
+
# @return [#call] resolver for the argument (+nil+ when none is given)
|
|
15
|
+
attr_reader :arg
|
|
16
|
+
|
|
17
|
+
# @param value [#call] resolver for the value being tested
|
|
18
|
+
# @param name [String, Symbol] name of a registered operator
|
|
19
|
+
# @param arg [#call] resolver for the argument
|
|
20
|
+
# @param operators [Hash{Symbol, String => #call}] the registered operators
|
|
21
|
+
# @param at [String] where the condition is, for error messages
|
|
22
|
+
# @raise [ConfigurationError] if +name+ is not registered, or its callable can't take +(value, arg)+
|
|
23
|
+
def initialize(value, name, arg, operators, at:)
|
|
24
|
+
@name, @operator = Registered.find(name, operators, kind: "operator", key: "op",
|
|
25
|
+
signature: [2, "(value, arg)"], at:)
|
|
26
|
+
@value = value
|
|
27
|
+
@arg = arg
|
|
28
|
+
freeze
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# @param item [Object]
|
|
32
|
+
# @param ctx [Object]
|
|
33
|
+
# @return [Boolean] whether the registered operator returned a truthy value
|
|
34
|
+
def call(item, ctx) = holds?(value.call(item, ctx), arg.call(item, ctx))
|
|
35
|
+
|
|
36
|
+
# @param item [Object]
|
|
37
|
+
# @param ctx [Object]
|
|
38
|
+
# @return [Array(Boolean, String)] the result of {#call}, and why, e.g.
|
|
39
|
+
# +ctx.customer #<Customer> is not is_vip+
|
|
40
|
+
def check(item, ctx)
|
|
41
|
+
found = value.call(item, ctx)
|
|
42
|
+
given = arg.call(item, ctx)
|
|
43
|
+
held = holds?(found, given)
|
|
44
|
+
[held, Reason.operator(value, found, name, [arg, given], held:)]
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
private
|
|
48
|
+
|
|
49
|
+
# Inside a {Run}, the operator runs once for a value and argument (see {Values::Source#call}).
|
|
50
|
+
def holds?(found, given)
|
|
51
|
+
run = Run.current
|
|
52
|
+
held = run ? run.remember(@operator, found, given) { operate(found, given) } : operate(found, given)
|
|
53
|
+
held ? true : false
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def operate(found, given) = UserCode.call(@operator, found, given)
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|