2023-04-04 15:16:21 +02:00
|
|
|
use sqlx::SqlitePool;
|
|
|
|
|
2023-04-05 22:01:50 +02:00
|
|
|
use super::planned_event::PlannedEvent;
|
|
|
|
|
2023-04-04 15:16:21 +02:00
|
|
|
pub struct UserTrip {}
|
|
|
|
|
|
|
|
impl UserTrip {
|
2023-04-05 22:01:50 +02:00
|
|
|
pub async fn create(
|
|
|
|
db: &SqlitePool,
|
|
|
|
user_id: i64,
|
|
|
|
trip_details_id: i64,
|
|
|
|
) -> Result<(), UserTripError> {
|
|
|
|
if PlannedEvent::is_full(db, trip_details_id).await {
|
|
|
|
return Err(UserTripError::EventAlreadyFull);
|
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
|
|
|
match sqlx::query!(
|
2023-04-04 15:16:21 +02:00
|
|
|
"INSERT INTO user_trip (user_id, trip_details_id) VALUES(?, ?)",
|
|
|
|
user_id,
|
|
|
|
trip_details_id
|
|
|
|
)
|
|
|
|
.execute(db)
|
|
|
|
.await
|
2023-04-05 22:01:50 +02:00
|
|
|
{
|
|
|
|
Ok(_) => Ok(()),
|
|
|
|
Err(_) => Err(UserTripError::AlreadyRegistered),
|
|
|
|
}
|
2023-04-04 15:16:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn delete(db: &SqlitePool, user_id: i64, trip_details_id: i64) {
|
|
|
|
let _ = sqlx::query!(
|
|
|
|
"DELETE FROM user_trip WHERE user_id = ? AND trip_details_id = ?",
|
|
|
|
user_id,
|
|
|
|
trip_details_id
|
|
|
|
)
|
|
|
|
.execute(db)
|
|
|
|
.await
|
|
|
|
.is_ok();
|
|
|
|
}
|
|
|
|
}
|
2023-04-05 22:01:50 +02:00
|
|
|
|
|
|
|
pub enum UserTripError {
|
|
|
|
AlreadyRegistered,
|
|
|
|
AlreadyRegisteredAsCox,
|
|
|
|
EventAlreadyFull,
|
|
|
|
}
|