common/direct_access/use_cases/
move_relationship.rs1use super::traits::WriteRelUoWFactory;
4use crate::types::EntityId;
5use crate::undo_redo::UndoRedoCommand;
6use anyhow::Result;
7use std::any::Any;
8use std::collections::VecDeque;
9
10pub struct MoveRelationshipUseCase<RF, F: WriteRelUoWFactory<RF>> {
15 uow_factory: F,
16 _phantom: std::marker::PhantomData<RF>,
17}
18
19impl<RF, F: WriteRelUoWFactory<RF>> MoveRelationshipUseCase<RF, F> {
20 pub fn new(uow_factory: F) -> Self {
21 MoveRelationshipUseCase {
22 uow_factory,
23 _phantom: std::marker::PhantomData,
24 }
25 }
26
27 pub fn execute(
28 &mut self,
29 id: &EntityId,
30 field: &RF,
31 ids_to_move: &[EntityId],
32 new_index: i32,
33 ) -> Result<Vec<EntityId>> {
34 let mut uow = self.uow_factory.create();
35 uow.begin_transaction()?;
36 let result = uow.move_relationship(id, field, ids_to_move, new_index)?;
37 uow.commit()?;
38 Ok(result)
39 }
40}
41
42pub struct UndoableMoveRelationshipUseCase<RF: Clone, F: WriteRelUoWFactory<RF>> {
47 uow_factory: F,
48 undo_stack: VecDeque<(EntityId, RF, Vec<EntityId>)>,
52 redo_stack: VecDeque<(EntityId, RF, Vec<EntityId>)>,
53}
54
55impl<RF: Clone, F: WriteRelUoWFactory<RF>> UndoableMoveRelationshipUseCase<RF, F> {
56 pub fn new(uow_factory: F) -> Self {
57 UndoableMoveRelationshipUseCase {
58 uow_factory,
59 undo_stack: VecDeque::new(),
60 redo_stack: VecDeque::new(),
61 }
62 }
63
64 pub fn execute(
65 &mut self,
66 id: &EntityId,
67 field: &RF,
68 ids_to_move: &[EntityId],
69 new_index: i32,
70 ) -> Result<Vec<EntityId>> {
71 let mut uow = self.uow_factory.create();
72 uow.begin_transaction()?;
73 let before = uow.get_relationship(id, field)?;
74 let result = uow.move_relationship(id, field, ids_to_move, new_index)?;
75 uow.commit()?;
76 self.undo_stack.push_back((*id, field.clone(), before));
77 self.redo_stack.clear();
79 Ok(result)
80 }
81}
82
83impl<RF: Clone + Send + 'static, F: WriteRelUoWFactory<RF> + Send + 'static> UndoRedoCommand
84 for UndoableMoveRelationshipUseCase<RF, F>
85{
86 fn undo(&mut self) -> Result<()> {
87 if let Some((id, field, before)) = self.undo_stack.pop_back() {
88 let mut uow = self.uow_factory.create();
89 uow.begin_transaction()?;
90 let current = uow.get_relationship(&id, &field)?;
92 uow.set_relationship(&id, &field, &before)?;
93 uow.commit()?;
94 self.redo_stack.push_back((id, field, current));
95 }
96 Ok(())
97 }
98
99 fn redo(&mut self) -> Result<()> {
100 if let Some((id, field, after)) = self.redo_stack.pop_back() {
101 let mut uow = self.uow_factory.create();
102 uow.begin_transaction()?;
103 let before = uow.get_relationship(&id, &field)?;
104 uow.set_relationship(&id, &field, &after)?;
105 uow.commit()?;
106 self.undo_stack.push_back((id, field, before));
107 }
108 Ok(())
109 }
110
111 fn as_any(&self) -> &dyn Any {
112 self
113 }
114}