BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / activity / feed.rs

feed.rs

feed.rs 25.5 KiB Download Raw
1use std::collections::BTreeSet;
2
3use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
4use serde::{Deserialize, Serialize};
5use store::ActivityRecord;
6
7use crate::notify::Incoming;
8use crate::reaction_model::tooltip_text;
9
10pub const RETENTION_DAYS: i64 = 14;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Kind {
14 Messages,
15 Mention,
16 Reaction,
17}
18
19impl Kind {
20 fn key(self) -> &'static str {
21 match self {
22 Kind::Messages => "messages",
23 Kind::Mention => "mention",
24 Kind::Reaction => "reaction",
25 }
26 }
27
28 fn from_key(key: &str) -> Option<Kind> {
29 [Kind::Messages, Kind::Mention, Kind::Reaction]
30 .into_iter()
31 .find(|kind| kind.key() == key)
32 }
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum Filter {
37 #[default]
38 All,
39 Mentions,
40 Unread,
41}
42
43impl Filter {
44 pub const ALL: [Filter; 3] = [Filter::All, Filter::Mentions, Filter::Unread];
45
46 pub fn label(self) -> &'static str {
47 match self {
48 Filter::All => "All",
49 Filter::Mentions => "@Mentions",
50 Filter::Unread => "Unread",
51 }
52 }
53
54 pub fn empty_label(self) -> &'static str {
55 match self {
56 Filter::All => "No activity yet",
57 Filter::Mentions => "No mentions",
58 Filter::Unread => "Nothing unread",
59 }
60 }
61
62 fn admits(self, entry: &Entry) -> bool {
63 match self {
64 Filter::All => true,
65 Filter::Mentions => entry.kind == Kind::Mention,
66 Filter::Unread => !entry.read,
67 }
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum Bucket {
73 Today,
74 Yesterday,
75 Earlier,
76}
77
78impl Bucket {
79 pub fn of(time: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> Bucket {
80 let days_ago = (today - time.with_timezone(&offset).date_naive()).num_days();
81 match days_ago {
82 ..=0 => Bucket::Today,
83 1 => Bucket::Yesterday,
84 _ => Bucket::Earlier,
85 }
86 }
87
88 pub fn label(self) -> &'static str {
89 match self {
90 Bucket::Today => "Today",
91 Bucket::Yesterday => "Yesterday",
92 Bucket::Earlier => "Earlier",
93 }
94 }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct Actor {
99 pub user_id: Option<String>,
100 pub name: String,
101}
102
103#[derive(Debug, Clone, PartialEq)]
104pub struct Entry {
105 pub id: i64,
106 pub conversation_id: String,
107 pub kind: Kind,
108 pub message_id: String,
109 pub actors: Vec<Actor>,
110 pub preview: String,
111 pub glyphs: Vec<String>,
112 pub count: u32,
113 pub updated_at: DateTime<Utc>,
114 pub read: bool,
115}
116
117impl Entry {
118 pub fn names(&self) -> String {
119 let names: Vec<&str> = self
120 .actors
121 .iter()
122 .map(|actor| actor.name.as_str())
123 .collect();
124 tooltip_text(&names)
125 }
126
127 pub fn latest_actor(&self) -> Option<&Actor> {
128 self.actors.last()
129 }
130
131 pub fn to_record(&self) -> ActivityRecord {
132 ActivityRecord {
133 id: self.id,
134 conversation_id: self.conversation_id.clone(),
135 kind: self.kind.key().to_owned(),
136 message_id: self.message_id.clone(),
137 actors_json: serde_json::to_string(&self.actors).unwrap_or_else(|_| "[]".to_owned()),
138 preview: self.preview.clone(),
139 glyphs: serde_json::to_string(&self.glyphs).unwrap_or_else(|_| "[]".to_owned()),
140 count: self.count,
141 updated_at: self.updated_at,
142 read: self.read,
143 }
144 }
145
146 pub fn from_record(record: ActivityRecord) -> Option<Entry> {
147 Some(Entry {
148 id: record.id,
149 kind: Kind::from_key(&record.kind)?,
150 conversation_id: record.conversation_id,
151 message_id: record.message_id,
152 actors: serde_json::from_str(&record.actors_json).unwrap_or_default(),
153 preview: record.preview,
154 glyphs: serde_json::from_str(&record.glyphs).unwrap_or_default(),
155 count: record.count,
156 updated_at: record.updated_at,
157 read: record.read,
158 })
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct Sighting {
164 pub user_id: Option<String>,
165 pub name: String,
166 pub glyph: String,
167 pub created_at: Option<DateTime<Utc>>,
168}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct ReactedMessage {
172 pub message_id: String,
173 pub preview: String,
174 pub sightings: Vec<Sighting>,
175}
176
177pub struct Section<'a> {
178 pub bucket: Bucket,
179 pub entries: Vec<&'a Entry>,
180}
181
182#[derive(Default)]
183pub struct Feed {
184 entries: Vec<Entry>,
185 next_id: i64,
186 dirty: BTreeSet<i64>,
187}
188
189pub fn start_time(saved: Option<DateTime<Utc>>, now: DateTime<Utc>) -> DateTime<Utc> {
190 saved
191 .unwrap_or(now)
192 .clamp(now - Duration::days(RETENTION_DAYS), now)
193}
194
195impl Feed {
196 pub fn load(records: Vec<ActivityRecord>) -> Feed {
197 let entries: Vec<Entry> = records.into_iter().filter_map(Entry::from_record).collect();
198 let next_id = entries.iter().map(|entry| entry.id).max().unwrap_or(0) + 1;
199 Feed {
200 entries,
201 next_id,
202 dirty: BTreeSet::new(),
203 }
204 }
205
206 pub fn add(&mut self, mut entry: Entry) -> i64 {
207 entry.id = self.next_id;
208 self.next_id += 1;
209 self.dirty.insert(entry.id);
210 let id = entry.id;
211 self.entries.push(entry);
212 id
213 }
214
215 pub fn get(&self, id: i64) -> Option<&Entry> {
216 self.entries.iter().find(|entry| entry.id == id)
217 }
218
219 pub fn unread_count(&self) -> usize {
220 self.entries.iter().filter(|entry| !entry.read).count()
221 }
222
223 pub fn take_dirty(&mut self) -> Vec<Entry> {
224 let dirty = std::mem::take(&mut self.dirty);
225 self.entries
226 .iter()
227 .filter(|entry| dirty.contains(&entry.id))
228 .cloned()
229 .collect()
230 }
231
232 pub fn sections(
233 &self,
234 filter: Filter,
235 today: NaiveDate,
236 offset: FixedOffset,
237 ) -> Vec<Section<'_>> {
238 let mut admitted: Vec<&Entry> = self
239 .entries
240 .iter()
241 .filter(|entry| filter.admits(entry))
242 .collect();
243 admitted.sort_by_key(|entry| std::cmp::Reverse((entry.updated_at, entry.id)));
244 let mut sections: Vec<Section<'_>> = Vec::new();
245 for entry in admitted {
246 let bucket = Bucket::of(entry.updated_at, today, offset);
247 match sections.last_mut() {
248 Some(section) if section.bucket == bucket => section.entries.push(entry),
249 _ => sections.push(Section {
250 bucket,
251 entries: vec![entry],
252 }),
253 }
254 }
255 sections
256 }
257
258 pub fn record_message(&mut self, incoming: &Incoming, preview: String) {
259 let actor = Actor {
260 user_id: incoming.sender_id.clone(),
261 name: incoming.sender_name.clone(),
262 };
263 if incoming.mentions_me {
264 self.add(Entry {
265 id: 0,
266 conversation_id: incoming.conversation_id.clone(),
267 kind: Kind::Mention,
268 message_id: incoming.message_id.clone(),
269 actors: vec![actor],
270 preview,
271 glyphs: Vec::new(),
272 count: 1,
273 updated_at: incoming.created_at,
274 read: false,
275 });
276 return;
277 }
278 let open_row = self.entries.iter().position(|entry| {
279 entry.kind == Kind::Messages
280 && !entry.read
281 && entry.conversation_id == incoming.conversation_id
282 });
283 let Some(index) = open_row else {
284 self.add(Entry {
285 id: 0,
286 conversation_id: incoming.conversation_id.clone(),
287 kind: Kind::Messages,
288 message_id: incoming.message_id.clone(),
289 actors: vec![actor],
290 preview,
291 glyphs: Vec::new(),
292 count: 1,
293 updated_at: incoming.created_at,
294 read: false,
295 });
296 return;
297 };
298 let entry = &mut self.entries[index];
299 entry.count += 1;
300 entry.preview = preview;
301 entry.updated_at = incoming.created_at;
302 move_to_end(&mut entry.actors, actor);
303 self.dirty.insert(entry.id);
304 }
305
306 pub fn record_chat_preview(
307 &mut self,
308 conversation_id: &str,
309 actor: Actor,
310 preview: String,
311 at: DateTime<Utc>,
312 ) {
313 let known = self.entries.iter().any(|entry| {
314 entry.conversation_id == conversation_id
315 && entry.kind != Kind::Reaction
316 && entry.updated_at >= at
317 });
318 if known {
319 return;
320 }
321 let open_row = self.entries.iter().position(|entry| {
322 entry.kind == Kind::Messages && !entry.read && entry.conversation_id == conversation_id
323 });
324 match open_row {
325 Some(index) => {
326 let entry = &mut self.entries[index];
327 entry.count += 1;
328 entry.preview = preview;
329 entry.updated_at = at;
330 move_to_end(&mut entry.actors, actor);
331 self.dirty.insert(entry.id);
332 }
333 None => {
334 self.add(Entry {
335 id: 0,
336 conversation_id: conversation_id.to_owned(),
337 kind: Kind::Messages,
338 message_id: String::new(),
339 actors: vec![actor],
340 preview,
341 glyphs: Vec::new(),
342 count: 1,
343 updated_at: at,
344 read: false,
345 });
346 }
347 }
348 }
349
350 pub fn record_reactions(
351 &mut self,
352 conversation_id: &str,
353 message: &ReactedMessage,
354 my_user_id: &str,
355 cutoff: DateTime<Utc>,
356 now: DateTime<Utc>,
357 ) {
358 for sighting in &message.sightings {
359 let Some(user_id) = sighting.user_id.as_deref().filter(|id| *id != my_user_id) else {
360 continue;
361 };
362 let existing = self.entries.iter().position(|entry| {
363 entry.kind == Kind::Reaction
364 && entry.conversation_id == conversation_id
365 && entry.message_id == message.message_id
366 });
367 let known = existing.is_some_and(|index| {
368 self.entries[index]
369 .actors
370 .iter()
371 .any(|actor| actor.user_id.as_deref() == Some(user_id))
372 });
373 if known {
374 if let Some(index) = existing {
375 self.add_glyph(index, &sighting.glyph);
376 }
377 continue;
378 }
379 let fresh = match sighting.created_at {
380 Some(created_at) => created_at > cutoff,
381 None => existing.is_some(),
382 };
383 if !fresh {
384 continue;
385 }
386 let actor = Actor {
387 user_id: Some(user_id.to_owned()),
388 name: sighting.name.clone(),
389 };
390 let at = sighting.created_at.unwrap_or(now);
391 match existing {
392 Some(index) => {
393 let entry = &mut self.entries[index];
394 entry.actors.push(actor);
395 entry.count = entry.actors.len() as u32;
396 entry.read = false;
397 entry.updated_at = entry.updated_at.max(at);
398 self.dirty.insert(entry.id);
399 self.add_glyph(index, &sighting.glyph);
400 }
401 None => {
402 self.add(Entry {
403 id: 0,
404 conversation_id: conversation_id.to_owned(),
405 kind: Kind::Reaction,
406 message_id: message.message_id.clone(),
407 actors: vec![actor],
408 preview: message.preview.clone(),
409 glyphs: vec![sighting.glyph.clone()],
410 count: 1,
411 updated_at: at,
412 read: false,
413 });
414 }
415 }
416 }
417 }
418
419 fn add_glyph(&mut self, index: usize, glyph: &str) {
420 let entry = &mut self.entries[index];
421 if !glyph.is_empty() && !entry.glyphs.iter().any(|known| known == glyph) {
422 entry.glyphs.push(glyph.to_owned());
423 self.dirty.insert(entry.id);
424 }
425 }
426
427 pub fn mark_read(&mut self, id: i64) -> bool {
428 self.mark_where(|entry| entry.id == id)
429 }
430
431 pub fn mark_all_read(&mut self) -> bool {
432 self.mark_where(|_| true)
433 }
434
435 pub fn mark_conversation_read(&mut self, conversation_id: &str) -> bool {
436 self.mark_where(|entry| entry.conversation_id == conversation_id)
437 }
438
439 pub fn sync_read(&mut self, read_at: impl Fn(&str) -> Option<DateTime<Utc>>) -> bool {
440 self.mark_where(|entry| {
441 read_at(&entry.conversation_id).is_some_and(|read_at| entry.updated_at <= read_at)
442 })
443 }
444
445 fn mark_where(&mut self, matches: impl Fn(&Entry) -> bool) -> bool {
446 let mut changed = false;
447 for entry in self.entries.iter_mut().filter(|entry| !entry.read) {
448 if matches(entry) {
449 entry.read = true;
450 self.dirty.insert(entry.id);
451 changed = true;
452 }
453 }
454 changed
455 }
456}
457
458fn move_to_end(actors: &mut Vec<Actor>, actor: Actor) {
459 actors.retain(|known| match (&known.user_id, &actor.user_id) {
460 (Some(known_id), Some(id)) => known_id != id,
461 _ => known.name != actor.name,
462 });
463 actors.push(actor);
464}
465
466#[cfg(test)]
467mod tests {
468 use chrono::TimeZone;
469
470 use super::*;
471 use crate::notify::{ChatKind, Preview};
472
473 fn at(hour: u32, minute: u32) -> DateTime<Utc> {
474 Utc.with_ymd_and_hms(2026, 10, 8, hour, minute, 0).unwrap()
475 }
476
477 fn incoming(conversation_id: &str, message_id: &str, sender: &str, minute: u32) -> Incoming {
478 Incoming {
479 conversation_id: conversation_id.into(),
480 message_id: message_id.into(),
481 kind: ChatKind::Direct,
482 chat_title: "Chat".into(),
483 sender_id: Some(format!("id-{sender}")),
484 sender_name: sender.into(),
485 preview: Preview::Text(format!("text {message_id}")),
486 mentions_me: false,
487 muted: false,
488 created_at: at(9, minute),
489 }
490 }
491
492 fn record(feed: &mut Feed, incoming: &Incoming) {
493 feed.record_message(incoming, format!("text {}", incoming.message_id));
494 }
495
496 fn sighting(user: &str, glyph: &str, created_at: Option<DateTime<Utc>>) -> Sighting {
497 Sighting {
498 user_id: Some(format!("id-{user}")),
499 name: user.into(),
500 glyph: glyph.into(),
501 created_at,
502 }
503 }
504
505 fn react(feed: &mut Feed, sightings: &[Sighting]) {
506 let message = ReactedMessage {
507 message_id: "mine".into(),
508 preview: "my text".into(),
509 sightings: sightings.to_vec(),
510 };
511 feed.record_reactions("chat", &message, "id-me", at(8, 0), at(10, 0));
512 }
513
514 fn all(feed: &Feed) -> Vec<&Entry> {
515 feed.sections(Filter::All, at(9, 0).date_naive(), offset())
516 .into_iter()
517 .flat_map(|section| section.entries)
518 .collect()
519 }
520
521 fn offset() -> FixedOffset {
522 FixedOffset::east_opt(0).unwrap()
523 }
524
525 #[test]
526 fn three_messages_share_one_row_and_keep_the_first_message_id() {
527 let mut feed = Feed::default();
528 for (index, message_id) in ["m1", "m2", "m3"].into_iter().enumerate() {
529 record(
530 &mut feed,
531 &incoming("chat", message_id, "Anna", index as u32),
532 );
533 }
534 let entries = all(&feed);
535 assert_eq!(entries.len(), 1);
536 assert_eq!(entries[0].count, 3);
537 assert_eq!(entries[0].message_id, "m1");
538 assert_eq!(entries[0].preview, "text m3");
539 assert_eq!(entries[0].updated_at, at(9, 2));
540 assert_eq!(feed.unread_count(), 1);
541 }
542
543 #[test]
544 fn latest_sender_moves_to_the_end() {
545 let mut feed = Feed::default();
546 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
547 record(&mut feed, &incoming("chat", "m2", "Ben", 2));
548 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
549 let entries = all(&feed);
550 let entry = entries[0];
551 assert_eq!(entry.names(), "Ben and Anna");
552 assert_eq!(entry.latest_actor().unwrap().name, "Anna");
553 }
554
555 #[test]
556 fn chat_preview_adds_a_row_only_when_newer_than_the_feed() {
557 let mut feed = Feed::default();
558 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
559 let anna = Actor {
560 user_id: Some("id-Anna".into()),
561 name: "Anna".into(),
562 };
563 feed.record_chat_preview("chat", anna.clone(), "text m1".into(), at(9, 1));
564 assert_eq!(all(&feed)[0].count, 1);
565 feed.record_chat_preview("chat", anna.clone(), "later".into(), at(9, 5));
566 assert_eq!(all(&feed)[0].count, 2);
567 assert_eq!(all(&feed)[0].preview, "later");
568 feed.record_chat_preview("other", anna, "offline".into(), at(9, 6));
569 let entries = all(&feed);
570 assert_eq!(entries.len(), 2);
571 assert_eq!(entries[0].message_id, "");
572 }
573
574 #[test]
575 fn message_after_read_opens_a_new_row() {
576 let mut feed = Feed::default();
577 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
578 feed.mark_conversation_read("chat");
579 record(&mut feed, &incoming("chat", "m2", "Anna", 2));
580 let entries = all(&feed);
581 assert_eq!(entries.len(), 2);
582 assert_eq!(entries[0].message_id, "m2");
583 assert!(!entries[0].read);
584 assert!(entries[1].read);
585 assert_eq!(entries[1].count, 1);
586 }
587
588 #[test]
589 fn mention_gets_its_own_row_and_is_not_counted_in_messages() {
590 let mut feed = Feed::default();
591 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
592 let mut mention = incoming("chat", "m2", "Ben", 2);
593 mention.mentions_me = true;
594 record(&mut feed, &mention);
595 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
596 let entries = all(&feed);
597 assert_eq!(entries.len(), 2);
598 let mention_row = entries
599 .iter()
600 .find(|entry| entry.kind == Kind::Mention)
601 .unwrap();
602 assert_eq!(mention_row.message_id, "m2");
603 let messages_row = entries
604 .iter()
605 .find(|entry| entry.kind == Kind::Messages)
606 .unwrap();
607 assert_eq!(messages_row.count, 2);
608 assert_eq!(messages_row.message_id, "m1");
609 }
610
611 #[test]
612 fn reactions_bundle_per_message_and_become_unread_again() {
613 let mut feed = Feed::default();
614 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
615 feed.mark_all_read();
616 assert_eq!(feed.unread_count(), 0);
617 react(
618 &mut feed,
619 &[
620 sighting("Anna", "A", Some(at(9, 1))),
621 sighting("Ben", "B", Some(at(9, 5))),
622 ],
623 );
624 let entries = all(&feed);
625 assert_eq!(entries.len(), 1);
626 assert_eq!(entries[0].names(), "Anna and Ben");
627 assert_eq!(entries[0].glyphs, vec!["A", "B"]);
628 assert_eq!(entries[0].count, 2);
629 assert_eq!(entries[0].updated_at, at(9, 5));
630 assert!(!entries[0].read);
631 assert_eq!(entries[0].preview, "my text");
632 }
633
634 #[test]
635 fn known_reactor_adding_a_glyph_does_not_reopen_the_row() {
636 let mut feed = Feed::default();
637 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
638 feed.mark_all_read();
639 react(&mut feed, &[sighting("Anna", "C", Some(at(9, 2)))]);
640 let entries = all(&feed);
641 assert_eq!(entries[0].glyphs, vec!["A", "C"]);
642 assert!(entries[0].read);
643 }
644
645 #[test]
646 fn own_and_anonymous_reactions_are_ignored() {
647 let mut feed = Feed::default();
648 let anonymous = Sighting {
649 user_id: None,
650 ..sighting("Anna", "A", Some(at(9, 1)))
651 };
652 react(&mut feed, &[sighting("me", "A", Some(at(9, 1))), anonymous]);
653 assert!(all(&feed).is_empty());
654 }
655
656 #[test]
657 fn old_reactions_on_first_sight_are_ignored() {
658 let mut feed = Feed::default();
659 react(
660 &mut feed,
661 &[
662 sighting("Anna", "A", Some(at(7, 0))),
663 sighting("Ben", "B", None),
664 ],
665 );
666 assert!(all(&feed).is_empty());
667 react(&mut feed, &[sighting("Cleo", "C", Some(at(9, 0)))]);
668 react(&mut feed, &[sighting("Dan", "D", None)]);
669 assert_eq!(all(&feed)[0].names(), "Cleo and Dan");
670 }
671
672 #[test]
673 fn reading_a_conversation_leaves_others_unread() {
674 let mut feed = Feed::default();
675 record(&mut feed, &incoming("a", "m1", "Anna", 1));
676 record(&mut feed, &incoming("b", "m2", "Ben", 2));
677 assert!(feed.mark_conversation_read("a"));
678 assert!(!feed.mark_conversation_read("a"));
679 assert_eq!(feed.unread_count(), 1);
680 let unread = all(&feed).into_iter().find(|entry| !entry.read).unwrap();
681 assert_eq!(unread.conversation_id, "b");
682 }
683
684 #[test]
685 fn read_sync_only_covers_rows_up_to_the_read_time() {
686 let mut feed = Feed::default();
687 record(&mut feed, &incoming("a", "m1", "Anna", 1));
688 feed.mark_conversation_read("a");
689 record(&mut feed, &incoming("a", "m2", "Anna", 30));
690 record(&mut feed, &incoming("b", "m3", "Ben", 1));
691 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 10)));
692 assert!(!changed);
693 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 45)));
694 assert!(changed);
695 assert_eq!(feed.unread_count(), 1);
696 }
697
698 #[test]
699 fn mark_all_read_clears_the_count_and_reports_change_once() {
700 let mut feed = Feed::default();
701 record(&mut feed, &incoming("a", "m1", "Anna", 1));
702 record(&mut feed, &incoming("b", "m2", "Ben", 2));
703 assert!(feed.mark_all_read());
704 assert_eq!(feed.unread_count(), 0);
705 assert!(!feed.mark_all_read());
706 }
707
708 #[test]
709 fn filters_pick_mentions_and_unread() {
710 let mut feed = Feed::default();
711 record(&mut feed, &incoming("a", "m1", "Anna", 1));
712 let mut mention = incoming("b", "m2", "Ben", 2);
713 mention.mentions_me = true;
714 record(&mut feed, &mention);
715 feed.mark_conversation_read("a");
716 let today = at(9, 0).date_naive();
717 let count = |filter| {
718 feed.sections(filter, today, offset())
719 .iter()
720 .map(|section| section.entries.len())
721 .sum::<usize>()
722 };
723 assert_eq!(count(Filter::All), 2);
724 assert_eq!(count(Filter::Mentions), 1);
725 assert_eq!(count(Filter::Unread), 1);
726 }
727
728 #[test]
729 fn buckets_follow_the_local_day() {
730 let today = at(12, 0).date_naive();
731 let utc = offset();
732 assert_eq!(Bucket::of(at(0, 5), today, utc), Bucket::Today);
733 assert_eq!(
734 Bucket::of(at(0, 5) - Duration::minutes(10), today, utc),
735 Bucket::Yesterday
736 );
737 assert_eq!(
738 Bucket::of(at(0, 5) - Duration::days(3), today, utc),
739 Bucket::Earlier
740 );
741 let east = FixedOffset::east_opt(2 * 3600).unwrap();
742 assert_eq!(
743 Bucket::of(at(23, 30) - Duration::days(1), today, east),
744 Bucket::Today
745 );
746 }
747
748 #[test]
749 fn sections_are_newest_first_and_grouped() {
750 let mut feed = Feed::default();
751 let mut old = incoming("a", "m1", "Anna", 1);
752 old.created_at = at(9, 0) - Duration::days(1);
753 record(&mut feed, &old);
754 record(&mut feed, &incoming("b", "m2", "Ben", 2));
755 record(&mut feed, &incoming("c", "m3", "Cleo", 3));
756 let today = at(9, 0).date_naive();
757 let sections = feed.sections(Filter::All, today, offset());
758 let labels: Vec<&str> = sections
759 .iter()
760 .map(|section| section.bucket.label())
761 .collect();
762 assert_eq!(labels, ["Today", "Yesterday"]);
763 assert_eq!(sections[0].entries[0].conversation_id, "c");
764 }
765
766 #[test]
767 fn dirty_rows_are_reported_once_and_survive_a_round_trip() {
768 let mut feed = Feed::default();
769 record(&mut feed, &incoming("a", "m1", "Anna", 1));
770 react(&mut feed, &[sighting("Ben", "B", Some(at(9, 1)))]);
771 let dirty = feed.take_dirty();
772 assert_eq!(dirty.len(), 2);
773 assert!(feed.take_dirty().is_empty());
774 let reloaded = Feed::load(dirty.iter().map(Entry::to_record).collect());
775 assert_eq!(all(&reloaded).len(), 2);
776 let mut reloaded = reloaded;
777 record(&mut reloaded, &incoming("c", "m9", "Cleo", 9));
778 let ids: BTreeSet<i64> = reloaded.take_dirty().iter().map(|entry| entry.id).collect();
779 assert_eq!(ids.len(), 1);
780 assert!(!dirty.iter().any(|entry| ids.contains(&entry.id)));
781 }
782
783 #[test]
784 fn start_time_defaults_to_now_and_is_clamped() {
785 let now = at(12, 0);
786 assert_eq!(start_time(None, now), now);
787 assert_eq!(start_time(Some(now + Duration::hours(1)), now), now);
788 assert_eq!(
789 start_time(Some(now - Duration::days(30)), now),
790 now - Duration::days(RETENTION_DAYS)
791 );
792 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
793 }
794}