176 lines
5.7 KiB
Rust
176 lines
5.7 KiB
Rust
use tracing::{debug, instrument};
|
|
use axum::{Extension, Json};
|
|
use std::collections::HashMap;
|
|
use serde_json::Value;
|
|
use axum::response::IntoResponse;
|
|
use axum::http::StatusCode;
|
|
use sea_orm::{ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter};
|
|
use anyhow::anyhow;
|
|
use axum::extract::{Multipart, Query};
|
|
use migration::{Condition, IntoCondition};
|
|
use chrono::{NaiveDate, NaiveTime};
|
|
use serde::Deserialize;
|
|
use crate::entity::time_entry::{ActiveModel, Entity as TimeEntry};
|
|
use crate::toggl_api::TogglApiClient;
|
|
use crate::toggl_api::types::{Current, Project, ProjectClient, ReportEntry, TogglQuery};
|
|
use crate::{entity, utils};
|
|
use crate::entity::time_entry;
|
|
|
|
#[instrument(skip(db, toggl_client))]
|
|
pub async fn report(
|
|
Extension(toggl_client): Extension<TogglApiClient>,
|
|
Extension(db): Extension<DatabaseConnection>,
|
|
Json(query): Json<TogglQuery>,
|
|
) -> utils::Result<Json<Vec<ReportEntry>>> {
|
|
let report = toggl_client.full_report(&query).await?;
|
|
debug!("Returned results: {:?}", report);
|
|
|
|
// We don't perform any deletes on report-fetched entries as they aren't necessarily exclusive
|
|
// on their time range.
|
|
cache_report(&db, &report, None).await?;
|
|
|
|
Ok(Json(report))
|
|
}
|
|
|
|
#[instrument(skip_all)]
|
|
pub async fn cache_report(
|
|
db: &DatabaseConnection,
|
|
models: &Vec<ReportEntry>,
|
|
exclusive_on: Option<Condition>,
|
|
) -> utils::Result<()> {
|
|
let models = models.iter().flat_map(|entry| entry.as_models());
|
|
let models = models.collect::<Vec<_>>();
|
|
let ids = models
|
|
.iter()
|
|
.map(|entry| entry.toggl_id.clone().unwrap())
|
|
.collect::<Vec<_>>();
|
|
debug!("Caching report entries: {:?}", models);
|
|
|
|
// TODO: Why is this needed?
|
|
if models.is_empty() {
|
|
return Ok(());
|
|
}
|
|
|
|
TimeEntry::insert_many(models)
|
|
.on_conflict(ReportEntry::grafting_conflict_statement())
|
|
.exec(db)
|
|
.await?;
|
|
|
|
if let Some(exclusive_on) = exclusive_on {
|
|
TimeEntry::delete_many()
|
|
.filter(
|
|
Condition::all()
|
|
.add(exclusive_on)
|
|
.add(time_entry::Column::TogglId.is_in(ids).not()),
|
|
)
|
|
.exec(db)
|
|
.await?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[instrument(skip(toggl_client))]
|
|
pub async fn current(
|
|
Extension(toggl_client): Extension<TogglApiClient>,
|
|
) -> utils::Result<Json<Option<Current>>> {
|
|
Ok(toggl_client.get_current().await.map(Json)?)
|
|
}
|
|
|
|
#[instrument(skip(toggl_client))]
|
|
pub async fn start_time_entry(
|
|
Extension(toggl_client): Extension<TogglApiClient>,
|
|
Json(body): Json<HashMap<String, Value>>,
|
|
) -> utils::Result<impl IntoResponse> {
|
|
toggl_client.start_time_entry(body).await?;
|
|
|
|
Ok((StatusCode::OK, "Ok"))
|
|
}
|
|
|
|
#[instrument(skip(db, toggl_client))]
|
|
pub async fn projects(
|
|
Extension(db): Extension<DatabaseConnection>,
|
|
Extension(toggl_client): Extension<TogglApiClient>,
|
|
) -> utils::Result<Json<Vec<Project>>> {
|
|
let projects = toggl_client.fetch_projects().await?;
|
|
|
|
entity::project::Entity::insert_many(projects.iter().map(Project::as_model))
|
|
.on_conflict(Project::grafting_conflict_statement())
|
|
.exec(&db)
|
|
.await?;
|
|
|
|
Ok(Json(projects))
|
|
}
|
|
|
|
#[instrument(skip(toggl_client, db))]
|
|
pub async fn clients(
|
|
Extension(db): Extension<DatabaseConnection>,
|
|
Extension(toggl_client): Extension<TogglApiClient>,
|
|
) -> utils::Result<Json<Vec<ProjectClient>>> {
|
|
let clients = toggl_client.fetch_clients().await?;
|
|
entity::client::Entity::insert_many(clients.iter().map(ProjectClient::as_model))
|
|
.on_conflict(ProjectClient::grafting_conflict_statement())
|
|
.exec(&db)
|
|
.await?;
|
|
|
|
Ok(Json(clients))
|
|
}
|
|
|
|
pub async fn health(Extension(toggl_client): Extension<TogglApiClient>) -> utils::Result<&'static str> {
|
|
return if toggl_client.check_health().await {
|
|
Ok("Ok")
|
|
} else {
|
|
Err(anyhow!("Panopto health check failed").into())
|
|
};
|
|
}
|
|
|
|
pub async fn import_csv(
|
|
Extension(db): Extension<DatabaseConnection>,
|
|
mut multipart: Multipart,
|
|
) -> utils::Result<impl IntoResponse> {
|
|
return Ok((StatusCode::NOT_IMPLEMENTED, "Not implemented"));
|
|
|
|
// while let Some(field) = multipart.next_field().await? {
|
|
// // if let Some("csv") = field.name() {
|
|
// // let csv = field.bytes().await?;
|
|
// // let mut csv = csv::Reader::from_reader(csv.as_ref());
|
|
// // let data = csv.records().filter_map(|f| f.ok()).map(from_csv_row);
|
|
// //
|
|
// // time_entry::Entity::insert_many(data.collect::<Result<_>>().unwrap())
|
|
// // .on_conflict(ReportEntry::grafting_conflict_statement())
|
|
// // .exec(&db)
|
|
// // .await
|
|
// // .unwrap()
|
|
// // }
|
|
// }
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
struct RefreshQuery {
|
|
start_date: Option<String>,
|
|
}
|
|
|
|
#[instrument(skip(toggl_client, db))]
|
|
pub async fn refresh(
|
|
Extension(toggl_client): Extension<TogglApiClient>,
|
|
Extension(db): Extension<DatabaseConnection>,
|
|
Query(RefreshQuery { start_date }): Query<RefreshQuery>,
|
|
) -> utils::Result<&'static str> {
|
|
let end_date = chrono::Utc::now();
|
|
let end_date_query_string = end_date.date_naive().format("%Y-%m-%d").to_string();
|
|
let start_date_query_string = start_date.unwrap_or(end_date_query_string.clone());
|
|
let start_date = NaiveDate::parse_from_str(&start_date_query_string, "%Y-%m-%d")?;
|
|
|
|
let query = TogglQuery {
|
|
start_date: Some(start_date_query_string),
|
|
end_date: Some(end_date_query_string),
|
|
..Default::default()
|
|
};
|
|
|
|
let report = toggl_client.full_report(&query).await?;
|
|
let exclusivity_condition = utils::day_exclusivity_condition(start_date, end_date.date_naive());
|
|
cache_report(&db, &report, Some(exclusivity_condition)).await?;
|
|
|
|
Ok("Ok")
|
|
}
|