1use crate::actor::Actor;
32use crate::date::DateTimeField;
33use crate::footnotes;
34use crate::yaml::Value;
35use std::fmt;
36
37#[derive(Clone, Debug, Default, PartialEq, Eq)]
42pub struct UsageWindow {
43 pub from: Option<DateTimeField>,
45 pub to: Option<DateTimeField>,
47}
48
49impl UsageWindow {
50 pub fn from_value(value: &Value) -> Option<Self> {
53 let map = value.as_mapping()?;
54 Some(Self {
55 from: map
56 .get("from")
57 .and_then(Value::as_display_string)
58 .map(DateTimeField::new),
59 to: map
60 .get("to")
61 .and_then(Value::as_display_string)
62 .map(DateTimeField::new),
63 })
64 }
65}
66
67impl fmt::Display for UsageWindow {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 let dash = |d: &Option<DateTimeField>| {
70 d.as_ref()
71 .map_or_else(|| "?".to_string(), |d| d.raw.clone())
72 };
73 write!(f, "{} to {}", dash(&self.from), dash(&self.to))
74 }
75}
76
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub enum ResourceKind {
80 Url,
82 Path,
84 Scope,
87 Missing,
90}
91
92#[derive(Clone, Debug, Default, PartialEq, Eq)]
94pub struct Source {
95 pub id: Option<String>,
98 pub resource: Option<String>,
100 pub title: Option<String>,
102 pub author: Option<Actor>,
105 pub usage_count: Option<i64>,
108 pub last_modified: Option<DateTimeField>,
111 pub usage_window: Option<UsageWindow>,
113}
114
115impl Source {
116 pub fn from_value(value: &Value) -> Option<Self> {
119 let map = value.as_mapping()?;
120 let string = |k: &str| map.get(k).and_then(Value::as_display_string);
121 Some(Self {
122 id: string("id"),
123 resource: string("resource"),
124 title: string("title"),
125 author: string("author").map(Actor::parse),
126 usage_count: map.get("usage_count").and_then(Value::as_int),
127 last_modified: string("last_modified").map(DateTimeField::new),
128 usage_window: map.get("usage_window").and_then(UsageWindow::from_value),
129 })
130 }
131
132 pub fn list_from_value(value: &Value) -> Vec<Self> {
137 match value {
138 Value::Sequence(items) => items.iter().filter_map(Self::from_value).collect(),
139 Value::Mapping(_) => Self::from_value(value).into_iter().collect(),
140 _ => Vec::new(),
141 }
142 }
143
144 pub fn resource_kind(&self) -> ResourceKind {
152 match self.resource.as_deref().map(str::trim) {
153 None | Some("") => ResourceKind::Missing,
154 Some(r) if r.contains("://") || r.starts_with("mailto:") => ResourceKind::Url,
155 Some(r) if r.chars().any(char::is_whitespace) => ResourceKind::Scope,
156 Some(_) => ResourceKind::Path,
157 }
158 }
159
160 #[must_use]
163 pub fn effective_usage_window<'a>(
164 &'a self,
165 shared: Option<&'a UsageWindow>,
166 ) -> Option<&'a UsageWindow> {
167 self.usage_window.as_ref().or(shared)
168 }
169
170 #[must_use]
172 pub fn label(&self) -> &str {
173 self.title
174 .as_deref()
175 .or(self.resource.as_deref())
176 .or(self.id.as_deref())
177 .unwrap_or("(unnamed source)")
178 }
179}
180
181impl fmt::Display for Source {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 match &self.id {
184 Some(id) => write!(f, "[{id}] {}", self.label()),
185 None => f.write_str(self.label()),
186 }
187 }
188}
189
190#[derive(Clone, Debug, PartialEq, Eq)]
193pub struct Attribution {
194 pub label: String,
196 pub source: Option<Source>,
198 pub references: usize,
200 pub definitions: usize,
202}
203
204impl Attribution {
205 #[must_use]
207 pub const fn is_resolved(&self) -> bool {
208 self.source.is_some()
209 }
210}
211
212#[must_use]
220pub fn attributions(sources: &[Source], body: &str) -> Vec<Attribution> {
221 let refs = footnotes::extract_refs(body);
222 let defs = footnotes::extract_definitions(body);
223
224 let mut order: Vec<String> = Vec::new();
225 let push = |label: &str, order: &mut Vec<String>| {
226 if !order.iter().any(|l| l == label) {
227 order.push(label.to_string());
228 }
229 };
230 for r in &refs {
231 push(&r.label, &mut order);
232 }
233 for d in &defs {
234 push(&d.label, &mut order);
235 }
236
237 order
238 .into_iter()
239 .map(|label| Attribution {
240 references: refs.iter().filter(|r| r.label == label).count(),
241 definitions: defs.iter().filter(|d| d.label == label).count(),
242 source: sources
243 .iter()
244 .find(|s| s.id.as_deref() == Some(label.as_str()))
245 .cloned(),
246 label,
247 })
248 .collect()
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254 use crate::date::Date;
255
256 const SOURCES: &str = "\
257- id: rev-policy
258 resource: https://wiki.acme/finance/revenue-recognition
259 title: Revenue recognition policy
260 author: team:finance-fpa
261 last_modified: 2026-04-02T00:00:00Z
262- id: exec-rev-dash
263 resource: dashboards/exec-revenue
264 title: Executive revenue dashboard
265 author: team:finance-fpa
266 usage_count: 5000
267 last_modified: 2026-06-18T00:00:00Z
268";
269
270 fn sources() -> Vec<Source> {
271 Source::list_from_value(&Value::parse(SOURCES).unwrap())
272 }
273
274 #[test]
275 fn reads_entries_and_credibility_signals() {
276 let s = sources();
277 assert_eq!(s.len(), 2);
278 assert_eq!(s[0].id.as_deref(), Some("rev-policy"));
279 assert_eq!(s[0].resource_kind(), ResourceKind::Url);
280 assert_eq!(s[0].author.as_ref().unwrap().as_str(), "team:finance-fpa");
281 assert_eq!(
282 s[0].last_modified.as_ref().unwrap().datetime.unwrap().date,
283 Date::new(2026, 4, 2).unwrap()
284 );
285 assert_eq!(s[0].usage_count, None);
286
287 assert_eq!(s[1].usage_count, Some(5000));
288 assert_eq!(s[1].resource_kind(), ResourceKind::Path);
289 assert_eq!(s[1].label(), "Executive revenue dashboard");
290 }
291
292 #[test]
293 fn scope_descriptors_are_not_paths() {
294 let s = Source::from_value(
295 &Value::parse("{ resource: all queries in BigQuery project X }").unwrap(),
296 )
297 .unwrap();
298 assert_eq!(s.resource_kind(), ResourceKind::Scope);
299
300 let missing = Source::from_value(&Value::parse("{ id: x }").unwrap()).unwrap();
301 assert_eq!(missing.resource_kind(), ResourceKind::Missing);
302 }
303
304 #[test]
305 fn usage_window_entry_overrides_shared() {
306 let shared = UsageWindow::from_value(
307 &Value::parse("{ from: 2026-06-01T00:00:00Z, to: 2026-06-30T00:00:00Z }").unwrap(),
308 )
309 .unwrap();
310 let plain = &sources()[1];
311 assert_eq!(plain.effective_usage_window(Some(&shared)), Some(&shared));
312
313 let overridden = Source::from_value(
314 &Value::parse(
315 "{ resource: x, usage_window: { from: 2026-01-01T00:00:00Z, to: 2026-01-31T00:00:00Z } }",
316 )
317 .unwrap(),
318 )
319 .unwrap();
320 let window = overridden.effective_usage_window(Some(&shared)).unwrap();
321 assert_eq!(window.from.as_ref().unwrap().raw, "2026-01-01T00:00:00Z");
322 }
323
324 #[test]
325 fn attribution_joins_footnote_labels_to_source_ids() {
326 let body = "Per the recognition policy,[^rev-policy] corroborated by the \
327 dashboard.[^exec-rev-dash] And once more.[^rev-policy]\n\n\
328 [^rev-policy]: Revenue recognition policy\n\
329 [^exec-rev-dash]: Executive revenue dashboard\n\
330 [^ghost]: Not in sources\n";
331 let attributions = attributions(&sources(), body);
332 assert_eq!(attributions.len(), 3);
333
334 assert_eq!(attributions[0].label, "rev-policy");
335 assert_eq!(attributions[0].references, 2);
336 assert_eq!(attributions[0].definitions, 1);
337 assert!(attributions[0].is_resolved());
338 assert_eq!(
339 attributions[0].source.as_ref().unwrap().title.as_deref(),
340 Some("Revenue recognition policy")
341 );
342
343 assert_eq!(attributions[2].label, "ghost");
345 assert_eq!(attributions[2].references, 0);
346 assert!(!attributions[2].is_resolved());
347 }
348
349 #[test]
350 fn reordering_sources_does_not_change_attribution() {
351 let body = "Claim.[^exec-rev-dash]\n\n[^exec-rev-dash]: Executive revenue dashboard\n";
352 let mut reversed = sources();
353 reversed.reverse();
354 let a = attributions(&sources(), body);
355 let b = attributions(&reversed, body);
356 assert_eq!(a, b);
357 assert_eq!(
358 a[0].source.as_ref().unwrap().id.as_deref(),
359 Some("exec-rev-dash")
360 );
361 }
362}