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,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ module Values
5
+ # Reads a value from the item or the context by a dotted path, as described in data:
6
+ # +{ item: "qty" }+, +{ ctx: "customer.group" }+, or with a lookup key,
7
+ # +{ ctx: "price_list", key: { item: "sku" } }+ for +ctx[:price_list][item[:sku]]+.
8
+ #
9
+ # Only Hashes are read, by key, never by calling methods, so a config can't run code. Each
10
+ # path segment is tried as a Symbol, then as a String; a lookup key is tried as it is, then in
11
+ # its other String / Symbol form (an Integer key as both). Anything missing, or a value that
12
+ # isn't a Hash along the way, gives +nil+, which steps treat as "skip" / "no override". A
13
+ # Hash's default value is never used, and a lookup key that resolves to +nil+ finds nothing.
14
+ #
15
+ # The item or context itself must be a Hash (or +nil+, meaning no data): anything else, such as
16
+ # a Struct or Rails' +ActionController::Parameters+, is a caller mistake and raises
17
+ # {InvalidAmount} instead of silently reading +nil+.
18
+ class Path
19
+ include Builtin
20
+
21
+ # @return [Symbol] +:item+ or +:ctx+
22
+ attr_reader :root
23
+ # @return [Array<String>] the path's segments
24
+ attr_reader :segments
25
+ # @return [#call, nil] resolver for the lookup key, if any
26
+ attr_reader :key
27
+
28
+ # @param root [Symbol] +:item+ or +:ctx+
29
+ # @param path [String, Symbol] dotted path such as "customer.group"
30
+ # @param key [#call, nil] resolver for a final lookup key
31
+ # @param at [String] where the description is, for error messages
32
+ # @raise [ConfigurationError] if +path+ is not a String or Symbol made of non-blank segments
33
+ def initialize(root, path, key: nil, at: "value")
34
+ @root = root
35
+ @segments = parse(path, at)
36
+ @lookups = segments.map { |segment| [segment.to_sym, segment].freeze }.freeze
37
+ @key = key
38
+ freeze
39
+ end
40
+
41
+ # @param item [Object]
42
+ # @param ctx [Object]
43
+ # @return [Object, nil] the value at the path, or +nil+ if anything along it (or the lookup key)
44
+ # is missing
45
+ # @raise [InvalidAmount] if the item or context is neither a Hash nor +nil+
46
+ def call(item, ctx)
47
+ value = @lookups.reduce(root!(root == :item ? item : ctx)) { |data, names| read(data, names) }
48
+ return value unless key
49
+
50
+ lookup = key.call(item, ctx)
51
+ lookup.nil? ? nil : read(value, Path.names_for(lookup))
52
+ end
53
+
54
+ # @return [String] how a trace names this path: +item.qty+, +ctx.price_list[item.sku]+
55
+ def label
56
+ text = "#{root}.#{segments.join(".")}"
57
+ key ? "#{text}[#{Conditions::Reason.label(key)}]" : text
58
+ end
59
+
60
+ # @api private
61
+ # @return [Array] the keys a lookup key is tried as: itself, then its other String / Symbol
62
+ # forms. A String with an invalid encoding can't be a Symbol, so it is only tried as it is.
63
+ def self.names_for(lookup)
64
+ case lookup
65
+ when String then lookup.valid_encoding? ? [lookup, lookup.to_sym] : [lookup]
66
+ when Symbol then [lookup, lookup.name]
67
+ when Integer then [lookup, lookup.to_s, lookup.to_s.to_sym]
68
+ else [lookup]
69
+ end
70
+ end
71
+
72
+ private
73
+
74
+ def root!(data)
75
+ return data if data.nil? || data.is_a?(Hash)
76
+
77
+ raise InvalidAmount, "#{root} must be a Hash to read #{segments.join(".").inspect}, got #{data.class} " \
78
+ "(pass a Hash you build, e.g. record.attributes)"
79
+ end
80
+
81
+ # Only keys the Hash has are read, so its default value or default proc never comes into play.
82
+ def read(data, names)
83
+ return nil unless data.is_a?(Hash)
84
+
85
+ found = names.find { |name| data.key?(name) }
86
+ found.nil? ? nil : data[found]
87
+ end
88
+
89
+ # A segment is matched exactly, so one with spaces around it could never be found.
90
+ def segment?(segment) = !segment.strip.empty? && segment.strip == segment
91
+
92
+ def split(path)
93
+ text = path.is_a?(Symbol) ? path.name : path
94
+ text.is_a?(String) && text.valid_encoding? ? text.split(".", -1) : []
95
+ end
96
+
97
+ def parse(path, at)
98
+ segments = split(path)
99
+ return segments.map(&:freeze).freeze if !segments.empty? && segments.all? { |s| segment?(s) }
100
+
101
+ raise ConfigurationError, "#{at}: #{root} path must be a dotted String such as \"customer.group\", " \
102
+ "without blank segments or spaces around them, got #{Conditions::Reason.show(path)}"
103
+ end
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ module Values
5
+ # A value from a function registered in Ruby and named in data: +{ source: "contract_price" }+.
6
+ # Sources are passed in as a Hash of name => callable +(item, ctx)+, so data can only use
7
+ # functions the app chose to expose.
8
+ class Source
9
+ include Builtin
10
+
11
+ # @return [Symbol] the source's name
12
+ attr_reader :name
13
+ # @return [#call] the registered callable +(item, ctx)+
14
+ attr_reader :callable
15
+
16
+ # @param name [String, Symbol] name of a registered source
17
+ # @param sources [Hash{Symbol, String => #call}] the registered sources
18
+ # @param at [String] where the description is, for error messages
19
+ # @raise [ConfigurationError] if +name+ is not registered (see {Registered.find}), or its callable
20
+ # can't take +(item, ctx)+
21
+ def initialize(name, sources, at: "value")
22
+ @name, @callable = Registered.find(name, sources, kind: "source", key: "source",
23
+ signature: [2, "(item, ctx)"], at:)
24
+ freeze
25
+ end
26
+
27
+ # Inside a {Run}, the callable runs once for an item and context; later calls in the run get
28
+ # the same result.
29
+ #
30
+ # @param item [Object]
31
+ # @param ctx [Object]
32
+ # @return [Object] whatever the registered callable returns
33
+ def call(item, ctx)
34
+ run = Run.current
35
+ return UserCode.call(callable, item, ctx) unless run
36
+
37
+ run.remember(callable, item, ctx) { UserCode.call(callable, item, ctx) }
38
+ end
39
+
40
+ # @return [String] how a trace names this source: +source contract_price+
41
+ def label = "source #{name}"
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PriceWaterfall
4
+ # Gem version, following semantic versioning.
5
+ VERSION = "0.1.0"
6
+ end
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "price_waterfall/version"
4
+ require_relative "price_waterfall/error"
5
+ require_relative "price_waterfall/configuration_error"
6
+ require_relative "price_waterfall/invalid_amount"
7
+ require_relative "price_waterfall/step_error"
8
+ require_relative "price_waterfall/rounding"
9
+ require_relative "price_waterfall/number"
10
+ require_relative "price_waterfall/percentage"
11
+ require_relative "price_waterfall/keys"
12
+ require_relative "price_waterfall/step_name"
13
+ require_relative "price_waterfall/user_code"
14
+ require_relative "price_waterfall/run"
15
+ require_relative "price_waterfall/registered"
16
+ require_relative "price_waterfall/timestamp"
17
+ require_relative "price_waterfall/values/literal"
18
+ require_relative "price_waterfall/values/path"
19
+ require_relative "price_waterfall/values/source"
20
+ require_relative "price_waterfall/values/list"
21
+ require_relative "price_waterfall/resolver"
22
+ require_relative "price_waterfall/conditions/reason"
23
+ require_relative "price_waterfall/conditions/compiled"
24
+ require_relative "price_waterfall/conditions/comparison"
25
+ require_relative "price_waterfall/conditions/group"
26
+ require_relative "price_waterfall/conditions/all"
27
+ require_relative "price_waterfall/conditions/any"
28
+ require_relative "price_waterfall/conditions/negation"
29
+ require_relative "price_waterfall/conditions/custom"
30
+ require_relative "price_waterfall/conditions/compiler"
31
+ require_relative "price_waterfall/time_window"
32
+ require_relative "price_waterfall/steps/cents"
33
+ require_relative "price_waterfall/steps/skipping"
34
+ require_relative "price_waterfall/steps/step"
35
+ require_relative "price_waterfall/steps/callable"
36
+ require_relative "price_waterfall/steps/base"
37
+ require_relative "price_waterfall/steps/override"
38
+ require_relative "price_waterfall/steps/percentage_change"
39
+ require_relative "price_waterfall/steps/percent"
40
+ require_relative "price_waterfall/steps/surcharge"
41
+ require_relative "price_waterfall/steps/amount"
42
+ require_relative "price_waterfall/steps/custom"
43
+ require_relative "price_waterfall/steps/tiered"
44
+ require_relative "price_waterfall/steps/round"
45
+ require_relative "price_waterfall/entry"
46
+ require_relative "price_waterfall/result"
47
+ require_relative "price_waterfall/pipeline"
48
+ require_relative "price_waterfall/builder/arguments"
49
+ require_relative "price_waterfall/builder"
50
+ require_relative "price_waterfall/registry"
51
+ require_relative "price_waterfall/loader"
52
+ require_relative "price_waterfall/loader/problems"
53
+ require_relative "price_waterfall/loader/step_entry"
54
+ require_relative "price_waterfall/loader/order"
55
+
56
+ # Layered, explainable price calculation in integer cents.
57
+ #
58
+ # Pure Ruby with no runtime dependencies. Every result carries the final price and a
59
+ # step-by-step trace of how it was reached.
60
+ module PriceWaterfall
61
+ # Defines a pipeline with the {Builder} DSL.
62
+ #
63
+ # @param version [String, nil] the rule set's version, copied into every {Result}
64
+ # @param sources [Hash{Symbol, String => #call}] value sources that data inputs may name
65
+ # @param operators [Hash{Symbol, String => #call}] operators that data conditions may name
66
+ # @param clock [#call, nil] clock for time-limited steps; defaults to +Time.now+
67
+ # @param hide_values [Boolean] write condition reasons without the values read; see {Pipeline#initialize}
68
+ # @param registry [Registry, nil] adds its sources and operators to +sources:+ and +operators:+,
69
+ # and is frozen
70
+ # @yieldparam builder [Builder] when the block takes any parameters (+|p|+, +|*a|+), keeping the
71
+ # caller's +self+; a block with none runs with the builder as +self+. A block with parameters
72
+ # must take the builder positionally.
73
+ # @return [Pipeline] frozen
74
+ # @raise [ConfigurationError] if a step, a shared setting or the pipeline is invalid, no block
75
+ # is given, the block has parameters but can't take the builder as its first, or a lambda is
76
+ # given that can't take the builder as its one argument
77
+ # @example
78
+ # pricing = PriceWaterfall.define do
79
+ # base { |item, _ctx| item[:list_price_cents] }
80
+ # percent :promo, 10, unless: { item: "net_price", eq: true }
81
+ # rounding :half_up, to: 5
82
+ # end
83
+ # pricing.call({ list_price_cents: 4599 }).cents # => 4140
84
+ def self.define(version: nil, sources: {}, operators: {}, clock: nil, hide_values: false, registry: nil, &block)
85
+ Builder.check_block!(block)
86
+ builder = Builder.new(**Builder.with_registry(Registry.check!(registry)&.freeze, sources:, operators:), clock:)
87
+ block.parameters.empty? ? builder.instance_eval(&block) : yield(builder)
88
+ Pipeline.new(builder.steps, version:, hide_values:)
89
+ end
90
+
91
+ # Builds a pipeline from rules written as data, so they can live in a JSON file, a YAML file or a
92
+ # database column and change without a deploy. Parsing is up to you: +load+ takes a Hash.
93
+ #
94
+ # @param config [Hash] +version+ (optional) and +steps+, a list of step entries such as
95
+ # +{ "type": "percent", "name": "promo", "value": 10, "if": { ... } }+; keys may be Strings
96
+ # or Symbols
97
+ # @param registry [Registry, nil] custom step types, sources and operators the config may name;
98
+ # frozen once loaded
99
+ # @param clock [#call, nil] clock for time-limited steps; defaults to +Time.now+
100
+ # @param hide_values [Boolean] see {Pipeline#initialize}
101
+ # @return [Pipeline] frozen
102
+ # @raise [ConfigurationError] naming the first problem and where it is:
103
+ # +steps[3].if.all[0]: unknown key "equals" (expected one of: ...)+
104
+ # @example
105
+ # pricing = PriceWaterfall.load(JSON.parse(File.read("pricing.json")))
106
+ def self.load(config, registry: nil, clock: nil, hide_values: false)
107
+ TimeWindow.check_clock!(clock)
108
+ Registry.check!(registry)&.freeze
109
+ Loader.new(config, registry:, clock:).pipeline(hide_values:)
110
+ end
111
+
112
+ # Checks rules written as data without building them, for an admin form that checks a change
113
+ # before saving it.
114
+ #
115
+ # @param config [Hash] as for {.load}
116
+ # @param registry [Registry, nil] as for {.load}; not frozen
117
+ # @return [Array<Hash{Symbol => String}>] every problem as +{ path:, message: }+, in order; empty
118
+ # when the config is valid
119
+ # @example
120
+ # PriceWaterfall.validate({ steps: [{ type: "percent", name: "promo", value: 150 }] })
121
+ # # => [{ path: "steps[0]", message: "percentage must be between 0 and 100, got 150" },
122
+ # # { path: "steps[0]", message: "the first step must be a base" }]
123
+ def self.validate(config, registry: nil)
124
+ Loader.new(config, registry: Registry.check!(registry)).problems.map(&:to_h)
125
+ end
126
+ end
metadata ADDED
@@ -0,0 +1,103 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: price_waterfall
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Pratik Baravkar
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Define a pricing waterfall (base price, overrides, percentage and fixed
13
+ discounts, volume tiers, rounding) with a small DSL. Every result returns the final
14
+ price in integer cents plus a step-by-step trace explaining how it was reached.
15
+ Pure Ruby, no runtime dependencies, works with or without Rails.
16
+ email:
17
+ - baravkarpratik5@gmail.com
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - CHANGELOG.md
23
+ - LICENSE.txt
24
+ - README.md
25
+ - lib/price_waterfall.rb
26
+ - lib/price_waterfall/builder.rb
27
+ - lib/price_waterfall/builder/arguments.rb
28
+ - lib/price_waterfall/conditions/all.rb
29
+ - lib/price_waterfall/conditions/any.rb
30
+ - lib/price_waterfall/conditions/comparison.rb
31
+ - lib/price_waterfall/conditions/compiled.rb
32
+ - lib/price_waterfall/conditions/compiler.rb
33
+ - lib/price_waterfall/conditions/custom.rb
34
+ - lib/price_waterfall/conditions/group.rb
35
+ - lib/price_waterfall/conditions/negation.rb
36
+ - lib/price_waterfall/conditions/reason.rb
37
+ - lib/price_waterfall/configuration_error.rb
38
+ - lib/price_waterfall/entry.rb
39
+ - lib/price_waterfall/error.rb
40
+ - lib/price_waterfall/invalid_amount.rb
41
+ - lib/price_waterfall/keys.rb
42
+ - lib/price_waterfall/loader.rb
43
+ - lib/price_waterfall/loader/order.rb
44
+ - lib/price_waterfall/loader/problems.rb
45
+ - lib/price_waterfall/loader/step_entry.rb
46
+ - lib/price_waterfall/number.rb
47
+ - lib/price_waterfall/percentage.rb
48
+ - lib/price_waterfall/pipeline.rb
49
+ - lib/price_waterfall/registered.rb
50
+ - lib/price_waterfall/registry.rb
51
+ - lib/price_waterfall/resolver.rb
52
+ - lib/price_waterfall/result.rb
53
+ - lib/price_waterfall/rounding.rb
54
+ - lib/price_waterfall/run.rb
55
+ - lib/price_waterfall/step_error.rb
56
+ - lib/price_waterfall/step_name.rb
57
+ - lib/price_waterfall/steps/amount.rb
58
+ - lib/price_waterfall/steps/base.rb
59
+ - lib/price_waterfall/steps/callable.rb
60
+ - lib/price_waterfall/steps/cents.rb
61
+ - lib/price_waterfall/steps/custom.rb
62
+ - lib/price_waterfall/steps/override.rb
63
+ - lib/price_waterfall/steps/percent.rb
64
+ - lib/price_waterfall/steps/percentage_change.rb
65
+ - lib/price_waterfall/steps/round.rb
66
+ - lib/price_waterfall/steps/skipping.rb
67
+ - lib/price_waterfall/steps/step.rb
68
+ - lib/price_waterfall/steps/surcharge.rb
69
+ - lib/price_waterfall/steps/tiered.rb
70
+ - lib/price_waterfall/time_window.rb
71
+ - lib/price_waterfall/timestamp.rb
72
+ - lib/price_waterfall/user_code.rb
73
+ - lib/price_waterfall/values/list.rb
74
+ - lib/price_waterfall/values/literal.rb
75
+ - lib/price_waterfall/values/path.rb
76
+ - lib/price_waterfall/values/source.rb
77
+ - lib/price_waterfall/version.rb
78
+ homepage: https://github.com/PratikBaravkar/price_waterfall
79
+ licenses:
80
+ - MIT
81
+ metadata:
82
+ source_code_uri: https://github.com/PratikBaravkar/price_waterfall
83
+ changelog_uri: https://github.com/PratikBaravkar/price_waterfall/blob/main/CHANGELOG.md
84
+ bug_tracker_uri: https://github.com/PratikBaravkar/price_waterfall/issues
85
+ rubygems_mfa_required: 'true'
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: 3.2.0
94
+ required_rubygems_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ requirements: []
100
+ rubygems_version: 3.6.9
101
+ specification_version: 4
102
+ summary: Ruby gem for layered, explainable price calculation in integer cents.
103
+ test_files: []