Skip to main content

excuse_attendance/
lib.rs

1//! Privacy-aware Japanese explanations for attendance decisions.
2//!
3//! Explanations preserve the source decision and progressively disclose
4//! details from a `decision-attendance` report.
5//!
6//! ```
7//! use decision_attendance::{
8//!     AttendanceCriterion, AttendancePolicy, DecisionAttendance, Evidence,
9//! };
10//! use excuse_attendance::{AttendanceExcuse, Disclosure, ReasonPolicy, ReasonTone};
11//!
12//! let criteria = [
13//!     AttendanceCriterion::required("schedule", Evidence::Supports)?,
14//!     AttendanceCriterion::preference("interest", 1, Evidence::Supports)?,
15//! ];
16//! let report = DecisionAttendance::evaluate(&criteria, AttendancePolicy::default())?;
17//! let reason = AttendanceExcuse::compose(
18//!     &report,
19//!     ReasonPolicy::new(Disclosure::Minimal, ReasonTone::Polite),
20//! )?;
21//! assert!(reason.text().contains("参加"));
22//! # Ok::<(), Box<dyn std::error::Error>>(())
23//! ```
24
25use std::collections::BTreeMap;
26use std::error::Error;
27use std::fmt::{self, Display, Formatter};
28
29pub use decision_attendance::{AttendanceDecision, AttendanceReport};
30
31/// Amount of source-decision detail placed in the explanation.
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
33pub enum Disclosure {
34    /// Decision only; no counts, score, or criterion identifiers.
35    #[default]
36    Minimal,
37    /// Counts and preference score, without criterion identifiers.
38    Summary,
39    /// Criterion labels and preference score.
40    Detailed,
41}
42
43/// Surface voice of the generated explanation.
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
45pub enum ReasonTone {
46    /// Courteous Japanese phrasing.
47    #[default]
48    Polite,
49    /// Short, direct Japanese phrasing.
50    Direct,
51}
52
53/// Explanation generation settings.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
55pub struct ReasonPolicy {
56    disclosure: Disclosure,
57    tone: ReasonTone,
58    max_chars: usize,
59}
60
61impl ReasonPolicy {
62    /// Creates a policy with a 280-character maximum.
63    pub const fn new(disclosure: Disclosure, tone: ReasonTone) -> Self {
64        Self {
65            disclosure,
66            tone,
67            max_chars: 280,
68        }
69    }
70
71    /// Sets the maximum Unicode character count.
72    pub fn with_max_chars(mut self, max_chars: usize) -> Result<Self, ReasonError> {
73        if max_chars == 0 {
74            return Err(ReasonError::ZeroMaxChars);
75        }
76        self.max_chars = max_chars;
77        Ok(self)
78    }
79
80    /// Disclosure level.
81    pub const fn disclosure(self) -> Disclosure {
82        self.disclosure
83    }
84
85    /// Output tone.
86    pub const fn tone(self) -> ReasonTone {
87        self.tone
88    }
89
90    /// Maximum Unicode character count.
91    pub const fn max_chars(self) -> usize {
92        self.max_chars
93    }
94}
95
96impl Default for ReasonPolicy {
97    fn default() -> Self {
98        Self::new(Disclosure::default(), ReasonTone::default())
99    }
100}
101
102/// Optional public labels for internal criterion identifiers.
103#[derive(Clone, Debug, Default, PartialEq, Eq)]
104pub struct ReasonBook {
105    labels: BTreeMap<String, String>,
106}
107
108impl ReasonBook {
109    /// Creates an empty label book.
110    pub const fn new() -> Self {
111        Self {
112            labels: BTreeMap::new(),
113        }
114    }
115
116    /// Adds or replaces a public label.
117    pub fn set(
118        &mut self,
119        criterion_id: impl Into<String>,
120        public_label: impl Into<String>,
121    ) -> Result<Option<String>, ReasonError> {
122        let criterion_id = criterion_id.into();
123        let public_label = public_label.into();
124        if criterion_id.trim().is_empty() {
125            return Err(ReasonError::EmptyCriterionId);
126        }
127        if public_label.trim().is_empty() {
128            return Err(ReasonError::EmptyPublicLabel);
129        }
130        Ok(self.labels.insert(criterion_id, public_label))
131    }
132
133    /// Returns the public label, falling back to the identifier.
134    pub fn resolve<'a>(&'a self, criterion_id: &'a str) -> &'a str {
135        self.labels
136            .get(criterion_id)
137            .map(String::as_str)
138            .unwrap_or(criterion_id)
139    }
140
141    /// Number of configured labels.
142    pub fn len(&self) -> usize {
143        self.labels.len()
144    }
145
146    /// Whether no labels are configured.
147    pub fn is_empty(&self) -> bool {
148        self.labels.is_empty()
149    }
150}
151
152/// Generated reason plus disclosure metadata.
153#[derive(Clone, Debug, PartialEq, Eq)]
154pub struct AttendanceReason {
155    decision: AttendanceDecision,
156    text: String,
157    disclosed_criterion_ids: Vec<String>,
158    score_disclosed: bool,
159}
160
161impl AttendanceReason {
162    /// Unchanged source decision.
163    pub const fn decision(&self) -> AttendanceDecision {
164        self.decision
165    }
166
167    /// Generated Japanese explanation.
168    pub fn text(&self) -> &str {
169        &self.text
170    }
171
172    /// Internal identifiers whose labels were included in detailed output.
173    pub fn disclosed_criterion_ids(&self) -> &[String] {
174        &self.disclosed_criterion_ids
175    }
176
177    /// Whether the preference score appears in the text.
178    pub const fn score_disclosed(&self) -> bool {
179        self.score_disclosed
180    }
181}
182
183impl Display for AttendanceReason {
184    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
185        f.write_str(&self.text)
186    }
187}
188
189/// Implements the attendance-reason principle.
190#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
191pub struct AttendanceExcuse;
192
193impl AttendanceExcuse {
194    /// Composes an explanation using internal identifiers as detailed labels.
195    pub fn compose(
196        report: &AttendanceReport,
197        policy: ReasonPolicy,
198    ) -> Result<AttendanceReason, ReasonError> {
199        Self::compose_with_book(report, policy, &ReasonBook::new())
200    }
201
202    /// Composes an explanation using an explicit public-label book.
203    pub fn compose_with_book(
204        report: &AttendanceReport,
205        policy: ReasonPolicy,
206        labels: &ReasonBook,
207    ) -> Result<AttendanceReason, ReasonError> {
208        let mut text = opening(report.decision(), policy.tone()).to_string();
209        let mut disclosed_criterion_ids = Vec::new();
210        let mut score_disclosed = false;
211
212        match policy.disclosure() {
213            Disclosure::Minimal => {}
214            Disclosure::Summary => {
215                append_summary(&mut text, report);
216                if let Some(score) = report.preference_score_basis_points() {
217                    append_score(&mut text, score);
218                    score_disclosed = true;
219                }
220            }
221            Disclosure::Detailed => {
222                append_detailed(
223                    &mut text,
224                    "満たされていない必須条件",
225                    report.blocking_required(),
226                    labels,
227                    &mut disclosed_criterion_ids,
228                );
229                append_detailed(
230                    &mut text,
231                    "確認が必要な必須条件",
232                    report.unknown_required(),
233                    labels,
234                    &mut disclosed_criterion_ids,
235                );
236                append_detailed(
237                    &mut text,
238                    "未確認の希望条件",
239                    report.unknown_preferences(),
240                    labels,
241                    &mut disclosed_criterion_ids,
242                );
243                if let Some(score) = report.preference_score_basis_points() {
244                    append_score(&mut text, score);
245                    score_disclosed = true;
246                }
247            }
248        }
249
250        let actual = text.chars().count();
251        if actual > policy.max_chars() {
252            return Err(ReasonError::TooLong {
253                actual,
254                max: policy.max_chars(),
255            });
256        }
257        Ok(AttendanceReason {
258            decision: report.decision(),
259            text,
260            disclosed_criterion_ids,
261            score_disclosed,
262        })
263    }
264}
265
266fn opening(decision: AttendanceDecision, tone: ReasonTone) -> &'static str {
267    match (decision, tone) {
268        (AttendanceDecision::Attend, ReasonTone::Polite) => {
269            "参加いたします。どうぞよろしくお願いいたします。"
270        }
271        (AttendanceDecision::Conditional, ReasonTone::Polite) => {
272            "条件を調整できれば、参加したいと考えています。"
273        }
274        (AttendanceDecision::Decline, ReasonTone::Polite) => "今回は参加を見送らせていただきます。",
275        (AttendanceDecision::Defer, ReasonTone::Polite) => {
276            "確認事項があるため、参加のお返事を少しお待ちください。"
277        }
278        (AttendanceDecision::Attend, ReasonTone::Direct) => "参加します。",
279        (AttendanceDecision::Conditional, ReasonTone::Direct) => "条件を調整できれば参加します。",
280        (AttendanceDecision::Decline, ReasonTone::Direct) => "今回は参加しません。",
281        (AttendanceDecision::Defer, ReasonTone::Direct) => "確認が済むまで参加判断を保留します。",
282    }
283}
284
285fn append_summary(text: &mut String, report: &AttendanceReport) {
286    if !report.blocking_required().is_empty() {
287        text.push_str(&format!(
288            "満たされていない必須条件が{}件あります。",
289            report.blocking_required().len()
290        ));
291    }
292    if !report.unknown_required().is_empty() {
293        text.push_str(&format!(
294            "確認が必要な必須条件が{}件あります。",
295            report.unknown_required().len()
296        ));
297    }
298    if !report.unknown_preferences().is_empty() {
299        text.push_str(&format!(
300            "未確認の希望条件が{}件あります。",
301            report.unknown_preferences().len()
302        ));
303    }
304}
305
306fn append_detailed(
307    text: &mut String,
308    heading: &str,
309    ids: &[String],
310    labels: &ReasonBook,
311    disclosed: &mut Vec<String>,
312) {
313    if ids.is_empty() {
314        return;
315    }
316    text.push_str(heading);
317    text.push_str(": ");
318    let public_labels: Vec<_> = ids
319        .iter()
320        .map(|id| {
321            disclosed.push(id.clone());
322            labels.resolve(id)
323        })
324        .collect();
325    text.push_str(&public_labels.join("、"));
326    text.push('。');
327}
328
329fn append_score(text: &mut String, basis_points: u16) {
330    let whole = basis_points / 100;
331    let fraction = basis_points % 100;
332    text.push_str(&format!(
333        "既知の希望条件の適合度は{whole}.{fraction:02}%です。"
334    ));
335}
336
337/// Invalid label, output limit, or generated length.
338#[derive(Clone, Debug, PartialEq, Eq)]
339#[non_exhaustive]
340pub enum ReasonError {
341    /// Label-book criterion identifier was empty.
342    EmptyCriterionId,
343    /// Public label was empty.
344    EmptyPublicLabel,
345    /// A zero-character maximum was requested.
346    ZeroMaxChars,
347    /// Generated text exceeded its Unicode character limit.
348    TooLong {
349        /// Actual character count.
350        actual: usize,
351        /// Configured maximum.
352        max: usize,
353    },
354}
355
356impl Display for ReasonError {
357    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
358        match self {
359            Self::EmptyCriterionId => f.write_str("criterion identifier cannot be empty"),
360            Self::EmptyPublicLabel => f.write_str("public criterion label cannot be empty"),
361            Self::ZeroMaxChars => f.write_str("maximum character count must be greater than zero"),
362            Self::TooLong { actual, max } => {
363                write!(
364                    f,
365                    "attendance reason has {actual} characters; maximum is {max}"
366                )
367            }
368        }
369    }
370}
371
372impl Error for ReasonError {}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use decision_attendance::{
378        AttendanceCriterion, AttendancePolicy, DecisionAttendance, Evidence,
379    };
380
381    fn report(criteria: &[AttendanceCriterion]) -> decision_attendance::AttendanceReport {
382        DecisionAttendance::evaluate(criteria, AttendancePolicy::default()).unwrap()
383    }
384
385    #[test]
386    fn minimal_reason_discloses_only_decision() {
387        let source =
388            report(&[
389                AttendanceCriterion::required("private-schedule", Evidence::Opposes).unwrap(),
390            ]);
391        let reason = AttendanceExcuse::compose(&source, ReasonPolicy::default()).unwrap();
392        assert_eq!(reason.decision(), AttendanceDecision::Decline);
393        assert!(!reason.text().contains("private-schedule"));
394        assert!(reason.disclosed_criterion_ids().is_empty());
395        assert!(!reason.score_disclosed());
396    }
397
398    #[test]
399    fn summary_discloses_counts_and_score_without_ids() {
400        let source = report(&[
401            AttendanceCriterion::preference("travel", 3, Evidence::Supports).unwrap(),
402            AttendanceCriterion::preference("cost", 1, Evidence::Opposes).unwrap(),
403            AttendanceCriterion::preference("weather", 1, Evidence::Unknown).unwrap(),
404        ]);
405        let policy = ReasonPolicy::new(Disclosure::Summary, ReasonTone::Direct);
406        let reason = AttendanceExcuse::compose(&source, policy).unwrap();
407        assert!(reason.text().contains("75.00%"));
408        assert!(reason.text().contains("1件"));
409        assert!(!reason.text().contains("weather"));
410        assert!(reason.score_disclosed());
411    }
412
413    #[test]
414    fn detailed_reason_uses_public_labels() {
415        let source =
416            report(&[
417                AttendanceCriterion::required("internal_schedule", Evidence::Unknown).unwrap(),
418            ]);
419        let mut labels = ReasonBook::new();
420        labels.set("internal_schedule", "日程").unwrap();
421        let policy = ReasonPolicy::new(Disclosure::Detailed, ReasonTone::Polite);
422        let reason = AttendanceExcuse::compose_with_book(&source, policy, &labels).unwrap();
423        assert!(reason.text().contains("日程"));
424        assert!(!reason.text().contains("internal_schedule"));
425        assert_eq!(reason.disclosed_criterion_ids(), ["internal_schedule"]);
426    }
427
428    #[test]
429    fn decision_is_never_changed_by_tone_or_disclosure() {
430        let source =
431            report(&[AttendanceCriterion::preference("interest", 1, Evidence::Supports).unwrap()]);
432        for disclosure in [
433            Disclosure::Minimal,
434            Disclosure::Summary,
435            Disclosure::Detailed,
436        ] {
437            for tone in [ReasonTone::Polite, ReasonTone::Direct] {
438                let reason =
439                    AttendanceExcuse::compose(&source, ReasonPolicy::new(disclosure, tone))
440                        .unwrap();
441                assert_eq!(reason.decision(), source.decision());
442            }
443        }
444    }
445
446    #[test]
447    fn all_decisions_have_distinct_openings() {
448        let attend = report(&[AttendanceCriterion::required("r", Evidence::Supports).unwrap()]);
449        let conditional = report(&[
450            AttendanceCriterion::preference("yes", 1, Evidence::Supports).unwrap(),
451            AttendanceCriterion::preference("no", 1, Evidence::Opposes).unwrap(),
452        ]);
453        let decline = report(&[AttendanceCriterion::required("r", Evidence::Opposes).unwrap()]);
454        let defer = report(&[AttendanceCriterion::required("r", Evidence::Unknown).unwrap()]);
455        let texts: Vec<_> = [&attend, &conditional, &decline, &defer]
456            .into_iter()
457            .map(|source| {
458                AttendanceExcuse::compose(
459                    source,
460                    ReasonPolicy::new(Disclosure::Minimal, ReasonTone::Direct),
461                )
462                .unwrap()
463                .text
464            })
465            .collect();
466        let unique: std::collections::BTreeSet<_> = texts.iter().collect();
467        assert_eq!(unique.len(), 4);
468    }
469
470    #[test]
471    fn generation_is_deterministic() {
472        let source = report(&[
473            AttendanceCriterion::required("z", Evidence::Unknown).unwrap(),
474            AttendanceCriterion::required("a", Evidence::Unknown).unwrap(),
475        ]);
476        let policy = ReasonPolicy::new(Disclosure::Detailed, ReasonTone::Polite);
477        assert_eq!(
478            AttendanceExcuse::compose(&source, policy).unwrap(),
479            AttendanceExcuse::compose(&source, policy).unwrap()
480        );
481    }
482
483    #[test]
484    fn invalid_labels_and_length_are_rejected() {
485        let mut labels = ReasonBook::new();
486        assert_eq!(
487            labels.set("", "label").unwrap_err(),
488            ReasonError::EmptyCriterionId
489        );
490        assert_eq!(
491            labels.set("id", " ").unwrap_err(),
492            ReasonError::EmptyPublicLabel
493        );
494        assert_eq!(
495            ReasonPolicy::default().with_max_chars(0).unwrap_err(),
496            ReasonError::ZeroMaxChars
497        );
498        let source = report(&[AttendanceCriterion::required("r", Evidence::Supports).unwrap()]);
499        let policy = ReasonPolicy::default().with_max_chars(1).unwrap();
500        assert!(matches!(
501            AttendanceExcuse::compose(&source, policy),
502            Err(ReasonError::TooLong { max: 1, .. })
503        ));
504    }
505}