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
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 87a787eab8d9a632f44dd4564c07af18d01debcbdc359ac0a9e9db4c0441aba3
4
+ data.tar.gz: 52932f5e2835586763498e74487231d993faf39ffe021b5298a207466c1759f1
5
+ SHA512:
6
+ metadata.gz: cb13943e4571fa6c50355c1e75167a684dd4c830c4152f9772590b319aab2b9ecc80bcaaa7a3f24f5b8f3cacf8871bc5d88d27ded107fa543be9e1989ac1a35d
7
+ data.tar.gz: 4a48e143aca0fbe66c2159840084baa092c853af01c6a7de4fb5797f4cee15edcc5ea732286fceca22a82690cbcf04086ef82ef9a360fa6a008d9c3f028b56d8
data/CHANGELOG.md ADDED
@@ -0,0 +1,186 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-12-01
4
+
5
+ First release.
6
+
7
+ ### Added
8
+
9
+ - Error classes: `PriceWaterfall::Error` (base), `ConfigurationError`, `InvalidAmount` and
10
+ `StepError` (keeps the original exception as `#cause`). Every error raised by or inside a step
11
+ carries the step's name in `#step`.
12
+ - `PriceWaterfall::Rounding.apply` / `.validate!` (returns the normalized mode): exact Rational rounding to a multiple
13
+ of N cents with `half_up`, `bankers`, `ceiling` and `floor` modes. Rejects Float, String, nil and
14
+ BigDecimal amounts with `InvalidAmount`.
15
+ - `PriceWaterfall::Rounding` accepts String mode names (`"half_up"`) as well as Symbols, matching
16
+ the known names only; `Rounding.normalize_mode` does the lookup. `Rounding.rounder` checks a
17
+ configuration once and returns a frozen `Rounding::Rounder` (`mode`, `to`, `#call`); a `Rounder`
18
+ validates however it is built (`new`, `with`).
19
+ - Step classes under `PriceWaterfall::Steps`: `Base`, `Override`, `Percent`, `Surcharge`, `Amount`,
20
+ `Tiered`, `Round` and `Custom` (callable or block). Each returns the new price and a trace note
21
+ (`-460 (10%)`, `skipped (qty 4 below 10)`, `half_up to 5`), supports `condition:` / `skip_if:`,
22
+ is frozen on creation, checks the price going in and coming out, and names itself in every error.
23
+ Any exception raised by user code, including the gem's own errors, is wrapped in `StepError`.
24
+ `Round` is named `:rounding` unless given a name (`Round.new(:pre_tax, mode: :floor)`), so a
25
+ pipeline can round more than once; a name that is also a mode (`Round.new(:floor)`) needs an
26
+ explicit `mode:`. `Base` can't be conditional. `Step`, `Callable` and `PercentageChange` are
27
+ abstract and can't be built. Trace notes are frozen.
28
+ - Errors are handled at two boundaries: anything going wrong while a step is built comes out as
29
+ `ConfigurationError`, and while it runs as `InvalidAmount` (or `StepError` for user code), always
30
+ with the step's name. Arguments that don't fit a step (an unknown or missing keyword) raise
31
+ `ConfigurationError` naming the step. Step names must not be blank. Tier minimums are parsed like
32
+ quantities (`"+10"`, `10.0` work). A percentage change that rounds
33
+ to 0 cents is recorded as skipped.
34
+ `Tiered` accepts integer String and Symbol minimums (`"10"`, `:"10"`) as parsed JSON and YAML
35
+ give them, and quantities may be numeric Strings (`"12"`); negative quantities are rejected.
36
+ - `condition:` / `skip_if:` accept only a callable `(item, ctx)`, `true` or `false`, so a typo such
37
+ as `condition: :premium?` or `"false"` fails at build time instead of applying to everyone.
38
+ - Percentages for `Percent` and `Tiered` must be in `0..100`; `Surcharge` allows any
39
+ non-negative percentage.
40
+ - Steps take a Ruby callable `(item, ctx)` or a literal value. Literals are checked and converted
41
+ once when the step is built, and callables must accept `(item, ctx)`, checked against their
42
+ required and optional parameters (`ConfigurationError`);
43
+ values from callables are checked when the step runs (`InvalidAmount`, with a conversion hint for
44
+ Float / BigDecimal / String prices).
45
+ - `Amount` caps the price at 0 when the discount is larger than the price; `cap: false` raises
46
+ `InvalidAmount` instead. A capped discount on a price of 0 is skipped.
47
+ - `PriceWaterfall::Number`: exact parsing of Integer, Rational, Float (via its decimal form),
48
+ BigDecimal and numeric Strings, shared by percentages and quantities.
49
+ - `PriceWaterfall::Percentage`: percentage parsing on top of `Number`, half-up share of a price, and trace formatting (long decimals
50
+ are rounded to 6 places and marked with `~`).
51
+ - `PriceWaterfall::Resolver` (with `.check_arity!`) and `PriceWaterfall::Values::Literal`.
52
+ - Values described in data, with String or Symbol keys: `{ item: "qty" }`,
53
+ `{ ctx: "customer.group" }`, `{ ctx: "price_list", key: { item: "sku" } }` (`Values::Path`, reads
54
+ Hashes only, by keys they have, never their default value; the item or context itself must be a
55
+ Hash or `nil`, otherwise `InvalidAmount`; lookup keys are also tried in their other String /
56
+ Symbol form, including Integers) and `{ source: "name" }` for a
57
+ callable registered in `sources:` (`Values::Source`). `{ value: ... }` passes a literal, including
58
+ a Hash. Accepted anywhere a step takes a value; unknown keys are rejected.
59
+ - `PriceWaterfall::Registered`: one lookup for registered sources and operators; names must be
60
+ Strings (with a valid encoding) or Symbols, and a name registered as both a String and a Symbol is rejected. `Base`
61
+ rejects `operators:` and `clock:` as well as conditions and time windows. Path
62
+ segments with spaces around them are rejected.
63
+ - Conditions described in data for `condition:` / `skip_if:` (`Conditions::Compiler`): `eq`,
64
+ `not_eq`, `in`, `not_in`, `gt`, `gte`, `lt`, `lte`, `between`, `present`, `blank`, `all`, `any`,
65
+ `not`, and operators registered in `operators:` (`op:` / `arg:`). Values are compared without type
66
+ conversion; impossible comparisons are false. Ordering compares only numbers or Times, and a
67
+ literal ordering operand must be a number or a `Time` (Strings are read as numbers or zoned
68
+ ISO-8601 times; `nil` and `Date` are rejected); literal `between` bounds must be in order;
69
+ `in` / `not_in` take an Array or a Set, and a missing list is empty; `between` needs exactly two
70
+ bounds; a literal list is built once (a frozen Set for Strings, otherwise a frozen Array), and a
71
+ list may also be a value description or a callable. Conditions and `key:` lookups
72
+ nest at most 32 levels deep. Built-in conditions never raise for odd input (a comparison that
73
+ raises is false). Errors from registered sources and operators, and from Ruby callables inside
74
+ descriptions, are `StepError` (the original exception when called outside a step), while the
75
+ gem's own code reports `InvalidAmount`. `condition:` rejects the gem's value resolvers but
76
+ accepts compiled conditions. Errors name where they are
77
+ (`condition.all[0]: unknown key "equals"`), including for callable conditions.
78
+ - Time windows: `starts_at:` / `ends_at:` on every step except `Base` (`TimeWindow`), ISO-8601 with
79
+ a time and a zone (`Z`, `+05:30`, `+0530` or `+05`) or `Time` (`PriceWaterfall::Timestamp`); any other value, such as `false`, and dates that
80
+ don't exist (`2026-02-30`) are rejected. "Now" is the `now:` argument of the call, which must be a
81
+ `Time` (a String raises), otherwise `clock:` (default `Time.now`, checked
82
+ even without a window). Skip notes
83
+ `skipped (not active: starts ...)` / `skipped (expired ...)`.
84
+ - README sections for steps, value sources, conditions in data and time windows; every README
85
+ example is run by the spec suite.
86
+ - `PriceWaterfall::Entry` (one step of a trace: `step`, `before`, `after`, `delta`, `note`) and
87
+ `PriceWaterfall::Result` (`cents`, frozen `entries`, `version`, `explain`, `to_h`). Both are
88
+ frozen, validated (whole non-negative cents; entries must follow on from each other; `version`
89
+ is a String or nil) and compare by value. `explain` writes one line per step with names aligned
90
+ and prices right-aligned; `to_h` is ready to store as JSON.
91
+ - Skipped data conditions say why in the note, always as a true fact:
92
+ `skipped (condition: item.qty 4 < 10)`,
93
+ `skipped (condition: item.qty "12" can't be compared with 10)`, `item.qty is missing`,
94
+ `skipped (skip_if: item.net_price true is present)`. `not` passes its inner fact through; a
95
+ failed `any` joins its branches' facts with "and", capped at three plus a count. A missing
96
+ operand is named (`ctx.min_qty is missing`), and every side when more than one is
97
+ missing (`item.coupon and ctx.used are missing`, `item.qty and ctx.lo are missing`). Numbers are
98
+ written as decimals (`item.qty 4 < 12.5`, not `(25/2)`), and times, including an object that
99
+ says it is a Time (`ActiveSupport::TimeWithZone`), in ISO-8601 like time window notes. `all`
100
+ and `any` need at least one condition however they are built. The reason is worked out only on the skip path; if
101
+ it disagrees with the decision (a changing source), fails, or the condition is a callable, the
102
+ note is just `skipped (condition)` or `skipped (skip_if)`, so writing a note never stops pricing. Values are shortened
103
+ (each list entry on its own, so the count of the rest always shows), nested lists are written
104
+ as `[...]`, Hashes show only their size, objects other than simple values show only their class
105
+ (`#<User>`), and anything that can't be written safely is `#<unprintable>`. `explain` escapes
106
+ control characters, line separators and every invisible format character (bidirectional
107
+ controls, zero-width spaces, tag characters such as `\u{E0041}`) except the zero-width joiner,
108
+ non-joiner and soft hyphen, in notes and names (backslashes are kept, so values in condition
109
+ reasons aren't escaped twice). It converts both to
110
+ UTF-8 first, so mixed encodings, or one Ruby can't convert, can't make it raise. Numbers of
111
+ more than 36 digits are written approximately, in the same form whatever their type
112
+ (`BigDecimal("1e1000000")` in item data as `~1e1000000`, `10**50` as `~1.0e+50`, a negative
113
+ one as `~-1e300000`), in condition reasons and `Tiered` notes alike, so a huge value can't
114
+ make a note slow and a long one isn't cut short.
115
+ - `Entry.new` accepts the `delta` that `to_h` writes and checks it; `Entry.from_h` and
116
+ `Result.from_h` read stored results back (Symbol or String keys), keeping step names, notes and `version` in UTF-8 so `to_h` can
117
+ always be written as JSON, and checking `cents` and each `delta` (Integers)
118
+ against the entries. Every problem with a stored row, including a bad `version`, raises
119
+ `InvalidAmount` naming the entry (`result.entries[3]: ...`). Errors about results, entries,
120
+ step names, prices and data keys shorten the values they show, as notes do. A missing value or
121
+ argument of a registered operator, or a missing bound of `between`, is named
122
+ (`ctx.lo is missing`). `Group#conditions` and `Negation#condition` return the conditions as given.
123
+ - Step names (in steps and entries) follow one rule, so a step and its entries share a name:
124
+ they are converted to UTF-8 (binary text is read as UTF-8 bytes; a name that can't be
125
+ converted is rejected) and then must not contain control characters such as line breaks, or be only whitespace, Unicode included
126
+ (`PriceWaterfall::StepName`). `all`, `any` and `not` accept plain callable children, run as
127
+ user code. Conditions return real booleans.
128
+ - Numbers parsed from a BigDecimal or a numeric String (percentages, `Tiered` quantities and
129
+ minimums, numbers in data conditions) may have at most 1000 digits, counted as the number is
130
+ written out in decimal (`1e999` and `1e-1000` have 1000; signs, spaces and the decimal point
131
+ don't count, while a String's leading zeros do); a longer one is rejected with `InvalidAmount` before it is converted, so a huge
132
+ value in request data (`BigDecimal("1e100000000")`) can't hold up pricing. A String that is not
133
+ a number is written in short in the error.
134
+ - `PriceWaterfall.define` and `PriceWaterfall::Pipeline`: a DSL with one method per step type
135
+ (`base`, `override`, `percent`, `surcharge`, `amount`, `tiered`, `step`, `rounding`), `if:` /
136
+ `unless:` for conditions, and shared `sources:`, `operators:` and `clock:` for every step,
137
+ checked once even if no step uses them; a step's own `sources:` / `operators:` are added to the
138
+ shared ones, and a step's own `clock:`, `sources:` or `operators:` set to `nil` keeps the
139
+ shared one. `base :msrp do ... end` names the base. A block with any parameters keeps the
140
+ caller's `self`. Every mistake in a DSL call (a missing value, an unknown keyword, tiers or a
141
+ value description without braces, a wrong number of arguments, a rounding mode given twice, a
142
+ block given to `tiered` or `rounding`, a define block that can't take the builder as its first parameter) raises `ConfigurationError`
143
+ naming the step, with a hint where Ruby read a Hash argument as keywords. The
144
+ pipeline is checked when defined (a base first and only there, unique step names, the name
145
+ `:rounding` kept for the rounding step, which must be last), frozen, and
146
+ `call(item, ctx)` returns a `Result` with its `version`. `Pipeline.new(steps, version:)` builds
147
+ one from steps directly.
148
+ - Error messages write the values they show as trace notes do (`Reason.show`): briefly, a Hash
149
+ by its size, other objects by class, numbers as decimals (`got 100.5`, not `got (201/2)`), so a
150
+ large or personal value in a config or in request data isn't written out in full. A value or
151
+ condition that names none, or several, of `item`, `ctx`, `source` and `value` lists the ones it
152
+ found (`got item, ctx`, `got none`). An unknown or missing keyword names the step as it would
153
+ be built, in UTF-8, so `error.step` matches the step's name. A number too big for a Float is
154
+ written as the power of ten nearest it, the same for a BigDecimal as for an Integer or Rational.
155
+ - "Now" is an argument: `pipeline.call(item, ctx, now:)` and `step.call(cents, item, ctx, now:)`.
156
+ The context is no longer read for it, so request data can't move the clock. A pipeline call
157
+ reads "now" once (the argument, or each clock asked once), so every step sees the same moment
158
+ and two promotions ending at midnight agree on which side of it a quote is.
159
+ - Registered sources and operators run once per step for the same inputs (compared by identity),
160
+ so a skipped step's note doesn't call them again; the next step calls them afresh, so it sees a
161
+ change an earlier step made to the item or context. A Ruby callable inside a description is
162
+ still called again for a note.
163
+ - `define(hide_values: true)` / `Pipeline.new(steps, hide_values: true)` writes condition reasons
164
+ without the values read (`item.qty < ctx.min_qty`), for stored results that must not hold
165
+ customer data; values written in the rules still show, and step notes keep the prices,
166
+ percentages and quantities they apply. A step called with its own `now:` inside a pipeline
167
+ keeps the setting. A list operand is named by its entries (`[ctx.lo, 9]`).
168
+ - `Entry#skipped?` (stored by `to_h` as `skipped`, `false` when a stored row has none): whether
169
+ the step left the price as it was because it didn't apply, by its time window, condition or
170
+ `skip_if`, or with nothing to apply (no value, a share that rounds to 0 cents, an override with
171
+ no price). Recorded by the step, so callers don't read notes to find skipped steps. An entry
172
+ can't be skipped and change the price.
173
+ - Rules as data: `PriceWaterfall.load(config, registry:, clock:, hide_values:)` builds a frozen
174
+ `Pipeline` from a Hash with `version` and `steps` (from JSON, YAML or a database; String or
175
+ Symbol keys). Each step entry names a built-in `type` (`base`, `override`, `percent`,
176
+ `surcharge`, `amount`, `tiered`, `rounding`) or a registered one, and goes through the same
177
+ `Builder` methods as the DSL, so both apply the same checks and give the same results.
178
+ - `PriceWaterfall.validate(config, registry:)` lists every problem as `{ path:, message: }`
179
+ (`steps[3].if.all[0]`, `steps[2].type`), empty when the config is valid; `load` raises the first
180
+ as a `ConfigurationError` naming its path and step. It checks the config's shape, known types and
181
+ keys, required keys, each step as `define` would, and the order (a base first and only there,
182
+ unique names, the rounding step last), each with the path of the step at fault.
183
+ - `PriceWaterfall::Registry`: custom step types (`step(name) { |cents, item, ctx, params| ... }`,
184
+ the entry's other keys passed as frozen `params`), value sources and operators, registered by
185
+ name for data to use. Names that are built in or registered twice are rejected; a registry is
186
+ frozen once a pipeline is built from it. `define(registry:)` adds its sources and operators.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Pratik Baravkar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.