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
data/README.md
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
# PriceWaterfall
|
|
2
|
+
|
|
3
|
+
A Ruby gem for layered, explainable price calculation in integer cents. **Every price explains itself.**
|
|
4
|
+
|
|
5
|
+
Prices in B2B and e-commerce apps pass through many layers: list price, price lists,
|
|
6
|
+
customer-group discounts, volume tiers, rounding. When a line comes out wrong, nobody can
|
|
7
|
+
quickly answer *"why is this line $41.40?"*. PriceWaterfall runs those layers as an explicit,
|
|
8
|
+
ordered pipeline and returns the final price in integer cents together with a step-by-step trace.
|
|
9
|
+
|
|
10
|
+
```ruby
|
|
11
|
+
pricing = PriceWaterfall.define do
|
|
12
|
+
base { |item, _ctx| item[:list_price_cents] }
|
|
13
|
+
override :price_list, ->(item, ctx) { ctx.dig(:price_list, item[:sku]) }
|
|
14
|
+
percent :customer_tier, ->(_item, ctx) { ctx[:tier_discount] }
|
|
15
|
+
tiered :volume, { 10 => 5, 50 => 10 }, quantity: ->(item, _ctx) { item[:qty] }
|
|
16
|
+
rounding :half_up, to: 5
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
result = pricing.call({ list_price_cents: 4599, qty: 4 }, { tier_discount: 10 })
|
|
20
|
+
result.cents # => 4140
|
|
21
|
+
result.explain
|
|
22
|
+
# base 4599 base
|
|
23
|
+
# price_list 4599 no override
|
|
24
|
+
# customer_tier 4139 -460 (10%)
|
|
25
|
+
# volume 4139 skipped (qty 4 below 10)
|
|
26
|
+
# rounding 4140 half_up to 5
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Contents
|
|
30
|
+
|
|
31
|
+
- [Installation](#installation) · [Design rules](#design-rules)
|
|
32
|
+
- [Pipelines](#pipelines): define the steps in Ruby
|
|
33
|
+
- [Rules as data](#rules-as-data): load them from JSON, YAML or a database, and
|
|
34
|
+
[check them before saving](#checking-before-saving)
|
|
35
|
+
- [Results and explain](#results-and-explain): the trace, `to_h` for audit trails
|
|
36
|
+
- Reference: [Steps](#steps), [Value sources](#value-sources), [Conditions in data](#conditions-in-data),
|
|
37
|
+
[Time windows](#time-windows)
|
|
38
|
+
- [Security](#security) · [Development](#development)
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
Add it to your app's Gemfile:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
bundle add price_waterfall
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Or install it on its own, without Bundler:
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
gem install price_waterfall
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```ruby
|
|
55
|
+
require "price_waterfall"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
It has no runtime dependencies and needs Ruby 3.2 or newer (CI tests 3.2, 3.3, 3.4 and 4.0).
|
|
59
|
+
Rails is not required.
|
|
60
|
+
|
|
61
|
+
## Design rules
|
|
62
|
+
|
|
63
|
+
- Pure Ruby, no runtime dependencies; works with or without Rails.
|
|
64
|
+
- Integer cents only — no floats for money.
|
|
65
|
+
- Explicit, ordered steps; skipped steps still appear in the trace.
|
|
66
|
+
- Immutable results.
|
|
67
|
+
|
|
68
|
+
## Pipelines
|
|
69
|
+
|
|
70
|
+
`PriceWaterfall.define` builds a pipeline from a small DSL, one method per step type, in the order
|
|
71
|
+
the steps run. It checks everything once and returns a frozen `PriceWaterfall::Pipeline`, so define
|
|
72
|
+
it once (a constant is fine) and share it across threads; `call(item, ctx)` prices one item and
|
|
73
|
+
returns a [`Result`](#results-and-explain). `call(item, ctx, now: time)` prices it as of `time`
|
|
74
|
+
for [time windows](#time-windows); otherwise the clock is asked once for the whole call.
|
|
75
|
+
|
|
76
|
+
```ruby
|
|
77
|
+
pricing = PriceWaterfall.define(version: "2026-11-05") do
|
|
78
|
+
base { |item, _ctx| item[:list_price_cents] }
|
|
79
|
+
override :contract, { ctx: "contract_prices", key: { item: "sku" } }
|
|
80
|
+
percent :customer_tier, { ctx: "tier_discount" }, unless: { item: "net_price", eq: true }
|
|
81
|
+
amount :loyalty, ->(_item, ctx) { ctx[:loyalty_off_cents] }
|
|
82
|
+
tiered :volume, { 10 => 5, 50 => 10 }, quantity: { item: "qty" }
|
|
83
|
+
step(:min_margin) { |cents, item, _ctx| [[cents, item[:cost_cents]].max, "floor at cost"] }
|
|
84
|
+
rounding :half_up, to: 5
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
item = { sku: "TEE-1", list_price_cents: 4599, cost_cents: 2000, qty: 60 }
|
|
88
|
+
result = pricing.call(item, { tier_discount: 10, loyalty_off_cents: 200 })
|
|
89
|
+
result.cents # => 3545
|
|
90
|
+
result.version # => "2026-11-05"
|
|
91
|
+
pricing.names # => [:base, :contract, :customer_tier, :loyalty, :volume, :min_margin, :rounding]
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
| DSL | Step | |
|
|
95
|
+
|---|---|---|
|
|
96
|
+
| `base value` or `base { \|item, ctx\| ... }` | `Base` | named `:base` unless given a name: `base :msrp do ... end` or `name: :msrp` |
|
|
97
|
+
| `override name, value` | `Override` | |
|
|
98
|
+
| `percent name, value` / `surcharge name, value` | `Percent` / `Surcharge` | |
|
|
99
|
+
| `amount name, value` | `Amount` | caps at 0; `cap: false` raises instead |
|
|
100
|
+
| `tiered name, { tiers }, quantity: value` | `Tiered` | the tiers need braces, or Ruby reads them as keywords (so does a value description: `percent :p, { ctx: "pct" }`) |
|
|
101
|
+
| `step(name) { \|cents, item, ctx\| ... }` | `Custom` | returns `[new_cents, note]` |
|
|
102
|
+
| `rounding mode, to: n` | `Round` | named `:rounding` unless given `name:` |
|
|
103
|
+
|
|
104
|
+
- **Values** are anything a step takes: a literal, a callable `(item, ctx)`, a block, or a
|
|
105
|
+
[value description](#value-sources).
|
|
106
|
+
- **`if:` / `unless:`** take the same forms as a step's `condition:` / `skip_if:`: a callable,
|
|
107
|
+
a [data condition](#conditions-in-data), `true` or `false`. `starts_at:` and `ends_at:` limit a
|
|
108
|
+
step to a [time window](#time-windows).
|
|
109
|
+
- **`hide_values: true`** writes condition reasons without the values they read, for results you
|
|
110
|
+
store (see [Conditions in data](#conditions-in-data)).
|
|
111
|
+
- **Shared settings**: `define(sources:, operators:, clock:)` passes them to every step, so data
|
|
112
|
+
inputs and conditions can name your sources and operators. A step's own `sources:` or
|
|
113
|
+
`operators:` are added to the shared ones, replacing any with the same name; a step's own
|
|
114
|
+
`clock:` replaces the shared clock. A step's own `clock:`, `sources:` or `operators:` set to
|
|
115
|
+
`nil` keeps the shared one, so settings passed along (`clock: opts[:clock]`) can be `nil`.
|
|
116
|
+
- **A block with a parameter keeps your `self`**, so your own methods and instance variables work
|
|
117
|
+
inside it:
|
|
118
|
+
|
|
119
|
+
```ruby
|
|
120
|
+
class Pricing
|
|
121
|
+
def pipeline = PriceWaterfall.define { |p| p.base(1000) && p.percent(:promo, promo_pct) }
|
|
122
|
+
def promo_pct = 10
|
|
123
|
+
end
|
|
124
|
+
Pricing.new.pipeline.call({}).cents # => 900
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
- **Checked when defined**, as `PriceWaterfall::ConfigurationError`: the first step is a base, and
|
|
128
|
+
only the first; step names are unique; the name `:rounding` is kept for the rounding step, which
|
|
129
|
+
is last (name an earlier one: `rounding :floor, name: :pre_tax`); the shared settings; each
|
|
130
|
+
step's own checks; and each DSL call, so a forgotten value or a mistyped keyword names the step.
|
|
131
|
+
|
|
132
|
+
```ruby
|
|
133
|
+
PriceWaterfall.define { percent :promo, 10 } # raises PriceWaterfall::ConfigurationError
|
|
134
|
+
PriceWaterfall.define { base(100) && percent(:promo) } # raises PriceWaterfall::ConfigurationError
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Rules as data
|
|
138
|
+
|
|
139
|
+
Discount rules change more often than code is deployed, so a whole pipeline can also be written as
|
|
140
|
+
data and loaded at run time: a Hash with `version` and `steps`, from a JSON file, a YAML file or a
|
|
141
|
+
database column. `PriceWaterfall.load` checks it and returns the same frozen `Pipeline` as
|
|
142
|
+
`define`. Parsing is up to you; keys may be Strings or Symbols.
|
|
143
|
+
|
|
144
|
+
```ruby
|
|
145
|
+
require "json"
|
|
146
|
+
|
|
147
|
+
config = JSON.parse(<<~JSON)
|
|
148
|
+
{ "version": "2026-11-01",
|
|
149
|
+
"steps": [
|
|
150
|
+
{ "type": "base", "value": { "item": "list_price_cents" } },
|
|
151
|
+
{ "type": "percent", "name": "customer_tier", "value": { "ctx": "tier_discount" } },
|
|
152
|
+
{ "type": "percent", "name": "black_friday", "value": 20,
|
|
153
|
+
"if": { "item": "category", "in": ["apparel", "shoes"] },
|
|
154
|
+
"starts_at": "2026-11-27T00:00:00Z", "ends_at": "2026-12-01T00:00:00Z" },
|
|
155
|
+
{ "type": "tiered", "name": "volume", "tiers": { "10": 5, "50": 10 }, "quantity": { "item": "qty" } },
|
|
156
|
+
{ "type": "min_margin", "margin_cents": 100 },
|
|
157
|
+
{ "type": "rounding", "mode": "half_up", "to": 5 } ] }
|
|
158
|
+
JSON
|
|
159
|
+
|
|
160
|
+
registry = PriceWaterfall::Registry.new
|
|
161
|
+
registry.step(:min_margin) do |cents, item, _ctx, params|
|
|
162
|
+
[[cents, item[:cost_cents] + params[:margin_cents]].max, "floor at cost + #{params[:margin_cents]}"]
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
pricing = PriceWaterfall.load(config, registry:)
|
|
166
|
+
item = { list_price_cents: 4599, category: "shoes", qty: 12, cost_cents: 3100 }
|
|
167
|
+
result = pricing.call(item, { tier_discount: 10 }, now: Time.utc(2026, 11, 28))
|
|
168
|
+
result.cents # => 3200
|
|
169
|
+
result.entries[-2].note # => "floor at cost + 100"
|
|
170
|
+
result.version # => "2026-11-01"
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
| `type` | Keys besides `type` |
|
|
174
|
+
|---|---|
|
|
175
|
+
| `base` | `value`; `name` (default `base`) |
|
|
176
|
+
| `override`, `percent`, `surcharge` | `name`, `value` |
|
|
177
|
+
| `amount` | `name`, `value`; `cap` (default `true`) |
|
|
178
|
+
| `tiered` | `name`, `tiers`, `quantity` |
|
|
179
|
+
| `rounding` | `mode` (default `half_up`), `to` (default `1`); `name` (default `rounding`) |
|
|
180
|
+
| a registered step | `name` (default its type); any other keys are its `params` |
|
|
181
|
+
|
|
182
|
+
- **Every step but `base`** also takes `if`, `unless`, `starts_at` and `ends_at`, written as in
|
|
183
|
+
[conditions in data](#conditions-in-data) and [time windows](#time-windows). Values are
|
|
184
|
+
[value sources](#value-sources) or literals.
|
|
185
|
+
- **A `Registry`** holds what data may use beyond the built-ins: step types
|
|
186
|
+
(`step(name) { |cents, item, ctx, params| ... }`, returning `[new_cents, note]`), value sources
|
|
187
|
+
(`source(name) { |item, ctx| ... }`) and operators (`operator(name) { |value, arg| ... }`). A
|
|
188
|
+
custom step's other keys are its `params`, a frozen Hash with Symbol keys. Pass the registry to
|
|
189
|
+
`load` (or `define(registry:)`); there is no global one, so apps, tenants and tests can't affect
|
|
190
|
+
each other. A name that is built in or registered twice is rejected, and a registry is frozen
|
|
191
|
+
once a pipeline is built from it.
|
|
192
|
+
- **Data can't run code.** A config can only name the built-in step types and what you
|
|
193
|
+
registered in Ruby, so rules edited in an admin form can't call anything else.
|
|
194
|
+
- `load(config, registry:, clock:, hide_values:)` takes the same settings as `define`.
|
|
195
|
+
|
|
196
|
+
### Checking before saving
|
|
197
|
+
|
|
198
|
+
`PriceWaterfall.validate` checks a config without building it and lists **every** problem with
|
|
199
|
+
where it is, for an admin form that checks a change before saving it. It returns `[]` for a valid
|
|
200
|
+
config. `load` raises the first as a `ConfigurationError` (`steps[1].if.all[0]: unknown key ...`).
|
|
201
|
+
|
|
202
|
+
```ruby
|
|
203
|
+
problems = PriceWaterfall.validate(
|
|
204
|
+
{ "steps" => [{ "type" => "base", "value" => { "item" => "price" } },
|
|
205
|
+
{ "type" => "percent", "name" => "promo", "value" => 10, "if" => { "ctx" => "channel", "equals" => "b2b" } },
|
|
206
|
+
{ "type" => "percent", "name" => "vip", "vlaue" => 5 },
|
|
207
|
+
{ "type" => "percnt", "name" => "x" }] }
|
|
208
|
+
)
|
|
209
|
+
problems.map { |problem| problem[:path] } # => ["steps[1].if", "steps[2]", "steps[3].type"]
|
|
210
|
+
problems[2][:message]
|
|
211
|
+
# => "unknown step type \"percnt\" (expected one of: base, override, percent, surcharge, amount, tiered, rounding)"
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Checks cover every rule `define` applies: known types and keys (a typo such as `vlaue` is
|
|
215
|
+
caught), required keys, valid values, conditions and times, a base first and only there, unique
|
|
216
|
+
names, and the rounding step last. Each step reports its first problem. Values read from the item
|
|
217
|
+
or context are still checked when pricing, as for any pipeline.
|
|
218
|
+
|
|
219
|
+
### Storing rules and previewing changes
|
|
220
|
+
|
|
221
|
+
A typical admin flow keeps each rule set in a database row (a JSON column), checks a change
|
|
222
|
+
before saving it, and previews it on sample items before it goes live:
|
|
223
|
+
|
|
224
|
+
```ruby
|
|
225
|
+
draft = { id: 42, config: { "steps" => [{ "type" => "base", "value" => { "item" => "price" } },
|
|
226
|
+
{ "type" => "percent", "name" => "black_friday", "value" => 20,
|
|
227
|
+
"starts_at" => "2026-11-27T00:00:00Z" }] } }
|
|
228
|
+
|
|
229
|
+
# 1. Check before saving; show any problems next to the fields their paths name.
|
|
230
|
+
PriceWaterfall.validate(draft[:config]) # => []
|
|
231
|
+
|
|
232
|
+
# 2. Preview: price a sample item with the draft, as of the day the sale starts.
|
|
233
|
+
preview = PriceWaterfall.load(draft[:config].merge("version" => "rule-set-#{draft[:id]}"))
|
|
234
|
+
sample = preview.call({ price: 1000 }, {}, now: Time.utc(2026, 11, 27))
|
|
235
|
+
sample.cents # => 800
|
|
236
|
+
sample.version # => "rule-set-42"
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
- **Load once per saved version**, not on every call: keep the pipeline in a constant or a cache
|
|
240
|
+
keyed by the row and its version. A pipeline is frozen and safe to share across threads.
|
|
241
|
+
- **Stamp the version** (a row id, a date, a git sha), so every stored price can be traced back to
|
|
242
|
+
the exact rules that produced it (`result.version`).
|
|
243
|
+
|
|
244
|
+
## Results and explain
|
|
245
|
+
|
|
246
|
+
Every price comes back as a `PriceWaterfall::Result`: the final `cents`, one `Entry` per step
|
|
247
|
+
(name, price before and after, the change, the note, and whether it was skipped), and the
|
|
248
|
+
`version` of the rules that
|
|
249
|
+
produced it. A [pipeline](#pipelines) builds it for you; it can also be built from entries directly:
|
|
250
|
+
|
|
251
|
+
```ruby
|
|
252
|
+
entry = ->(step, before, after, note, skipped = false) { PriceWaterfall::Entry.new(step:, before:, after:, note:, skipped:) }
|
|
253
|
+
result = PriceWaterfall::Result.new(
|
|
254
|
+
entries: [entry.(:base, 0, 4599, "base"),
|
|
255
|
+
entry.(:customer_tier, 4599, 4139, "-460 (10%)"),
|
|
256
|
+
entry.(:volume, 4139, 4139, "skipped (condition: item.qty 4 < 10)", true),
|
|
257
|
+
entry.(:rounding, 4139, 4140, "half_up to 5")],
|
|
258
|
+
version: "2026-11-01"
|
|
259
|
+
)
|
|
260
|
+
result.cents # => 4140
|
|
261
|
+
result.entries[1].delta # => -460
|
|
262
|
+
result.entries.select(&:skipped?).map(&:step) # => [:volume]
|
|
263
|
+
result.explain.lines.first # => "base 4599 base\n"
|
|
264
|
+
result.to_h[:entries].first # => { step: :base, before: 0, after: 4599, delta: 4599, note: "base", skipped: false }
|
|
265
|
+
|
|
266
|
+
require "json"
|
|
267
|
+
stored = JSON.generate(result.to_h)
|
|
268
|
+
PriceWaterfall::Result.from_h(JSON.parse(stored)) == result # => true
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
`puts result.explain` prints one line per step, names aligned and prices right-aligned:
|
|
272
|
+
|
|
273
|
+
```text
|
|
274
|
+
base 4599 base
|
|
275
|
+
customer_tier 4139 -460 (10%)
|
|
276
|
+
volume 4139 skipped (condition: item.qty 4 < 10)
|
|
277
|
+
rounding 4140 half_up to 5
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
- **`skipped?`** says a step left the price as it was because it didn't apply: outside its time
|
|
281
|
+
window, by its condition or `skip_if`, or with nothing to apply (no value, a share that rounds to
|
|
282
|
+
0 cents, an override with no price). Each step records it, so find the promotions a line didn't
|
|
283
|
+
get with `entries.select(&:skipped?)` rather than by reading notes. A stored entry can't be
|
|
284
|
+
skipped and change the price.
|
|
285
|
+
- **`version`** is any String your app chooses (a date, a git sha, a database row id), so a stored
|
|
286
|
+
price can be traced back to the rules that made it.
|
|
287
|
+
- **`to_h`** gives `cents`, `version` and every entry as plain values, ready to store as JSON for an
|
|
288
|
+
audit trail. **`Result.from_h`** reads it back (Symbol or String keys) and checks it: `cents` must
|
|
289
|
+
match the entries and each `delta` must equal `after - before`, so a changed row is caught.
|
|
290
|
+
Step names, notes and `version` are kept in UTF-8 (converted if needed), so `to_h` can always
|
|
291
|
+
be written as JSON, and a step and its entries always share a name. Any problem with a stored
|
|
292
|
+
row raises `InvalidAmount`, naming the entry (`result.entries[3]: ...`).
|
|
293
|
+
- **`explain` is safe to print.** Notes and names are written as UTF-8 whatever their encoding, and
|
|
294
|
+
control characters, line separators and invisible format characters (text-direction controls,
|
|
295
|
+
zero-width spaces, hidden tag characters) are escaped (`\n`, `\t`, `\e`, `\u202E`, `\u200B`,
|
|
296
|
+
`\u{E0041}`), so each step stays on one line and a note can't colour, reorder or hide text in a
|
|
297
|
+
terminal or log. Backslashes are kept, so values in condition reasons read as written; a note
|
|
298
|
+
that contains the text `\n` looks like an escaped line break, but `to_h` keeps every note
|
|
299
|
+
exactly as written. The zero-width joiner and non-joiner (needed by emoji
|
|
300
|
+
and Indic scripts) and the soft hyphen are kept; flags built from tag characters (🏴 for
|
|
301
|
+
Scotland) show their tags as escapes.
|
|
302
|
+
- **Entries must follow on**: each starts at the price the previous one ended at, so a trace can't
|
|
303
|
+
be stitched together wrongly. Results and entries are frozen and compare by value.
|
|
304
|
+
|
|
305
|
+
## Steps
|
|
306
|
+
|
|
307
|
+
A pipeline is an ordered list of steps. Each step takes the running price in integer cents and
|
|
308
|
+
returns the new price and a note for the trace. [Pipelines](#pipelines) build and run them for you;
|
|
309
|
+
the step classes below are what they're made of, and can also be used on their own.
|
|
310
|
+
|
|
311
|
+
| Step | What it does | Trace notes |
|
|
312
|
+
|---|---|---|
|
|
313
|
+
| `Base` | Starting price; first in every pipeline, never conditional | `base` |
|
|
314
|
+
| `Override` | Replaces the price when its value isn't `nil` (price lists, contract prices) | `override (was 4599)`, `no override` |
|
|
315
|
+
| `Percent` | Percentage discount, 0–100 | `-460 (10%)` |
|
|
316
|
+
| `Surcharge` | Percentage increase, 0 or more | `+230 (5%)` |
|
|
317
|
+
| `Amount` | Fixed discount in cents | `-500 (fixed)` |
|
|
318
|
+
| `Tiered` | Percentage discount picked by quantity | `-350 (10% at qty >= 50)`, `skipped (qty 4 below 10)` |
|
|
319
|
+
| `Round` | Rounds to a multiple of N cents | `half_up to 5` |
|
|
320
|
+
| `Custom` | Your own logic, as a block or callable | the note you return |
|
|
321
|
+
|
|
322
|
+
Every step answers `call(cents, item, ctx)` with `[new_cents, note]`:
|
|
323
|
+
|
|
324
|
+
```ruby
|
|
325
|
+
steps = PriceWaterfall::Steps
|
|
326
|
+
|
|
327
|
+
steps::Base.new(:base, ->(item, _ctx) { item[:list_price_cents] }).call(0, { list_price_cents: 4599 }, {}) # => [4599, "base"]
|
|
328
|
+
steps::Percent.new(:customer_tier, 10).call(4599, {}, {}) # => [4139, "-460 (10%)"]
|
|
329
|
+
steps::Surcharge.new(:small_order, 5).call(4599, {}, {}) # => [4829, "+230 (5%)"]
|
|
330
|
+
steps::Amount.new(:loyalty, 500).call(4000, {}, {}) # => [3500, "-500 (fixed)"]
|
|
331
|
+
steps::Round.new(mode: :half_up, to: 5).call(4139, {}, {}) # => [4140, "half_up to 5"]
|
|
332
|
+
|
|
333
|
+
volume = steps::Tiered.new(:volume, { 10 => 5, 50 => 10 }, quantity: ->(item, _ctx) { item[:qty] })
|
|
334
|
+
volume.call(3500, { qty: 60 }, {}) # => [3150, "-350 (10% at qty >= 50)"]
|
|
335
|
+
volume.call(3500, { qty: 4 }, {}) # => [3500, "skipped (qty 4 below 10)"]
|
|
336
|
+
|
|
337
|
+
floor = steps::Custom.new(:min_margin) { |cents, item, _ctx| [[cents, item[:cost_cents]].max, "floor at cost"] }
|
|
338
|
+
floor.call(1000, { cost_cents: 1200 }, {}) # => [1200, "floor at cost"]
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
### Inputs
|
|
342
|
+
|
|
343
|
+
A step's value (the price, percentage, amount or quantity) can be:
|
|
344
|
+
|
|
345
|
+
- a literal: `Percent.new(:promo, 10)`, `"12.5"`, `Rational(1, 3)`;
|
|
346
|
+
- a callable taking `(item, ctx)`: `->(_item, ctx) { ctx[:tier_discount] }`;
|
|
347
|
+
- a value described in data, such as `{ ctx: "tier_discount" }` (see [Value sources](#value-sources)).
|
|
348
|
+
|
|
349
|
+
Literals are checked once, when the step is built. Values from callables and data are checked every
|
|
350
|
+
time the step runs. A `nil` or zero value skips the step (`skipped (no percentage)`,
|
|
351
|
+
`skipped (no amount)`), and an `Override` that gets `nil` leaves the price alone.
|
|
352
|
+
|
|
353
|
+
### Semantics
|
|
354
|
+
|
|
355
|
+
- **Integer cents in and out.** A Float, BigDecimal or String price is rejected, with a hint to
|
|
356
|
+
convert it first (`45.99 -> 4599`). "Cents" means your currency's smallest unit (cents, pence,
|
|
357
|
+
paise); for a currency without one, such as yen, use whole units.
|
|
358
|
+
- **Prices are per unit.** A pipeline prices one unit of an item; multiply by the quantity yourself
|
|
359
|
+
for a line total. `Tiered` reads a quantity only to pick its tier.
|
|
360
|
+
- **Exact percentages.** All maths uses `Rational`; a Float percentage is read through its decimal
|
|
361
|
+
form, so `12.5` is exactly 12.5%. A percentage share is rounded half up to whole cents before
|
|
362
|
+
it's applied, and a share that rounds to 0 cents is skipped (`skipped (1% rounds to 0)`).
|
|
363
|
+
- **Discounts compound** in step order: each step works on the price left by the one before.
|
|
364
|
+
- **No negative prices.** `Amount` caps the price at 0 by default
|
|
365
|
+
(`-300 (fixed 500, capped at price)`); pass `cap: false` to raise instead.
|
|
366
|
+
- **Rounding modes** are `half_up`, `bankers`, `ceiling` and `floor`, as Symbols or Strings. A
|
|
367
|
+
rounding step is named `:rounding` unless you name it, so a pipeline can round more than once:
|
|
368
|
+
`Round.new(:pre_tax, mode: :floor)`.
|
|
369
|
+
- **Steps are frozen** once built, so one definition can be shared across threads.
|
|
370
|
+
|
|
371
|
+
### Conditions
|
|
372
|
+
|
|
373
|
+
Every step except `Base` takes `condition:` (run only when true) and `skip_if:` (skip when true).
|
|
374
|
+
Each is a callable `(item, ctx)`, a condition described in data (see [Conditions in data](#conditions-in-data)),
|
|
375
|
+
`true` or `false`. Anything else, such as a mistyped `:premium?` or the String `"false"`, is
|
|
376
|
+
rejected when the step is built, so a typo can't apply a discount to everyone.
|
|
377
|
+
|
|
378
|
+
```ruby
|
|
379
|
+
promo = PriceWaterfall::Steps::Percent.new(:promo, 10, skip_if: ->(item, _ctx) { item[:net_price] })
|
|
380
|
+
promo.call(1000, { net_price: true }, {}) # => [1000, "skipped (skip_if)"]
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
### Errors
|
|
384
|
+
|
|
385
|
+
Every error is a `PriceWaterfall::Error` and names the step, in the message and in `#step`:
|
|
386
|
+
|
|
387
|
+
| Error | When |
|
|
388
|
+
|---|---|
|
|
389
|
+
| `ConfigurationError` | A step is built with something invalid: a percentage of 150, an unknown rounding mode, a callable taking the wrong arguments, a malformed condition |
|
|
390
|
+
| `InvalidAmount` | A value at run time isn't allowed: a Float price, a negative quantity, a price that would go below 0 with `cap: false`, an item or context that isn't a Hash when a data path reads it; also any unexpected error in the gem's own code |
|
|
391
|
+
| `StepError` | Your code (a callable, block, registered source or operator) raised; the original exception is its `cause`. Paths and conditions described in data are the gem's code, so they never cause a `StepError` |
|
|
392
|
+
|
|
393
|
+
```ruby
|
|
394
|
+
PriceWaterfall::Steps::Percent.new(:promo, 150) # raises PriceWaterfall::ConfigurationError
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
## Value sources
|
|
398
|
+
|
|
399
|
+
Instead of a Ruby callable, a value can be described in data, so it can live in a JSON config or
|
|
400
|
+
a database column. Keys may be Strings or Symbols.
|
|
401
|
+
|
|
402
|
+
| Description | Reads |
|
|
403
|
+
|---|---|
|
|
404
|
+
| `{ "item": "qty" }` | `item[:qty]` |
|
|
405
|
+
| `{ "ctx": "customer.group" }` | `ctx[:customer][:group]` |
|
|
406
|
+
| `{ "ctx": "price_list", "key": { "item": "sku" } }` | `ctx[:price_list][item[:sku]]` |
|
|
407
|
+
| `{ "source": "contract_price" }` | a function you registered in Ruby |
|
|
408
|
+
| `{ "value": { "min": 1, "max": 5 } }` | the value itself, as it is |
|
|
409
|
+
|
|
410
|
+
```ruby
|
|
411
|
+
price_list = PriceWaterfall::Steps::Override.new(:price_list, { "ctx" => "price_list", "key" => { "item" => "sku" } })
|
|
412
|
+
price_list.call(4599, { sku: "TEE-1" }, { price_list: { "TEE-1" => 4000 } }) # => [4000, "override (was 4599)"]
|
|
413
|
+
price_list.call(4599, { sku: "CAP-9" }, { price_list: { "TEE-1" => 4000 } }) # => [4599, "no override"]
|
|
414
|
+
|
|
415
|
+
contract = PriceWaterfall::Steps::Override.new(:contract, { source: "contract_price" },
|
|
416
|
+
sources: { contract_price: ->(item, ctx) { ctx.dig(:contracts, item[:sku]) } })
|
|
417
|
+
contract.call(4599, { sku: "TEE-1" }, { contracts: { "TEE-1" => 3900 } }) # => [3900, "override (was 4599)"]
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
- Paths only read Hashes, by key: never methods, so a config can't run code. Each segment is tried
|
|
421
|
+
as a Symbol, then as a String, exactly as written: `"qty "` with a space is rejected.
|
|
422
|
+
- **The item and context must be Hashes** (or `nil`) for data paths. Anything else, such as a
|
|
423
|
+
Struct or Rails' `ActionController::Parameters`, raises `InvalidAmount` rather than silently
|
|
424
|
+
reading `nil`: pass a Hash you build, such as `record.attributes`. Values nested inside them that aren't
|
|
425
|
+
Hashes just give `nil`.
|
|
426
|
+
- A lookup `key` is tried as it is, then in its other String / Symbol form, so `"TEE-1"`, `:TEE1`
|
|
427
|
+
and `5` find `{ TEE1: ... }`, `{ "TEE1" => ... }` and `{ "5": ... }`. A key that can't be
|
|
428
|
+
read (such as a String with broken encoding) just finds nothing. A String is never tried as a
|
|
429
|
+
number: `"123"` does not find `{ 123 => ... }`, since values are never converted.
|
|
430
|
+
- Anything missing along the path gives `nil`, which skips the step (or means "no override"). A
|
|
431
|
+
Hash's default value is never used, and a lookup `key` that is missing finds nothing. `key`
|
|
432
|
+
lookups nest at most 32 levels deep.
|
|
433
|
+
- A Hash given as a value is read as a description, so wrap a literal Hash in `value`:
|
|
434
|
+
|
|
435
|
+
```ruby
|
|
436
|
+
PriceWaterfall::Resolver.build({ "value" => { "min" => 1 } }).call({}, {}) # => { "min" => 1 }
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
- A source is a callable `(item, ctx)` passed in `sources:`. Data can only name sources you
|
|
440
|
+
registered, and an unknown name is rejected when the step is built, as is a name registered
|
|
441
|
+
twice (`"vip"` and `:vip`).
|
|
442
|
+
- **Sources and operators run once per step.** Within a step, a source runs once for the item and
|
|
443
|
+
context, and an operator once for each value and argument it is given, so writing a skipped
|
|
444
|
+
step's note doesn't call them again. The next step calls them afresh and sees any change an
|
|
445
|
+
earlier step made to the item or context. Keep them free of side effects all the same. A Ruby callable inside a description (such as a `key:` lambda) is called again to
|
|
446
|
+
write a skipped step's note; if it then gives a different answer or raises, the step still
|
|
447
|
+
skips, with the note `skipped (condition)` or `skipped (skip_if)`.
|
|
448
|
+
|
|
449
|
+
> **Build `item` and `ctx` yourself.** Data paths and conditions read whatever these Hashes
|
|
450
|
+
> contain, so never pass request params straight in (`ctx = params.to_h`): a customer could add
|
|
451
|
+
> `customer.group` or other keys a rule depends on. Copy in only the values you trust.
|
|
452
|
+
|
|
453
|
+
## Conditions in data
|
|
454
|
+
|
|
455
|
+
A condition reads a value (same forms as above) and tests it with one operator:
|
|
456
|
+
|
|
457
|
+
| Operator | Example |
|
|
458
|
+
|---|---|
|
|
459
|
+
| `eq`, `not_eq` | `{ "ctx": "channel", "eq": "wholesale" }` |
|
|
460
|
+
| `in`, `not_in` | `{ "item": "category", "in": ["apparel", "shoes"] }` |
|
|
461
|
+
| `gt`, `gte`, `lt`, `lte` | `{ "item": "qty", "gte": 10 }` |
|
|
462
|
+
| `between` (inclusive) | `{ "ctx": "order_total_cents", "between": [10000, 50000] }` |
|
|
463
|
+
| `present`, `blank` | `{ "ctx": "coupon_code", "present": true }` |
|
|
464
|
+
| `all`, `any`, `not` | `{ "any": [{ ... }, { ... }] }`, `{ "not": { ... } }` |
|
|
465
|
+
| registered operator | `{ "ctx": "customer", "op": "is_vip" }`, optionally with `"arg"` |
|
|
466
|
+
|
|
467
|
+
```ruby
|
|
468
|
+
black_friday = PriceWaterfall::Steps::Percent.new(
|
|
469
|
+
:black_friday, 20,
|
|
470
|
+
condition: { "all" => [{ "item" => "category", "in" => %w[apparel shoes] },
|
|
471
|
+
{ "ctx" => "customer.group", "not_eq" => "staff" }] }
|
|
472
|
+
)
|
|
473
|
+
black_friday.call(1000, { category: "shoes" }, { customer: { group: "retail" } }) # => [800, "-200 (20%)"]
|
|
474
|
+
black_friday.call(1000, { category: "shoes" }, { customer: { group: "staff" } })
|
|
475
|
+
# => [1000, "skipped (condition: ctx.customer.group \"staff\" == \"staff\")"]
|
|
476
|
+
black_friday.call(1000, { category: "hats" }, { customer: { group: "retail" } })
|
|
477
|
+
# => [1000, "skipped (condition: item.category \"hats\" not in [\"apparel\", \"shoes\"])"]
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
- **Skipped steps say why.** The note is always a true fact: the test that did hold
|
|
481
|
+
(`item.qty 4 < 10`), `can't be compared with` when the types don't fit
|
|
482
|
+
(`item.qty "12" can't be compared with 10`), or `item.qty is missing`. `skip_if:` says what
|
|
483
|
+
matched (`skipped (skip_if: item.net_price true is present)`). `all`, `any` and `not` pass these
|
|
484
|
+
facts on: a failed `any` lists why each branch failed, joined with "and" (the first three, then
|
|
485
|
+
a count). A Ruby callable condition can't say why, so its note is just `skipped (condition)` or
|
|
486
|
+
`skipped (skip_if)`.
|
|
487
|
+
- **Notes contain values.** Only simple values are written (Strings, numbers, Symbols, Times,
|
|
488
|
+
`true`, `false`, `nil`), cut to 40 characters. Numbers are written as decimals (`12.5`, as
|
|
489
|
+
conditions parse them) and times in ISO-8601, like the other notes; a list shows its first three entries and a count,
|
|
490
|
+
a Hash only its size, and any other object only its class (`#<User>`), never its attributes.
|
|
491
|
+
Strings such as an email address can still appear. Treat `explain` as internal. If you store
|
|
492
|
+
`to_h` (an audit trail) where customer data must not go, define the pipeline with
|
|
493
|
+
`hide_values: true`: reasons then name what was read, not its value
|
|
494
|
+
(`skipped (condition: ctx.customer.email is not staff "example.com")`,
|
|
495
|
+
`item.qty < ctx.min_qty`); values written in the rules themselves still show. This covers
|
|
496
|
+
condition reasons only: step notes keep the prices, percentages and quantities they apply
|
|
497
|
+
(`-460 (10%)`, `skipped (qty 4 below 10)`), as they are the trace itself.
|
|
498
|
+
|
|
499
|
+
- **No type guessing.** Values are compared as they are: `"10"` is not `10`, and a comparison that
|
|
500
|
+
can't be made (`nil >= 10`, `"12" >= 10`, or an object whose `==` raises) is false, never an
|
|
501
|
+
error.
|
|
502
|
+
- **Ordering compares numbers or Times only.** `gt`, `gte`, `lt`, `lte` and `between` never order
|
|
503
|
+
Strings, so `"9"` is not greater than `"10"`. A literal operand of these operators must be a
|
|
504
|
+
number or a `Time`. A String is read as a number (`"gte": "10"` from a form) or, when it starts
|
|
505
|
+
like a date, as a time with a zone (`"lt": "2026-01-01T00:00:00Z"`, same rules as
|
|
506
|
+
[time windows](#time-windows)). Anything else (`"gte": "ten"`, `nil`, or a `Date`, which YAML
|
|
507
|
+
gives for `2026-01-01`) is rejected when the step is built. The value it is compared with must then be a
|
|
508
|
+
number or a `Time`; a String time in the context is never converted. `eq` keeps Strings as they
|
|
509
|
+
are, so `"eq": "10"` does not match `10` even though `"gte": "10"` and `"lte": "10"` together do.
|
|
510
|
+
- **`between` bounds must be in order** (`[low, high]`) when both are written in the config.
|
|
511
|
+
- **`in` / `not_in` take an Array or a Set**, written in the config or read from the context. A
|
|
512
|
+
missing list counts as empty, so `not_in` a missing
|
|
513
|
+
exclusion list is true, the same as `not` with `in`.
|
|
514
|
+
- **Operands can be values too:** `{ "item": "qty", "gte": { "ctx": "min_qty" } }`.
|
|
515
|
+
- **Registered operators** are callables `(value, arg)` passed in `operators:`, such as
|
|
516
|
+
`{ is_vip: ->(customer, _arg) { customer[:vip] } }`.
|
|
517
|
+
- **Conditions nest at most 32 levels deep** (`all`, `any`, `not`).
|
|
518
|
+
- **Mistakes are caught when the step is built**, with where they are:
|
|
519
|
+
|
|
520
|
+
```ruby
|
|
521
|
+
PriceWaterfall::Steps::Percent.new(:promo, 10, condition: { all: [{ ctx: "channel", equals: "b2b" }] })
|
|
522
|
+
# raises PriceWaterfall::ConfigurationError
|
|
523
|
+
# step :promo: condition.all[0]: unknown key "equals" (expected one of: item, ctx, key, source, eq, ...)
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
## Time windows
|
|
527
|
+
|
|
528
|
+
Any step except `Base` can be limited in time with `starts_at:` (inclusive) and `ends_at:`
|
|
529
|
+
(exclusive), as a `Time` or an ISO-8601 String **with a zone** (`Z`, `+05:30`, `+0530` or `+05`), so
|
|
530
|
+
"midnight" means the same moment on every server. A date alone (`"2026-11-27"`), a `DateTime` or
|
|
531
|
+
a date that doesn't exist (`"2026-02-30T00:00:00Z"`) is rejected. Outside the window the step is skipped:
|
|
532
|
+
|
|
533
|
+
```ruby
|
|
534
|
+
sale = PriceWaterfall::Steps::Percent.new(:black_friday, 20,
|
|
535
|
+
starts_at: "2026-11-27T00:00:00Z", ends_at: "2026-12-01T00:00:00Z")
|
|
536
|
+
sale.call(1000, {}, {}, now: Time.utc(2026, 11, 28)) # => [800, "-200 (20%)"]
|
|
537
|
+
sale.call(1000, {}, {}, now: Time.utc(2026, 11, 1)) # => [1000, "skipped (not active: starts 2026-11-27T00:00:00Z)"]
|
|
538
|
+
sale.call(1000, {}, {}, now: Time.utc(2026, 12, 1)) # => [1000, "skipped (expired 2026-12-01T00:00:00Z)"]
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
"Now" is the `now:` given to the call (`pricing.call(item, ctx, now:)` for a
|
|
542
|
+
[pipeline](#pipelines)), so a preview or a test can price "as of" any moment. It must be a `Time`:
|
|
543
|
+
a String raises `InvalidAmount`. The context is never read for "now", so a customer can't move
|
|
544
|
+
the clock through request data; parse it yourself for a preview
|
|
545
|
+
(`now: Time.iso8601(params[:as_of])`, after checking the user may preview).
|
|
546
|
+
Otherwise it comes from `clock:` (a callable with no arguments), which defaults to `Time.now`.
|
|
547
|
+
`clock:` is checked even on a step without a window.
|
|
548
|
+
|
|
549
|
+
**One moment per call.** A pipeline reads "now" once for the whole call: every step sees the
|
|
550
|
+
moment given, or else each clock is asked once. Two promotions that end at midnight can't see
|
|
551
|
+
different sides of it, so a quote never gets half a bundle.
|
|
552
|
+
|
|
553
|
+
## Security
|
|
554
|
+
|
|
555
|
+
PriceWaterfall prices with whatever you give it, so a few rules keep customers from changing
|
|
556
|
+
their own prices:
|
|
557
|
+
|
|
558
|
+
- **Build `item` and `ctx` yourself.** Never pass request params straight in: data paths and
|
|
559
|
+
conditions read whatever keys these Hashes hold. Copy in only values you trust. Data paths read
|
|
560
|
+
Hashes only, by key, never methods ([value sources](#value-sources)).
|
|
561
|
+
- **Rules as data can't run code.** A config can name only the built-in step types and what you
|
|
562
|
+
registered in Ruby ([rules as data](#rules-as-data)); there is no `eval`, `send` or method call
|
|
563
|
+
by name. Validate a config before saving it.
|
|
564
|
+
- **The clock is an argument.** "Now" comes only from `now:` or your `clock:`, never from the
|
|
565
|
+
context, so request data can't move a sale's dates ([time windows](#time-windows)).
|
|
566
|
+
- **Huge numbers are rejected early.** Numbers parsed from BigDecimals or Strings may have at most
|
|
567
|
+
1000 digits, so a value in request data can't hold up pricing.
|
|
568
|
+
- **Traces can hold values.** Condition reasons show the values they read; use
|
|
569
|
+
`hide_values: true` when storing results where customer data must not go
|
|
570
|
+
([conditions in data](#conditions-in-data)). `explain` escapes control and invisible characters,
|
|
571
|
+
so a note can't hide or reorder text in a terminal or log.
|
|
572
|
+
- **Errors are typed.** Every error is a `PriceWaterfall::Error` naming the step; your own code's
|
|
573
|
+
exceptions are wrapped in `StepError` with the original as `cause` ([errors](#errors)).
|
|
574
|
+
|
|
575
|
+
## Development
|
|
576
|
+
|
|
577
|
+
After checking out the repo, run `bin/setup` to install dependencies, then `bundle exec rake`
|
|
578
|
+
to run the specs and RuboCop. `bin/console` gives an interactive prompt.
|
|
579
|
+
|
|
580
|
+
## License
|
|
581
|
+
|
|
582
|
+
Available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module PriceWaterfall
|
|
4
|
+
class Builder
|
|
5
|
+
# @api private
|
|
6
|
+
# Checks of the DSL's arguments, so a mistake in a call raises a {ConfigurationError} naming
|
|
7
|
+
# the step, with a hint where Ruby read a Hash argument as keywords.
|
|
8
|
+
module Arguments
|
|
9
|
+
# Said when +tiered+ gets no tiers but keywords it doesn't take: tiers written without braces.
|
|
10
|
+
TIERS_HINT = "write the tiers in braces, such as tiered :volume, { 10 => 5 }, quantity: ..."
|
|
11
|
+
# The value description keys, as Strings, for {#braces_hint}.
|
|
12
|
+
VALUE_KEY_NAMES = Resolver::VALUE_KEYS.map(&:to_s).freeze
|
|
13
|
+
|
|
14
|
+
private
|
|
15
|
+
|
|
16
|
+
# +base+'s arguments with the name first, whether it came first or as +name:+.
|
|
17
|
+
def base_args(args, name)
|
|
18
|
+
return [name || :base, *args] unless args.first.is_a?(Symbol)
|
|
19
|
+
return args unless name
|
|
20
|
+
|
|
21
|
+
raise ConfigurationError.new("step #{args.first.inspect}: give the name once, as base #{args.first.inspect} " \
|
|
22
|
+
"or name: #{args.first.inspect}", step: args.first)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# The name, checked here so every message can show it.
|
|
26
|
+
def step_name!(method, args)
|
|
27
|
+
raise ConfigurationError, "#{method} needs a step name first" if args.empty?
|
|
28
|
+
|
|
29
|
+
StepName.check!(args.first, ConfigurationError, "step name")
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def one_input(method, name, values, block, options)
|
|
33
|
+
return block if values.empty? && block
|
|
34
|
+
return values.first if values.size == 1 && block.nil?
|
|
35
|
+
|
|
36
|
+
problem = if values.empty? then "needs a value or a block#{braces_hint(method, name, options)}"
|
|
37
|
+
elsif block then "takes a value or a block, not both"
|
|
38
|
+
else "takes one value, got #{values.size}#{name_hint(method, values)}"
|
|
39
|
+
end
|
|
40
|
+
raise ConfigurationError.new("step #{name.inspect}: #{problem}", step: name)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# A value description written without braces arrives as keywords (+percent :p, ctx: "pct"+).
|
|
44
|
+
# Keys are matched as Strings too (+percent :p, "ctx" => "pct"+), and shown as they were written.
|
|
45
|
+
def braces_hint(method, name, options)
|
|
46
|
+
key = options.keys.find { |given| VALUE_KEY_NAMES.include?(given.to_s) }
|
|
47
|
+
return "" unless key
|
|
48
|
+
|
|
49
|
+
entry = key.is_a?(Symbol) ? "#{key}: ..." : "#{key.inspect} => ..."
|
|
50
|
+
example = if method.to_s == "base" && name == :base then "base({ #{entry} })"
|
|
51
|
+
else "#{method} #{name.inspect}, { #{entry} }"
|
|
52
|
+
end
|
|
53
|
+
"; write the value description in braces, such as #{example}"
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# +base "msrp", 4599+: only a Symbol is taken as a name, since a String could be a value.
|
|
57
|
+
def name_hint(method, values)
|
|
58
|
+
return "" unless method.to_s == "base" && values.first.is_a?(String)
|
|
59
|
+
|
|
60
|
+
"; a name given first must be a Symbol (base :msrp, ...)"
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def no_block!(method, name, block)
|
|
64
|
+
raise ConfigurationError.new("step #{name.inspect}: #{method} doesn't take a block", step: name) if block
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def check_options!(name, options)
|
|
68
|
+
problem = options_problem(options)
|
|
69
|
+
raise ConfigurationError.new("step #{name.inspect}: #{problem}", step: name) if problem
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def options_problem(options)
|
|
73
|
+
loose = options.keys.grep_v(Symbol)
|
|
74
|
+
unless loose.empty?
|
|
75
|
+
return "#{loose.map { |key| Conditions::Reason.show(key) }.join(", ")} can't be an option name; " \
|
|
76
|
+
"option names are Symbols, and a Hash argument needs braces"
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
RENAMED.each do |dsl, keyword|
|
|
80
|
+
return "use #{dsl}: or #{keyword}:, not both" if options.key?(dsl) && options.key?(keyword)
|
|
81
|
+
end
|
|
82
|
+
nil
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|