koprogo_api/domain/entities/
user_role_assignment.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use uuid::Uuid;
4
5use super::user::UserRole;
6
7/// Represents an assignment of a role to a user within an optional organization scope.
8#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
9pub struct UserRoleAssignment {
10    pub id: Uuid,
11    pub user_id: Uuid,
12    pub role: UserRole,
13    pub organization_id: Option<Uuid>,
14    pub is_primary: bool,
15    pub created_at: DateTime<Utc>,
16    pub updated_at: DateTime<Utc>,
17}
18
19impl UserRoleAssignment {
20    /// Creates a new role assignment. Primary flag indicates the active role for the user.
21    pub fn new(
22        user_id: Uuid,
23        role: UserRole,
24        organization_id: Option<Uuid>,
25        is_primary: bool,
26    ) -> Self {
27        let now = Utc::now();
28        Self {
29            id: Uuid::new_v4(),
30            user_id,
31            role,
32            organization_id,
33            is_primary,
34            created_at: now,
35            updated_at: now,
36        }
37    }
38
39    pub fn set_primary(&mut self, primary: bool) {
40        self.is_primary = primary;
41        self.updated_at = Utc::now();
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_new_assignment_defaults() {
51        let user_id = Uuid::new_v4();
52        let assignment = UserRoleAssignment::new(user_id, UserRole::Syndic, None, true);
53
54        assert_eq!(assignment.user_id, user_id);
55        assert_eq!(assignment.role, UserRole::Syndic);
56        assert!(assignment.is_primary);
57        assert!(assignment.organization_id.is_none());
58    }
59
60    #[test]
61    fn test_set_primary_updates_timestamp() {
62        let mut assignment =
63            UserRoleAssignment::new(Uuid::new_v4(), UserRole::Accountant, None, false);
64        let original_updated_at = assignment.updated_at;
65
66        assignment.set_primary(true);
67
68        assert!(assignment.is_primary);
69        assert!(
70            assignment.updated_at > original_updated_at,
71            "Updated_at should change when toggling primary flag"
72        );
73    }
74}