1use sheetkit_xml::threaded_comment::{Person, PersonList, ThreadedComment, ThreadedComments};
8
9use crate::error::{Error, Result};
10
11#[derive(Debug, Clone, PartialEq)]
13pub struct ThreadedCommentInput {
14 pub author: String,
16 pub text: String,
18 pub parent_id: Option<String>,
20}
21
22#[derive(Debug, Clone, PartialEq)]
24pub struct PersonInput {
25 pub display_name: String,
27 pub user_id: Option<String>,
29 pub provider_id: Option<String>,
31}
32
33#[derive(Debug, Clone, PartialEq)]
35pub struct ThreadedCommentData {
36 pub id: String,
38 pub cell_ref: String,
40 pub text: String,
42 pub author: String,
44 pub person_id: String,
46 pub date_time: String,
48 pub parent_id: Option<String>,
50 pub done: bool,
52}
53
54#[derive(Debug, Clone, PartialEq)]
56pub struct PersonData {
57 pub id: String,
59 pub display_name: String,
61 pub user_id: Option<String>,
63 pub provider_id: Option<String>,
65}
66
67fn generate_guid() -> String {
69 format!("{{{}}}", uuid::Uuid::new_v4().to_string().to_uppercase())
70}
71
72fn current_timestamp() -> String {
75 let now = chrono::Utc::now();
76 let base = now.format("%Y-%m-%dT%H:%M:%S").to_string();
77 let centiseconds = now.timestamp_subsec_millis() / 10;
78 format!("{base}.{centiseconds:02}")
79}
80
81fn generate_unique_guid(
83 person_list: &PersonList,
84 threaded_comments: Option<&ThreadedComments>,
85) -> String {
86 loop {
87 let id = generate_guid();
88 let person_collision = person_list.persons.iter().any(|p| p.id == id);
89 let comment_collision = threaded_comments
90 .map(|tc| tc.comments.iter().any(|c| c.id == id))
91 .unwrap_or(false);
92 if !person_collision && !comment_collision {
93 return id;
94 }
95 }
96}
97
98pub fn find_or_create_person(
100 person_list: &mut PersonList,
101 display_name: &str,
102 user_id: Option<&str>,
103 provider_id: Option<&str>,
104) -> String {
105 find_or_create_person_with_collision_check(
106 person_list,
107 display_name,
108 user_id,
109 provider_id,
110 None,
111 )
112}
113
114fn find_or_create_person_with_collision_check(
116 person_list: &mut PersonList,
117 display_name: &str,
118 user_id: Option<&str>,
119 provider_id: Option<&str>,
120 threaded_comments: Option<&ThreadedComments>,
121) -> String {
122 if let Some(existing) = person_list
123 .persons
124 .iter()
125 .find(|p| p.display_name == display_name)
126 {
127 return existing.id.clone();
128 }
129
130 let id = generate_unique_guid(person_list, threaded_comments);
131 person_list.persons.push(Person {
132 display_name: display_name.to_string(),
133 id: id.clone(),
134 user_id: user_id.map(|s| s.to_string()),
135 provider_id: provider_id.map(|s| s.to_string()),
136 });
137 id
138}
139
140pub fn add_threaded_comment(
145 threaded_comments: &mut Option<ThreadedComments>,
146 person_list: &mut PersonList,
147 cell: &str,
148 input: &ThreadedCommentInput,
149) -> Result<String> {
150 crate::utils::cell_ref::cell_name_to_coordinates(cell)?;
151
152 if let Some(ref parent_id) = input.parent_id {
153 let tc = threaded_comments.as_ref();
154 let parent_exists = tc
155 .map(|t| t.comments.iter().any(|c| c.id == *parent_id))
156 .unwrap_or(false);
157 if !parent_exists {
158 return Err(Error::ThreadedCommentNotFound {
159 id: parent_id.clone(),
160 });
161 }
162 }
163
164 let person_id = find_or_create_person_with_collision_check(
165 person_list,
166 &input.author,
167 None,
168 None,
169 threaded_comments.as_ref(),
170 );
171 let comment_id = generate_unique_guid(person_list, threaded_comments.as_ref());
172
173 let tc = threaded_comments.get_or_insert_with(ThreadedComments::default);
174 tc.comments.push(ThreadedComment {
175 cell_ref: cell.to_string(),
176 date_time: current_timestamp(),
177 person_id,
178 id: comment_id.clone(),
179 parent_id: input.parent_id.clone(),
180 done: None,
181 text: input.text.clone(),
182 });
183
184 Ok(comment_id)
185}
186
187pub fn get_threaded_comments(
189 threaded_comments: &Option<ThreadedComments>,
190 person_list: &PersonList,
191) -> Vec<ThreadedCommentData> {
192 let Some(tc) = threaded_comments.as_ref() else {
193 return Vec::new();
194 };
195
196 tc.comments
197 .iter()
198 .map(|c| {
199 let author = person_list
200 .persons
201 .iter()
202 .find(|p| p.id == c.person_id)
203 .map(|p| p.display_name.clone())
204 .unwrap_or_default();
205 ThreadedCommentData {
206 id: c.id.clone(),
207 cell_ref: c.cell_ref.clone(),
208 text: c.text.clone(),
209 author,
210 person_id: c.person_id.clone(),
211 date_time: c.date_time.clone(),
212 parent_id: c.parent_id.clone(),
213 done: matches!(c.done.as_deref(), Some("1" | "true")),
214 }
215 })
216 .collect()
217}
218
219pub fn get_threaded_comments_by_cell(
221 threaded_comments: &Option<ThreadedComments>,
222 person_list: &PersonList,
223 cell: &str,
224) -> Vec<ThreadedCommentData> {
225 get_threaded_comments(threaded_comments, person_list)
226 .into_iter()
227 .filter(|c| c.cell_ref == cell)
228 .collect()
229}
230
231pub fn delete_threaded_comment(
235 threaded_comments: &mut Option<ThreadedComments>,
236 comment_id: &str,
237) -> Result<()> {
238 if let Some(ref mut tc) = threaded_comments {
239 let before = tc.comments.len();
240 tc.comments
242 .retain(|c| c.id != comment_id && c.parent_id.as_deref() != Some(comment_id));
243 if tc.comments.len() == before {
244 return Err(Error::ThreadedCommentNotFound {
245 id: comment_id.to_string(),
246 });
247 }
248
249 if tc.comments.is_empty() {
250 *threaded_comments = None;
251 }
252
253 Ok(())
254 } else {
255 Err(Error::ThreadedCommentNotFound {
256 id: comment_id.to_string(),
257 })
258 }
259}
260
261pub fn resolve_threaded_comment(
265 threaded_comments: &mut Option<ThreadedComments>,
266 comment_id: &str,
267 done: bool,
268) -> Result<()> {
269 if let Some(ref mut tc) = threaded_comments {
270 if let Some(comment) = tc.comments.iter_mut().find(|c| c.id == comment_id) {
271 comment.done = if done { Some("1".to_string()) } else { None };
272 return Ok(());
273 }
274 }
275 Err(Error::ThreadedCommentNotFound {
276 id: comment_id.to_string(),
277 })
278}
279
280pub const LEGACY_PLACEHOLDER_PREFIX: &str = "[Threaded comment]";
283
284const LEGACY_PLACEHOLDER_NOTICE: &str = "Your version of Excel allows you to read this threaded comment; however, any edits to it will get removed if the file is opened in a newer version of Excel. Learn more: https://go.microsoft.com/fwlink/?linkid=870924";
285
286pub fn is_legacy_placeholder(text: &str) -> bool {
289 text.starts_with(LEGACY_PLACEHOLDER_PREFIX)
290}
291
292pub fn is_legacy_twin(author: &str, text: &str) -> bool {
296 author.starts_with("tc=") && is_legacy_placeholder(text)
297}
298
299pub fn legacy_comment_for_cell(
305 threaded_comments: &Option<ThreadedComments>,
306 cell: &str,
307) -> Option<(String, String)> {
308 let comments: Vec<&ThreadedComment> = threaded_comments
309 .as_ref()?
310 .comments
311 .iter()
312 .filter(|c| c.cell_ref == cell)
313 .collect();
314 let root = comments
315 .iter()
316 .find(|c| c.parent_id.is_none())
317 .or_else(|| comments.first())?;
318 let mut text = format!(
319 "{LEGACY_PLACEHOLDER_PREFIX}\n\n{LEGACY_PLACEHOLDER_NOTICE}\n\nComment:\n {}",
320 root.text
321 );
322 for reply in comments.iter().filter(|c| c.id != root.id) {
323 text.push_str("\nReply:\n ");
324 text.push_str(&reply.text);
325 }
326 Some((format!("tc={}", root.id), text))
327}
328
329pub fn add_person(person_list: &mut PersonList, input: &PersonInput) -> String {
331 find_or_create_person(
332 person_list,
333 &input.display_name,
334 input.user_id.as_deref(),
335 input.provider_id.as_deref(),
336 )
337}
338
339pub fn get_persons(person_list: &PersonList) -> Vec<PersonData> {
341 person_list
342 .persons
343 .iter()
344 .map(|p| PersonData {
345 id: p.id.clone(),
346 display_name: p.display_name.clone(),
347 user_id: p.user_id.clone(),
348 provider_id: p.provider_id.clone(),
349 })
350 .collect()
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356
357 #[test]
358 fn test_add_threaded_comment() {
359 let mut tc = None;
360 let mut pl = PersonList::default();
361 let input = ThreadedCommentInput {
362 author: "Alice".to_string(),
363 text: "Hello thread".to_string(),
364 parent_id: None,
365 };
366 let id = add_threaded_comment(&mut tc, &mut pl, "A1", &input).unwrap();
367 assert!(!id.is_empty());
368 assert!(tc.is_some());
369
370 let comments = get_threaded_comments(&tc, &pl);
371 assert_eq!(comments.len(), 1);
372 assert_eq!(comments[0].cell_ref, "A1");
373 assert_eq!(comments[0].text, "Hello thread");
374 assert_eq!(comments[0].author, "Alice");
375 assert!(!comments[0].done);
376 assert!(comments[0].parent_id.is_none());
377 }
378
379 #[test]
380 fn test_add_reply() {
381 let mut tc = None;
382 let mut pl = PersonList::default();
383
384 let parent_id = add_threaded_comment(
385 &mut tc,
386 &mut pl,
387 "A1",
388 &ThreadedCommentInput {
389 author: "Alice".to_string(),
390 text: "Initial comment".to_string(),
391 parent_id: None,
392 },
393 )
394 .unwrap();
395
396 let reply_id = add_threaded_comment(
397 &mut tc,
398 &mut pl,
399 "A1",
400 &ThreadedCommentInput {
401 author: "Bob".to_string(),
402 text: "This is a reply".to_string(),
403 parent_id: Some(parent_id.clone()),
404 },
405 )
406 .unwrap();
407
408 let comments = get_threaded_comments(&tc, &pl);
409 assert_eq!(comments.len(), 2);
410 assert_eq!(comments[1].parent_id, Some(parent_id));
411 assert_ne!(reply_id, comments[0].id);
412 }
413
414 #[test]
415 fn test_reply_to_nonexistent_parent() {
416 let mut tc = None;
417 let mut pl = PersonList::default();
418 let input = ThreadedCommentInput {
419 author: "Alice".to_string(),
420 text: "Bad reply".to_string(),
421 parent_id: Some("{NONEXISTENT}".to_string()),
422 };
423 let result = add_threaded_comment(&mut tc, &mut pl, "A1", &input);
424 assert!(result.is_err());
425 }
426
427 #[test]
428 fn test_get_by_cell() {
429 let mut tc = None;
430 let mut pl = PersonList::default();
431
432 add_threaded_comment(
433 &mut tc,
434 &mut pl,
435 "A1",
436 &ThreadedCommentInput {
437 author: "Alice".to_string(),
438 text: "On A1".to_string(),
439 parent_id: None,
440 },
441 )
442 .unwrap();
443
444 add_threaded_comment(
445 &mut tc,
446 &mut pl,
447 "B2",
448 &ThreadedCommentInput {
449 author: "Bob".to_string(),
450 text: "On B2".to_string(),
451 parent_id: None,
452 },
453 )
454 .unwrap();
455
456 let a1_comments = get_threaded_comments_by_cell(&tc, &pl, "A1");
457 assert_eq!(a1_comments.len(), 1);
458 assert_eq!(a1_comments[0].text, "On A1");
459
460 let b2_comments = get_threaded_comments_by_cell(&tc, &pl, "B2");
461 assert_eq!(b2_comments.len(), 1);
462 assert_eq!(b2_comments[0].text, "On B2");
463
464 let empty = get_threaded_comments_by_cell(&tc, &pl, "C3");
465 assert!(empty.is_empty());
466 }
467
468 #[test]
469 fn test_delete_threaded_comment() {
470 let mut tc = None;
471 let mut pl = PersonList::default();
472
473 let id = add_threaded_comment(
474 &mut tc,
475 &mut pl,
476 "A1",
477 &ThreadedCommentInput {
478 author: "Alice".to_string(),
479 text: "Delete me".to_string(),
480 parent_id: None,
481 },
482 )
483 .unwrap();
484
485 delete_threaded_comment(&mut tc, &id).unwrap();
486 assert!(tc.is_none());
487 }
488
489 #[test]
490 fn test_delete_nonexistent_comment() {
491 let mut tc: Option<ThreadedComments> = None;
492 let result = delete_threaded_comment(&mut tc, "{NONEXISTENT}");
493 assert!(result.is_err());
494 }
495
496 #[test]
497 fn test_delete_one_of_multiple() {
498 let mut tc = None;
499 let mut pl = PersonList::default();
500
501 let id1 = add_threaded_comment(
502 &mut tc,
503 &mut pl,
504 "A1",
505 &ThreadedCommentInput {
506 author: "Alice".to_string(),
507 text: "First".to_string(),
508 parent_id: None,
509 },
510 )
511 .unwrap();
512
513 add_threaded_comment(
514 &mut tc,
515 &mut pl,
516 "B2",
517 &ThreadedCommentInput {
518 author: "Bob".to_string(),
519 text: "Second".to_string(),
520 parent_id: None,
521 },
522 )
523 .unwrap();
524
525 delete_threaded_comment(&mut tc, &id1).unwrap();
526 assert!(tc.is_some());
527 let remaining = get_threaded_comments(&tc, &pl);
528 assert_eq!(remaining.len(), 1);
529 assert_eq!(remaining[0].text, "Second");
530 }
531
532 #[test]
533 fn test_resolve_threaded_comment() {
534 let mut tc = None;
535 let mut pl = PersonList::default();
536
537 let id = add_threaded_comment(
538 &mut tc,
539 &mut pl,
540 "A1",
541 &ThreadedCommentInput {
542 author: "Alice".to_string(),
543 text: "Resolve me".to_string(),
544 parent_id: None,
545 },
546 )
547 .unwrap();
548
549 resolve_threaded_comment(&mut tc, &id, true).unwrap();
550 let comments = get_threaded_comments(&tc, &pl);
551 assert!(comments[0].done);
552
553 resolve_threaded_comment(&mut tc, &id, false).unwrap();
554 let comments = get_threaded_comments(&tc, &pl);
555 assert!(!comments[0].done);
556 }
557
558 #[test]
559 fn test_done_field_accepts_true_string() {
560 let mut tc: Option<ThreadedComments> = Some(ThreadedComments::default());
561 let mut pl = PersonList::default();
562 let id = add_threaded_comment(
563 &mut tc,
564 &mut pl,
565 "A1",
566 &ThreadedCommentInput {
567 author: "Alice".to_string(),
568 text: "check done".to_string(),
569 parent_id: None,
570 },
571 )
572 .unwrap();
573
574 let tc_inner = tc.as_mut().unwrap();
576 tc_inner
577 .comments
578 .iter_mut()
579 .find(|c| c.id == id)
580 .unwrap()
581 .done = Some("true".to_string());
582
583 let comments = get_threaded_comments(&tc, &pl);
584 assert!(comments[0].done, "done='true' should be treated as done");
585 }
586
587 #[test]
588 fn test_resolve_nonexistent() {
589 let mut tc: Option<ThreadedComments> = None;
590 let result = resolve_threaded_comment(&mut tc, "{NONEXISTENT}", true);
591 assert!(result.is_err());
592 }
593
594 #[test]
595 fn test_add_person() {
596 let mut pl = PersonList::default();
597 let id = add_person(
598 &mut pl,
599 &PersonInput {
600 display_name: "Alice".to_string(),
601 user_id: Some("[email protected]".to_string()),
602 provider_id: Some("ADAL".to_string()),
603 },
604 );
605
606 assert!(!id.is_empty());
607 let persons = get_persons(&pl);
608 assert_eq!(persons.len(), 1);
609 assert_eq!(persons[0].display_name, "Alice");
610 assert_eq!(persons[0].user_id, Some("[email protected]".to_string()));
611 }
612
613 #[test]
614 fn test_add_duplicate_person() {
615 let mut pl = PersonList::default();
616 let id1 = add_person(
617 &mut pl,
618 &PersonInput {
619 display_name: "Alice".to_string(),
620 user_id: None,
621 provider_id: None,
622 },
623 );
624 let id2 = add_person(
625 &mut pl,
626 &PersonInput {
627 display_name: "Alice".to_string(),
628 user_id: None,
629 provider_id: None,
630 },
631 );
632
633 assert_eq!(id1, id2);
634 assert_eq!(get_persons(&pl).len(), 1);
635 }
636
637 #[test]
638 fn test_get_persons_empty() {
639 let pl = PersonList::default();
640 assert!(get_persons(&pl).is_empty());
641 }
642
643 #[test]
644 fn test_get_threaded_comments_empty() {
645 let tc: Option<ThreadedComments> = None;
646 let pl = PersonList::default();
647 assert!(get_threaded_comments(&tc, &pl).is_empty());
648 }
649
650 #[test]
651 fn test_person_auto_created_on_add_comment() {
652 let mut tc = None;
653 let mut pl = PersonList::default();
654
655 add_threaded_comment(
656 &mut tc,
657 &mut pl,
658 "A1",
659 &ThreadedCommentInput {
660 author: "Alice".to_string(),
661 text: "Auto person".to_string(),
662 parent_id: None,
663 },
664 )
665 .unwrap();
666
667 let persons = get_persons(&pl);
668 assert_eq!(persons.len(), 1);
669 assert_eq!(persons[0].display_name, "Alice");
670 }
671
672 #[test]
673 fn test_comment_has_timestamp() {
674 let mut tc = None;
675 let mut pl = PersonList::default();
676
677 add_threaded_comment(
678 &mut tc,
679 &mut pl,
680 "A1",
681 &ThreadedCommentInput {
682 author: "Alice".to_string(),
683 text: "Timestamp check".to_string(),
684 parent_id: None,
685 },
686 )
687 .unwrap();
688
689 let comments = get_threaded_comments(&tc, &pl);
690 assert!(!comments[0].date_time.is_empty());
691 assert!(comments[0].date_time.contains('T'));
692 }
693
694 #[test]
695 fn test_multiple_authors_multiple_cells() {
696 let mut tc = None;
697 let mut pl = PersonList::default();
698
699 add_threaded_comment(
700 &mut tc,
701 &mut pl,
702 "A1",
703 &ThreadedCommentInput {
704 author: "Alice".to_string(),
705 text: "Alice on A1".to_string(),
706 parent_id: None,
707 },
708 )
709 .unwrap();
710
711 add_threaded_comment(
712 &mut tc,
713 &mut pl,
714 "B2",
715 &ThreadedCommentInput {
716 author: "Bob".to_string(),
717 text: "Bob on B2".to_string(),
718 parent_id: None,
719 },
720 )
721 .unwrap();
722
723 add_threaded_comment(
724 &mut tc,
725 &mut pl,
726 "C3",
727 &ThreadedCommentInput {
728 author: "Alice".to_string(),
729 text: "Alice on C3".to_string(),
730 parent_id: None,
731 },
732 )
733 .unwrap();
734
735 let persons = get_persons(&pl);
736 assert_eq!(persons.len(), 2);
737
738 let all = get_threaded_comments(&tc, &pl);
739 assert_eq!(all.len(), 3);
740 }
741
742 #[test]
743 fn test_generated_ids_are_unique() {
744 let mut ids = std::collections::HashSet::new();
745 for _ in 0..1000 {
746 let id = generate_guid();
747 assert!(ids.insert(id.clone()), "duplicate ID generated: {}", id);
748 }
749 }
750
751 #[test]
752 fn test_generated_id_format() {
753 let id = generate_guid();
754 assert!(id.starts_with('{'));
755 assert!(id.ends_with('}'));
756 let inner = &id[1..id.len() - 1];
757 let parts: Vec<&str> = inner.split('-').collect();
758 assert_eq!(parts.len(), 5, "GUID should have 5 hyphen-separated parts");
759 assert_eq!(parts[0].len(), 8);
760 assert_eq!(parts[1].len(), 4);
761 assert_eq!(parts[2].len(), 4);
762 assert_eq!(parts[3].len(), 4);
763 assert_eq!(parts[4].len(), 12);
764 }
765
766 #[test]
767 fn test_no_id_collision_with_existing_workbook() {
768 let mut pl = PersonList::default();
769 pl.persons.push(Person {
770 display_name: "Existing".to_string(),
771 id: "{EXISTING-PERSON-ID}".to_string(),
772 user_id: None,
773 provider_id: None,
774 });
775
776 let mut tc = Some(ThreadedComments {
777 xmlns: sheetkit_xml::threaded_comment::THREADED_COMMENTS_NS.to_string(),
778 comments: vec![ThreadedComment {
779 cell_ref: "A1".to_string(),
780 date_time: "2024-01-01T00:00:00.00".to_string(),
781 person_id: "{EXISTING-PERSON-ID}".to_string(),
782 id: "{EXISTING-COMMENT-ID}".to_string(),
783 parent_id: None,
784 done: None,
785 text: "Pre-existing".to_string(),
786 }],
787 });
788
789 let new_id = add_threaded_comment(
790 &mut tc,
791 &mut pl,
792 "B2",
793 &ThreadedCommentInput {
794 author: "NewUser".to_string(),
795 text: "New comment".to_string(),
796 parent_id: None,
797 },
798 )
799 .unwrap();
800
801 assert_ne!(new_id, "{EXISTING-COMMENT-ID}");
802 assert_ne!(new_id, "{EXISTING-PERSON-ID}");
803
804 let persons = get_persons(&pl);
805 let new_person = persons
806 .iter()
807 .find(|p| p.display_name == "NewUser")
808 .unwrap();
809 assert_ne!(new_person.id, "{EXISTING-PERSON-ID}");
810 assert_ne!(new_person.id, "{EXISTING-COMMENT-ID}");
811 }
812
813 #[test]
814 fn test_delete_nonexistent_returns_error() {
815 let mut tc = None;
816 let mut pl = PersonList::default();
817
818 add_threaded_comment(
819 &mut tc,
820 &mut pl,
821 "A1",
822 &ThreadedCommentInput {
823 author: "Alice".to_string(),
824 text: "Exists".to_string(),
825 parent_id: None,
826 },
827 )
828 .unwrap();
829
830 let result = delete_threaded_comment(&mut tc, "{DOES-NOT-EXIST}");
831 assert!(result.is_err());
832 let err = result.unwrap_err();
833 assert!(
834 err.to_string().contains("DOES-NOT-EXIST"),
835 "error should contain the missing ID"
836 );
837 }
838
839 #[test]
840 fn test_resolve_nonexistent_returns_error() {
841 let mut tc = None;
842 let mut pl = PersonList::default();
843
844 add_threaded_comment(
845 &mut tc,
846 &mut pl,
847 "A1",
848 &ThreadedCommentInput {
849 author: "Alice".to_string(),
850 text: "Exists".to_string(),
851 parent_id: None,
852 },
853 )
854 .unwrap();
855
856 let result = resolve_threaded_comment(&mut tc, "{DOES-NOT-EXIST}", true);
857 assert!(result.is_err());
858 let err = result.unwrap_err();
859 assert!(
860 err.to_string().contains("DOES-NOT-EXIST"),
861 "error should contain the missing ID"
862 );
863 }
864
865 #[test]
866 fn test_add_comment_invalid_cell_reference() {
867 let mut tc = None;
868 let mut pl = PersonList::default();
869
870 let result = add_threaded_comment(
871 &mut tc,
872 &mut pl,
873 "INVALID",
874 &ThreadedCommentInput {
875 author: "Alice".to_string(),
876 text: "Bad cell".to_string(),
877 parent_id: None,
878 },
879 );
880 assert!(result.is_err());
881
882 let result = add_threaded_comment(
883 &mut tc,
884 &mut pl,
885 "",
886 &ThreadedCommentInput {
887 author: "Alice".to_string(),
888 text: "Empty cell".to_string(),
889 parent_id: None,
890 },
891 );
892 assert!(result.is_err());
893 }
894}