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)
}
}