1use std::fmt;
15
16pub const LINE_ITEMS: [(&str, &str, f64); 12] = [
18 ("cabinets", "Cabinets and shelving", 0.25),
19 ("labor", "Installation and labor", 0.15),
20 ("appliances", "Appliances", 0.15),
21 ("countertops", "Countertops and backsplash", 0.10),
22 ("flooring", "Flooring", 0.07),
23 ("lighting", "Lighting", 0.05),
24 ("painting", "Painting and drywall", 0.05),
25 ("design", "Designer", 0.05),
26 ("sink", "Sink and faucet", 0.05),
27 ("doors_windows", "Doors and windows", 0.04),
28 ("plumbing", "Plumbing", 0.03),
29 ("misc", "Miscellaneous", 0.01),
30];
31
32#[derive(Debug, Clone, Copy, PartialEq)]
34pub struct Preset {
35 pub key: &'static str,
36 pub label: &'static str,
37 pub construction: f64,
38 pub permit: f64,
39}
40
41pub const PRESETS: [Preset; 3] = [
42 Preset { key: "minor-midrange", label: "Minor remodel, midrange", construction: 29728.0, permit: 500.0 },
43 Preset { key: "major-midrange", label: "Major remodel, midrange", construction: 86480.0, permit: 2500.0 },
44 Preset { key: "major-upscale", label: "Major remodel, upscale", construction: 171950.0, permit: 4000.0 },
45];
46
47pub const DEFAULT_TAX_RATE: f64 = 0.103;
48pub const DEFAULT_CONTINGENCY_RATE: f64 = 0.10;
49pub const PRESET_SOURCE: &str = "Cost vs Value 2025, Pacific region averages (200 sq ft kitchen)";
50pub const SHARE_SOURCE: &str = "HomeGuide kitchen remodel cost breakdown";
51
52#[derive(Debug, Clone, PartialEq)]
54pub struct Error(pub String);
55impl fmt::Display for Error {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.0) }
57}
58impl std::error::Error for Error {}
59
60#[derive(Debug, Clone, PartialEq)]
62pub struct Options {
63 pub tax_rate: f64,
64 pub contingency_rate: f64,
65 pub permit: f64,
66 pub shares: Vec<(String, f64)>,
68}
69impl Default for Options {
70 fn default() -> Self {
71 Options { tax_rate: DEFAULT_TAX_RATE, contingency_rate: DEFAULT_CONTINGENCY_RATE, permit: 0.0, shares: vec![] }
72 }
73}
74
75#[derive(Debug, Clone, PartialEq)]
76pub struct Line { pub key: String, pub label: String, pub share: f64, pub amount: f64 }
77
78#[derive(Debug, Clone, PartialEq)]
79pub struct Breakdown {
80 pub mode: &'static str,
81 pub lines: Vec<Line>,
82 pub construction: f64,
83 pub contingency: f64,
84 pub tax: f64,
85 pub permit: f64,
86 pub total: f64,
87 pub tax_rate: f64,
88 pub contingency_rate: f64,
89}
90
91fn round(x: f64) -> i64 { (x + 0.5).floor() as i64 }
92
93fn num(name: &str, v: f64, max: Option<f64>) -> Result<f64, Error> {
94 if !v.is_finite() || v < 0.0 { return Err(Error(format!("{name} must be a finite number >= 0"))); }
95 if let Some(m) = max { if v > m { return Err(Error(format!("{name} must be <= {m}"))); } }
96 Ok(v)
97}
98
99pub fn normalise_shares(overrides: &[(String, f64)]) -> Result<Vec<(String, String, f64)>, Error> {
101 let mut items: Vec<(String, String, f64)> =
102 LINE_ITEMS.iter().map(|(k, l, s)| (k.to_string(), l.to_string(), *s)).collect();
103 for (k, v) in overrides {
104 let it = items.iter_mut().find(|i| &i.0 == k).ok_or_else(|| Error(format!("unknown line item: {k}")))?;
105 it.2 = num(&format!("share {k}"), *v, None)?;
106 }
107 let mut sum = 0.0;
108 for i in &items { sum += i.2; }
109 if sum <= 0.0 { return Err(Error("shares must not all be zero".into())); }
110 for i in items.iter_mut() { i.2 /= sum; }
111 Ok(items)
112}
113
114fn allocate(cents: i64, items: &[(String, String, f64)]) -> Vec<Line> {
115 let mut base: Vec<i64> = Vec::with_capacity(items.len());
116 let mut frac: Vec<(usize, f64)> = Vec::with_capacity(items.len());
117 for (i, it) in items.iter().enumerate() {
118 let raw = cents as f64 * it.2;
119 let b = raw.floor();
120 base.push(b as i64);
121 frac.push((i, raw - b));
122 }
123 let mut left = cents - base.iter().sum::<i64>();
124 frac.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap().then(a.0.cmp(&b.0)));
125 let mut j = 0;
126 while left > 0 { base[frac[j % frac.len()].0] += 1; j += 1; left -= 1; }
127 items.iter().zip(base).map(|(it, c)| Line { key: it.0.clone(), label: it.1.clone(), share: it.2, amount: c as f64 / 100.0 }).collect()
128}
129
130struct Checked { tax: f64, cont: f64, permit: f64, items: Vec<(String, String, f64)> }
131
132fn check(o: &Options) -> Result<Checked, Error> {
133 Ok(Checked {
134 tax: num("tax_rate", o.tax_rate, Some(1.0))?,
135 cont: num("contingency_rate", o.contingency_rate, Some(1.0))?,
136 permit: num("permit", o.permit, None)?,
137 items: normalise_shares(&o.shares)?,
138 })
139}
140
141fn result(mode: &'static str, c: i64, k: i64, t: i64, p: i64, o: &Checked) -> Breakdown {
142 Breakdown {
143 mode, lines: allocate(c, &o.items),
144 construction: c as f64 / 100.0, contingency: k as f64 / 100.0, tax: t as f64 / 100.0,
145 permit: p as f64 / 100.0, total: (c + k + t + p) as f64 / 100.0,
146 tax_rate: o.tax, contingency_rate: o.cont,
147 }
148}
149
150pub fn estimate(construction: f64, opts: &Options) -> Result<Breakdown, Error> {
152 let o = check(opts)?;
153 let c = round(num("construction", construction, None)? * 100.0);
154 let k = round(c as f64 * o.cont);
155 let t = round((c + k) as f64 * o.tax);
156 Ok(result("estimate", c, k, t, round(o.permit * 100.0), &o))
157}
158
159pub fn split_budget(total: f64, opts: &Options) -> Result<Breakdown, Error> {
161 let o = check(opts)?;
162 let p = round(o.permit * 100.0);
163 let a = round(num("total", total, None)? * 100.0) - p;
164 if a <= 0 { return Err(Error("total must be larger than the permit allowance".into())); }
165 let c = round(a as f64 / ((1.0 + o.cont) * (1.0 + o.tax)));
166 let mut k = round(c as f64 * o.cont);
167 let t = round((c + k) as f64 * o.tax);
168 k += a - c - k - t;
169 Ok(result("split", c, k, t, p, &o))
170}
171
172pub fn preset(name: &str) -> Result<Preset, Error> {
174 PRESETS.iter().copied().find(|p| p.key == name).ok_or_else(|| {
175 Error(format!("unknown preset: {name} (use minor-midrange, major-midrange, major-upscale)"))
176 })
177}
178
179pub fn estimate_preset(name: &str, opts: &Options, permit: Option<f64>) -> Result<Breakdown, Error> {
181 let p = preset(name)?;
182 let mut o = opts.clone();
183 o.permit = permit.unwrap_or(p.permit);
184 estimate(p.construction, &o)
185}
186
187pub fn money(v: f64) -> String {
189 let c = round(v * 100.0);
190 let (d, r) = (c / 100, c % 100);
191 let s = d.to_string();
192 let mut out = String::new();
193 for (i, ch) in s.chars().enumerate() {
194 if i > 0 && (s.len() - i) % 3 == 0 { out.push(','); }
195 out.push(ch);
196 }
197 format!("${out}.{r:02}")
198}
199
200fn pct(rate: f64) -> String {
201 let s = format!("{:.2}", rate * 100.0);
202 s.trim_end_matches('0').trim_end_matches('.').to_string()
203}
204
205pub fn format_table(r: &Breakdown) -> String {
207 let mut rows: Vec<[String; 3]> = r.lines.iter()
208 .map(|l| [l.label.clone(), format!("{:.1}%", l.share * 100.0), money(l.amount)]).collect();
209 rows.push(["Construction subtotal".into(), String::new(), money(r.construction)]);
210 rows.push([format!("Contingency reserve ({}%)", pct(r.contingency_rate)), String::new(), money(r.contingency)]);
211 rows.push([format!("Sales tax ({}%)", pct(r.tax_rate)), String::new(), money(r.tax)]);
212 rows.push(["Permit allowance".into(), String::new(), money(r.permit)]);
213 rows.push(["Total".into(), String::new(), money(r.total)]);
214 let head = ["Line item".to_string(), "Share".to_string(), "Amount".to_string()];
215 let w: Vec<usize> = (0..3).map(|c| rows.iter().map(|x| x[c].len()).chain([head[c].len()]).max().unwrap()).collect();
216 let line = |x: &[String; 3]| format!("{:<w0$} {:>w1$} {:>w2$}", x[0], x[1], x[2], w0 = w[0], w1 = w[1], w2 = w[2]);
217 let sep = "-".repeat(w[0] + w[1] + w[2] + 4);
218 let mut body: Vec<String> = rows.iter().map(line).collect();
219 body.insert(r.lines.len(), sep.clone());
220 let n = body.len() - 1;
221 body.insert(n, sep.clone());
222 let mut out = vec![line(&head), sep];
223 out.extend(body);
224 out.join("\n")
225}
226
227#[cfg(test)]
228mod tests {
229 use super::*;
230 fn d() -> Options { Options::default() }
231 fn sum(r: &Breakdown) -> i64 { r.lines.iter().map(|l| round(l.amount * 100.0)).sum() }
232
233 #[test]
234 fn estimate_reference() {
235 let r = estimate(60000.0, &Options { permit: 1500.0, ..d() }).unwrap();
236 assert_eq!((r.construction, r.contingency, r.tax, r.total), (60000.0, 6000.0, 6798.0, 74298.0));
237 assert_eq!(r.lines[0].amount, 15000.0);
238 assert_eq!(sum(&r), 6_000_000);
239 }
240
241 #[test]
242 fn split_reference() {
243 let r = split_budget(100000.0, &Options { permit: 2500.0, ..d() }).unwrap();
244 assert_eq!((r.construction, r.contingency, r.tax), (80359.35, 8035.94, 9104.71));
245 assert_eq!(r.lines[0].amount, 20089.84);
246 }
247
248 #[test]
249 fn split_exact() {
250 for t in [10000.0, 33333.33, 60000.0, 98765.43, 250000.0] {
251 let r = split_budget(t, &Options { permit: 1000.0, ..d() }).unwrap();
252 assert_eq!(round(r.total * 100.0), round(t * 100.0));
253 assert_eq!(sum(&r), round(r.construction * 100.0));
254 }
255 }
256
257 #[test]
258 fn ties() {
259 let r = split_budget(33333.33, &d()).unwrap();
260 assert_eq!((r.construction, r.contingency, r.tax), (27473.28, 2747.33, 3112.72));
261 assert_eq!(r.lines[6].amount, 1373.67);
262 assert_eq!(r.lines[7].amount, 1373.66);
263 }
264
265 #[test]
266 fn presets_and_errors() {
267 let r = estimate_preset("major-midrange", &d(), None).unwrap();
268 assert_eq!((r.permit, r.tax, r.total), (2500.0, 9798.18, 107426.18));
269 assert!(estimate_preset("nope", &d(), None).is_err());
270 assert!(estimate(-1.0, &d()).is_err());
271 assert!(estimate(1.0, &Options { tax_rate: 2.0, ..d() }).is_err());
272 assert!(split_budget(100.0, &Options { permit: 200.0, ..d() }).is_err());
273 assert!(estimate(1.0, &Options { shares: vec![("garage".into(), 1.0)], ..d() }).is_err());
274 let r = estimate(1000.0, &Options { tax_rate: 0.0, contingency_rate: 0.0, shares: vec![("cabinets".into(), 50.0)], ..d() }).unwrap();
275 assert!(r.lines[0].share > 0.5);
276 assert_eq!(sum(&r), 100_000);
277 }
278
279 #[test]
280 fn table() {
281 let t = format_table(&estimate(60000.0, &Options { permit: 1500.0, ..d() }).unwrap());
282 assert!(t.contains("Cabinets and shelving 25.0% $15,000.00"));
283 assert!(t.contains("$74,298.00"));
284 assert_eq!(money(1234567.891), "$1,234,567.89");
285 }
286}