rowt/src/model/usertrip.rs

103 lines
2.5 KiB
Rust

use sqlx::SqlitePool;
use super::tripdetails::TripDetails;
pub struct UserTrip {}
impl UserTrip {
pub async fn create(
db: &SqlitePool,
user_id: i64,
trip_details_id: i64,
) -> Result<(), UserTripError> {
let trip_details = TripDetails::find_by_id(db, trip_details_id)
.await
.ok_or(UserTripError::TripDetailsNotFound)?;
if trip_details.is_full(db).await {
return Err(UserTripError::EventAlreadyFull);
}
//check if cox if own event
let is_cox = sqlx::query!(
"SELECT count(*) as amount
FROM trip
WHERE trip_details_id = ?
AND cox_id = ?",
trip_details_id,
user_id
)
.fetch_one(db)
.await
.unwrap();
if is_cox.amount > 0 {
return Err(UserTripError::AlreadyRegisteredAsCox);
}
//check if cox if planned_event
let is_cox = sqlx::query!(
"SELECT count(*) as amount
FROM trip
WHERE planned_event_id = (
SELECT id FROM planned_event WHERE trip_details_id = ?
)
AND cox_id = ?",
trip_details_id,
user_id
)
.fetch_one(db)
.await
.unwrap();
if is_cox.amount > 0 {
return Err(UserTripError::AlreadyRegisteredAsCox);
}
match sqlx::query!(
"INSERT INTO user_trip (user_id, trip_details_id) VALUES(?, ?)",
user_id,
trip_details_id
)
.execute(db)
.await
{
Ok(_) => Ok(()),
Err(_) => Err(UserTripError::AlreadyRegistered),
}
}
pub async fn delete(db: &SqlitePool, user_id: i64, trip_details_id: i64) {
//TODO: Check if > 2 hrs to event
let _ = sqlx::query!(
"DELETE FROM user_trip WHERE user_id = ? AND trip_details_id = ?",
user_id,
trip_details_id
)
.execute(db)
.await
.is_ok();
}
}
#[derive(Debug)]
pub enum UserTripError {
AlreadyRegistered,
AlreadyRegisteredAsCox,
EventAlreadyFull,
TripDetailsNotFound,
}
#[cfg(test)]
mod test {
//use crate::testdb;
//use super::User;
//use sqlx::SqlitePool;
//#[sqlx::test]
//fn test_find_correct_id() {
// let pool = testdb!();
// let user = User::find_by_id(&pool, 1).await.unwrap();
// assert_eq!(user.id, 1);
//}
}