DEVELOPMENT ENVIRONMENT

~liljamo/ulairi

ref: e78be1f39347874c13c8ff1c08025ec375b5e928 ulairi/ulairi-api/src/hour_entries/model.rs -rw-r--r-- 2.2 KiB
e78be1f3Jonni Liljamo I lost the old commit history... 1 year, 11 months ago
                                                                                
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
use crate::schema::hour_entries;

use diesel;
use diesel::pg::PgConnection;
use diesel::prelude::*;

use serde::{Deserialize, Serialize};

use chrono::NaiveDate;

#[derive(Serialize, Deserialize, Queryable, AsChangeset)]
#[table_name = "hour_entries"]
pub struct HourEntry {
    pub id: i32,
    pub user_id: i32,
    pub hours: i32,
    pub date_worked: NaiveDate,
    pub date_entered: NaiveDate,
}

#[derive(Serialize, Deserialize, Insertable)]
#[table_name = "hour_entries"]
pub struct InsertableHourEntry {
    pub user_id: i32,
    pub hours: i32,
    pub date_worked: NaiveDate,
    pub date_entered: NaiveDate,
}

impl HourEntry {
    pub fn create(
        user_id: i32,
        hours: i32,
        date_worked: String,
        connection: &PgConnection,
    ) -> QueryResult<HourEntry> {
        let date_worked = NaiveDate::parse_from_str(&date_worked, "%Y-%m-%d").unwrap();
        let date_entered = chrono::Utc::now().naive_utc().date();

        // Create a new hour entry
        let hour_entry = InsertableHourEntry {
            user_id,
            hours,
            date_worked,
            date_entered,
        };

        // Insert the new hour entry
        diesel::insert_into(hour_entries::table)
            .values(hour_entry)
            .execute(connection)?;

        // Return the new hour entry
        hour_entries::table
            .order(hour_entries::id.desc())
            .first(connection)
    }

    pub fn delete(id: i32, connection: &PgConnection) -> QueryResult<HourEntry> {
        // Delete the hour entry
        diesel::delete(hour_entries::table.find(id)).execute(connection)?;

        // Find entry with id, returns an error if not found, which we want
        hour_entries::table
            .filter(hour_entries::id.eq(id))
            .first(connection)
    }

    pub fn get_all(user_id: i32, connection: &PgConnection) -> QueryResult<Vec<HourEntry>> {
        hour_entries::table
            .filter(hour_entries::user_id.eq(user_id))
            .order(hour_entries::date_worked.desc())
            .load(connection)
    }

    pub fn get_by_id(id: i32, connection: &PgConnection) -> QueryResult<HourEntry> {
        hour_entries::table
            .filter(hour_entries::id.eq(id))
            .first(connection)
    }
}