chimes_rust/entity/
chimes_user_roles.rs

1use rbatis::error::Error;
2use rbatis::rbatis::Rbatis;
3use serde_derive::{Deserialize, Serialize};
4/**
5 * Generate the file for chimes_user_roles.rs,
6 */
7use std::fmt::Debug;
8
9use crate::entity::ChimeProfileInfo;
10use crate::entity::ChimesRoleInfo;
11use crate::entity::ChimesUserInfo;
12use crate::entity::ChimesUserRoleInfo;
13
14#[derive(Debug, Clone, Default, Deserialize, Serialize)]
15pub struct ChimesUserRoles {
16    pub user_id: Option<i64>,
17    pub dept_id: Option<i64>,
18    pub company_id: Option<i64>,
19    pub company_code: Option<String>,
20    pub username: Option<String>,
21    pub nick_name: Option<String>,
22    pub gender: Option<String>,
23    pub phone: Option<String>,
24    pub email: Option<String>,
25    pub area_id: Option<String>,
26    pub avatar_name: Option<String>,
27    pub avatar_path: Option<String>,
28    pub password: Option<String>,
29    pub is_admin: Option<bool>,
30    pub open_id: Option<String>,
31    pub union_id: Option<String>,
32    pub enabled: Option<bool>,
33    pub create_by: Option<String>,
34    pub update_by: Option<String>,
35    pub data_scope: Option<String>,
36    pub pwd_reset_time: Option<rbatis::DateTimeNative>,
37    pub create_time: Option<rbatis::DateTimeNative>,
38    pub update_time: Option<rbatis::DateTimeNative>,
39    #[serde(rename(deserialize = "user_id"))]
40    pub profile: Option<ChimeProfileInfo>,
41    #[serde(rename(deserialize = "role_id"))]
42    pub roles: Vec<ChimesRoleInfo>,
43}
44
45impl ChimesUserRoles {
46    #[allow(dead_code)]
47    pub fn from_user(param: &ChimesUserInfo) -> Self {
48        ChimesUserRoles {
49            user_id: param.user_id,
50            dept_id: param.dept_id,
51            username: param.username.clone(),
52            nick_name: param.nick_name.clone(),
53            gender: param.gender.clone(),
54            phone: param.phone.clone(),
55            email: param.email.clone(),
56            area_id: param.area_id.clone(),
57            avatar_name: param.avatar_name.clone(),
58            avatar_path: param.avatar_path.clone(),
59            password: param.password.clone(),
60            is_admin: param.is_admin,
61            enabled: param.enabled,
62            open_id: param.open_id.clone(),
63            union_id: param.union_id.clone(),
64            create_by: param.create_by.clone(),
65            update_by: param.update_by.clone(),
66            data_scope: param.data_scope.clone(),
67            pwd_reset_time: param.pwd_reset_time,
68            create_time: param.create_time,
69            update_time: param.update_time,
70            company_code: param.company_code.clone(),
71            company_id: param.company_id,
72            profile: None,
73            roles: vec![],
74        }
75    }
76
77    #[allow(dead_code)]
78    pub fn to_user(&self) -> ChimesUserInfo {
79        let roles = self
80            .roles
81            .clone()
82            .into_iter()
83            .map(|f| f.role_code.unwrap_or_default())
84            .collect::<Vec<String>>()
85            .join(",");
86        ChimesUserInfo {
87            user_id: self.user_id,
88            dept_id: self.dept_id,
89            username: self.username.clone(),
90            nick_name: self.nick_name.clone(),
91            gender: self.gender.clone(),
92            phone: self.phone.clone(),
93            email: self.email.clone(),
94            area_id: self.area_id.clone(),
95            avatar_name: self.avatar_name.clone(),
96            avatar_path: self.avatar_path.clone(),
97            password: self.password.clone(),
98            is_admin: self.is_admin,
99            open_id: self.open_id.clone(),
100            union_id: self.union_id.clone(),
101            data_scope: self.data_scope.clone(),
102            company_code: self.company_code.clone(),
103            company_id: self.company_id,
104            enabled: self.enabled,
105            create_by: self.create_by.clone(),
106            update_by: self.update_by.clone(),
107            pwd_reset_time: self.pwd_reset_time,
108            create_time: self.create_time,
109            update_time: self.update_time,
110            simulate_roles: if roles.is_empty() { None } else { Some(roles) },
111        }
112    }
113
114    #[allow(dead_code)]
115    pub async fn find_user_by_role(
116        rb: &Rbatis,
117        role_name: &str,
118    ) -> Result<Vec<ChimesUserInfo>, Error> {
119        let mut sql = "select cu.* from chimes_user cu inner join chimes_users_roles cur on cur.user_id = cu.user_id inner join chimes_role cr on cr.role_id = cur.role_id ".to_string();
120        let mut rb_args = vec![];
121        if role_name.contains(',') {
122            let role_names = role_name
123                .split(',')
124                .map(|f| f.trim().to_string())
125                .collect::<Vec<String>>();
126            sql.push_str(" where cr.role_code in (");
127            for rn in role_names {
128                sql.push_str("?,");
129                rb_args.push(rbson::to_bson(&rn.clone()).unwrap_or_default());
130            }
131            if sql.ends_with(',') {
132                sql.remove(sql.len() - 1);
133            }
134            sql.push(')');
135        } else {
136            sql.push_str(" where cr.role_code = ?");
137            rb_args.push(rbson::to_bson(role_name.to_owned()).unwrap_or_default());
138        }
139        rb.fetch::<Vec<ChimesUserInfo>>(&sql, rb_args).await
140    }
141
142    #[allow(dead_code)]
143    pub async fn load(rb: &Rbatis, user_id: &i64) -> Result<Option<Self>, Error> {
144        match ChimesUserInfo::from_id(rb, user_id).await {
145            Ok(ts) => match ts {
146                Some(mp) => {
147                    let mut selfmp = Self::from_user(&mp);
148                    let tmp_profile = ChimeProfileInfo {
149                        user_id: selfmp.user_id,
150                        ..Default::default()
151                    };
152                    selfmp.profile = match tmp_profile.query_list(rb).await {
153                        Ok(lst) => {
154                            if !lst.is_empty() {
155                                Some(lst[0].clone())
156                            } else {
157                                None
158                            }
159                        }
160                        Err(_) => None,
161                    };
162                    let mut rb_args = vec![];
163                    let sql_role = "SELECT tp.* FROM chimes_role tp INNER JOIN chimes_users_roles mt ON tp.role_id = mt.role_id WHERE mt.user_id = ?";
164                    rb_args.push(
165                        rbson::to_bson(selfmp.user_id.unwrap_or_default()).unwrap_or_default(),
166                    );
167                    selfmp.roles = match rb.fetch(sql_role, rb_args).await {
168                        Ok(lst) => lst,
169                        Err(_) => {
170                            vec![]
171                        }
172                    };
173                    Ok(Some(selfmp))
174                }
175                None => Ok(None),
176            },
177            Err(err) => Err(err),
178        }
179    }
180
181    #[allow(dead_code)]
182    pub async fn save(&self, rb: &Rbatis) -> Result<bool, Error> {
183        let mut ret: Option<Error>;
184        let mut self_user = self.to_user();
185        if self_user.user_id.is_none() {
186            ret = match self_user.save(rb).await {
187                Ok(_rs) => None,
188                Err(err) => {
189                    log::warn!("Save user occurred an error {}", err);
190                    Some(err)
191                }
192            }
193        } else {
194            ret = match self_user.update(rb).await {
195                Ok(_rs) => None,
196                Err(err) => {
197                    log::warn!("Update user occurred an error {}", err);
198                    Some(err)
199                }
200            }
201        }
202        if ret.is_none() {
203            ret = match self.profile.clone() {
204                Some(tp) => {
205                    let mut mtp = tp.clone();
206                    mtp.user_id = self_user.user_id;
207                    if mtp.user_id.is_none() {
208                        match mtp.save(rb).await {
209                            Ok(_mtpsave) => None,
210                            Err(err) => {
211                                log::warn!("Save profile occurred an error {}", err);
212                                Some(err)
213                            }
214                        }
215                    } else {
216                        match mtp.update(rb).await {
217                            Ok(_mtpsave) => None,
218                            Err(err) => {
219                                log::warn!("Save profile occurred an error {}", err);
220                                Some(err)
221                            }
222                        }
223                    }
224                }
225                None => None,
226            };
227        }
228        // remove batch for ChimesUserRoleInfo.
229        if ret.is_none() {
230            let rm_user_role_info = ChimesUserRoleInfo {
231                role_id: self.user_id,
232                ..Default::default()
233            };
234            ret = match rm_user_role_info.remove_batch(rb).await {
235                Ok(_) => None,
236                Err(err) => {
237                    log::warn!("Remove user_role_info occurred an error {}", err);
238                    Some(err)
239                }
240            };
241        }
242        for row in self.roles.clone() {
243            let mut svrow_user_role_info = ChimesUserRoleInfo {
244                user_id: self.user_id,
245                role_id: row.role_id,
246            };
247            ret = match svrow_user_role_info.save(rb).await {
248                Ok(_) => None,
249                Err(err) => {
250                    log::warn!("Save user_role_info occurred an error {}", err);
251                    Some(err)
252                }
253            };
254        }
255        match ret {
256            Some(err) => Err(err),
257            None => Ok(true),
258        }
259    }
260
261    #[allow(dead_code)]
262    pub async fn remove(&self, rb: &Rbatis) -> Result<bool, Error> {
263        let mut ret: Option<Error> = None;
264        if ret.is_none() {
265            ret = match self.profile.clone() {
266                Some(tp) => {
267                    let mut mtp = tp.clone();
268                    match mtp.remove(rb).await {
269                        Ok(_rtremove) => None,
270                        Err(err) => {
271                            log::warn!("Remove profile occurred an error {}", err);
272                            Some(err)
273                        }
274                    }
275                }
276                None => None,
277            };
278        }
279        // remove batch for ChimesUserRoleInfo.
280        if ret.is_none() {
281            let rm_user_role_info = ChimesUserRoleInfo {
282                role_id: self.user_id,
283                ..Default::default()
284            };
285
286            ret = match rm_user_role_info.remove_batch(rb).await {
287                Ok(_rtremove) => None,
288                Err(err) => {
289                    log::warn!("Remove user_role_info occurred an error {}", err);
290                    Some(err)
291                }
292            };
293        }
294        if let Some(ret) = ret {
295            Err(ret)
296        } else {
297            match self.to_user().remove(rb).await {
298                Ok(_rs) => Ok(true),
299                Err(err) => {
300                    log::warn!("Remove user occurred an error {}", err);
301                    Err(err)
302                }
303            }
304        }
305    }
306}