Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vingo: add recent scans #112

Merged
merged 3 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions vingo/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions vingo/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,5 @@ tracing = "=0.1"
tracing-subscriber = "=0.3"

migration = { path = "migration" }
dotenvy = "0.15.7"
sea-query = { version = "0.32.0", default-features = false}
7 changes: 5 additions & 2 deletions vingo/migration/src/m20240903_194156_create_scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ pub struct Migration;
enum Scan {
Table,
Id,
Time,
#[allow(clippy::enum_variant_names)] //TODO: rename ScanTime -> Time
ScanTime,
CardSerial,
}

Expand All @@ -22,7 +23,9 @@ impl MigrationTrait for Migration {
.table(Scan::Table)
.col(pk_auto(Scan::Id))
.col(text(Scan::CardSerial))
.col(timestamp_with_time_zone(Scan::Time).default(Expr::current_timestamp()))
.col(
timestamp_with_time_zone(Scan::ScanTime).default(Expr::current_timestamp()),
)
.foreign_key(
ForeignKey::create()
.from(Scan::Table, Scan::CardSerial)
Expand Down
5 changes: 4 additions & 1 deletion vingo/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ struct RegisterState {

#[tokio::main]
async fn main() {
let _ = dotenvy::dotenv();

tracing_subscriber::fmt()
.with_max_level(tracing::Level::DEBUG)
.init();
Expand Down Expand Up @@ -103,6 +105,8 @@ fn open_routes() -> Router<AppState> {
.route("/auth/callback", get(auth::callback))
.route("/scans", post(scans::add))
.route("/version", get(info::version))
.route("/recent_scans", get(scans::recent))
.route("/seasons", get(seasons::get_until_now))
}

fn authenticated_routes() -> Router<AppState> {
Expand All @@ -118,7 +122,6 @@ fn authenticated_routes() -> Router<AppState> {
)
.route("/scans", get(scans::get_for_current_user))
.route("/leaderboard", get(leaderboard::get))
.route("/seasons", get(seasons::get_until_now))
.route("/settings", get(settings::get).patch(settings::update))
.route_layer(from_fn(middleware::is_logged_in))
}
Expand Down
47 changes: 44 additions & 3 deletions vingo/src/routes/scans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,16 @@ use crate::{
};

use axum::{extract::State, Json};
use chrono::Local;
use chrono::{Duration, Local};
use migration::Expr;
use reqwest::StatusCode;
use sea_orm::{
ActiveModelTrait, ColumnTrait, EntityTrait, JoinType::InnerJoin, QueryFilter, QuerySelect,
RelationTrait, Set,
entity::prelude::DateTimeWithTimeZone,
ActiveModelTrait, ColumnTrait, EntityTrait, FromQueryResult, IdenStatic,
JoinType::{self, InnerJoin},
QueryFilter, QueryOrder, QuerySelect, RelationTrait, Set,
};
use serde::Serialize;
use tower_sessions::Session;

use super::util::{
Expand Down Expand Up @@ -102,3 +106,40 @@ pub async fn add(state: State<AppState>, body: String) -> ResponseResult<String>

Ok(user.name)
}

#[derive(Debug, FromQueryResult, Serialize)]
pub struct RecentScanItem {
id: i32,
scan_time: DateTimeWithTimeZone,
}

pub async fn recent(state: State<AppState>) -> ResponseResult<Json<Vec<RecentScanItem>>> {
let fourteen_days_ago = (Local::now() - Duration::days(14)).naive_local();
let scans = Scan::find()
.select_only()
.expr(Expr::cust(format!(
"DISTINCT ON ({}, DATE({})) scan.{}, scan.{}", //NOTE: this is a pain
card::Column::UserId.as_str(),
scan::Column::ScanTime.as_str(),
scan::Column::Id.as_str(),
scan::Column::ScanTime.as_str(),
)))
.join(JoinType::InnerJoin, scan::Relation::Card.def())
.join(JoinType::InnerJoin, card::Relation::User.def())
xerbalind marked this conversation as resolved.
Show resolved Hide resolved
.filter(scan::Column::ScanTime.gt(fourteen_days_ago))
.order_by_asc(card::Column::UserId)
Topvennie marked this conversation as resolved.
Show resolved Hide resolved
.order_by_asc(Expr::cust(format!(
"DATE({})",
scan::Column::ScanTime.as_str()
)))
.order_by_asc(scan::Column::Id)
.into_model::<RecentScanItem>()
.all(&state.db)
.await
.or_log((
StatusCode::INTERNAL_SERVER_ERROR,
"could not get all recent scans",
))?;

Ok(Json(scans))
}
Loading