amanextractionsie 0.1.0

Explainable stage gates for place-led hospitality expansion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Explainable stage gates for place-led hospitality expansion.
//!
//! Candidate quality and portfolio capacity are evaluated separately. A weak
//! principle is a veto; a strong candidate can still be deferred when openings
//! are concentrated in one year or region.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;

/// A quality to preserve while entering a destination.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ExpansionPrinciple {
    /// The concept begins with the site's distinct landscape and character.
    PlaceIntegrity,
    /// Local culture is respected through durable participation and context.
    CulturalContinuity,
    /// Density and spatial planning preserve personal privacy and room.
    PrivacyAndSpace,
    /// Arrival, acoustics, movement, and programming support calm.
    QuietExperience,
    /// People, training, systems, and supply chains can sustain service.
    ServiceReadiness,
    /// Maintenance, environmental care, and local relationships endure.
    LongTermStewardship,
}

impl ExpansionPrinciple {
    /// Every principle in stable report order.
    pub const ALL: [Self; 6] = [
        Self::PlaceIntegrity,
        Self::CulturalContinuity,
        Self::PrivacyAndSpace,
        Self::QuietExperience,
        Self::ServiceReadiness,
        Self::LongTermStewardship,
    ];
}

/// A scored principle with supporting evidence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrincipleAssessment {
    score: u8,
    evidence: String,
}

impl PrincipleAssessment {
    /// Creates an assessment with a score from 0 to 100 and non-blank evidence.
    pub fn new(score: u8, evidence: impl Into<String>) -> Result<Self, ExpansionError> {
        if score > 100 {
            return Err(ExpansionError::ScoreOutOfRange(score));
        }
        let evidence = evidence.into();
        if evidence.trim().is_empty() {
            return Err(ExpansionError::EmptyEvidence);
        }
        Ok(Self { score, evidence })
    }

    /// Returns the score from 0 to 100.
    pub const fn score(&self) -> u8 {
        self.score
    }

    /// Returns the evidence text.
    pub fn evidence(&self) -> &str {
        &self.evidence
    }
}

/// A proposed destination and its principle assessments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExpansionCandidate {
    name: String,
    region: String,
    opening_year: u16,
    assessments: BTreeMap<ExpansionPrinciple, PrincipleAssessment>,
}

impl ExpansionCandidate {
    /// Creates an unassessed candidate.
    pub fn new(
        name: impl Into<String>,
        region: impl Into<String>,
        opening_year: u16,
    ) -> Result<Self, ExpansionError> {
        let name = non_blank(name.into(), "candidate")?;
        let region = non_blank(region.into(), "region")?;
        Ok(Self {
            name,
            region,
            opening_year,
            assessments: BTreeMap::new(),
        })
    }

    /// Adds or replaces one assessment and returns the candidate for chaining.
    pub fn assess(
        mut self,
        principle: ExpansionPrinciple,
        score: u8,
        evidence: impl Into<String>,
    ) -> Result<Self, ExpansionError> {
        self.set_assessment(principle, score, evidence)?;
        Ok(self)
    }

    /// Adds or replaces one assessment in place.
    pub fn set_assessment(
        &mut self,
        principle: ExpansionPrinciple,
        score: u8,
        evidence: impl Into<String>,
    ) -> Result<(), ExpansionError> {
        self.assessments
            .insert(principle, PrincipleAssessment::new(score, evidence)?);
        Ok(())
    }

    /// Returns the candidate name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the portfolio region label.
    pub fn region(&self) -> &str {
        &self.region
    }

    /// Returns the proposed opening year.
    pub const fn opening_year(&self) -> u16 {
        self.opening_year
    }

    /// Returns an assessment when recorded.
    pub fn assessment(&self, principle: ExpansionPrinciple) -> Option<&PrincipleAssessment> {
        self.assessments.get(&principle)
    }
}

/// A destination already committed in the expansion pipeline.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommittedOpening {
    name: String,
    region: String,
    opening_year: u16,
}

impl CommittedOpening {
    /// Creates a committed opening with non-blank name and region.
    pub fn new(
        name: impl Into<String>,
        region: impl Into<String>,
        opening_year: u16,
    ) -> Result<Self, ExpansionError> {
        Ok(Self {
            name: non_blank(name.into(), "opening")?,
            region: non_blank(region.into(), "region")?,
            opening_year,
        })
    }

    /// Returns the opening name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns its region label.
    pub fn region(&self) -> &str {
        &self.region
    }

    /// Returns its opening year.
    pub const fn opening_year(&self) -> u16 {
        self.opening_year
    }
}

/// Existing expansion commitments used to check concentration.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Portfolio {
    openings: Vec<CommittedOpening>,
}

impl Portfolio {
    /// Creates an empty portfolio.
    pub const fn new() -> Self {
        Self {
            openings: Vec::new(),
        }
    }

    /// Adds a uniquely named commitment.
    pub fn commit(&mut self, opening: CommittedOpening) -> Result<(), ExpansionError> {
        if self.openings.iter().any(|item| item.name == opening.name) {
            return Err(ExpansionError::DuplicateOpeningName(opening.name));
        }
        self.openings.push(opening);
        self.openings.sort_by(|left, right| {
            left.opening_year
                .cmp(&right.opening_year)
                .then_with(|| left.region.cmp(&right.region))
                .then_with(|| left.name.cmp(&right.name))
        });
        Ok(())
    }

    /// Returns commitments in year, region, and name order.
    pub fn openings(&self) -> &[CommittedOpening] {
        &self.openings
    }
}

/// Stage-gate thresholds and portfolio concentration limits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExpansionPolicy {
    minimum_principle_score: u8,
    ready_average_score: u8,
    max_openings_per_year: u16,
    max_openings_per_region_per_year: u16,
}

impl ExpansionPolicy {
    /// Creates an expansion policy.
    pub fn new(
        minimum_principle_score: u8,
        ready_average_score: u8,
        max_openings_per_year: u16,
        max_openings_per_region_per_year: u16,
    ) -> Result<Self, ExpansionError> {
        if minimum_principle_score > 100 || ready_average_score > 100 {
            return Err(ExpansionError::PolicyScoreOutOfRange);
        }
        if ready_average_score < minimum_principle_score {
            return Err(ExpansionError::ReadyScoreBelowMinimum);
        }
        if max_openings_per_year == 0 || max_openings_per_region_per_year == 0 {
            return Err(ExpansionError::ZeroPortfolioLimit);
        }
        Ok(Self {
            minimum_principle_score,
            ready_average_score,
            max_openings_per_year,
            max_openings_per_region_per_year,
        })
    }

    /// Evaluates candidate quality and portfolio capacity.
    pub fn evaluate(
        &self,
        candidate: &ExpansionCandidate,
        portfolio: &Portfolio,
    ) -> ExpansionReport {
        let mut missing = Vec::new();
        let mut below_minimum = Vec::new();
        let mut score_sum = 0_u16;

        for principle in ExpansionPrinciple::ALL {
            match candidate.assessment(principle) {
                None => missing.push(principle),
                Some(assessment) => {
                    score_sum += u16::from(assessment.score);
                    if assessment.score < self.minimum_principle_score {
                        below_minimum.push(principle);
                    }
                }
            }
        }

        let score_basis_points = if missing.is_empty() {
            Some(score_sum * 100 / ExpansionPrinciple::ALL.len() as u16)
        } else {
            None
        };

        let same_year = portfolio
            .openings
            .iter()
            .filter(|opening| opening.opening_year == candidate.opening_year)
            .count();
        let same_region_year = portfolio
            .openings
            .iter()
            .filter(|opening| {
                opening.opening_year == candidate.opening_year && opening.region == candidate.region
            })
            .count();
        let mut constraints = Vec::new();
        if same_year + 1 > usize::from(self.max_openings_per_year) {
            constraints.push(PortfolioConstraint::AnnualOpeningLimit);
        }
        if same_region_year + 1 > usize::from(self.max_openings_per_region_per_year) {
            constraints.push(PortfolioConstraint::RegionalOpeningLimit);
        }

        let decision = if !below_minimum.is_empty() {
            ExpansionDecision::Reject
        } else if !missing.is_empty() {
            ExpansionDecision::NeedsEvidence
        } else if score_basis_points.unwrap() < u16::from(self.ready_average_score) * 100 {
            ExpansionDecision::Refine
        } else if !constraints.is_empty() {
            ExpansionDecision::Defer
        } else {
            ExpansionDecision::Advance
        };

        ExpansionReport {
            decision,
            score_basis_points,
            missing,
            below_minimum,
            constraints,
        }
    }
}

/// Portfolio limit exceeded by adding a candidate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PortfolioConstraint {
    /// The maximum openings in the candidate year would be exceeded.
    AnnualOpeningLimit,
    /// The region-and-year maximum would be exceeded.
    RegionalOpeningLimit,
}

/// Outcome of the expansion stage gate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExpansionDecision {
    /// A known weak principle vetoes the candidate.
    Reject,
    /// One or more principle assessments are missing.
    NeedsEvidence,
    /// The candidate clears every floor but misses the average quality gate.
    Refine,
    /// Candidate quality passes, but portfolio capacity is concentrated.
    Defer,
    /// Candidate quality and portfolio capacity both pass.
    Advance,
}

/// Explainable candidate and portfolio evaluation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExpansionReport {
    decision: ExpansionDecision,
    score_basis_points: Option<u16>,
    missing: Vec<ExpansionPrinciple>,
    below_minimum: Vec<ExpansionPrinciple>,
    constraints: Vec<PortfolioConstraint>,
}

impl ExpansionReport {
    /// Returns the stage-gate decision.
    pub const fn decision(&self) -> ExpansionDecision {
        self.decision
    }

    /// Returns average principle score in basis points, or `None` if incomplete.
    pub const fn score_basis_points(&self) -> Option<u16> {
        self.score_basis_points
    }

    /// Returns missing principles in stable order.
    pub fn missing(&self) -> &[ExpansionPrinciple] {
        &self.missing
    }

    /// Returns principles below the hard floor.
    pub fn below_minimum(&self) -> &[ExpansionPrinciple] {
        &self.below_minimum
    }

    /// Returns portfolio limits that would be exceeded.
    pub fn constraints(&self) -> &[PortfolioConstraint] {
        &self.constraints
    }
}

/// Invalid candidate, assessment, portfolio, or policy input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExpansionError {
    /// A named text field was blank.
    EmptyName(&'static str),
    /// Assessment evidence was blank.
    EmptyEvidence,
    /// An assessment score exceeded 100.
    ScoreOutOfRange(u8),
    /// A policy score exceeded 100.
    PolicyScoreOutOfRange,
    /// The average readiness score was lower than the hard principle floor.
    ReadyScoreBelowMinimum,
    /// A portfolio opening limit was zero.
    ZeroPortfolioLimit,
    /// A commitment reused an existing opening name.
    DuplicateOpeningName(String),
}

impl fmt::Display for ExpansionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyName(kind) => write!(formatter, "{kind} name must not be blank"),
            Self::EmptyEvidence => formatter.write_str("assessment evidence must not be blank"),
            Self::ScoreOutOfRange(score) => write!(formatter, "score {score} is outside 0..=100"),
            Self::PolicyScoreOutOfRange => {
                formatter.write_str("policy scores must be within 0..=100")
            }
            Self::ReadyScoreBelowMinimum => {
                formatter.write_str("ready average must not be below the principle floor")
            }
            Self::ZeroPortfolioLimit => {
                formatter.write_str("portfolio limits must be greater than zero")
            }
            Self::DuplicateOpeningName(name) => {
                write!(formatter, "opening {name:?} already exists")
            }
        }
    }
}

impl Error for ExpansionError {}

fn non_blank(value: String, kind: &'static str) -> Result<String, ExpansionError> {
    if value.trim().is_empty() {
        Err(ExpansionError::EmptyName(kind))
    } else {
        Ok(value)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn candidate(scores: [u8; 6]) -> ExpansionCandidate {
        ExpansionPrinciple::ALL
            .into_iter()
            .zip(scores)
            .try_fold(
                ExpansionCandidate::new("retreat", "north", 2030).unwrap(),
                |candidate, (principle, score)| {
                    candidate.assess(principle, score, "documented evidence")
                },
            )
            .unwrap()
    }

    fn policy() -> ExpansionPolicy {
        ExpansionPolicy::new(70, 80, 2, 1).unwrap()
    }

    #[test]
    fn strong_candidate_advances() {
        let report = policy().evaluate(&candidate([90, 85, 88, 82, 80, 85]), &Portfolio::new());
        assert_eq!(report.decision(), ExpansionDecision::Advance);
        assert_eq!(report.score_basis_points(), Some(8500));
    }

    #[test]
    fn weak_principle_is_a_veto() {
        let report =
            policy().evaluate(&candidate([100, 100, 100, 100, 100, 60]), &Portfolio::new());
        assert_eq!(report.decision(), ExpansionDecision::Reject);
        assert_eq!(
            report.below_minimum(),
            &[ExpansionPrinciple::LongTermStewardship]
        );
    }

    #[test]
    fn missing_principles_need_evidence() {
        let candidate = ExpansionCandidate::new("retreat", "north", 2030)
            .unwrap()
            .assess(ExpansionPrinciple::PlaceIntegrity, 90, "evidence")
            .unwrap();
        let report = policy().evaluate(&candidate, &Portfolio::new());
        assert_eq!(report.decision(), ExpansionDecision::NeedsEvidence);
        assert_eq!(report.score_basis_points(), None);
        assert_eq!(report.missing(), &ExpansionPrinciple::ALL[1..]);
    }

    #[test]
    fn passing_floors_but_low_average_requires_refinement() {
        let report = policy().evaluate(&candidate([79, 79, 79, 79, 79, 79]), &Portfolio::new());
        assert_eq!(report.decision(), ExpansionDecision::Refine);
    }

    #[test]
    fn regional_concentration_defers_a_good_candidate() {
        let mut portfolio = Portfolio::new();
        portfolio
            .commit(CommittedOpening::new("existing", "north", 2030).unwrap())
            .unwrap();
        let report = policy().evaluate(&candidate([90; 6]), &portfolio);
        assert_eq!(report.decision(), ExpansionDecision::Defer);
        assert_eq!(
            report.constraints(),
            &[PortfolioConstraint::RegionalOpeningLimit]
        );
    }

    #[test]
    fn annual_concentration_is_reported_separately() {
        let mut portfolio = Portfolio::new();
        portfolio
            .commit(CommittedOpening::new("one", "south", 2030).unwrap())
            .unwrap();
        portfolio
            .commit(CommittedOpening::new("two", "west", 2030).unwrap())
            .unwrap();
        let report = policy().evaluate(&candidate([90; 6]), &portfolio);
        assert_eq!(report.decision(), ExpansionDecision::Defer);
        assert_eq!(
            report.constraints(),
            &[PortfolioConstraint::AnnualOpeningLimit]
        );
    }

    #[test]
    fn duplicate_commitments_and_invalid_policy_are_rejected() {
        let mut portfolio = Portfolio::new();
        portfolio
            .commit(CommittedOpening::new("one", "north", 2030).unwrap())
            .unwrap();
        assert_eq!(
            portfolio.commit(CommittedOpening::new("one", "south", 2031).unwrap()),
            Err(ExpansionError::DuplicateOpeningName("one".into()))
        );
        assert_eq!(
            ExpansionPolicy::new(80, 70, 1, 1),
            Err(ExpansionError::ReadyScoreBelowMinimum)
        );
        assert_eq!(
            ExpansionPolicy::new(70, 80, 0, 1),
            Err(ExpansionError::ZeroPortfolioLimit)
        );
    }
}