first commit

This commit is contained in:
phattaranun.a committed 2026-05-24 22:55:17 +07:00
commit 2a1854ab08
120 files changed
+11300

No files matched your search

+1
View File
@@ -0,0 +1 @@
// no DTOs beyond path id
+18
View File
@@ -0,0 +1,18 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{
extract::{Path, State},
http::StatusCode,
routing::delete,
Router,
};
use uuid::Uuid;
pub fn route() -> Router<AppState> {
Router::new().route("/api/images/:id", delete(handler))
}
async fn handler(State(state): State<AppState>, Path(id): Path<Uuid>) -> AppResult<StatusCode> {
service::handle(&state, id).await?;
Ok(StatusCode::NO_CONTENT)
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+34
View File
@@ -0,0 +1,34 @@
use sqlx::PgPool;
use uuid::Uuid;
pub struct ImageRowMin {
pub fid: String,
pub url_path: String,
}
pub async fn fetch_min(pool: &PgPool, id: Uuid) -> Result<Option<ImageRowMin>, sqlx::Error> {
let row: Option<(String, String)> =
sqlx::query_as("SELECT fid, url_path FROM images WHERE id = $1")
.bind(id)
.fetch_optional(pool)
.await?;
Ok(row.map(|(fid, url_path)| ImageRowMin { fid, url_path }))
}
pub async fn delete(pool: &PgPool, id: Uuid) -> Result<u64, sqlx::Error> {
let r = sqlx::query("DELETE FROM images WHERE id = $1")
.bind(id)
.execute(pool)
.await?;
Ok(r.rows_affected())
}
pub async fn mark_pending_gc(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> {
sqlx::query(
"UPDATE images SET meta = meta || '{\"pending_gc\":true}'::jsonb WHERE id = $1",
)
.bind(id)
.execute(pool)
.await?;
Ok(())
}
+25
View File
@@ -0,0 +1,25 @@
use super::repo;
use crate::{error::{AppError, AppResult}, state::AppState};
use uuid::Uuid;
pub async fn handle(state: &AppState, id: Uuid) -> AppResult<()> {
let Some(row) = repo::fetch_min(&state.db, id).await? else {
return Err(AppError::NotFound);
};
// strip public_base prefix to compute filer relative path
let rel = row
.url_path
.strip_prefix(state.public_base.as_str())
.unwrap_or(&row.url_path);
match state.seaweed.delete(rel).await {
Ok(()) => {
repo::delete(&state.db, id).await?;
Ok(())
}
Err(e) => {
tracing::warn!("filer delete failed for {id}: {e:?}; marking pending_gc");
repo::mark_pending_gc(&state.db, id).await?;
Err(AppError::Internal("storage delete failed".into()))
}
}
}
+16
View File
@@ -0,0 +1,16 @@
use serde::Serialize;
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct RouteDetail {
pub route_id: String,
pub name_th: String,
pub vehicle_type: String,
pub route_group_id: i16,
pub route_group_code: String,
pub route_group_label_th: String,
pub contact: SqlxJson<serde_json::Value>,
pub metadata: SqlxJson<serde_json::Value>,
pub province_ids: Vec<i16>,
pub images: SqlxJson<serde_json::Value>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Path, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/routes/:route_id", get(handler))
}
async fn handler(
State(state): State<AppState>,
Path(route_id): Path<String>,
) -> AppResult<Json<serde_json::Value>> {
let row = service::handle(&state, &route_id).await?;
Ok(Json(serde_json::to_value(row).unwrap()))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+31
View File
@@ -0,0 +1,31 @@
use super::dto::RouteDetail;
use sqlx::PgPool;
pub async fn fetch(pool: &PgPool, route_id: &str) -> Result<Option<RouteDetail>, sqlx::Error> {
let sql = r#"
SELECT r.route_id,
r.name_th,
r.vehicle_type::text AS vehicle_type,
r.route_group_id,
g.code AS route_group_code,
g.label_th AS route_group_label_th,
r.contact,
r.metadata,
COALESCE(ARRAY(SELECT province_id FROM route_provinces rp WHERE rp.route_id = r.route_id ORDER BY province_id), '{}') AS province_ids,
COALESCE((
SELECT jsonb_agg(jsonb_build_object(
'id', i.id, 'kind', i.kind, 'url_path', i.url_path,
'display_order', i.display_order, 'meta', i.meta
) ORDER BY i.display_order)
FROM images i
WHERE i.entity_type = 'route' AND i.entity_id = r.route_id
), '[]'::jsonb) AS images
FROM routes r
JOIN route_groups g ON g.id = r.route_group_id
WHERE r.route_id = $1
"#;
sqlx::query_as::<_, RouteDetail>(sql)
.bind(route_id)
.fetch_optional(pool)
.await
}
+8
View File
@@ -0,0 +1,8 @@
use super::{dto::RouteDetail, repo};
use crate::{error::{AppError, AppResult}, state::AppState};
pub async fn handle(state: &AppState, route_id: &str) -> AppResult<RouteDetail> {
repo::fetch(&state.db, route_id)
.await?
.ok_or(AppError::NotFound)
}
+18
View File
@@ -0,0 +1,18 @@
use serde::Serialize;
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct StopDetail {
pub id: i32,
pub code: String,
pub name_th: String,
pub city_th: Option<String>,
pub province_th: Option<String>,
pub station_type: String,
pub attributes: SqlxJson<serde_json::Value>,
pub metadata: SqlxJson<serde_json::Value>,
pub images: SqlxJson<serde_json::Value>,
pub routes: SqlxJson<serde_json::Value>,
pub lng: Option<f64>,
pub lat: Option<f64>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Path, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/stops/:stop_code", get(handler))
}
async fn handler(
State(state): State<AppState>,
Path(code): Path<String>,
) -> AppResult<Json<serde_json::Value>> {
let row = service::handle(&state, &code).await?;
Ok(Json(serde_json::to_value(row).unwrap()))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+38
View File
@@ -0,0 +1,38 @@
use super::dto::StopDetail;
use sqlx::PgPool;
pub async fn fetch(pool: &PgPool, code: &str) -> Result<Option<StopDetail>, sqlx::Error> {
let sql = r#"
SELECT s.id, s.code, s.name_th, s.city_th, s.province_th,
s.station_type::text AS station_type,
s.attributes, s.metadata,
COALESCE((
SELECT jsonb_agg(jsonb_build_object(
'id', i.id, 'kind', i.kind, 'url_path', i.url_path,
'display_order', i.display_order, 'meta', i.meta
) ORDER BY i.display_order)
FROM images i
WHERE i.entity_type = 'station' AND i.entity_id = s.code
), '[]'::jsonb) AS images,
COALESCE((
SELECT jsonb_agg(jsonb_build_object(
'route_id', r.route_id,
'name_th', r.name_th,
'vehicle_type', r.vehicle_type::text,
'route_group_code', g.code,
'route_group_label_th', g.label_th
) ORDER BY rs.stop_sequence, r.route_id)
FROM route_stops rs
JOIN routes r ON r.route_id = rs.route_id
JOIN route_groups g ON g.id = r.route_group_id
WHERE rs.station_id = s.id
), '[]'::jsonb) AS routes,
s.lng, s.lat
FROM stations s
WHERE s.code = $1
"#;
sqlx::query_as::<_, StopDetail>(sql)
.bind(code)
.fetch_optional(pool)
.await
}
+6
View File
@@ -0,0 +1,6 @@
use super::{dto::StopDetail, repo};
use crate::{error::{AppError, AppResult}, state::AppState};
pub async fn handle(state: &AppState, code: &str) -> AppResult<StopDetail> {
repo::fetch(&state.db, code).await?.ok_or(AppError::NotFound)
}
+15
View File
@@ -0,0 +1,15 @@
use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize)]
pub struct ByPageQuery {
pub path: String,
pub since: Option<NaiveDate>,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct DailyPoint {
pub visit_date: NaiveDate,
pub total_visits: i64,
pub unique_visitors: i64,
}
@@ -0,0 +1,15 @@
use super::{dto::ByPageQuery, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Query, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/visits/by-page", get(handler))
}
async fn handler(
State(state): State<AppState>,
Query(q): Query<ByPageQuery>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &q).await?;
Ok(Json(serde_json::json!({ "path": q.path, "series": rows })))
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
@@ -0,0 +1,18 @@
use super::dto::{ByPageQuery, DailyPoint};
use sqlx::PgPool;
pub async fn series(pool: &PgPool, q: &ByPageQuery) -> Result<Vec<DailyPoint>, sqlx::Error> {
sqlx::query_as::<_, DailyPoint>(
r#"
SELECT visit_date, total_visits, unique_visitors
FROM visit_daily_stats
WHERE page_path = $1
AND ($2::date IS NULL OR visit_date >= $2)
ORDER BY visit_date
"#,
)
.bind(&q.path)
.bind(q.since)
.fetch_all(pool)
.await
}
@@ -0,0 +1,6 @@
use super::{dto::*, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, q: &ByPageQuery) -> AppResult<Vec<DailyPoint>> {
Ok(repo::series(&state.db, q).await?)
}
+16
View File
@@ -0,0 +1,16 @@
use serde::Serialize;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct TopPage {
pub page_path: String,
pub total_visits: i64,
pub unique_visitors: i64,
}
#[derive(Debug, Serialize)]
pub struct VisitsSummary {
pub total_all_time: i64,
pub total_today: i64,
pub unique_today: i64,
pub top_pages: Vec<TopPage>,
}
@@ -0,0 +1,11 @@
use super::{dto::VisitsSummary, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::State, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/visits/summary", get(handler))
}
async fn handler(State(state): State<AppState>) -> AppResult<Json<VisitsSummary>> {
Ok(Json(service::handle(&state).await?))
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
@@ -0,0 +1,24 @@
use super::dto::{TopPage, VisitsSummary};
use sqlx::PgPool;
pub async fn fetch(pool: &PgPool) -> Result<VisitsSummary, sqlx::Error> {
let (total_all_time,): (i64,) =
sqlx::query_as("SELECT total_all_time FROM visit_totals WHERE id = 1")
.fetch_one(pool)
.await?;
let today: Option<(i64, i64)> = sqlx::query_as(
"SELECT COALESCE(SUM(total_visits),0)::bigint, COALESCE(SUM(unique_visitors),0)::bigint \
FROM visit_daily_stats WHERE visit_date = CURRENT_DATE",
)
.fetch_optional(pool)
.await?;
let (total_today, unique_today) = today.unwrap_or((0, 0));
let top_pages = sqlx::query_as::<_, TopPage>(
"SELECT page_path, total_visits, unique_visitors \
FROM visit_daily_stats WHERE visit_date = CURRENT_DATE \
ORDER BY total_visits DESC LIMIT 10",
)
.fetch_all(pool)
.await?;
Ok(VisitsSummary { total_all_time, total_today, unique_today, top_pages })
}
@@ -0,0 +1,6 @@
use super::{dto::VisitsSummary, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState) -> AppResult<VisitsSummary> {
Ok(repo::fetch(&state.db).await?)
}
+7
View File
@@ -0,0 +1,7 @@
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct ListImagesQuery {
pub entity_type: Option<String>,
pub entity_id: Option<String>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::{dto::ListImagesQuery, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Query, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/images", get(handler))
}
async fn handler(
State(state): State<AppState>,
Query(q): Query<ListImagesQuery>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &q).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+19
View File
@@ -0,0 +1,19 @@
use super::dto::ListImagesQuery;
use crate::shared::ImageRef;
use sqlx::PgPool;
pub async fn list(pool: &PgPool, q: &ListImagesQuery) -> Result<Vec<ImageRef>, sqlx::Error> {
sqlx::query_as::<_, ImageRef>(
r#"
SELECT id, entity_type, entity_id, kind, url_path, display_order, meta
FROM images
WHERE ($1::text IS NULL OR entity_type = $1)
AND ($2::text IS NULL OR entity_id = $2)
ORDER BY entity_type, entity_id, display_order, created_at
"#,
)
.bind(q.entity_type.as_deref())
.bind(q.entity_id.as_deref())
.fetch_all(pool)
.await
}
+6
View File
@@ -0,0 +1,6 @@
use super::{dto::*, repo};
use crate::{error::AppResult, shared::ImageRef, state::AppState};
pub async fn handle(state: &AppState, q: &ListImagesQuery) -> AppResult<Vec<ImageRef>> {
Ok(repo::list(&state.db, q).await?)
}
+7
View File
@@ -0,0 +1,7 @@
use serde::Serialize;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct ProvinceRow {
pub id: i16,
pub name_th: String,
}
+13
View File
@@ -0,0 +1,13 @@
use super::service;
use crate::error::AppResult;
use crate::state::AppState;
use axum::{extract::State, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/provinces", get(handler))
}
async fn handler(State(state): State<AppState>) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+10
View File
@@ -0,0 +1,10 @@
use super::dto::ProvinceRow;
use sqlx::PgPool;
pub async fn list(pool: &PgPool) -> Result<Vec<ProvinceRow>, sqlx::Error> {
sqlx::query_as::<_, ProvinceRow>(
"SELECT id, name_th FROM provinces ORDER BY id",
)
.fetch_all(pool)
.await
}
@@ -0,0 +1,7 @@
use super::{dto::ProvinceRow, repo};
use crate::error::AppResult;
use crate::state::AppState;
pub async fn handle(state: &AppState) -> AppResult<Vec<ProvinceRow>> {
Ok(repo::list(&state.db).await?)
}
+10
View File
@@ -0,0 +1,10 @@
use serde::Serialize;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct RouteGroupRow {
pub id: i16,
pub code: String,
pub label_th: String,
pub display_order: i16,
pub is_active: bool,
}
@@ -0,0 +1,12 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{extract::State, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/route-groups", get(handler))
}
async fn handler(State(state): State<AppState>) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+11
View File
@@ -0,0 +1,11 @@
use super::dto::RouteGroupRow;
use sqlx::PgPool;
pub async fn list(pool: &PgPool) -> Result<Vec<RouteGroupRow>, sqlx::Error> {
sqlx::query_as::<_, RouteGroupRow>(
"SELECT id, code, label_th, display_order, is_active \
FROM route_groups WHERE is_active ORDER BY display_order, id",
)
.fetch_all(pool)
.await
}
@@ -0,0 +1,6 @@
use super::{dto::RouteGroupRow, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState) -> AppResult<Vec<RouteGroupRow>> {
Ok(repo::list(&state.db).await?)
}
+14
View File
@@ -0,0 +1,14 @@
use serde::Serialize;
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct RouteStopRow {
pub stop_sequence: i16,
pub station_id: i32,
pub code: String,
pub name_th: String,
pub city_th: Option<String>,
pub province_th: Option<String>,
pub station_type: String,
pub attributes: SqlxJson<serde_json::Value>,
}
@@ -0,0 +1,15 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Path, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/routes/:route_id/stops", get(handler))
}
async fn handler(
State(state): State<AppState>,
Path(route_id): Path<String>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &route_id).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+23
View File
@@ -0,0 +1,23 @@
use super::dto::RouteStopRow;
use sqlx::PgPool;
pub async fn list(pool: &PgPool, route_id: &str) -> Result<Vec<RouteStopRow>, sqlx::Error> {
let sql = r#"
SELECT rs.stop_sequence,
s.id AS station_id,
s.code,
s.name_th,
s.city_th,
s.province_th,
s.station_type::text AS station_type,
s.attributes
FROM route_stops rs
JOIN stations s ON s.id = rs.station_id
WHERE rs.route_id = $1
ORDER BY rs.stop_sequence
"#;
sqlx::query_as::<_, RouteStopRow>(sql)
.bind(route_id)
.fetch_all(pool)
.await
}
@@ -0,0 +1,6 @@
use super::{dto::RouteStopRow, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, route_id: &str) -> AppResult<Vec<RouteStopRow>> {
Ok(repo::list(&state.db, route_id).await?)
}
+22
View File
@@ -0,0 +1,22 @@
use serde::{Deserialize, Serialize};
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Deserialize)]
pub struct ListRoutesQuery {
pub group: Option<String>,
pub province: Option<i16>,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct RouteListRow {
pub route_id: String,
pub name_th: String,
pub vehicle_type: String,
pub route_group_id: i16,
pub route_group_code: String,
pub route_group_label_th: String,
pub contact: SqlxJson<serde_json::Value>,
pub metadata: SqlxJson<serde_json::Value>,
pub province_ids: Vec<i16>,
pub images: SqlxJson<serde_json::Value>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::{dto::ListRoutesQuery, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Query, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/routes", get(handler))
}
async fn handler(
State(state): State<AppState>,
Query(q): Query<ListRoutesQuery>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &q).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+36
View File
@@ -0,0 +1,36 @@
use super::dto::{ListRoutesQuery, RouteListRow};
use sqlx::PgPool;
pub async fn list(pool: &PgPool, q: &ListRoutesQuery) -> Result<Vec<RouteListRow>, sqlx::Error> {
let sql = r#"
SELECT r.route_id,
r.name_th,
r.vehicle_type::text AS vehicle_type,
r.route_group_id,
g.code AS route_group_code,
g.label_th AS route_group_label_th,
r.contact,
r.metadata,
COALESCE(ARRAY(SELECT province_id FROM route_provinces rp WHERE rp.route_id = r.route_id ORDER BY province_id), '{}') AS province_ids,
COALESCE((
SELECT jsonb_agg(jsonb_build_object(
'id', i.id, 'kind', i.kind, 'url_path', i.url_path,
'display_order', i.display_order, 'meta', i.meta
) ORDER BY i.display_order)
FROM images i
WHERE i.entity_type = 'route' AND i.entity_id = r.route_id
), '[]'::jsonb) AS images
FROM routes r
JOIN route_groups g ON g.id = r.route_group_id
WHERE ($1::text IS NULL OR g.code = $1)
AND ($2::smallint IS NULL OR EXISTS (
SELECT 1 FROM route_provinces rp
WHERE rp.route_id = r.route_id AND rp.province_id = $2))
ORDER BY g.display_order, r.route_id
"#;
sqlx::query_as::<_, RouteListRow>(sql)
.bind(q.group.as_deref())
.bind(q.province)
.fetch_all(pool)
.await
}
+6
View File
@@ -0,0 +1,6 @@
use super::{dto::*, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, q: &ListRoutesQuery) -> AppResult<Vec<RouteListRow>> {
Ok(repo::list(&state.db, q).await?)
}
+22
View File
@@ -0,0 +1,22 @@
use serde::{Deserialize, Serialize};
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Deserialize)]
pub struct ListSchedulesQuery {
pub route_id: Option<String>,
pub stop_id: Option<i32>,
pub stop_code: Option<String>,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct ScheduleRow {
pub id: i32,
pub route_id: String,
pub station_id: i32,
pub station_code: String,
pub station_name_th: String,
pub direction_note: Option<String>,
pub departure_times: Vec<String>,
pub variants: SqlxJson<serde_json::Value>,
pub schedule_note: Option<String>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::{dto::ListSchedulesQuery, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Query, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/schedules", get(handler))
}
async fn handler(
State(state): State<AppState>,
Query(q): Query<ListSchedulesQuery>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &q).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+28
View File
@@ -0,0 +1,28 @@
use super::dto::{ListSchedulesQuery, ScheduleRow};
use sqlx::PgPool;
pub async fn list(pool: &PgPool, q: &ListSchedulesQuery) -> Result<Vec<ScheduleRow>, sqlx::Error> {
let sql = r#"
SELECT sc.id,
sc.route_id,
sc.station_id,
s.code AS station_code,
s.name_th AS station_name_th,
sc.direction_note,
ARRAY(SELECT to_char(t, 'HH24:MI') FROM unnest(sc.departure_times) AS t) AS departure_times,
sc.variants,
sc.schedule_note
FROM schedules sc
JOIN stations s ON s.id = sc.station_id
WHERE ($1::text IS NULL OR sc.route_id = $1)
AND ($2::int IS NULL OR sc.station_id = $2)
AND ($3::text IS NULL OR s.code = $3)
ORDER BY sc.route_id, sc.station_id, sc.id
"#;
sqlx::query_as::<_, ScheduleRow>(sql)
.bind(q.route_id.as_deref())
.bind(q.stop_id)
.bind(q.stop_code.as_deref())
.fetch_all(pool)
.await
}
@@ -0,0 +1,6 @@
use super::{dto::*, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, q: &ListSchedulesQuery) -> AppResult<Vec<ScheduleRow>> {
Ok(repo::list(&state.db, q).await?)
}
+23
View File
@@ -0,0 +1,23 @@
use serde::{Deserialize, Serialize};
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Deserialize)]
pub struct ListStopsQuery {
/// "minLng,minLat,maxLng,maxLat"
pub bbox: Option<String>,
pub q: Option<String>,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct StopRow {
pub id: i32,
pub code: String,
pub name_th: String,
pub city_th: Option<String>,
pub province_th: Option<String>,
pub station_type: String,
pub attributes: SqlxJson<serde_json::Value>,
pub images: SqlxJson<serde_json::Value>,
pub lng: Option<f64>,
pub lat: Option<f64>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::{dto::ListStopsQuery, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Query, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/stops", get(handler))
}
async fn handler(
State(state): State<AppState>,
Query(q): Query<ListStopsQuery>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &q).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+39
View File
@@ -0,0 +1,39 @@
use super::dto::{ListStopsQuery, StopRow};
use sqlx::PgPool;
pub async fn list(pool: &PgPool, q: &ListStopsQuery) -> Result<Vec<StopRow>, sqlx::Error> {
let (min_lng, min_lat, max_lng, max_lat) = parse_bbox(q.bbox.as_deref());
let sql = r#"
SELECT s.id, s.code, s.name_th, s.city_th, s.province_th,
s.station_type::text AS station_type, s.attributes,
COALESCE((
SELECT jsonb_agg(jsonb_build_object(
'id', i.id, 'kind', i.kind, 'url_path', i.url_path,
'display_order', i.display_order, 'meta', i.meta
) ORDER BY i.display_order)
FROM images i
WHERE i.entity_type = 'station' AND i.entity_id = s.code
), '[]'::jsonb) AS images,
s.lng, s.lat
FROM stations s
WHERE ($1::float8 IS NULL OR s.lng IS NULL OR (s.lng BETWEEN $1 AND $3 AND s.lat BETWEEN $2 AND $4))
AND ($5::text IS NULL OR s.name_th ILIKE '%' || $5 || '%')
ORDER BY s.id
"#;
sqlx::query_as::<_, StopRow>(sql)
.bind(min_lng)
.bind(min_lat)
.bind(max_lng)
.bind(max_lat)
.bind(q.q.as_deref())
.fetch_all(pool)
.await
}
fn parse_bbox(s: Option<&str>) -> (Option<f64>, Option<f64>, Option<f64>, Option<f64>) {
let Some(s) = s else { return (None, None, None, None); };
let parts: Vec<_> = s.split(',').collect();
if parts.len() != 4 { return (None, None, None, None); }
let p: Vec<Option<f64>> = parts.iter().map(|x| x.trim().parse().ok()).collect();
(p[0], p[1], p[2], p[3])
}
+6
View File
@@ -0,0 +1,6 @@
use super::{dto::*, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, q: &ListStopsQuery) -> AppResult<Vec<StopRow>> {
Ok(repo::list(&state.db, q).await?)
}
+37
View File
@@ -0,0 +1,37 @@
use crate::state::AppState;
use axum::Router;
pub mod list_provinces;
pub mod list_route_groups;
pub mod list_routes;
pub mod get_route;
pub mod list_route_stops;
pub mod list_stops;
pub mod get_stop;
pub mod list_schedules;
pub mod upload_image;
pub mod list_images;
pub mod delete_image;
pub mod proxy_file;
pub mod record_visit;
pub mod get_visits_summary;
pub mod get_visits_by_page;
pub fn router() -> Router<AppState> {
Router::new()
.merge(list_provinces::route())
.merge(list_route_groups::route())
.merge(list_routes::route())
.merge(get_route::route())
.merge(list_route_stops::route())
.merge(list_stops::route())
.merge(get_stop::route())
.merge(list_schedules::route())
.merge(upload_image::route())
.merge(list_images::route())
.merge(delete_image::route())
.merge(proxy_file::route())
.merge(record_visit::route())
.merge(get_visits_summary::route())
.merge(get_visits_by_page::route())
}
+29
View File
@@ -0,0 +1,29 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{
extract::{Path, State},
http::{header, HeaderMap, HeaderValue},
response::IntoResponse,
routing::get,
Router,
};
pub fn route() -> Router<AppState> {
Router::new().route("/files/*path", get(handler))
}
async fn handler(
State(state): State<AppState>,
Path(path): Path<String>,
) -> AppResult<impl IntoResponse> {
let (bytes, mime) = service::fetch(&state, &path).await?;
let mut h = HeaderMap::new();
if let Ok(v) = HeaderValue::from_str(&mime) {
h.insert(header::CONTENT_TYPE, v);
}
h.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=31536000, immutable"),
);
Ok((h, bytes))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod handler;
pub mod service;
pub use handler::route;
pub mod dto { /* empty */ }
pub mod repo { /* empty */ }
+9
View File
@@ -0,0 +1,9 @@
use crate::{error::{AppError, AppResult}, state::AppState};
pub async fn fetch(state: &AppState, path: &str) -> AppResult<(bytes::Bytes, String)> {
state
.seaweed
.fetch(&format!("/{}", path.trim_start_matches('/')))
.await
.map_err(|e| AppError::Internal(e.to_string()))
}
+14
View File
@@ -0,0 +1,14 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Deserialize)]
pub struct RecordVisitBody {
pub page_path: String,
pub visitor_id: Uuid,
}
#[derive(Debug, Serialize)]
pub struct RecordVisitResp {
pub counted: bool,
pub unique_today: bool,
}
+14
View File
@@ -0,0 +1,14 @@
use super::{dto::*, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::State, routing::post, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/visits", post(handler))
}
async fn handler(
State(state): State<AppState>,
Json(body): Json<RecordVisitBody>,
) -> AppResult<Json<RecordVisitResp>> {
Ok(Json(service::handle(&state, body).await?))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+41
View File
@@ -0,0 +1,41 @@
use sqlx::PgPool;
use uuid::Uuid;
pub async fn record(pool: &PgPool, visitor_id: Uuid, page_path: &str) -> Result<bool, sqlx::Error> {
let mut tx = pool.begin().await?;
// returns true when newly inserted (unique today)
let row: Option<(bool,)> = sqlx::query_as(
r#"
INSERT INTO visitor_seen (visitor_id, page_path, visit_date)
VALUES ($1, $2, CURRENT_DATE)
ON CONFLICT DO NOTHING
RETURNING (xmax = 0) AS is_new
"#,
)
.bind(visitor_id)
.bind(page_path)
.fetch_optional(&mut *tx)
.await?;
let is_new = row.map(|(b,)| b).unwrap_or(false);
sqlx::query(
r#"
INSERT INTO visit_daily_stats (visit_date, page_path, total_visits, unique_visitors)
VALUES (CURRENT_DATE, $1, 1, $2::bigint)
ON CONFLICT (visit_date, page_path) DO UPDATE
SET total_visits = visit_daily_stats.total_visits + 1,
unique_visitors = visit_daily_stats.unique_visitors + EXCLUDED.unique_visitors
"#,
)
.bind(page_path)
.bind(if is_new { 1i64 } else { 0i64 })
.execute(&mut *tx)
.await?;
sqlx::query("UPDATE visit_totals SET total_all_time = total_all_time + 1 WHERE id = 1")
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(is_new)
}
+7
View File
@@ -0,0 +1,7 @@
use super::{dto::*, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, body: RecordVisitBody) -> AppResult<RecordVisitResp> {
let is_new = repo::record(&state.db, body.visitor_id, &body.page_path).await?;
Ok(RecordVisitResp { counted: true, unique_today: is_new })
}
+27
View File
@@ -0,0 +1,27 @@
use serde::{Deserialize, Serialize};
use sqlx::types::Json as SqlxJson;
use uuid::Uuid;
#[derive(Debug, Deserialize)]
pub struct UploadForm {
pub entity_type: String,
pub entity_id: String,
#[serde(default = "default_kind")]
pub kind: String,
pub alt_th: Option<String>,
#[serde(default)]
pub display_order: i16,
}
fn default_kind() -> String { "photo".into() }
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct CreatedImage {
pub id: Uuid,
pub entity_type: String,
pub entity_id: String,
pub kind: String,
pub url_path: String,
pub display_order: i16,
pub meta: SqlxJson<serde_json::Value>,
}
+64
View File
@@ -0,0 +1,64 @@
use super::{dto::*, service};
use crate::{error::{AppError, AppResult}, state::AppState};
use axum::{extract::{Multipart, State}, routing::post, Json, Router};
use bytes::Bytes;
pub fn route() -> Router<AppState> {
Router::new().route("/api/images", post(handler))
}
async fn handler(
State(state): State<AppState>,
mut mp: Multipart,
) -> AppResult<Json<serde_json::Value>> {
let mut entity_type: Option<String> = None;
let mut entity_id: Option<String> = None;
let mut kind: Option<String> = None;
let mut alt_th: Option<String> = None;
let mut display_order: i16 = 0;
let mut filename: Option<String> = None;
let mut mime: Option<String> = None;
let mut bytes: Option<Bytes> = None;
while let Some(field) = mp
.next_field()
.await
.map_err(|e| AppError::BadRequest(e.to_string()))?
{
match field.name().unwrap_or("") {
"entity_type" => entity_type = Some(field.text().await.map_err(io)?),
"entity_id" => entity_id = Some(field.text().await.map_err(io)?),
"kind" => kind = Some(field.text().await.map_err(io)?),
"alt_th" => alt_th = Some(field.text().await.map_err(io)?),
"display_order" => {
display_order = field.text().await.map_err(io)?.parse().unwrap_or(0)
}
"file" => {
filename = field.file_name().map(|s| s.to_string());
mime = field.content_type().map(|s| s.to_string());
bytes = Some(field.bytes().await.map_err(io)?);
}
_ => {}
}
}
let form = UploadForm {
entity_type: entity_type.ok_or_else(|| AppError::BadRequest("entity_type".into()))?,
entity_id: entity_id.ok_or_else(|| AppError::BadRequest("entity_id".into()))?,
kind: kind.unwrap_or_else(|| "photo".into()),
alt_th,
display_order,
};
let input = service::UploadInput {
form,
filename: filename.unwrap_or_else(|| "upload.bin".into()),
mime: mime.unwrap_or_else(|| "application/octet-stream".into()),
bytes: bytes.ok_or_else(|| AppError::BadRequest("file missing".into()))?,
};
let row = service::upload(&state, input).await?;
Ok(Json(serde_json::to_value(row).unwrap()))
}
fn io(e: axum::extract::multipart::MultipartError) -> AppError {
AppError::BadRequest(e.to_string())
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+54
View File
@@ -0,0 +1,54 @@
use super::dto::CreatedImage;
use sqlx::PgPool;
use uuid::Uuid;
pub async fn insert(
pool: &PgPool,
entity_type: &str,
entity_id: &str,
kind: &str,
fid: &str,
url_path: &str,
display_order: i16,
meta: &serde_json::Value,
) -> Result<CreatedImage, sqlx::Error> {
sqlx::query_as::<_, CreatedImage>(
r#"
INSERT INTO images (entity_type, entity_id, kind, fid, url_path, display_order, meta)
VALUES ($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT (fid) DO UPDATE
SET entity_type = EXCLUDED.entity_type,
entity_id = EXCLUDED.entity_id,
kind = EXCLUDED.kind,
url_path = EXCLUDED.url_path,
display_order = EXCLUDED.display_order,
meta = EXCLUDED.meta
RETURNING id, entity_type, entity_id, kind, url_path, display_order, meta
"#,
)
.bind(entity_type)
.bind(entity_id)
.bind(kind)
.bind(fid)
.bind(url_path)
.bind(display_order)
.bind(meta)
.fetch_one(pool)
.await
}
pub async fn count(pool: &PgPool) -> Result<i64, sqlx::Error> {
let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM images")
.fetch_one(pool)
.await?;
Ok(n)
}
pub async fn exists_fid(pool: &PgPool, fid: &str) -> Result<bool, sqlx::Error> {
let row: Option<(Uuid,)> =
sqlx::query_as("SELECT id FROM images WHERE fid = $1")
.bind(fid)
.fetch_optional(pool)
.await?;
Ok(row.is_some())
}
+136
View File
@@ -0,0 +1,136 @@
use super::{dto::*, repo};
use crate::{error::{AppError, AppResult}, state::AppState};
use bytes::Bytes;
use sha2::{Digest, Sha256};
use std::path::Path;
pub struct UploadInput {
pub form: UploadForm,
pub filename: String,
pub mime: String,
pub bytes: Bytes,
}
pub async fn upload(state: &AppState, input: UploadInput) -> AppResult<CreatedImage> {
validate_entity_type(&input.form.entity_type)?;
validate_kind(&input.form.kind)?;
if input.bytes.is_empty() {
return Err(AppError::BadRequest("empty file".into()));
}
let (w, h) = probe_dimensions(&input.bytes);
let sha = hex::encode(Sha256::digest(&input.bytes));
let size = input.bytes.len() as i64;
let stored = state
.seaweed
.upload(
&input.form.entity_type,
&input.form.entity_id,
&input.filename,
&input.mime,
input.bytes,
)
.await
.map_err(|e| AppError::Internal(e.to_string()))?;
let meta = serde_json::json!({
"mime": input.mime,
"size_bytes": size,
"width": w,
"height": h,
"alt_th": input.form.alt_th,
"sha256": sha,
});
let row = repo::insert(
&state.db,
&input.form.entity_type,
&input.form.entity_id,
&input.form.kind,
&stored.fid,
&format!("{}{}", state.public_base, stored.url_path),
input.form.display_order,
&meta,
)
.await?;
Ok(row)
}
fn validate_entity_type(t: &str) -> AppResult<()> {
match t {
"route" | "station" | "sponsor" | "province" | "bus" | "misc" => Ok(()),
_ => Err(AppError::BadRequest("invalid entity_type".into())),
}
}
fn validate_kind(k: &str) -> AppResult<()> {
match k {
"photo" | "logo" | "icon" | "map" | "hero" => Ok(()),
_ => Err(AppError::BadRequest("invalid kind".into())),
}
}
fn probe_dimensions(bytes: &[u8]) -> (Option<u32>, Option<u32>) {
match image::load_from_memory(bytes) {
Ok(img) => (Some(img.width()), Some(img.height())),
Err(_) => (None, None),
}
}
/// Walk `dir/<entity_type>/<entity_id>/*.{jpg,png,webp}` and ingest each file
/// once. Skips files whose sha256 already lives in `images` (matched
/// by fid path).
pub async fn ingest_seed_dir(state: &AppState, dir: &str) -> AppResult<()> {
if repo::count(&state.db).await? > 0 {
tracing::info!("seed-assets: images table already populated, skipping");
return Ok(());
}
let base = Path::new(dir);
if !base.exists() {
tracing::warn!("seed-assets dir not found: {dir}");
return Ok(());
}
let mut count = 0;
for entry in walkdir::WalkDir::new(base).min_depth(3).max_depth(3) {
let entry = match entry { Ok(e) => e, Err(_) => continue };
if !entry.file_type().is_file() { continue; }
let path = entry.path();
let rel = match path.strip_prefix(base) { Ok(p) => p, Err(_) => continue };
let mut comps = rel.components();
let Some(et) = comps.next().and_then(|c| c.as_os_str().to_str()) else { continue };
let Some(eid) = comps.next().and_then(|c| c.as_os_str().to_str()) else { continue };
let Some(fname) = path.file_name().and_then(|s| s.to_str()) else { continue };
let mime = mime_guess::from_path(path).first_or_octet_stream().to_string();
let bytes = match tokio::fs::read(path).await {
Ok(b) => Bytes::from(b),
Err(e) => { tracing::warn!("read {path:?}: {e}"); continue }
};
let candidate_fid = format!("/{}/{}/{}", et, eid, fname);
if repo::exists_fid(&state.db, &candidate_fid).await.unwrap_or(false) {
continue;
}
let res = upload(
state,
UploadInput {
form: UploadForm {
entity_type: et.into(),
entity_id: eid.into(),
kind: "photo".into(),
alt_th: None,
display_order: 0,
},
filename: fname.into(),
mime,
bytes,
},
)
.await;
match res {
Ok(_) => count += 1,
Err(e) => tracing::warn!("ingest {path:?} failed: {e:?}"),
}
}
tracing::info!("seed-assets ingested {count} files from {dir}");
Ok(())
}