101 lines
4.0 KiB
Rust
101 lines
4.0 KiB
Rust
//! The user's invoices: the list, and the PDF fetched from Billingo on
|
|||
|
|
//! download (we keep every invoice detail, but not the PDF itself).
|
||
|
|
|
||
|
|
use std::time::Duration;
|
||
|
|
|
||
|
|
use axum::Json;
|
||
|
|
use axum::extract::{Path, State};
|
||
|
|
use axum::http::{HeaderValue, header};
|
||
|
|
use axum::response::{IntoResponse, Response};
|
||
|
|
use axum_extra::extract::WithRejection;
|
||
|
|
use serde_json::{Value, json};
|
||
|
|
use time::{Date, OffsetDateTime};
|
||
|
|
use uuid::Uuid;
|
||
|
|
|
||
|
|
use super::{IdPath, St};
|
||
|
|
use crate::auth::AuthUser;
|
||
|
|
use crate::error::{ApiError, ApiResult};
|
||
|
|
|
||
|
|
type Row = (Uuid, String, Option<String>, Option<Date>, String, i32, OffsetDateTime);
|
||
|
|
|
||
|
|
/// The user's invoices, newest first. Until Billingo has issued one it is
|
||
|
|
/// shown as being prepared.
|
||
|
|
pub async fn list(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
|
||
|
|
let rows: Vec<Row> = sqlx::query_as(
|
||
|
|
"SELECT id, status, invoice_number, invoice_date, item_name, gross_huf, created_at FROM invoices \
|
||
|
|
WHERE user_id = $1 ORDER BY created_at DESC",
|
||
|
|
)
|
||
|
|
.bind(auth.id())
|
||
|
|
.fetch_all(&state.db)
|
||
|
|
.await?;
|
||
|
|
let invoices: Vec<Value> = rows
|
||
|
|
.into_iter()
|
||
|
|
.map(|(id, status, number, date, item, gross, created_at)| {
|
||
|
|
json!({
|
||
|
|
"id": id,
|
||
|
|
"ready": status == "issued",
|
||
|
|
"invoice_number": number,
|
||
|
|
"invoice_date": date.map(|d| d.to_string()),
|
||
|
|
"item": item,
|
||
|
|
"gross_huf": gross,
|
||
|
|
"paid_at": created_at.format(&time::format_description::well_known::Rfc3339).ok(),
|
||
|
|
})
|
||
|
|
})
|
||
|
|
.collect();
|
||
|
|
Ok(Json(json!({ "invoices": invoices })))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The invoice's PDF, from Billingo.
|
||
|
|
pub async fn pdf(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Response> {
|
||
|
|
let row: Option<(i64, Option<String>)> = sqlx::query_as(
|
||
|
|
"SELECT billingo_document_id, invoice_number FROM invoices \
|
||
|
|
WHERE id = $1 AND user_id = $2 AND status = 'issued' AND billingo_document_id IS NOT NULL",
|
||
|
|
)
|
||
|
|
.bind(id)
|
||
|
|
.bind(auth.id())
|
||
|
|
.fetch_optional(&state.db)
|
||
|
|
.await?;
|
||
|
|
let (document, number) = row.ok_or(ApiError::NotFound("invoice"))?;
|
||
|
|
let unavailable = |detail: String| {
|
||
|
|
tracing::error!(error = %detail, invoice = %id, "invoice download failed");
|
||
|
|
ApiError::conflict("invoice_unavailable", "A számla letöltése most nem sikerült. Próbáld újra pár perc múlva.")
|
||
|
|
};
|
||
|
|
let key =
|
||
|
|
state.config.billingo_api_key.as_deref().ok_or_else(|| unavailable("BILLINGO_API_KEY is not set".into()))?;
|
||
|
|
let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build().expect("static configuration");
|
||
|
|
let res = http
|
||
|
|
.get(format!("{}/documents/{document}/download", state.config.billingo_api_url))
|
||
|
|
.header("X-API-KEY", key)
|
||
|
|
.header("Accept", "application/pdf")
|
||
|
|
.send()
|
||
|
|
.await
|
||
|
|
.map_err(|e| unavailable(e.to_string()))?;
|
||
|
|
let is_pdf = res
|
||
|
|
.headers()
|
||
|
|
.get(header::CONTENT_TYPE)
|
||
|
|
.and_then(|v| v.to_str().ok())
|
||
|
|
.is_some_and(|t| t.starts_with("application/pdf"));
|
||
|
|
if !res.status().is_success() || !is_pdf {
|
||
|
|
let status = res.status();
|
||
|
|
let body = res.text().await.unwrap_or_default();
|
||
|
|
return Err(unavailable(format!("HTTP {status}: {}", body.chars().take(300).collect::<String>())));
|
||
|
|
}
|
||
|
|
let bytes = res.bytes().await.map_err(|e| unavailable(e.to_string()))?;
|
||
|
|
let name: String = number
|
||
|
|
.unwrap_or_else(|| document.to_string())
|
||
|
|
.chars()
|
||
|
|
.map(|c| if c.is_ascii_alphanumeric() || c == '-' { c } else { '-' })
|
||
|
|
.collect();
|
||
|
|
let disposition = HeaderValue::from_str(&format!("attachment; filename=\"szamla-{name}.pdf\""))
|
||
|
|
.unwrap_or_else(|_| HeaderValue::from_static("attachment; filename=\"szamla.pdf\""));
|
||
|
|
Ok((
|
||
|
|
[
|
||
|
|
(header::CONTENT_TYPE, HeaderValue::from_static("application/pdf")),
|
||
|
|
(header::CONTENT_DISPOSITION, disposition),
|
||
|
|
(header::CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
|
||
|
|
],
|
||
|
|
bytes,
|
||
|
|
)
|
||
|
|
.into_response())
|
||
|
|
}
|