1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use crate::routes::SortOrder;
use crate::view_model::ActixAdminViewModelFilter;
use crate::{ActixAdminError, ActixAdminViewModelField};
use actix_multipart::{Multipart, MultipartError};
use actix_web::web::Bytes;
use async_trait::async_trait;
use chrono::{NaiveDate, NaiveDateTime};
use futures_util::stream::StreamExt as _;
use sea_orm::{DatabaseConnection, EntityTrait};
use serde_derive::Serialize;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};

#[async_trait]
pub trait ActixAdminModelTrait {
    async fn list_model(
        db: &DatabaseConnection,
        page: u64,
        posts_per_page: u64,
        filter_values: HashMap<String, Option<String>>,
        search: &str,
        sort_by: &str,
        sort_order: &SortOrder
    ) -> Result<(u64, Vec<ActixAdminModel>), ActixAdminError>;
    fn get_fields() -> &'static [ActixAdminViewModelField];
    fn validate_model(model: &mut ActixAdminModel);
}

pub trait ActixAdminModelValidationTrait<T> {
    fn validate(_model: &T) -> HashMap<String, String> {
        return HashMap::new();
    }
}

pub struct ActixAdminModelFilter<E: EntityTrait> {
    pub name: String,
    pub filter_type: ActixAdminModelFilterType,
    pub filter: fn(sea_orm::Select<E>, Option<String>) -> sea_orm::Select<E>,
    pub values: Option<Vec<(String, String)>>
}

#[derive(Clone, Debug, Serialize)]
pub enum ActixAdminModelFilterType {
    Text,
    SelectList,
    Date,
    DateTime,
    Checkbox
}

#[async_trait]
pub trait ActixAdminModelFilterTrait<E: EntityTrait> {
    fn get_filter() -> Vec<ActixAdminModelFilter<E>> {
        Vec::new()
    }
    async fn get_filter_values(_filter: &ActixAdminModelFilter<E>, _db: &DatabaseConnection)-> Option<Vec<(String, String)>> {
        None
    }
}

impl<T: EntityTrait> From<ActixAdminModelFilter<T>> for ActixAdminViewModelFilter {
    fn from(filter: ActixAdminModelFilter<T>) -> Self {
        ActixAdminViewModelFilter {
            name: filter.name,
            value: None,
            values: None,
            filter_type: Some(filter.filter_type)
        }
    }
}

#[derive(Clone, Debug, Serialize)]
pub struct ActixAdminModel {
    pub primary_key: Option<String>,
    pub values: HashMap<String, String>,
    pub errors: HashMap<String, String>,
    pub custom_errors: HashMap<String, String>,
}

impl ActixAdminModel {
    pub fn create_empty() -> ActixAdminModel {
        ActixAdminModel {
            primary_key: None,
            values: HashMap::new(),
            errors: HashMap::new(),
            custom_errors: HashMap::new(),
        }
    }

    pub async fn create_from_payload(
        mut payload: Multipart, file_upload_folder: &str
    ) -> Result<ActixAdminModel, MultipartError> {
        let mut hashmap = HashMap::<String, String>::new();

        while let Some(item) = payload.next().await {
            let mut field = item?;

            let mut binary_data: Vec<Bytes> = Vec::new();
            while let Some(chunk) = field.next().await {
                binary_data.push(chunk.unwrap());
                //println!("-- CHUNK: \n{:?}", String::from_utf8(chunk.map_or(Vec::new(), |c| c.to_vec())));
                // let res_string = String::from_utf8(chunk.map_or(Vec::new(), |c| c.to_vec()));
            }
            let binary_data = binary_data.concat();
            if field.content_disposition().get_filename().is_some() {
                let mut filename = field
                    .content_disposition()
                    .get_filename()
                    .unwrap()
                    .to_string();

                let mut file_path = format!("{}/{}", file_upload_folder, filename);
                let file_exists = std::path::Path::new(&file_path).exists();
                // Avoid overwriting existing files
                if file_exists {
                    filename =  format!("{}_{}", SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(), filename);
                    file_path = format!("{}/{}", file_upload_folder, filename);
                }

                let file = File::create(file_path);
                let _res = file.unwrap().write_all(&binary_data);

                hashmap.insert(
                    field.name().to_string(),
                    filename.clone()
                );
            } else {
                let res_string = String::from_utf8(binary_data);
                if res_string.is_ok() {
                    hashmap.insert(field.name().to_string(), res_string.unwrap());
                }
            }
        }

        Ok(ActixAdminModel {
            primary_key: None,
            values: hashmap,
            errors: HashMap::new(),
            custom_errors: HashMap::new(),
        })
    }

    pub fn get_value<T: std::str::FromStr>(
        &self,
        key: &str,
        is_option_or_string: bool,
        is_allowed_to_be_empty: bool
    ) -> Result<Option<T>, String> {
        self.get_value_by_closure(key, is_option_or_string, is_allowed_to_be_empty, |val| val.parse::<T>())
    }

    pub fn get_datetime(
        &self,
        key: &str,
        is_option_or_string: bool,
        is_allowed_to_be_empty: bool
    ) -> Result<Option<NaiveDateTime>, String> {
        self.get_value_by_closure(key, is_option_or_string, is_allowed_to_be_empty, |val| {
            NaiveDateTime::parse_from_str(val, "%Y-%m-%dT%H:%M")
        })
    }

    pub fn get_date(
        &self,
        key: &str,
        is_option_or_string: bool,
        is_allowed_to_be_empty: bool
    ) -> Result<Option<NaiveDate>, String> {
        self.get_value_by_closure(key, is_option_or_string, is_allowed_to_be_empty, |val| {
            NaiveDate::parse_from_str(val, "%Y-%m-%d")
        })
    }

    pub fn get_bool(&self, key: &str, is_option_or_string: bool, is_allowed_to_be_empty: bool) -> Result<Option<bool>, String> {
        let val = self.get_value_by_closure(key, is_option_or_string, is_allowed_to_be_empty ,|val| {
            if !val.is_empty() && (val == "true" || val == "yes") {
                Ok(true)
            } else {
                Ok(false)
            }
        });
        // not selected bool field equals to false and not to missing
        match val {
            Ok(val) => Ok(val),
            Err(_) => Ok(Some(false)),
        }
    }

    fn get_value_by_closure<T: std::str::FromStr>(
        &self,
        key: &str,
        is_option_or_string: bool,
        is_allowed_to_be_empty: bool,
        f: impl Fn(&String) -> Result<T, <T as std::str::FromStr>::Err>,
    ) -> Result<Option<T>, String> {
        let value = self.values.get(key);

        let res: Result<Option<T>, String> = match value {
            Some(val) => {
                match (val.is_empty(), is_option_or_string, is_allowed_to_be_empty) {
                    (true, true, true) => return Ok(None),
                    (true, true, false) => return Err("Cannot be empty".to_string()),
                    _ => {}
                };

                let parsed_val = f(val);

                match parsed_val {
                    Ok(val) => Ok(Some(val)),
                    Err(_) => Err("Invalid Value".to_string()),
                }
            }
            _ => {
                match (is_option_or_string, is_allowed_to_be_empty) {
                    (true, true) => Ok(None),
                    (true, false) => Err("Cannot be empty".to_string()),
                    (false, _) => Err("Invalid Value".to_string()), // a missing value in the form for a non-optional value
                }
            }
        };

        res
    }

    pub fn has_errors(&self) -> bool {
        return (&self.errors.len() + &self.custom_errors.len()) != 0 as usize;
    }
}