rowt/src/model/trip.rs

107 lines
2.8 KiB
Rust
Raw Normal View History

2023-04-04 15:16:21 +02:00
use chrono::NaiveDate;
use serde::Serialize;
use sqlx::SqlitePool;
#[derive(Serialize, Clone)]
pub struct Trip {
id: i64,
cox_id: i64,
cox_name: String,
trip_details_id: Option<i64>,
planned_starting_time: String,
max_people: i64,
day: String,
notes: Option<String>,
}
#[derive(Serialize)]
pub struct TripWithUser {
#[serde(flatten)]
trip: Trip,
rower: Vec<String>,
}
impl Trip {
pub async fn get_for_day(db: &SqlitePool, day: NaiveDate) -> Vec<TripWithUser> {
2023-04-04 19:49:27 +02:00
let day = format!("{day}");
2023-04-04 15:16:21 +02:00
let trips = sqlx::query_as!(
Trip,
"
SELECT trip.id, cox_id, user.name as cox_name, trip_details_id, planned_starting_time, max_people, day, notes
FROM trip
INNER JOIN trip_details ON trip.trip_details_id = trip_details.id
INNER JOIN user ON trip.cox_id = user.id
WHERE day=?
",
day
)
.fetch_all(db)
.await
.unwrap(); //TODO: fixme
let mut ret = Vec::new();
for trip in trips {
ret.push(TripWithUser {
trip: trip.clone(),
rower: Self::get_all_rower_for_id(db, trip.id).await,
2023-04-04 19:49:27 +02:00
});
2023-04-04 15:16:21 +02:00
}
ret
}
async fn get_all_rower_for_id(db: &SqlitePool, id: i64) -> Vec<String> {
let res = sqlx::query!(
"
SELECT (SELECT name FROM user WHERE user_trip.user_id = user.id) as name FROM user_trip WHERE trip_details_id = (SELECT trip_details_id FROM trip WHERE id = ?)
",
id
)
.fetch_all(db)
.await
.unwrap(); //TODO: fixme
2023-04-04 19:49:27 +02:00
res.into_iter().map(|x| x.name).collect()
2023-04-04 15:16:21 +02:00
}
pub async fn new_own(db: &SqlitePool, cox_id: i64, trip_details_id: i64) {
sqlx::query!(
"INSERT INTO trip (cox_id, trip_details_id) VALUES(?, ?)",
cox_id,
trip_details_id
)
.execute(db)
.await
.unwrap(); //TODO: fixme
}
/// Returns true if successfully inserted; false if not (e.g. because user is already
/// participant
pub async fn new_join(db: &SqlitePool, cox_id: i64, planned_event_id: i64) -> bool {
sqlx::query!(
"INSERT INTO trip (cox_id, planned_event_id) VALUES(?, ?)",
cox_id,
planned_event_id
)
.execute(db)
.await
.is_ok()
}
pub async fn delete(db: &SqlitePool, user_id: i64, planned_event_id: i64) {
let _ = sqlx::query!(
"DELETE FROM trip WHERE cox_id = ? AND planned_event_id = ?",
user_id,
planned_event_id
)
.execute(db)
.await
.is_ok();
}
//pub async fn delete(db: &SqlitePool, id: i64) {
// sqlx::query!("DELETE FROM planned_event WHERE id = ?", id)
// .execute(db)
// .await
// .unwrap(); //TODO: fixme
//}
}