use crate::deadline::{self, Clock, Item, Task};
use crate::{index, model, AppState, Reply, St, Q};
use axum::body::{to_bytes, Body};
use axum::extract::{Query, Request, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::Json;
use chrono::{NaiveDate, Utc};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::Arc;
pub const TODAY_HEADER: &str = "x-kyb-today";
fn bad_request(msg: String) -> Reply {
(StatusCode::BAD_REQUEST, Json(json!({ "error": msg })))
}
pub(crate) fn clock(headers: &HeaderMap) -> Result<Clock, Reply> {
let Some(raw) = headers.get(TODAY_HEADER) else {
return Ok(Clock::new(Utc::now(), None));
};
raw.to_str()
.ok()
.and_then(|s| NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
.map(|today| Clock::new(Utc::now(), Some(today)))
.ok_or_else(|| bad_request(format!("{TODAY_HEADER}: expected YYYY-MM-DD, got {raw:?}")))
}
fn open_items(st: &AppState, clock: &Clock) -> anyhow::Result<Vec<Item>> {
let limit = st.index.reader.searcher().num_docs().max(1) as usize;
let opts = index::SearchOpts { limit, kind: Some(model::KIND_TASK.into()), ..Default::default() };
let hits = st.index.search("", &opts)?;
Ok(hits
.iter()
.filter(|h| h.is_head && model::TASK_LIVE_STATUSES.contains(&h.status.as_str()))
.filter_map(|h| {
let task = Task {
key: &h.key,
title: &h.title,
status: &h.status,
assignee: &h.assignee,
tags: &h.tags,
deadline: &h.deadline,
};
deadline::item(&task, clock)
})
.filter(|i| !crate::is_archived(st, &i.key))
.collect())
}
pub async fn attach(State(st): State<Arc<AppState>>, req: Request, next: Next) -> Response {
let params: HashMap<String, String> =
Query::try_from_uri(req.uri()).map(|Query(p)| p).unwrap_or_default();
if params.get("deadlines").map(String::as_str) == Some("false") {
return next.run(req).await;
}
let clock = match clock(req.headers()) {
Ok(c) => c,
Err(reply) => return reply.into_response(),
};
let scope: Vec<String> = params
.get("tag")
.map(|t| t.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect())
.unwrap_or_default();
let resp = next.run(req).await;
let is_json = resp
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("application/json"));
if resp.status() != StatusCode::OK || !is_json {
return resp;
}
let (mut parts, body) = resp.into_parts();
let bytes = match to_bytes(body, usize::MAX).await {
Ok(b) => b,
Err(e) => {
return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))
.into_response()
}
};
let mut value: Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(_) => return Response::from_parts(parts, Body::from(bytes)),
};
let Some(obj) = value.as_object_mut() else {
return Response::from_parts(parts, Body::from(bytes));
};
match open_items(&st, &clock) {
Ok(items) => match deadline::block(items, &clock, &scope) {
Some(block) => {
obj.insert("deadlines".into(), block);
}
None => return Response::from_parts(parts, Body::from(bytes)),
},
Err(e) => {
eprintln!("kyb: deadline block skipped: {e:#}");
return Response::from_parts(parts, Body::from(bytes));
}
}
parts.headers.remove(header::CONTENT_LENGTH);
Response::from_parts(parts, Body::from(value.to_string()))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeadlinesQ {
within: Option<String>,
overdue: Option<String>,
hard: Option<String>,
tag: Option<String>,
assignee: Option<String>,
}
fn switch(name: &str, raw: &Option<String>) -> Result<bool, Reply> {
match raw.as_deref().map(str::trim).unwrap_or("") {
"" | "false" | "0" | "no" => Ok(false),
"true" | "1" | "yes" => Ok(true),
other => Err(bad_request(format!("{name}: expected true or false, got '{other}'"))),
}
}
fn parse_within(raw: &str) -> Option<i64> {
let s = raw.trim();
s.strip_suffix('d').unwrap_or(s).parse::<i64>().ok().filter(|d| *d >= 0)
}
pub async fn list(State(st): St, headers: HeaderMap, Q(q): Q<DeadlinesQ>) -> Reply {
let clock = match clock(&headers) {
Ok(c) => c,
Err(reply) => return reply,
};
let within = match q.within.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
None => None,
Some(raw) => match parse_within(raw) {
Some(d) => Some(d),
None => return bad_request(format!("within: expected a number of days like 30 or 30d, got '{raw}'")),
},
};
let (overdue, hard) = match (switch("overdue", &q.overdue), switch("hard", &q.hard)) {
(Ok(o), Ok(h)) => (o, h),
(Err(r), _) | (_, Err(r)) => return r,
};
let tags: Vec<String> = q
.tag
.as_deref()
.map(|t| t.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect())
.unwrap_or_default();
let assignee = q.assignee.as_deref().map(str::trim).filter(|s| !s.is_empty());
let mut items = match open_items(&st, &clock) {
Ok(items) => items,
Err(e) => return crate::err500(e),
};
items.retain(|i| {
within.is_none_or(|d| i.overdue || i.days_left <= d)
&& (!overdue || i.overdue)
&& (!hard || i.hard)
&& i.in_scope(&tags)
&& assignee.is_none_or(|a| i.assignee == a)
});
items.sort_by(|a, b| {
a.days_left
.cmp(&b.days_left)
.then(b.overdue.cmp(&a.overdue))
.then(b.hard.cmp(&a.hard))
.then(a.key.cmp(&b.key))
});
let rows: Vec<Value> = items
.iter()
.map(|i| {
let mut row = serde_json::to_value(i).expect("an item always serializes");
row["bucket"] = json!(i.bucket());
row
})
.collect();
(
StatusCode::OK,
Json(json!({"today": clock.today.to_string(), "count": rows.len(), "deadlines": rows})),
)
}
#[cfg(test)]
#[path = "deadline_api_tests.rs"]
mod tests;