rec23-rs 0.2.82

A library for REC23 CRM.
Documentation
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use std::error::Error;
use bb8_postgres::bb8::Pool;
use bb8_postgres::PostgresConnectionManager;
use bb8_postgres::tokio_postgres::{GenericClient, NoTls, Row};
use chrono::{Local, NaiveDateTime, TimeDelta};
use frankenstein::{AsyncTelegramApi};
use frankenstein::client_reqwest::Bot;
use frankenstein::methods::SendMessageParams;
use paperclip::actix::Apiv2Schema;
use serde::{Deserialize, Serialize};
use crate::task::Task;
use crate::user::User;

const GET_TASK_NOTIFICATIONS_BY_TASK_ID: &str = "SELECT notify.id, notify.notify_date, notify.repeat, notify.last_notify_date, notify.text, notify.task_id FROM rec23.notify notify WHERE notify.task_id = $1";
const INSERT_NOTIFY: &str = "INSERT INTO rec23.notify (notify_date, repeat, last_notify_date, text, task_id) VALUES($1, $2, $3, $4, $5) RETURNING id";
const UPDATE_NOTIFY: &str = "UPDATE rec23.notify SET notify_date = $2, repeat = $3, last_notify_date = $4, text = $5, task_id = $6 WHERE id = $1";
const DELETE_NOTIFY_BY_ID: &str = "UPDATE rec23.notify SET repeat = false, deleted = true WHERE id = $1";
const DELETE_NOTIFY_BY_TASK_ID: &str = "UPDATE rec23.notify SET repeat = false, deleted = true WHERE task_id = $1";
const GET_NOTIFICATIONS: &str = "SELECT notify.id, notify.notify_date, notify.repeat, notify.last_notify_date, notify.text, notify.task_id FROM rec23.notify notify WHERE notify.deleted = FALSE AND EXISTS (SELECT 1 FROM rec23.task task WHERE task.id = notify.task_id AND task.task_status_id != 2)";
//const GET_NOTIFICATIONS: &str = "SELECT notify.id, notify.notify_date, notify.repeat, notify.last_notify_date, notify.text, notify.task_id, task.assignee_id, task.employee_id FROM rec23.notify notify JOIN rec23.task task ON task.id = notify.task_id AND task.task_status_id != 2 WHERE notify.deleted = FALSE";
const DELETE_COMPLETED_NOTIFICATION: &str = "DELETE FROM rec23.task_sub_completed task_sub_completed WHERE task_sub_completed.task_id = $1";
#[derive(Serialize, Deserialize, Apiv2Schema)]
pub struct Notification {
    pub id: Option<i32>,
    pub notify_date: NaiveDateTime,
    pub repeat: bool,
    pub last_notify_date: Option<NaiveDateTime>,
    pub text: String,
    pub task_id: Option<i32>,
}

#[derive(Debug, Clone)]
pub struct ClientNotification {
    pub notify_date: NaiveDateTime,
    pub repeat: bool,
    pub last_notify_date: Option<NaiveDateTime>,
    pub text: String,
    pub task_id: Option<i32>
}

impl Into<Notification> for ClientNotification {
    /// Converts a `ClientRec23Notification` instance into a `Rec23Notification` instance.
    ///
    /// This function takes ownership of `self`, a `ClientRec23Notification` instance, and
    /// returns a new `Rec23Notification` instance where `id` is set to None and all other fields
    /// are populated from the corresponding fields in `self`.
    ///
    /// # Arguments
    ///
    /// * `self` - The `ClientRec23Notification` instance that is to be converted into `Rec23Notification`.
    ///
    /// # Returns
    ///
    /// This function returns a `Rec23Notification` instance derived from the `ClientRec23Notification` instance

    fn into(self) -> Notification {
        Notification {
            id: None,
            notify_date: self.notify_date,
            repeat: self.repeat,
            last_notify_date: self.last_notify_date,
            text: self.text,
            task_id: self.task_id,
        }
    }
}

impl ClientNotification {
    /// Creates a new instance of `ClientRec23Notification`.
    ///
    /// This function will initialize a `ClientRec23Notification` with given parameters.
    ///
    /// # Arguments
    ///
    /// * `notify_date` - A `NaiveDateTime` value that represents the date for the notification.
    /// * `repeat` - A `bool` value that indicates whether the notification needs to repeat.
    /// * `last_notify_date` - An `Option<NaiveDateTime>` that represents the last time notification was triggered. This field can be None if the notification has not been triggered yet.
    /// * `text` - A `String` that contains the text of the notification.
    /// * `task_id` - An `Option<i32>` that represents the id of the associated task. This field can be None if there is no associated task.
    ///
    /// # Returns
    ///
    /// This function returns a `ClientRec23Notification` instance.
    ///
    /// # Example
    ///
    /// ```Rust
    /// let notify_date = Utc::now();
    /// let repeat = true;
    /// let last_notify_date = Some(Utc::now());
    /// let text = "Notification Text".to_string();
    /// let task_id = Some(1);
    ///
    /// let notification = ClientRec23Notification::new(notify_date, repeat, last_notify_date, text, task_id);
    /// ```

    pub fn new(notify_date: NaiveDateTime, repeat: bool, last_notify_date: Option<NaiveDateTime>, text: String, task_id: Option<i32>) -> Self {
        Self {
            notify_date,
            repeat,
            last_notify_date,
            text,
            task_id,
        }
    }

    /// This method is used to save a client's notification to the database.
    ///
    /// # Arguments
    ///
    /// * `self` - A `ClientRec23Notification` object which represents the notification to be saved. The object is consumed in this function.
    /// * `pool` - A pool of Postgres connections. This connection pool is used to connect to the database and perform the save operation.
    ///
    /// # Returns
    ///
    /// This method returns a Result. In case of a successful operation, it will return a `Rec23Notification` - the saved notification entity with a filled out id field. In case of failure, it returns an error wrapped in a Box.
    ///
    /// # Errors
    ///
    /// This function will return an error if there is any issue connecting to the database or executing the SQL statement.
    ///
    /// # Example
    ///
    /// ```Rust
    /// let notification = ClientRec23Notification::new(
    ///     DateTime::from(Utc::now()),
    ///     true,
    ///     Some(DateTime::from(Utc::now())),
    ///     String::from("This is a test notification"),
    ///     Some(1),
    /// );
    /// let conn_pool: Pool<PostgresConnectionManager<NoTls>> = create_pool();
    /// notification.save(&conn_pool).await;
    /// ```

    pub async fn save(self, pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<Notification, Box<dyn Error + Sync + Send>> {
        let connection = pool.get().await?;
        let client = connection.client();
        let row = client.query_one(INSERT_NOTIFY, &[&self.notify_date, &self.repeat, &self.last_notify_date, &self.text, &self.task_id]).await?;
        let mut result: Notification = self.into();
        result.id = Some(row.get(0));
        Ok(result)
    }
}

impl Notification {
    /// Fetches `Rec23Notification` records based on a given task ID.
    ///
    /// This function retrieves all notifications associated with
    /// a specific task ID from the database.
    ///
    /// # Arguments
    ///
    /// * `pool` - A pool of Postgres connections.
    /// * `id` - The task ID to filter notifications.
    ///
    /// # Returns
    ///
    /// This function returns a `Result` wrapping either a `Vec` of `Rec23Notification`
    /// or a boxed `Error`.
    ///
    /// # Example
    ///
    /// ```Rust
    /// let pool: Pool<PostgresConnectionManager<NoTls>> = create_pool();
    /// let task_id = 1;
    ///
    /// let notifications = Rec23Notification::get_by_task_id(&pool, task_id).await.unwrap();
    ///
    /// for notification in notifications {
    ///     println!("{:?}", notification);
    /// }
    /// ```

    pub async fn get_by_task_id(pool: &Pool<PostgresConnectionManager<NoTls>>, id: i32) -> Result<Vec<Self>, Box<dyn Error + Sync + Send>> {
        let connection = pool.get().await?;
        let client = connection.client();

        let rows = client.query(GET_TASK_NOTIFICATIONS_BY_TASK_ID, &[&id]).await?;

        let mut notifications = Vec::new();

        for row in rows {
            let notification = Self::convert_from_row(row);
            notifications.push(notification);
        }

        Ok(notifications)
    }

    /// Converts a `Row` object to `Rec23Notification`.
    ///
    /// This function is responsible for converting a returned `Row`
    /// from database query into a `Rec23Notification` instance.
    ///
    /// # Arguments
    ///
    /// * `row` - The `Row` object from database query.
    ///
    /// # Returns
    ///
    /// This function returns a `Rec23Notification` instance.
    ///
    /// # Example
    ///
    /// ```Rust
    /// // Assume `row` is a response from database query
    /// let notification = Rec23Notification::convert_from_row(row);
    /// ```

    pub fn convert_from_row(row: Row) -> Self {
        Self {
            id: row.get("id"),
            notify_date: row.get("notify_date"),
            repeat: row.get("repeat"),
            last_notify_date: row.get("last_notify_date"),
            text: row.get("text"),
            task_id: row.get("task_id"),
        }
    }

    /// This is an asynchronous method that saves an instance of Rec23Notification to the database.
    ///
    /// This method attempts to get a Postgres connection from the supplied Pool.
    /// It then uses this connection to execute an SQL UPDATE query that updates a notification
    /// with id, notify_date, repeat, last_notify_date, text, and task_id fields from the
    /// Rec23Notification instance.
    ///
    /// # Arguments
    ///
    /// * `self` - An instance of `Rec23Notification` that contains the updated fields.
    /// * `pool` - A `Pool` of `PostgresConnectionManager<NoTls>` that is used to get
    ///             a Postgres connection for executing the SQL UPDATE query.
    ///
    /// # Returns
    ///
    /// This method returns `Result<(), Box<dyn Error>>`. It returns `Ok(())` if the operation
    /// is successful, and `Err(Box<dyn Error>)` if it encounters any errors.
    ///
    /// # Example
    ///
    /// ```Rust
    /// let pool: Pool<PostgresConnectionManager<NoTls>> = create_pool();
    /// let rec23_notification = Rec23Notification{
    ///     id: Some(1),
    ///     notify_date: Utc::now(),
    ///     repeat: true,
    ///     last_notify_date: Some(Utc.now()),
    ///     text: "Updated Notification Text".to_string(),
    ///     task_id: Some(1),
    /// };
    /// rec23_notification.save(&pool).await?
    /// ```

    pub async fn save(&self, pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<(), Box<dyn Error + Sync + Send>> {
        let connection = pool.get().await?;
        let client = connection.client();
        client.execute(UPDATE_NOTIFY, &[&self.id, &self.notify_date, &self.repeat, &self.last_notify_date, &self.text, &self.task_id]).await?;
        Ok(())
    }

    pub fn is_employee_notification(&self) -> bool {
        self.text.contains("[EmployeeNotification]")
    }

    pub fn is_assignee_notification(&self) -> bool {
        self.text.contains("[AssigneeNotification]")
    }

    /// Sends a push notification to the specified chat ID using the given API and database connection pool.
    ///
    /// # Arguments
    ///
    /// * `chat_id` - The ID of the chat to send the notification to.
    /// * `api` - A reference to the `AsyncApi` object used to send the notification.
    /// * `pool` - A reference to the `Pool<PostgresConnectionManager<NoTls>>` object representing the database connection pool.
    ///
    /// # Errors
    ///
    /// Returns an error if there is an issue retrieving the task or any user information from the database, or if there is an error sending the message.
    ///
    /// # Example
    ///
    /// ```Rust
    /// use async_api::AsyncApi;
    /// use postgres::types::NoTls;
    /// use async_std::task;
    /// use sqlx::postgres::PgPool;
    /// use std::error::Error;
    ///
    /// #[async_std::main]
    /// async fn main() -> Result<(), Box<dyn Error>> {
    ///     let api = AsyncApi::new(...);
    ///     let pool = PgPool::new(...).await?;
    ///     let task_id = 123;
    ///     let chat_id = 456;
    ///
    ///     push_notify(task_id, chat_id, &api, &pool).await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn push_notify(&self, chat_id: i64, api: &Bot, pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<i32, Box<dyn Error + Sync + Send>> {
        let task = Task::get_by_id(self.task_id.unwrap(), pool).await?;
        let mut text = self.text.clone();
        if task.task_type != 3 {
            if let Some(task_header) = task.header {
                text = format!("{}\n{}", task_header, text);
            }
            if let Some(employee_id) = task.employee_id {
                if let Some(employee) = User::get_user_by_id(employee_id, pool).await? {
                    if let Some(telegram_name) = employee.telegram_name {
                        text.push_str(&format!("\n{}", telegram_name));
                    }

                    if task.task_type == 2 && (employee.dept_id.unwrap() == 3 || employee.dept_id.unwrap() == 5) {
                        if let Some(assignee) = User::get_user_by_id(task.assignee_id, pool).await? {
                            if let Some(telegram_name) = assignee.telegram_name {
                                text.push_str(&format!("\n{}", telegram_name));
                            }
                        }
                    }
                }
            }
        } else {
            if self.is_assignee_notification() {
                {
                    if let Some(assignee) = User::get_user_by_id(task.assignee_id, pool).await? {
                        if let Some(telegram_name) = assignee.telegram_name {
                            text.push_str(&format!("\n{}", telegram_name));
                        }
                    }
                }
            }
            if self.is_employee_notification() {
                if let Some(employee) = User::get_user_by_id(task.employee_id.unwrap(), pool).await? {
                    if let Some(telegram_name) = employee.telegram_name {
                        text.push_str(&format!("\n{}", telegram_name));
                    }
                }
            }
            text = text.replace("[EmployeeNotification]", "");
            text = text.replace("[AssigneeNotification]", "");
        }
        if text.len() == 0 {
            text = "-".to_string();
        }
        let send_message_params = SendMessageParams::builder().chat_id(chat_id).text(text).build();
        let result = api.send_message(&send_message_params).await?;
        Ok(result.result.message_id)
    }

    pub async fn push_notify_short(&self, chat_id: i64, api: &Bot, pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<i32, Box<dyn Error + Sync + Send>> {
        let task = Task::get_by_id(self.task_id.unwrap(), pool).await?;
        let mut text = self.text.clone();
        if let Some(task_header) = task.header {
            text = format!("{}\n{}", task_header, text);
        }
        if let Some(employee_id) = task.employee_id {
            if let Some(employee) = User::get_user_by_id(employee_id, pool).await? {
                if let Some(telegram_name) = employee.telegram_name {
                    text.push_str(&format!("\n{}", telegram_name));
                }
            }
        }
        if text.len() == 0 {
            text = "-".to_string();
        }
        let send_message_params = SendMessageParams::builder().chat_id(chat_id).text(text).build();
        let result = api.send_message(&send_message_params).await?;
        Ok(result.result.message_id)
    }

    pub async fn push_notify_header(&self, chat_id: i64, api: &Bot, pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<i32, Box<dyn Error + Sync + Send>> {
        let task = Task::get_by_id(self.task_id.unwrap(), pool).await?;
        let mut text = self.text.clone();
        if let Some(task_header) = task.header {
            text = format!("{}\n{}", task_header, text);
        }
        if text.len() == 0 {
            text = "-".to_string();
        }
        let send_message_params = SendMessageParams::builder().chat_id(chat_id).text(text).build();
        let result = api.send_message(&send_message_params).await?;
        Ok(result.result.message_id)
    }

    /// Deletes a record from the database using the given connection pool.
    ///
    /// # Arguments
    ///
    /// * `pool` - A reference to the connection pool.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the record is successfully deleted, otherwise returns an error.
    ///
    /// # Errors
    ///
    /// This function can return any error that implements the `Error` trait.
    /// Possible errors include:
    ///   - Connection pool errors, if the pool fails to establish a connection.
    ///   - Query execution errors, if the delete query fails to execute.
    ///
    /// # Examples
    ///
    /// ```Rust
    /// use sqlx::postgres::{PgPool, PgConnection};
    /// use anyhow::Result;
    ///
    /// async fn delete_record(pool: &PgPool) -> Result<()> {
    ///     let connection = pool.get().await?;
    ///     let client = connection.client();
    ///     client.execute(DELETE_NOTIFY_BY_ID, &[&self.id]).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn delete(self, pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<(), Box<dyn Error + Sync + Send>> {
        let connection = pool.get().await?;
        let client = connection.client();
        client.execute(DELETE_NOTIFY_BY_ID, &[&self.id]).await?;
        Ok(())
    }

    pub async fn delete_completed_notification(id: i32, pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<(), Box<dyn Error + Sync + Send>> {
        let connection = pool.get().await?;
        let client = connection.client();
        client.execute(DELETE_COMPLETED_NOTIFICATION, &[&id]).await?;
        Ok(())
    }

    /// Deletes notifications by task ID.
    ///
    /// This function deletes notifications based on the provided task ID. It takes a mutable reference to an `i32` representing the task ID
    /// and a mutable reference to a `Pool<PostgresConnectionManager<NoTls>>` representing the database connection pool.
    ///
    /// # Arguments
    ///
    /// * `task_id` - A mutable reference to an `i32` representing the task ID.
    /// * `pool` - A mutable reference to a `Pool<PostgresConnectionManager<NoTls>>` representing the database connection pool.
    ///
    /// # Returns
    ///
    /// This function returns a `Result<(), Box<dyn Error>>` indicating the result of the delete operation. If the operation is successful, `Ok(())` is returned.
    /// If an error occurs, an `Err` variant containing the specific error is returned.
    ///
    /// # Example
    ///
    /// ```Rust
    /// let task_id = 123;
    /// let pool = pool.clone();
    ///
    /// let result = delete_by_task_id(&task_id, &pool).await;
    ///
    /// assert!(result.is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn delete_by_task_id(task_id: &i32, pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<(), Box<dyn Error + Sync + Send>> {
        let connection = pool.get().await?;
        let client = connection.client();
        client.execute(DELETE_NOTIFY_BY_TASK_ID, &[task_id]).await?;
        Ok(())
    }

    /// Retrieves a list of notifications from the database.
    ///
    /// # Arguments
    ///
    /// * `pool` - A reference to a `Pool<PostgresConnectionManager<NoTls>>` object.
    ///
    /// # Returns
    ///
    /// * `Result<Vec<Notification>, Box<dyn Error>>` - A `Result` object where the `Ok` variant contains a vector of `Notification` objects if successful, or a `Box<dyn Error>` if an error occurs.
    ///
    /// # Example
    ///
    /// ```Rust
    /// const GET_NOTIFICATIONS: &str = "SELECT * FROM notifications";
    ///
    /// pub async fn get(pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<Vec<Notification>, Box<dyn Error>> {
    ///     let connection = pool.get().await?;
    ///     let client = connection.client();
    ///     let rows = client.query(GET_NOTIFICATIONS, &[]).await?;
    ///     let result = rows.into_iter().map(|row| Notification::convert_from_row(row)).collect();
    ///     Ok(result)
    /// }
    /// ```
    pub async fn get(pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<Vec<Notification>, Box<dyn Error + Sync + Send>> {
        let connection = pool.get().await?;
        let client = connection.client();
        let rows = client.query(GET_NOTIFICATIONS, &[]).await?;
        let result = rows.into_iter().map(|row| Notification::convert_from_row(row)).collect();
        Ok(result)
    }

    pub fn last_notify_date_checked_add_signed(&mut self, rhs: TimeDelta) {
        self.last_notify_date = Some(self.last_notify_date.unwrap_or(Local::now().naive_local()).checked_add_signed(rhs).unwrap());
    }

    pub fn signed_duration(&self) -> TimeDelta {
        let difference = Local::now().naive_local().signed_duration_since(self.last_notify_date.unwrap_or(Local::now().naive_local()));
        TimeDelta::new(difference.num_seconds(), 0).unwrap()
    }
}