ctb_io_webui/controllers/rpc/
calculator.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! JSON-RPC dispatcher for Calculator math functions.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use serde_json::Value;
30
31/// Dispatches a Calculator RPC method call.
32pub async fn handle_calculator_call(
33    func: &str,
34    args: &[Value],
35) -> anyhow::Result<Value> {
36    use ctb_formats_math::calculator_classic::{
37        CONST_E, CONST_PI, RpsOutcome, SquareRootResult, add,
38        celsius_to_fahrenheit, circle_area, divide, evaluate_basic_op,
39        evaluate_expression, fahrenheit_to_celsius, format_square_root,
40        generate_scaled_random_table, generate_unique_random_triplet,
41        integer_divide, modulo, multiply, play_rps, power, rectangle_area,
42        rectangle_perimeter, rps_choice_from_int, scaled_random, square_root,
43        subtract, verify_prime_and_factors,
44    };
45
46    match func {
47        "evaluateExpression" => {
48            let expr = args
49                .first()
50                .and_then(Value::as_str)
51                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: expression"))?;
52            let res = evaluate_expression(expr)?;
53            Ok(serde_json::to_value(res)?)
54        }
55        "getRandomScaleTable" => {
56            // Reason for fallback: default to uniform random scale in 0.0..1.0 if raw argument omitted.
57            let raw =
58                args.first().and_then(Value::as_f64).unwrap_or_else(|| {
59                    use rand::Rng;
60                    rand::rng().random_range(0.0..1.0)
61                });
62            let table = generate_scaled_random_table(raw);
63            Ok(serde_json::to_value(table)?)
64        }
65        "evaluateBasicOp" => {
66            let op = args
67                .first()
68                .and_then(Value::as_str)
69                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: operator"))?;
70            let a = args
71                .get(1)
72                .and_then(Value::as_f64)
73                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: operand a"))?;
74            let b = args
75                .get(2)
76                .and_then(Value::as_f64)
77                .ok_or_else(|| anyhow::anyhow!("Missing arg 2: operand b"))?;
78            let res = evaluate_basic_op(op, a, b)?;
79            Ok(serde_json::to_value(res)?)
80        }
81        "add" => {
82            let a = args
83                .first()
84                .and_then(Value::as_f64)
85                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: a"))?;
86            let b = args
87                .get(1)
88                .and_then(Value::as_f64)
89                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: b"))?;
90            Ok(serde_json::to_value(add(a, b))?)
91        }
92        "subtract" => {
93            let a = args
94                .first()
95                .and_then(Value::as_f64)
96                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: a"))?;
97            let b = args
98                .get(1)
99                .and_then(Value::as_f64)
100                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: b"))?;
101            Ok(serde_json::to_value(subtract(a, b))?)
102        }
103        "multiply" => {
104            let a = args
105                .first()
106                .and_then(Value::as_f64)
107                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: a"))?;
108            let b = args
109                .get(1)
110                .and_then(Value::as_f64)
111                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: b"))?;
112            Ok(serde_json::to_value(multiply(a, b))?)
113        }
114        "divide" => {
115            let a = args
116                .first()
117                .and_then(Value::as_f64)
118                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: a"))?;
119            let b = args
120                .get(1)
121                .and_then(Value::as_f64)
122                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: b"))?;
123            Ok(serde_json::to_value(divide(a, b)?)?)
124        }
125        "power" => {
126            let a = args
127                .first()
128                .and_then(Value::as_f64)
129                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: base"))?;
130            let b = args
131                .get(1)
132                .and_then(Value::as_f64)
133                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: exponent"))?;
134            Ok(serde_json::to_value(power(a, b))?)
135        }
136        "integerDivide" => {
137            let a = args
138                .first()
139                .and_then(Value::as_i64)
140                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: a"))?;
141            let b = args
142                .get(1)
143                .and_then(Value::as_i64)
144                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: b"))?;
145            Ok(serde_json::to_value(integer_divide(a, b)?)?)
146        }
147        "modulo" => {
148            let a = args
149                .first()
150                .and_then(Value::as_i64)
151                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: a"))?;
152            let b = args
153                .get(1)
154                .and_then(Value::as_i64)
155                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: b"))?;
156            Ok(serde_json::to_value(modulo(a, b)?)?)
157        }
158        "circleArea" => {
159            let r = args
160                .first()
161                .and_then(Value::as_f64)
162                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: radius"))?;
163            Ok(serde_json::to_value(circle_area(r))?)
164        }
165        "rectangleArea" => {
166            let b = args
167                .first()
168                .and_then(Value::as_f64)
169                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: base"))?;
170            let h = args
171                .get(1)
172                .and_then(Value::as_f64)
173                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: height"))?;
174            Ok(serde_json::to_value(rectangle_area(b, h))?)
175        }
176        "rectanglePerimeter" => {
177            let b = args
178                .first()
179                .and_then(Value::as_f64)
180                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: base"))?;
181            let h = args
182                .get(1)
183                .and_then(Value::as_f64)
184                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: height"))?;
185            Ok(serde_json::to_value(rectangle_perimeter(b, h))?)
186        }
187        "squareRoot" => {
188            let x = args
189                .first()
190                .and_then(Value::as_f64)
191                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: x"))?;
192            let formatted = format_square_root(x);
193            Ok(serde_json::to_value(formatted)?)
194        }
195        "fahrenheitToCelsius" => {
196            let f = args
197                .first()
198                .and_then(Value::as_f64)
199                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: fahrenheit"))?;
200            Ok(serde_json::to_value(fahrenheit_to_celsius(f))?)
201        }
202        "celsiusToFahrenheit" => {
203            let c = args
204                .first()
205                .and_then(Value::as_f64)
206                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: celsius"))?;
207            Ok(serde_json::to_value(celsius_to_fahrenheit(c))?)
208        }
209        "verifyPrimeAndFactors" => {
210            let n = args
211                .first()
212                .and_then(Value::as_i64)
213                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: n"))?;
214            let result = verify_prime_and_factors(n);
215            Ok(serde_json::json!({
216                "is_prime": result.is_prime,
217                "factor_a": result.factor_a,
218                "factor_b": result.factor_b
219            }))
220        }
221        "scaledRandom" => {
222            let raw = args
223                .first()
224                .and_then(Value::as_f64)
225                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: raw_random"))?;
226            let mult = args
227                .get(1)
228                .and_then(Value::as_f64)
229                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: multiplier"))?;
230            Ok(serde_json::to_value(scaled_random(raw, mult))?)
231        }
232        "generateUniqueRandomTriplet" => {
233            let min = args
234                .first()
235                .and_then(Value::as_i64)
236                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: min"))?;
237            let max = args
238                .get(1)
239                .and_then(Value::as_i64)
240                .ok_or_else(|| anyhow::anyhow!("Missing arg 1: max"))?;
241            let min_i32 = i32::try_from(min)?;
242            let max_i32 = i32::try_from(max)?;
243            let mut rng = rand::rng();
244            use rand::Rng;
245            let triplet = generate_unique_random_triplet(
246                || rng.random_range(min_i32..=max_i32),
247                min_i32,
248                max_i32,
249            )?;
250            Ok(serde_json::to_value(triplet)?)
251        }
252        "playRps" => {
253            let user_int = args
254                .first()
255                .and_then(Value::as_i64)
256                .ok_or_else(|| anyhow::anyhow!("Missing arg 0: user_choice"))?;
257            let user_i32 = i32::try_from(user_int)?;
258            let user_choice = rps_choice_from_int(user_i32)?;
259            let mut rng = rand::rng();
260            use rand::Rng;
261            let comp_int: i32 = rng.random_range(1..=3);
262            let comp_choice = rps_choice_from_int(comp_int)?;
263            let outcome = play_rps(user_choice, comp_choice);
264            let outcome_str = match outcome {
265                RpsOutcome::Win => "Win",
266                RpsOutcome::Loss => "Loss",
267                RpsOutcome::Draw => "Draw",
268            };
269            Ok(serde_json::json!({
270                "userChoice": user_int,
271                "computerChoice": comp_int,
272                "outcome": outcome_str
273            }))
274        }
275        "getConstants" => {
276            let radical13_val = match square_root(13.0) {
277                SquareRootResult::Real(v) => v,
278                SquareRootResult::Imaginary(v) => v,
279            };
280            Ok(serde_json::json!({
281                "pi": CONST_PI,
282                "e": CONST_E,
283                "radical13": radical13_val
284            }))
285        }
286        _ => anyhow::bail!("Unknown calculator function: {func}"),
287    }
288}