//! What the main window shows about calls: the rows of the call list and //! the detail of the selected call, shaped from the stored data. use std::collections::BTreeMap; use chrono::{DateTime, Local}; use serde::Serialize; use crate::corrections::correct_segment_text; use crate::merge; use crate::model::{Call, CallId, CallStatus, Segment, Speaker}; /// A row of the call list. #[derive(Serialize, Clone, Debug, PartialEq)] pub struct CallListItem { pub id: CallId, pub app: String, pub started_at: DateTime, /// Whole seconds from start to end; 0 while recording. pub duration_secs: i64, pub status: CallStatus, /// What the status pill shows and whether the row needs the user's /// attention — see [`ListState`]. Computed from `status` and /// [`uploaded_here`] so the UI does not re-implement the rule. pub list_state: ListState, /// Whether this row needs the user to act on it (the dot in /// `CallList.svelte` and the sidebar header's "N offen" count). Equal /// to `list_state.needs_action()`, kept as its own field so the UI /// does not need to know `ListState`'s variants to filter by it. pub needs_action: bool, pub interrupted: bool, /// The name the user gave the call, if any. pub title: Option, /// The id the CRM gave the transcript at its last upload. pub crm_transcript_id: Option, /// When the transcript was last uploaded. pub uploaded_at: Option>, } impl CallListItem { /// `backend_url` is this build's backend (`crate::backend::BACKEND_URL` /// in the app): an upload recorded for a different one is shown as not /// uploaded at all ([`uploaded_here`]) — e.g. a transcript sent to the /// test backend must not look done to a release build reading the same /// row. Nothing is deleted; the fields are just not shown as set. pub fn of(call: &Call, backend_url: &str) -> Self { let uploaded = uploaded_here(call, backend_url); let list_state = ListState::of(call.status, uploaded); Self { id: call.id, app: call.app.clone(), started_at: call.started_at, duration_secs: duration_secs(call), status: call.status, list_state, needs_action: list_state.needs_action(), interrupted: call.interrupted, title: call.title.clone(), crm_transcript_id: if uploaded { call.crm_transcript_id.clone() } else { None }, uploaded_at: if uploaded { call.uploaded_at } else { None }, } } } /// What the call list row (and the detail header's pill) shows about a /// call's status. Mirrors [`CallStatus`] one-to-one, except that `Done` /// splits in two: a call is only ever shown as done ("fertig") once its /// transcript has actually reached *this build's* backend ([`uploaded_here`]); /// otherwise — never uploaded, or uploaded to a different backend — it is /// `ReadyToUpload` ("bereit zum Hochladen"), because from this build's /// point of view the CRM has not seen it yet. #[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ListState { Recording, AwaitingDecision, Processing, Failed, Done, ReadyToUpload, } impl ListState { fn of(status: CallStatus, uploaded_here: bool) -> Self { match status { CallStatus::Recording => ListState::Recording, CallStatus::AwaitingDecision => ListState::AwaitingDecision, CallStatus::Processing => ListState::Processing, CallStatus::Failed => ListState::Failed, CallStatus::Done if uploaded_here => ListState::Done, CallStatus::Done => ListState::ReadyToUpload, } } /// Whether a row in this state needs the user to act on it: not yet /// transcribed, or transcribed but not uploaded here. Excludes /// `Failed` (already shown in red) and the transient /// `Recording`/`Processing` states. pub fn needs_action(self) -> bool { matches!(self, ListState::AwaitingDecision | ListState::ReadyToUpload) } } /// Whole seconds from `started_at` to `ended_at`; 0 while the call has not /// ended (and never negative). pub fn duration_secs(call: &Call) -> i64 { call.ended_at .map_or(0, |end| (end - call.started_at).num_seconds().max(0)) } /// Whether `call`'s upload belongs to `backend_url`: its /// `crm_transcript_id` is set *and* `crm_base_url` is exactly this /// backend. An upload recorded for a different one (e.g. the test backend, /// read by a release build) counts as not uploaded: the CRM this /// `backend_url` talks to has never seen the transcript, so the UI offers /// the normal upload control again instead of claiming it is done. pub fn uploaded_here(call: &Call, backend_url: &str) -> bool { call.crm_transcript_id.is_some() && call.crm_base_url.as_deref() == Some(backend_url) } /// The selected call's header data: its list row plus the error of a /// failed run and when it was transcribed (only a transcribed call can be /// uploaded). #[derive(Serialize, Clone, Debug, PartialEq)] pub struct CallHeader { #[serde(flatten)] pub item: CallListItem, pub error: Option, pub transcribed_at: Option>, } /// A transcript line with the speaker's display label. #[derive(Serialize, Clone, Debug, PartialEq)] pub struct SegmentView { /// [`crate::model::Speaker::key`], stable across renames. pub speaker_key: String, pub label: String, pub start: f64, pub end: f64, pub text: String, } /// A merged speaker: "Sprecher 2 → Frau Beispiel zusammengeführt". #[derive(Serialize, Clone, Debug, PartialEq)] pub struct MergeView { pub from_key: String, /// The source's default label: its own rename is not in effect while /// it is merged. pub from_label: String, /// The speaker the source's lines now belong to (the end of a chain of /// merges). pub into_key: String, pub into_label: String, } /// Everything the detail pane shows about one call. #[derive(Serialize, Clone, Debug, PartialEq)] pub struct CallDetail { pub call: CallHeader, /// The transcript with speaker merges applied /// ([`merge::apply_merges`]). pub segments: Vec, /// Renamed speakers by key; speakers not in here keep their default /// label. pub speaker_names: BTreeMap, /// The call's speaker merges, by source speaker number. pub merges: Vec, /// Whether the transcript is being uploaded right now. Set by the app, /// which tracks its uploads; `false` from [`CallDetail::of`]. pub uploading: bool, /// Whether the call's audio is still on disk to be played /// ([`crate::playback::audio_available`]). Set by the app; `false` from /// [`CallDetail::of`], which does not look at the files. pub audio_available: bool, /// Whether retention deleted the call's audio (as opposed to the files /// being missing for another reason). pub audio_deleted: bool, } impl CallDetail { /// `segments` are the stored ones; `merges` the stored speaker merges /// (source key → target key); `backend_url` is this build's backend /// (see [`CallListItem::of`]); `language` is the call-language setting /// in effect now (not necessarily what the call was transcribed with), /// used to apply [`correct_segment_text`] to each segment's text — /// non-destructively, so it also corrects transcripts from before the /// correction existed. pub fn of( call: &Call, segments: &[Segment], speaker_names: BTreeMap, merges: &BTreeMap, backend_url: &str, language: &str, ) -> Self { let segments = merge::apply_merges(segments, merges) .iter() .map(|segment| SegmentView { speaker_key: segment.speaker.key(), label: merge::label(&segment.speaker, &speaker_names), start: segment.start, end: segment.end, text: correct_segment_text(&segment.text, language), }) .collect(); Self { call: CallHeader { item: CallListItem::of(call, backend_url), error: call.error.clone(), transcribed_at: call.transcribed_at, }, segments, merges: merge_views(merges, &speaker_names), uploading: false, audio_available: false, audio_deleted: call.audio_deleted, speaker_names, } } } impl CallDetail { /// The transcript as plain text for the CRM, as the user sees it /// (speaker merges and renames applied): a header with title, date, /// call app and duration, a blank line, then one `[mm:ss] Name: text` /// line per segment (`h:mm:ss` from one hour on). Blank segments are /// left out; with none left, the error is [`NO_TRANSCRIPT`]. pub fn upload_text(&self) -> Result { let lines: Vec = self .segments .iter() .filter(|segment| !segment.text.trim().is_empty()) .map(|segment| { format!( "[{}] {}: {}", offset(segment.start), segment.label, segment.text.trim() ) }) .collect(); if lines.is_empty() { return Err(NO_TRANSCRIPT.to_string()); } let item = &self.call.item; let date = item.started_at.format("%d.%m.%Y %H:%M").to_string(); let title = match &item.title { Some(title) => title.clone(), None => format!("{} · {date}", item.app), }; let minutes = ((item.duration_secs as f64 / 60.0).round() as i64).max(1); let header = [ format!("Titel: {title}"), format!("Datum: {date}"), format!("Kanal: {}", item.app), format!("Dauer: {minutes} min"), String::new(), ]; Ok(header .into_iter() .chain(lines) .collect::>() .join("\n")) } } /// Why [`CallDetail::upload_text`] has nothing to upload. pub const NO_TRANSCRIPT: &str = "Kein Transkript zum Hochladen"; /// Position in the recording: "04:07", or "1:02:07" from one hour on (like /// the transcript view). fn offset(secs: f64) -> String { let total = if secs.is_finite() && secs > 0.0 { secs as u64 } else { 0 }; let (h, m, s) = (total / 3600, total % 3600 / 60, total % 60); if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m:02}:{s:02}") } } fn merge_views( merges: &BTreeMap, speaker_names: &BTreeMap, ) -> Vec { let mut views: Vec<(u32, MergeView)> = merge::resolve_merges(merges) .into_iter() .filter_map(|(from_key, into_key)| { let (Some(Speaker::Remote(n)), Some(into)) = (Speaker::from_key(&from_key), Speaker::from_key(&into_key)) else { return None; }; let view = MergeView { from_label: Speaker::Remote(n).default_label(), into_label: merge::label(&into, speaker_names), from_key, into_key, }; Some((n, view)) }) .collect(); views.sort_by_key(|(n, _)| *n); views.into_iter().map(|(_, view)| view).collect() } #[cfg(test)] mod tests { use std::path::PathBuf; use chrono::TimeZone; use serde_json::json; use super::*; use crate::model::Speaker; /// This build's backend, for `CallListItem::of`/`CallDetail::of`. const BACKEND: &str = "https://backend.example"; /// A different backend, for the "uploaded elsewhere" cases. const OTHER_BACKEND: &str = "https://other.example"; fn at(h: u32, m: u32, s: u32) -> DateTime { Local.with_ymd_and_hms(2026, 11, 5, h, m, s).unwrap() } fn call(ended_at: Option>) -> Call { Call { id: 7, app: "Microsoft Teams".into(), started_at: at(10, 14, 0), ended_at, status: CallStatus::Done, interrupted: false, error: None, mic_path: PathBuf::from("7-mic.wav"), out_path: PathBuf::from("7-out.wav"), transcribed_at: None, audio_deleted: false, title: None, crm_transcript_id: None, crm_base_url: None, uploaded_at: None, } } fn segment(speaker: Speaker, start: f64, text: &str) -> Segment { Segment { speaker, start, end: start + 2.0, text: text.into(), } } #[test] fn duration_runs_from_start_to_end() { assert_eq!(duration_secs(&call(Some(at(10, 46, 30)))), 32 * 60 + 30); } #[test] fn duration_is_zero_while_recording_and_never_negative() { assert_eq!(duration_secs(&call(None)), 0); assert_eq!(duration_secs(&call(Some(at(10, 13, 0)))), 0); } #[test] fn list_item_carries_the_row_fields() { let mut c = call(Some(at(10, 15, 0))); c.status = CallStatus::AwaitingDecision; c.interrupted = true; assert_eq!( CallListItem::of(&c, BACKEND), CallListItem { id: 7, app: "Microsoft Teams".into(), started_at: at(10, 14, 0), duration_secs: 60, status: CallStatus::AwaitingDecision, list_state: ListState::AwaitingDecision, needs_action: true, interrupted: true, title: None, crm_transcript_id: None, uploaded_at: None, } ); c.title = Some("Angebot Rioja".into()); c.crm_transcript_id = Some("4711".into()); c.crm_base_url = Some(BACKEND.into()); c.uploaded_at = Some(at(11, 0, 0)); let item = CallListItem::of(&c, BACKEND); assert_eq!(item.title.as_deref(), Some("Angebot Rioja")); assert_eq!(item.crm_transcript_id.as_deref(), Some("4711")); assert_eq!(item.uploaded_at, Some(at(11, 0, 0))); } #[test] fn uploaded_here_needs_a_transcript_id_and_a_matching_backend() { let mut c = call(Some(at(10, 15, 0))); assert!(!uploaded_here(&c, BACKEND), "never uploaded"); c.crm_transcript_id = Some("4711".into()); c.crm_base_url = Some(OTHER_BACKEND.into()); assert!( !uploaded_here(&c, BACKEND), "uploaded, but to a different backend" ); c.crm_base_url = Some(BACKEND.into()); assert!(uploaded_here(&c, BACKEND)); } #[test] fn done_is_fertig_only_once_uploaded_to_this_backend() { let mut c = call(Some(at(10, 15, 0))); c.status = CallStatus::Done; // Never uploaded. assert_eq!( CallListItem::of(&c, BACKEND).list_state, ListState::ReadyToUpload ); // Uploaded, but to a different backend. c.crm_transcript_id = Some("4711".into()); c.crm_base_url = Some(OTHER_BACKEND.into()); assert_eq!( CallListItem::of(&c, BACKEND).list_state, ListState::ReadyToUpload ); // Uploaded to this build's backend. c.crm_base_url = Some(BACKEND.into()); assert_eq!(CallListItem::of(&c, BACKEND).list_state, ListState::Done); } #[test] fn needs_action_marks_awaiting_and_ready_to_upload_only() { let mut c = call(Some(at(10, 15, 0))); c.status = CallStatus::AwaitingDecision; assert!(CallListItem::of(&c, BACKEND).needs_action, "awaiting"); c.status = CallStatus::Done; assert!( CallListItem::of(&c, BACKEND).needs_action, "done, never uploaded" ); for status in [ CallStatus::Processing, CallStatus::Failed, CallStatus::Recording, ] { c.status = status; assert!( !CallListItem::of(&c, BACKEND).needs_action, "{status:?} must not show the dot" ); } c.status = CallStatus::Done; c.crm_transcript_id = Some("4711".into()); c.crm_base_url = Some(BACKEND.into()); assert!( !CallListItem::of(&c, BACKEND).needs_action, "done and uploaded here" ); } #[test] fn an_upload_to_another_backend_is_hidden_from_the_list_item() { // Uploaded to OTHER_BACKEND; this build's backend is BACKEND: the // row still has crm_transcript_id/uploaded_at, but the view must // not show them, so the UI offers the normal upload control again. let mut c = call(Some(at(10, 15, 0))); c.crm_transcript_id = Some("4711".into()); c.crm_base_url = Some(OTHER_BACKEND.into()); c.uploaded_at = Some(at(11, 0, 0)); let item = CallListItem::of(&c, BACKEND); assert_eq!(item.crm_transcript_id, None); assert_eq!(item.uploaded_at, None); // The same row, read by a build whose backend actually matches: // shown normally. let item = CallListItem::of(&c, OTHER_BACKEND); assert_eq!(item.crm_transcript_id.as_deref(), Some("4711")); assert_eq!(item.uploaded_at, Some(at(11, 0, 0))); } #[test] fn detail_labels_segments_with_renames_and_defaults() { let segments = [ segment(Speaker::Me, 0.0, "Guten Tag."), segment(Speaker::Remote(1), 2.5, "Hallo."), segment(Speaker::Remote(2), 5.0, "Moin."), ]; let mut names = BTreeMap::new(); names.insert("remote:1".to_string(), "Frau Beispiel".to_string()); names.insert("remote:2".to_string(), " ".to_string()); let detail = CallDetail::of( &call(Some(at(10, 15, 0))), &segments, names.clone(), &BTreeMap::new(), BACKEND, "de", ); let lines: Vec<_> = detail .segments .iter() .map(|s| (s.speaker_key.as_str(), s.label.as_str(), s.text.as_str())) .collect(); assert_eq!( lines, [ ("me", "Ich", "Guten Tag."), ("remote:1", "Frau Beispiel", "Hallo."), ("remote:2", "Sprecher 2", "Moin."), ] ); assert_eq!(detail.segments[1].start, 2.5); assert_eq!(detail.segments[1].end, 4.5); assert_eq!(detail.speaker_names, names); assert_eq!(detail.merges, []); } fn keys(pairs: &[(&str, &str)]) -> BTreeMap { pairs .iter() .map(|(a, b)| (a.to_string(), b.to_string())) .collect() } #[test] fn detail_shows_merged_speakers_under_their_target() { let segments = [ segment(Speaker::Remote(1), 0.0, "Guten Tag,"), segment(Speaker::Remote(2), 2.5, "hier Weingut Beispiel."), segment(Speaker::Me, 5.0, "Hallo."), segment(Speaker::Remote(3), 7.5, "Zur Lieferung:"), segment(Speaker::Remote(4), 10.0, "Moin."), ]; let names = keys(&[("remote:1", "Frau Beispiel"), ("remote:2", "Herr Probe")]); let merges = keys(&[ ("remote:3", "remote:2"), ("remote:2", "remote:1"), ("remote:10", "remote:4"), ]); let detail = CallDetail::of( &call(Some(at(10, 15, 0))), &segments, names, &merges, BACKEND, "de", ); let lines: Vec<_> = detail .segments .iter() .map(|s| (s.speaker_key.as_str(), s.label.as_str(), s.text.as_str())) .collect(); assert_eq!( lines, [ ( "remote:1", "Frau Beispiel", "Guten Tag, hier Weingut Beispiel." ), ("me", "Ich", "Hallo."), ("remote:1", "Frau Beispiel", "Zur Lieferung:"), ("remote:4", "Sprecher 4", "Moin."), ] ); let merge_lines: Vec<_> = detail .merges .iter() .map(|m| { ( m.from_key.as_str(), m.from_label.as_str(), m.into_key.as_str(), m.into_label.as_str(), ) }) .collect(); assert_eq!( merge_lines, [ ("remote:2", "Sprecher 2", "remote:1", "Frau Beispiel"), ("remote:3", "Sprecher 3", "remote:1", "Frau Beispiel"), ("remote:10", "Sprecher 10", "remote:4", "Sprecher 4"), ] ); } #[test] fn detail_serializes_the_call_header_flat() { let mut c = call(Some(at(10, 15, 0))); c.status = CallStatus::Failed; c.error = Some("Netzwerkfehler".into()); c.title = Some("Reklamation".into()); c.transcribed_at = Some(at(10, 20, 0)); let merges = keys(&[("remote:2", "remote:1")]); let value = serde_json::to_value(CallDetail::of( &c, &[], BTreeMap::new(), &merges, BACKEND, "de", )) .unwrap(); assert_eq!( value, json!({ "call": { "id": 7, "app": "Microsoft Teams", "started_at": serde_json::to_value(at(10, 14, 0)).unwrap(), "duration_secs": 60, "status": "failed", "list_state": "failed", "needs_action": false, "interrupted": false, "title": "Reklamation", "crm_transcript_id": null, "uploaded_at": null, "error": "Netzwerkfehler", "transcribed_at": serde_json::to_value(at(10, 20, 0)).unwrap(), }, "segments": [], "speaker_names": {}, "merges": [{ "from_key": "remote:2", "from_label": "Sprecher 2", "into_key": "remote:1", "into_label": "Sprecher 1", }], "uploading": false, "audio_available": false, "audio_deleted": false, }) ); } fn detail_with(c: &Call, segments: &[Segment], names: &[(&str, &str)]) -> CallDetail { detail_with_language(c, segments, names, "de") } fn detail_with_language( c: &Call, segments: &[Segment], names: &[(&str, &str)], language: &str, ) -> CallDetail { CallDetail::of( c, segments, keys(names), &keys(&[("remote:2", "remote:1")]), BACKEND, language, ) } #[test] fn the_upload_text_has_a_header_and_the_lines_the_user_sees() { let segments = [ segment(Speaker::Remote(1), 0.0, "Guten Tag,"), segment(Speaker::Remote(2), 2.5, "hier Weingut Beispiel."), segment(Speaker::Me, 65.9, "Hallo."), segment(Speaker::Remote(3), 600.0, " "), segment(Speaker::Remote(1), 3725.0, "Zur Lieferung."), ]; let c = call(Some(at(10, 46, 0))); let text = detail_with(&c, &segments, &[("remote:1", "Frau Beispiel")]).upload_text(); assert_eq!( text.as_deref(), Ok("Titel: Microsoft Teams · 05.11.2026 10:14\n\ Datum: 05.11.2026 10:14\n\ Kanal: Microsoft Teams\n\ Dauer: 32 min\n\ \n\ [00:00] Frau Beispiel: Guten Tag, hier Weingut Beispiel.\n\ [01:05] Ich: Hallo.\n\ [1:02:05] Frau Beispiel: Zur Lieferung.") ); } #[test] fn the_upload_text_uses_the_title_and_at_least_one_minute() { let mut c = call(Some(at(10, 14, 10))); c.title = Some("Angebot Rioja".into()); let text = detail_with(&c, &[segment(Speaker::Me, 0.0, "Hallo.")], &[]) .upload_text() .unwrap(); let header: Vec<_> = text.lines().take(4).collect(); assert_eq!( header, [ "Titel: Angebot Rioja", "Datum: 05.11.2026 10:14", "Kanal: Microsoft Teams", "Dauer: 1 min", ] ); } #[test] fn an_empty_transcript_is_not_uploaded() { let c = call(Some(at(10, 46, 0))); for segments in [vec![], vec![segment(Speaker::Me, 0.0, " ")]] { assert_eq!( detail_with(&c, &segments, &[]).upload_text(), Err(NO_TRANSCRIPT.to_string()) ); } assert_eq!(NO_TRANSCRIPT, "Kein Transkript zum Hochladen"); } #[test] fn a_whole_segment_mistranscribed_as_english_is_corrected_in_the_detail_view() { let c = call(Some(at(10, 15, 0))); let segments = [ segment(Speaker::Me, 0.0, "Cheers!"), segment(Speaker::Remote(3), 3.0, "Perfect."), segment(Speaker::Remote(1), 6.0, "Cheers, see you later."), ]; let detail = detail_with(&c, &segments, &[]); let texts: Vec<_> = detail.segments.iter().map(|s| s.text.as_str()).collect(); assert_eq!(texts, ["Tschüss!", "Perfekt.", "Cheers, see you later."]); } #[test] fn corrections_are_not_applied_outside_german_calls() { let c = call(Some(at(10, 15, 0))); let segments = [segment(Speaker::Me, 0.0, "Cheers!")]; let detail = detail_with_language(&c, &segments, &[], "en"); assert_eq!(detail.segments[0].text, "Cheers!"); } #[test] fn the_upload_text_uses_the_corrected_segment_text() { let c = call(Some(at(10, 46, 0))); let segments = [segment(Speaker::Me, 0.0, "Cheers!")]; let text = detail_with(&c, &segments, &[]).upload_text().unwrap(); assert!(text.ends_with("Ich: Tschüss!"), "upload text was: {text}"); } }