use actix_http::StatusCode;
use chrono::Days;
use uuid::Uuid;
use crate::{
config::data::SharedPool,
error::ServiceError,
model::{
dto::{
core::TimelinePage,
plantings::{
DeletePlantingDto, PlantingDto, PlantingSearchParameters, UpdatePlantingDto,
},
},
entity::{plantings::Planting, plantings_impl::FindPlantingsParameters},
},
};
pub const TIME_LINE_LOADING_OFFSET_DAYS: u64 = 356;
pub async fn find(
search_parameters: PlantingSearchParameters,
pool: &SharedPool,
) -> Result<TimelinePage<PlantingDto>, ServiceError> {
let mut conn = pool.get().await?;
let from = search_parameters
.relative_to_date
.checked_sub_days(Days::new(TIME_LINE_LOADING_OFFSET_DAYS))
.ok_or_else(|| {
ServiceError::new(
StatusCode::BAD_REQUEST,
"Could not add days to relative_to_date",
)
})?;
let to = search_parameters
.relative_to_date
.checked_add_days(Days::new(TIME_LINE_LOADING_OFFSET_DAYS))
.ok_or_else(|| {
ServiceError::new(
StatusCode::BAD_REQUEST,
"Could not add days to relative_to_date",
)
})?;
let search_parameters = FindPlantingsParameters {
layer_id: search_parameters.layer_id,
plant_id: search_parameters.plant_id,
from,
to,
};
let result = Planting::find(search_parameters, &mut conn).await?;
Ok(TimelinePage {
results: result,
from,
to,
})
}
pub async fn find_by_seed_id(
seed_id: i32,
pool: &SharedPool,
) -> Result<Vec<PlantingDto>, ServiceError> {
let mut conn = pool.get().await?;
let result = Planting::find_by_seed_id(seed_id, &mut conn).await?;
Ok(result)
}
pub async fn create(
dtos: Vec<PlantingDto>,
map_id: i32,
user_id: Uuid,
pool: &SharedPool,
) -> Result<Vec<PlantingDto>, ServiceError> {
let mut conn = pool.get().await?;
let result = Planting::create(dtos, map_id, user_id, &mut conn).await?;
Ok(result)
}
pub async fn update(
dto: UpdatePlantingDto,
map_id: i32,
user_id: Uuid,
pool: &SharedPool,
) -> Result<Vec<PlantingDto>, ServiceError> {
let mut conn = pool.get().await?;
let result = Planting::update(dto, map_id, user_id, &mut conn).await?;
Ok(result)
}
pub async fn delete_by_ids(
dtos: Vec<DeletePlantingDto>,
map_id: i32,
user_id: Uuid,
pool: &SharedPool,
) -> Result<(), ServiceError> {
let mut conn = pool.get().await?;
let _ = Planting::delete_by_ids(dtos, map_id, user_id, &mut conn).await?;
Ok(())
}