acts_as_calculator 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/.rspec +3 -0
- data/.rubocop.yml +38 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +133 -0
- data/Rakefile +12 -0
- data/app/controllers/acts_as_calculator/application_controller.rb +76 -0
- data/app/controllers/acts_as_calculator/formula_versions_controller.rb +50 -0
- data/app/controllers/acts_as_calculator/formulas_controller.rb +58 -0
- data/app/controllers/acts_as_calculator/imports_controller.rb +33 -0
- data/app/controllers/acts_as_calculator/templates_controller.rb +66 -0
- data/app/models/acts_as_calculator/formula.rb +21 -0
- data/app/models/acts_as_calculator/formula_version.rb +88 -0
- data/app/models/acts_as_calculator/lookup_table.rb +25 -0
- data/app/models/acts_as_calculator/lookup_table_entry.rb +26 -0
- data/app/models/acts_as_calculator/record.rb +12 -0
- data/app/models/acts_as_calculator/run.rb +24 -0
- data/app/models/acts_as_calculator/template.rb +56 -0
- data/app/models/acts_as_calculator/variable.rb +20 -0
- data/config/routes.rb +36 -0
- data/lib/acts_as_calculator/aggregate_results.rb +57 -0
- data/lib/acts_as_calculator/aggregation.rb +9 -0
- data/lib/acts_as_calculator/apportion_amount.rb +62 -0
- data/lib/acts_as_calculator/apportionment.rb +57 -0
- data/lib/acts_as_calculator/build_calculator.rb +24 -0
- data/lib/acts_as_calculator/build_lookups.rb +37 -0
- data/lib/acts_as_calculator/calculable.rb +84 -0
- data/lib/acts_as_calculator/calculator_cache.rb +36 -0
- data/lib/acts_as_calculator/cast_date.rb +16 -0
- data/lib/acts_as_calculator/cast_decimal.rb +15 -0
- data/lib/acts_as_calculator/cast_json_safe.rb +37 -0
- data/lib/acts_as_calculator/cast_liquid_value.rb +58 -0
- data/lib/acts_as_calculator/cast_variable_attributes.rb +17 -0
- data/lib/acts_as_calculator/configuration.rb +31 -0
- data/lib/acts_as_calculator/distribute_remainder.rb +49 -0
- data/lib/acts_as_calculator/divide_proportionally.rb +27 -0
- data/lib/acts_as_calculator/engine.rb +19 -0
- data/lib/acts_as_calculator/errors.rb +23 -0
- data/lib/acts_as_calculator/evaluate_expression.rb +49 -0
- data/lib/acts_as_calculator/evaluate_formula.rb +53 -0
- data/lib/acts_as_calculator/find_lookup_table_references.rb +68 -0
- data/lib/acts_as_calculator/find_owned_record.rb +38 -0
- data/lib/acts_as_calculator/find_tier.rb +25 -0
- data/lib/acts_as_calculator/formula_version_drop.rb +55 -0
- data/lib/acts_as_calculator/function_registry.rb +83 -0
- data/lib/acts_as_calculator/import_definitions.rb +70 -0
- data/lib/acts_as_calculator/import_formula.rb +102 -0
- data/lib/acts_as_calculator/import_lookup_table.rb +94 -0
- data/lib/acts_as_calculator/import_outcome.rb +20 -0
- data/lib/acts_as_calculator/import_summary.rb +29 -0
- data/lib/acts_as_calculator/import_template.rb +57 -0
- data/lib/acts_as_calculator/liquid_filters.rb +70 -0
- data/lib/acts_as_calculator/persist_run.rb +31 -0
- data/lib/acts_as_calculator/promote_template.rb +21 -0
- data/lib/acts_as_calculator/publish_formula_version.rb +54 -0
- data/lib/acts_as_calculator/publish_template.rb +18 -0
- data/lib/acts_as_calculator/read_import_file.rb +23 -0
- data/lib/acts_as_calculator/render_liquid.rb +113 -0
- data/lib/acts_as_calculator/render_template.rb +43 -0
- data/lib/acts_as_calculator/resolve_formula_version.rb +57 -0
- data/lib/acts_as_calculator/resolve_import_owner.rb +38 -0
- data/lib/acts_as_calculator/resolve_template.rb +41 -0
- data/lib/acts_as_calculator/resolve_variables.rb +105 -0
- data/lib/acts_as_calculator/result.rb +32 -0
- data/lib/acts_as_calculator/result_drop.rb +46 -0
- data/lib/acts_as_calculator/serialize_formula.rb +18 -0
- data/lib/acts_as_calculator/serialize_formula_version.rb +26 -0
- data/lib/acts_as_calculator/serialize_import_summary.rb +21 -0
- data/lib/acts_as_calculator/serialize_template.rb +13 -0
- data/lib/acts_as_calculator/supersede_formula_versions.rb +83 -0
- data/lib/acts_as_calculator/tier.rb +31 -0
- data/lib/acts_as_calculator/variable_spec.rb +33 -0
- data/lib/acts_as_calculator/version.rb +5 -0
- data/lib/acts_as_calculator.rb +78 -0
- data/lib/generators/acts_as_calculator/import/import_generator.rb +26 -0
- data/lib/generators/acts_as_calculator/install/install_generator.rb +31 -0
- data/lib/generators/acts_as_calculator/install/templates/create_acts_as_calculator_tables.rb.tt +133 -0
- data/lib/tasks/acts_as_calculator.rake +21 -0
- data/sig/acts_as_calculator.rbs +4 -0
- metadata +251 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 3c4c2ae76d289d7d038706eaace2037b440d0043375970acbe19e10df2aef610
|
|
4
|
+
data.tar.gz: 5785e9931c5bee714ab33c56c1d3f6fb1f7e2fbf866e5bb2534a59c49d0fe678
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: f3758535be10ef2eb3cbc481232a5450be2ff2223ad0ea89eb0c7eca34ca09a4673fbe16a77df16fcc04fdab031aa8022a3f5bec8a6e3c503d455cd4cd7dc8a6
|
|
7
|
+
data.tar.gz: 62e82cdda250fc79160066529fcedbecb5e49d6032a3731a48e958131197bcdcdb0fbf7ab96227d3a0de64d29abe55cf877247023d7c73ff95fb9c432a2b6a39
|
data/.rspec
ADDED
data/.rubocop.yml
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
AllCops:
|
|
2
|
+
TargetRubyVersion: 3.2
|
|
3
|
+
NewCops: disable
|
|
4
|
+
SuggestExtensions: false
|
|
5
|
+
|
|
6
|
+
# Decrees are invoked as `DoSomething.(...)` at call sites but delegate with an explicit
|
|
7
|
+
# `new(...).call` — see the decree-service-objects skill. Neither style is wrong here.
|
|
8
|
+
Style/LambdaCall:
|
|
9
|
+
Enabled: false
|
|
10
|
+
|
|
11
|
+
# Decrees take keyword arguments by design (docs/PLAN.md, "Code guidelines"), and a
|
|
12
|
+
# keyword argument costs a reader nothing at the call site — counting them would turn the
|
|
13
|
+
# gem's mandated style into an offence. Positional parameters are still capped.
|
|
14
|
+
Metrics/ParameterLists:
|
|
15
|
+
CountKeywordArgs: false
|
|
16
|
+
|
|
17
|
+
Metrics/BlockLength:
|
|
18
|
+
inherit_mode:
|
|
19
|
+
merge:
|
|
20
|
+
- Exclude
|
|
21
|
+
Exclude:
|
|
22
|
+
- "spec/**/*"
|
|
23
|
+
|
|
24
|
+
Naming/VariableNumber:
|
|
25
|
+
inherit_mode:
|
|
26
|
+
merge:
|
|
27
|
+
- Exclude
|
|
28
|
+
Exclude:
|
|
29
|
+
- "spec/**/*"
|
|
30
|
+
|
|
31
|
+
Style/StringLiterals:
|
|
32
|
+
EnforcedStyle: double_quotes
|
|
33
|
+
|
|
34
|
+
Style/StringLiteralsInInterpolation:
|
|
35
|
+
EnforcedStyle: double_quotes
|
|
36
|
+
|
|
37
|
+
Style/Documentation:
|
|
38
|
+
Enabled: false
|
data/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
|
2
|
+
|
|
3
|
+
## Our Pledge
|
|
4
|
+
|
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
|
10
|
+
identity and orientation.
|
|
11
|
+
|
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
|
13
|
+
diverse, inclusive, and healthy community.
|
|
14
|
+
|
|
15
|
+
## Our Standards
|
|
16
|
+
|
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
|
18
|
+
community include:
|
|
19
|
+
|
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
|
24
|
+
and learning from the experience
|
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
|
26
|
+
community
|
|
27
|
+
|
|
28
|
+
Examples of unacceptable behavior include:
|
|
29
|
+
|
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
|
31
|
+
any kind
|
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
|
33
|
+
* Public or private harassment
|
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
|
35
|
+
without their explicit permission
|
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
|
37
|
+
professional setting
|
|
38
|
+
|
|
39
|
+
## Enforcement Responsibilities
|
|
40
|
+
|
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
|
44
|
+
or harmful.
|
|
45
|
+
|
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
|
49
|
+
decisions when appropriate.
|
|
50
|
+
|
|
51
|
+
## Scope
|
|
52
|
+
|
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
|
54
|
+
an individual is officially representing the community in public spaces.
|
|
55
|
+
Examples of representing our community include using an official email address,
|
|
56
|
+
posting via an official social media account, or acting as an appointed
|
|
57
|
+
representative at an online or offline event.
|
|
58
|
+
|
|
59
|
+
## Enforcement
|
|
60
|
+
|
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
|
62
|
+
reported to the community leaders responsible for enforcement at
|
|
63
|
+
[INSERT CONTACT METHOD].
|
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
|
65
|
+
|
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
|
67
|
+
reporter of any incident.
|
|
68
|
+
|
|
69
|
+
## Enforcement Guidelines
|
|
70
|
+
|
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
|
73
|
+
|
|
74
|
+
### 1. Correction
|
|
75
|
+
|
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
|
77
|
+
unprofessional or unwelcome in the community.
|
|
78
|
+
|
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
|
82
|
+
|
|
83
|
+
### 2. Warning
|
|
84
|
+
|
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
|
86
|
+
actions.
|
|
87
|
+
|
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
|
93
|
+
ban.
|
|
94
|
+
|
|
95
|
+
### 3. Temporary Ban
|
|
96
|
+
|
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
|
98
|
+
sustained inappropriate behavior.
|
|
99
|
+
|
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
|
101
|
+
communication with the community for a specified period of time. No public or
|
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
|
104
|
+
Violating these terms may lead to a permanent ban.
|
|
105
|
+
|
|
106
|
+
### 4. Permanent Ban
|
|
107
|
+
|
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
|
111
|
+
|
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
|
113
|
+
community.
|
|
114
|
+
|
|
115
|
+
## Attribution
|
|
116
|
+
|
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
|
118
|
+
version 2.1, available at
|
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
|
120
|
+
|
|
121
|
+
Community Impact Guidelines were inspired by
|
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
|
123
|
+
|
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
|
127
|
+
|
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 lautarograc
|
|
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.
|
data/README.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# ActsAsCalculator
|
|
2
|
+
|
|
3
|
+
A pricing and calculation engine built on [Dentaku](https://github.com/rubysolo/dentaku). Mix `Calculable` into any model to get effective-dated, versioned formulas; apportionment and aggregation helpers; and Liquid-rendered output — reusable across payroll, e-commerce, and insurance domains.
|
|
4
|
+
|
|
5
|
+
This gem is under active development. See the [architecture plan](https://claude.ai/code/artifact/b02e27b6-eb9c-4b8d-8037-ef69f177c282) for the full design: data model, calculation flow, extensibility points, and build order.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
Not yet released to RubyGems. Once published:
|
|
10
|
+
|
|
11
|
+
$ bundle add acts_as_calculator
|
|
12
|
+
|
|
13
|
+
## JSON import
|
|
14
|
+
|
|
15
|
+
Formulas, lookup tables and templates can be authored as JSON and imported either once
|
|
16
|
+
through a generator or repeatedly from a deploy script:
|
|
17
|
+
|
|
18
|
+
$ rails generate acts_as_calculator:import config/calculator/payroll.json
|
|
19
|
+
$ rake acts_as_calculator:import[config/calculator/payroll.json]
|
|
20
|
+
|
|
21
|
+
Both run the same code and print the same created/updated/skipped/failed summary; the rake
|
|
22
|
+
task exits non-zero if any entry failed. One file may declare any of the three sections.
|
|
23
|
+
|
|
24
|
+
```json
|
|
25
|
+
{
|
|
26
|
+
"lookup_tables": [
|
|
27
|
+
{ "key": "federal_2026", "scope": "payroll",
|
|
28
|
+
"entries": [{ "from": 0, "to": 20000, "value": 0.1 },
|
|
29
|
+
{ "from": 20000, "to": null, "value": 0.25 }] }
|
|
30
|
+
],
|
|
31
|
+
"formulas": [
|
|
32
|
+
{ "key": "net_pay", "scope": "payroll",
|
|
33
|
+
"expression": "salary - (salary * federal_2026)",
|
|
34
|
+
"effective_from": "2026-01-01", "effective_to": null,
|
|
35
|
+
"status": "active", "change_note": "2026 rates",
|
|
36
|
+
"variables": [
|
|
37
|
+
{ "name": "salary", "source_type": "attribute" },
|
|
38
|
+
{ "name": "federal_2026", "source_type": "lookup",
|
|
39
|
+
"source_config": { "table": "federal_2026", "using": "salary" } }
|
|
40
|
+
] }
|
|
41
|
+
],
|
|
42
|
+
"templates": [
|
|
43
|
+
{ "key": "payslip", "scope": "payroll", "format": "text",
|
|
44
|
+
"body": "Net: {{ result.value | currency }}" }
|
|
45
|
+
]
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`scope` defaults to `"default"`, a formula's `status` to `"active"`, a template's `format`
|
|
50
|
+
to `"html"`, and a variable's `source_type` to `"context"` and `required` to `true`. Any
|
|
51
|
+
entry may carry `"owner": { "type": "Company", "id": 7 }` to import into a tenant-scoped
|
|
52
|
+
row instead of the global one.
|
|
53
|
+
|
|
54
|
+
Importing is idempotent, keyed on `[key, scope, owner]`:
|
|
55
|
+
|
|
56
|
+
- **Formulas** — re-importing unchanged content is a no-op. Changed content adds a *new*
|
|
57
|
+
version; existing versions are never edited. Publishing an active version closes out or
|
|
58
|
+
retires the one it supersedes, but never rewrites its expression — and it is refused
|
|
59
|
+
outright if superseding would leave part of the incumbent's range with no active version,
|
|
60
|
+
rather than silently deleting coverage a past calculation relied on. Extend the new
|
|
61
|
+
version's `effective_to`, or declare the version taking over the tail earlier in the file.
|
|
62
|
+
- **Lookup tables** — unchanged entries are a no-op, and changed entries are replaced in
|
|
63
|
+
place *only* if no active or retired formula version resolves to that table. If one does,
|
|
64
|
+
the import fails that entry rather than retroactively changing what an audited
|
|
65
|
+
calculation was measured against; author a new table key and a new formula version
|
|
66
|
+
pointing at it.
|
|
67
|
+
- **Templates** — unchanged body and format are a no-op; a change publishes a new version
|
|
68
|
+
and demotes the previous one, which stays in the history for rollback.
|
|
69
|
+
|
|
70
|
+
## The API
|
|
71
|
+
|
|
72
|
+
The gem ships a mountable REST/JSON API that is **off by default** — not guarded, off. The
|
|
73
|
+
routes are behind a routing constraint, so with `enable_api` false they do not match at
|
|
74
|
+
all: requests 404 because there is no such path, not because a controller declined.
|
|
75
|
+
|
|
76
|
+
```ruby
|
|
77
|
+
# config/initializers/acts_as_calculator.rb
|
|
78
|
+
ActsAsCalculator.configure { |c| c.enable_api = true }
|
|
79
|
+
|
|
80
|
+
# config/routes.rb
|
|
81
|
+
mount ActsAsCalculator::Engine => "/calculator"
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The gem implements **no authentication or authorization** and never will — wrap the mount
|
|
85
|
+
point in whatever your app already uses.
|
|
86
|
+
|
|
87
|
+
| Method | Path | What it does |
|
|
88
|
+
|---|---|---|
|
|
89
|
+
| `GET` | `/formulas` | Identity only (`key`, `scope`, `owner`); filter with `?key=&scope=` |
|
|
90
|
+
| `POST` | `/formulas` | Creates a formula identity |
|
|
91
|
+
| `GET` | `/formulas/:id` | The formula plus its version history |
|
|
92
|
+
| `PATCH` | `/formulas/:id` | Updates only the identity attributes that were sent — including `owner`, unguarded; re-owning a formula silently re-targets every future `#calculate` resolution for that key, it isn't a rename-only endpoint |
|
|
93
|
+
| `DELETE` | `/formulas/:id` | 409s instead of deleting a formula whose versions have runs |
|
|
94
|
+
| `GET` | `/formulas/:id/versions` | Versions in version order |
|
|
95
|
+
| `GET` | `/formulas/:id/versions/:id` | One version with its declared variables |
|
|
96
|
+
| `POST` | `/formulas/:id/versions` | Publishes a version and its variables |
|
|
97
|
+
| `GET` | `/templates` | Every version; `?current=true` narrows to the published one |
|
|
98
|
+
| `POST` | `/templates` | Publishes a new version and demotes the outgoing one |
|
|
99
|
+
| `GET`/`DELETE` | `/templates/:id` | |
|
|
100
|
+
| `POST` | `/templates/:id/preview` | Renders against a posted `context` → `{ body:, format: }` |
|
|
101
|
+
| `POST` | `/templates/:id/promote` | Rollback — points `current` at this version |
|
|
102
|
+
| `POST` | `/import` | The JSON import document above, over HTTP |
|
|
103
|
+
|
|
104
|
+
Writes go through the same Decrees the other authoring paths use, so the API is not a way
|
|
105
|
+
around the rules: publishing a version supersedes the one in force rather than overlapping
|
|
106
|
+
it, and a supersede that would leave part of the incumbent's range with no active version
|
|
107
|
+
comes back as `409 Conflict` rather than silently creating a gap. `POST /import` is
|
|
108
|
+
`ImportDefinitions` handed the parsed body — same idempotency, same lookup-table guard, and
|
|
109
|
+
the same per-entry created/updated/skipped/failed summary the rake task prints, as JSON.
|
|
110
|
+
|
|
111
|
+
Errors are `{ "error": { "type": ..., "message": ..., "details": {...} } }`: 422 on
|
|
112
|
+
validation failure (with the model's own messages), 404 on a record or template that isn't
|
|
113
|
+
there, 409 on a conflict with existing state, 400 on a malformed request body.
|
|
114
|
+
|
|
115
|
+
Lookup tables have no CRUD endpoints of their own. `docs/PLAN.md` names formulas, versions
|
|
116
|
+
and templates as the API's surface, and lookup tables are already authorable over HTTP
|
|
117
|
+
through `POST /import` — which is also the only path that enforces the guard against
|
|
118
|
+
editing a table an audited formula version resolves to.
|
|
119
|
+
|
|
120
|
+
## Development
|
|
121
|
+
|
|
122
|
+
$ bin/setup
|
|
123
|
+
$ rake spec
|
|
124
|
+
|
|
125
|
+
`bin/console` gives an interactive prompt for experimenting.
|
|
126
|
+
|
|
127
|
+
## Contributing
|
|
128
|
+
|
|
129
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/lautarograc/acts_as_calculator. This project follows the [code of conduct](https://github.com/lautarograc/acts_as_calculator/blob/main/CODE_OF_CONDUCT.md).
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
Available as open source under the [MIT License](https://opensource.org/licenses/MIT).
|
data/Rakefile
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActsAsCalculator
|
|
4
|
+
# There is deliberately no authentication or authorization here, and no `before_action`
|
|
5
|
+
# stub inviting one (docs/PLAN.md, "Constraints & non-goals"). The gem's only gate is the
|
|
6
|
+
# routing constraint in config/routes.rb; a host that opts the API on wraps the mounted
|
|
7
|
+
# engine in its own auth, at its own mount point.
|
|
8
|
+
class ApplicationController < ActionController::API
|
|
9
|
+
# rescue_from matches the most recently registered handler first, so the catch-all for
|
|
10
|
+
# the gem's own errors goes first and the narrower ones override it below.
|
|
11
|
+
rescue_from Error, with: :render_unprocessable
|
|
12
|
+
rescue_from FormulaNotFoundError, TemplateNotFoundError, NoEffectiveVersionError, with: :render_not_found
|
|
13
|
+
rescue_from PartialSupersedeError, with: :render_conflict
|
|
14
|
+
rescue_from ::ActiveRecord::RecordNotFound, with: :render_not_found
|
|
15
|
+
rescue_from ::ActiveRecord::RecordInvalid, with: :render_record_invalid
|
|
16
|
+
rescue_from ::ActiveRecord::RecordNotDestroyed, with: :render_record_not_destroyed
|
|
17
|
+
rescue_from ::ActionController::ParameterMissing, with: :render_bad_request
|
|
18
|
+
|
|
19
|
+
private
|
|
20
|
+
|
|
21
|
+
def render_error(error, status, details: nil)
|
|
22
|
+
payload = { type: error.class.name, message: error.message }
|
|
23
|
+
payload[:details] = details if details
|
|
24
|
+
|
|
25
|
+
render json: { error: payload }, status:
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def render_unprocessable(error)
|
|
29
|
+
render_error(error, :unprocessable_entity)
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def render_not_found(error)
|
|
33
|
+
render_error(error, :not_found)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def render_bad_request(error)
|
|
37
|
+
render_error(error, :bad_request)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# 409, not 422: the request is well-formed and the state is valid — the two are just
|
|
41
|
+
# irreconcilable without the operator saying which range they meant to keep.
|
|
42
|
+
def render_conflict(error)
|
|
43
|
+
render_error(error, :conflict)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def render_record_invalid(error)
|
|
47
|
+
render_error(error, :unprocessable_entity, details: error.record.errors.messages)
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Reached when a version still has runs: the audit trail is never deleted to make room
|
|
51
|
+
# for a delete of something else (docs/PLAN.md, "Data model").
|
|
52
|
+
def render_record_not_destroyed(error)
|
|
53
|
+
render_error(error, :conflict, details: error.record.errors.messages)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Nested params arrive as ActionController::Parameters, which is not a Hash — anything
|
|
57
|
+
# handed to a Decree has to be a plain one first.
|
|
58
|
+
def plain_hash(value)
|
|
59
|
+
value.respond_to?(:to_unsafe_h) ? value.to_unsafe_h.to_h : (value || {}).to_h
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# `key` alone never identifies a row in this gem (docs/PLAN.md, "Data model"), so an
|
|
63
|
+
# index filters on the pair.
|
|
64
|
+
def filter_by_key_and_scope(relation)
|
|
65
|
+
relation = relation.where(key: params[:key]) if params[:key].present?
|
|
66
|
+
relation = relation.where(scope: params[:scope]) if params[:scope].present?
|
|
67
|
+
relation
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# `{"type": "Company", "id": 7}` — the same owner reference the JSON import takes, run
|
|
71
|
+
# through the same guard that refuses a type which isn't an ActiveRecord model.
|
|
72
|
+
def resolve_owner(reference)
|
|
73
|
+
ResolveImportOwner.(plain_hash(reference).presence)
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
end
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActsAsCalculator
|
|
4
|
+
class FormulaVersionsController < ApplicationController
|
|
5
|
+
def index
|
|
6
|
+
versions = formula.versions.order(:version_number)
|
|
7
|
+
|
|
8
|
+
render json: { versions: versions.map { |version| SerializeFormulaVersion.(version:) } }
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
def show
|
|
12
|
+
render json: { version: SerializeFormulaVersion.(version:, variables: true) }
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# Straight through `PublishFormulaVersion`, so the API takes exactly the same route
|
|
16
|
+
# through the effective-dating rules as the JSON import does: the incumbent is
|
|
17
|
+
# superseded, never rewritten, and a supersede that would leave part of its range with
|
|
18
|
+
# no active version raises `PartialSupersedeError` — surfaced as a 409, not swallowed.
|
|
19
|
+
def create
|
|
20
|
+
published = PublishFormulaVersion.(formula:, **version_attributes)
|
|
21
|
+
|
|
22
|
+
render json: { version: SerializeFormulaVersion.(version: published, variables: true) },
|
|
23
|
+
status: :created
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
private
|
|
27
|
+
|
|
28
|
+
def formula
|
|
29
|
+
@formula ||= Formula.find(params[:formula_id])
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def version
|
|
33
|
+
@version ||= formula.versions.find(params[:id])
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def version_attributes
|
|
37
|
+
permitted = params.require(:version).permit(
|
|
38
|
+
:expression, :effective_from, :effective_to, :status, :change_note,
|
|
39
|
+
variables: [:name, :source_type, :required, { source_config: {} }]
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
{ expression: permitted[:expression],
|
|
43
|
+
effective_from: permitted[:effective_from],
|
|
44
|
+
effective_to: permitted[:effective_to].presence,
|
|
45
|
+
status: permitted[:status].presence || FormulaVersion::ACTIVE,
|
|
46
|
+
change_note: permitted[:change_note],
|
|
47
|
+
variables: Array(permitted[:variables]).map { |variable| plain_hash(variable) } }
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActsAsCalculator
|
|
4
|
+
# Identity only — `key`, `scope`, `owner`. Everything that can change about a formula is
|
|
5
|
+
# a version, which is why there is a separate controller for those.
|
|
6
|
+
class FormulasController < ApplicationController
|
|
7
|
+
def index
|
|
8
|
+
render json: { formulas: scoped_formulas.map { |formula| SerializeFormula.(formula:) } }
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
def show
|
|
12
|
+
render json: { formula: SerializeFormula.(formula:, versions: true) }
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def create
|
|
16
|
+
created = Formula.create!(**formula_attributes)
|
|
17
|
+
|
|
18
|
+
render json: { formula: SerializeFormula.(formula: created) }, status: :created
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def update
|
|
22
|
+
formula.update!(**formula_attributes)
|
|
23
|
+
|
|
24
|
+
render json: { formula: SerializeFormula.(formula:) }
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def destroy
|
|
28
|
+
formula.destroy!
|
|
29
|
+
|
|
30
|
+
head :no_content
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
private
|
|
34
|
+
|
|
35
|
+
def formula
|
|
36
|
+
@formula ||= Formula.find(params[:id])
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def scoped_formulas
|
|
40
|
+
filter_by_key_and_scope(Formula.order(:scope, :key, :id))
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def formula_params
|
|
44
|
+
params.require(:formula).permit(:key, :scope, owner: %i[type id])
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Only what was sent, so a PATCH that renames a formula doesn't blank its scope. `scope`
|
|
48
|
+
# is left to the column default on create rather than defaulted here.
|
|
49
|
+
def formula_attributes
|
|
50
|
+
permitted = formula_params
|
|
51
|
+
attributes = {}
|
|
52
|
+
attributes[:key] = permitted[:key].to_s if permitted.key?(:key)
|
|
53
|
+
attributes[:scope] = permitted[:scope].to_s if permitted.key?(:scope)
|
|
54
|
+
attributes[:owner] = resolve_owner(permitted[:owner]) if permitted.key?(:owner)
|
|
55
|
+
attributes
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActsAsCalculator
|
|
4
|
+
# docs/PLAN.md lists JSON import and the API as two authoring paths, not two import
|
|
5
|
+
# mechanisms: this is `ImportDefinitions` handed the parsed request body, so an HTTP
|
|
6
|
+
# import means exactly what the generator and the rake task mean, idempotency and
|
|
7
|
+
# lookup-table guard included.
|
|
8
|
+
class ImportsController < ApplicationController
|
|
9
|
+
def create
|
|
10
|
+
summary = ImportDefinitions.(data: definitions)
|
|
11
|
+
|
|
12
|
+
render json: SerializeImportSummary.(summary:),
|
|
13
|
+
status: summary.success? ? :ok : :unprocessable_entity
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
private
|
|
17
|
+
|
|
18
|
+
# The request body itself, not `params` — which carries `controller` and `action`, and
|
|
19
|
+
# `ImportDefinitions` rejects a section it doesn't recognise rather than ignoring it.
|
|
20
|
+
#
|
|
21
|
+
# An empty document is refused for the same reason a misspelled section is: reporting
|
|
22
|
+
# "0 created, 0 failed" to a caller whose body never parsed looks exactly like success.
|
|
23
|
+
def definitions
|
|
24
|
+
body = request.request_parameters
|
|
25
|
+
if body.empty?
|
|
26
|
+
raise ImportError, "no import document in the request body — POST JSON with at least one of " \
|
|
27
|
+
"#{ImportDefinitions::SECTIONS.keys.join(", ")}"
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
body
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActsAsCalculator
|
|
4
|
+
class TemplatesController < ApplicationController
|
|
5
|
+
def index
|
|
6
|
+
render json: { templates: scoped_templates.map { |template| SerializeTemplate.(template:) } }
|
|
7
|
+
end
|
|
8
|
+
|
|
9
|
+
def show
|
|
10
|
+
render json: { template: SerializeTemplate.(template:) }
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def create
|
|
14
|
+
published = PublishTemplate.(**template_attributes)
|
|
15
|
+
|
|
16
|
+
render json: { template: SerializeTemplate.(template: published) }, status: :created
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def destroy
|
|
20
|
+
template.destroy!
|
|
21
|
+
|
|
22
|
+
head :no_content
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# `{ body:, format: }`, never `html_safe` — whether API-authored markup is safe to
|
|
26
|
+
# inject into a page is the host's call, not this gem's (Phase 3).
|
|
27
|
+
def preview
|
|
28
|
+
body = RenderTemplate.(template:, context: plain_hash(params[:context]))
|
|
29
|
+
|
|
30
|
+
render json: { preview: { body:, format: template.format } }
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Rollback: point `current` at an older version instead of deleting the one that went
|
|
34
|
+
# wrong, which is the whole reason the version history exists.
|
|
35
|
+
def promote
|
|
36
|
+
render json: { template: SerializeTemplate.(template: PromoteTemplate.(template:)) }
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
private
|
|
40
|
+
|
|
41
|
+
def template
|
|
42
|
+
@template ||= Template.find(params[:id])
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def scoped_templates
|
|
46
|
+
templates = filter_by_key_and_scope(Template.order(:scope, :key, :version_number, :id))
|
|
47
|
+
current_only? ? templates.current : templates
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Spelled out rather than reaching for ActiveModel::Type::Boolean, which the gemspec
|
|
51
|
+
# doesn't declare and which is more machinery than one query parameter is worth.
|
|
52
|
+
def current_only?
|
|
53
|
+
%w[true 1].include?(params[:current].to_s)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def template_attributes
|
|
57
|
+
permitted = params.require(:template).permit(:key, :body, :scope, :format, owner: %i[type id])
|
|
58
|
+
|
|
59
|
+
{ key: permitted[:key].to_s,
|
|
60
|
+
body: permitted[:body].to_s,
|
|
61
|
+
scope: permitted[:scope].presence,
|
|
62
|
+
format: permitted[:format].presence || Template::HTML,
|
|
63
|
+
owner: resolve_owner(permitted[:owner]) }
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
end
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActsAsCalculator
|
|
4
|
+
class Formula < Record
|
|
5
|
+
self.table_name = "calculator_formulas"
|
|
6
|
+
|
|
7
|
+
belongs_to :owner, polymorphic: true, optional: true
|
|
8
|
+
|
|
9
|
+
has_many :versions,
|
|
10
|
+
class_name: "ActsAsCalculator::FormulaVersion",
|
|
11
|
+
foreign_key: :formula_id,
|
|
12
|
+
inverse_of: :formula,
|
|
13
|
+
dependent: :destroy
|
|
14
|
+
|
|
15
|
+
validates :key, presence: true, uniqueness: { scope: %i[scope owner_type owner_id] }
|
|
16
|
+
validates :scope, presence: true
|
|
17
|
+
|
|
18
|
+
scope :owned_by, ->(owner) { where(owner_type: owner&.class&.polymorphic_name, owner_id: owner&.id) }
|
|
19
|
+
scope :global, -> { where(owner_type: nil, owner_id: nil) }
|
|
20
|
+
end
|
|
21
|
+
end
|