Accueil : bascule graphique / tableau et années précédentes
Sur la carte « Mois par mois », un contrôle segmenté remplace le graphique par le tableau, et des boutons − / + ajoutent ou retirent des années précédentes (jusqu'à 7, sans remonter avant la première mesure). Les deux choix sont mémorisés dans le localStorage. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
01abab8ef4
commit
feb0123f70
8 files changed
+315
-95
No files matched your search
Generated
+1
@@ -252,6 +252,7 @@ dependencies = [
|
|||||||
"tower-sessions",
|
"tower-sessions",
|
||||||
"tower-sessions-sqlx-store",
|
"tower-sessions-sqlx-store",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
|
"web-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ chrono = { version = "0.4", default-features = false, features = ["clock", "serd
|
|||||||
# Client (WASM)
|
# Client (WASM)
|
||||||
console_error_panic_hook = { version = "0.1", optional = true }
|
console_error_panic_hook = { version = "0.1", optional = true }
|
||||||
wasm-bindgen = { version = "=0.2.128", optional = true }
|
wasm-bindgen = { version = "=0.2.128", optional = true }
|
||||||
|
web-sys = { version = "0.3", features = ["Storage"] }
|
||||||
|
|
||||||
# Serveur uniquement
|
# Serveur uniquement
|
||||||
axum = { version = "0.8", optional = true }
|
axum = { version = "0.8", optional = true }
|
||||||
|
|||||||
+212
-59
@@ -143,10 +143,22 @@ pub fn LastRainfalls(#[prop(into)] reload: Signal<usize>) -> impl IntoView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Chiffres clés et comparaison mois par mois avec l'an dernier (page d'accueil).
|
/// Chiffres clés et comparaison mois par mois avec les années précédentes (page d'accueil).
|
||||||
#[component]
|
#[component]
|
||||||
pub fn YearOverview(#[prop(into)] reload: Signal<usize>) -> impl IntoView {
|
pub fn YearOverview(#[prop(into)] reload: Signal<usize>) -> impl IntoView {
|
||||||
let summary = Resource::new(move || reload.get(), |_| rainfall::last_months());
|
let show_table = RwSignal::new(false);
|
||||||
|
let years_back = RwSignal::new(1u32);
|
||||||
|
// Lus après l'hydratation, pour que le rendu serveur et le premier rendu client concordent.
|
||||||
|
Effect::new(move |_| {
|
||||||
|
show_table.set(stored(MONTHLY_VIEW_KEY).is_some_and(|view| view == "table"));
|
||||||
|
if let Some(n) = stored(YEARS_BACK_KEY).and_then(|n| n.parse().ok()) {
|
||||||
|
years_back.set(n);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let summary = Resource::new(
|
||||||
|
move || (reload.get(), years_back.get()),
|
||||||
|
|(_, years_back)| rainfall::last_months(years_back),
|
||||||
|
);
|
||||||
let last = Resource::new(move || reload.get(), |_| rainfall::list_rainfalls(1));
|
let last = Resource::new(move || reload.get(), |_| rainfall::list_rainfalls(1));
|
||||||
view! {
|
view! {
|
||||||
<Transition fallback=|| {
|
<Transition fallback=|| {
|
||||||
@@ -164,7 +176,7 @@ pub fn YearOverview(#[prop(into)] reload: Signal<usize>) -> impl IntoView {
|
|||||||
summary
|
summary
|
||||||
.get()
|
.get()
|
||||||
.map(|result| match result {
|
.map(|result| match result {
|
||||||
Ok(summary) => view! { <Overview summary last /> }.into_any(),
|
Ok(summary) => view! { <Overview summary last show_table years_back /> }.into_any(),
|
||||||
Err(e) => view! { <ErrorBanner message=Some(error_message(&e)) /> }.into_any(),
|
Err(e) => view! { <ErrorBanner message=Some(error_message(&e)) /> }.into_any(),
|
||||||
})
|
})
|
||||||
}}
|
}}
|
||||||
@@ -172,11 +184,36 @@ pub fn YearOverview(#[prop(into)] reload: Signal<usize>) -> impl IntoView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Couleurs des séries, de l'année en cours à la plus ancienne (ordre fixe : une année
|
||||||
|
/// garde sa couleur quand on en ajoute ou en retire).
|
||||||
|
const SERIES_COLORS: [&str; 8] = [
|
||||||
|
"bg-chart-1",
|
||||||
|
"bg-chart-2",
|
||||||
|
"bg-chart-3",
|
||||||
|
"bg-chart-4",
|
||||||
|
"bg-chart-5",
|
||||||
|
"bg-chart-6",
|
||||||
|
"bg-chart-7",
|
||||||
|
"bg-chart-8",
|
||||||
|
];
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
fn Overview(summary: MonthlySummary, last: Option<rainfall::Rainfall>) -> impl IntoView {
|
fn Overview(
|
||||||
|
summary: MonthlySummary,
|
||||||
|
last: Option<rainfall::Rainfall>,
|
||||||
|
show_table: RwSignal<bool>,
|
||||||
|
years_back: RwSignal<u32>,
|
||||||
|
) -> impl IntoView {
|
||||||
let year = summary.current_year;
|
let year = summary.current_year;
|
||||||
let month = rainfall::today().month();
|
let month = rainfall::today().month();
|
||||||
let this_month = summary.rows.iter().find(|r| r.month == month).cloned();
|
let this_month = summary.rows.iter().find(|r| r.month == month).cloned();
|
||||||
|
let first_year = summary.first_year;
|
||||||
|
let shown_years_back = summary.total_previous.len() as u32;
|
||||||
|
// On ne remonte pas avant la première mesure.
|
||||||
|
let max_years_back = summary
|
||||||
|
.first_year
|
||||||
|
.map_or(1, |first| (year - first).max(1) as u32)
|
||||||
|
.min(rainfall::MAX_YEARS_BACK);
|
||||||
|
|
||||||
let difference = summary.total_current - summary.total_previous_to_date;
|
let difference = summary.total_current - summary.total_previous_to_date;
|
||||||
let year_detail = format!(
|
let year_detail = format!(
|
||||||
@@ -187,23 +224,21 @@ fn Overview(summary: MonthlySummary, last: Option<rainfall::Rainfall>) -> impl I
|
|||||||
format_number(difference),
|
format_number(difference),
|
||||||
);
|
);
|
||||||
|
|
||||||
let series = vec![
|
let series = (0..=summary.total_previous.len())
|
||||||
Series {
|
.map(|back| Series {
|
||||||
name: year.to_string(),
|
name: (year - back as i32).to_string(),
|
||||||
color: "bg-chart-1",
|
color: SERIES_COLORS[back],
|
||||||
},
|
})
|
||||||
Series {
|
.collect::<Vec<_>>();
|
||||||
name: (year - 1).to_string(),
|
|
||||||
color: "bg-chart-2",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
let columns = summary
|
let columns = summary
|
||||||
.rows
|
.rows
|
||||||
.iter()
|
.iter()
|
||||||
.map(|row| Column {
|
.map(|row| Column {
|
||||||
label: month_short(row.month).to_string(),
|
label: month_short(row.month).to_string(),
|
||||||
title: Some(row.label.clone()),
|
title: Some(row.label.clone()),
|
||||||
values: vec![row.current, Some(row.previous)],
|
values: std::iter::once(row.current)
|
||||||
|
.chain(row.previous.iter().copied().map(Some))
|
||||||
|
.collect(),
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
@@ -224,7 +259,7 @@ fn Overview(summary: MonthlySummary, last: Option<rainfall::Rainfall>) -> impl I
|
|||||||
unit="mm"
|
unit="mm"
|
||||||
detail=format!(
|
detail=format!(
|
||||||
"{} mm en {} {}",
|
"{} mm en {} {}",
|
||||||
format_number(this_month.map(|r| r.previous).unwrap_or(0)),
|
format_number(this_month.map(|r| r.previous[0]).unwrap_or(0)),
|
||||||
month_name(month).to_lowercase(),
|
month_name(month).to_lowercase(),
|
||||||
year - 1,
|
year - 1,
|
||||||
)
|
)
|
||||||
@@ -252,57 +287,175 @@ fn Overview(summary: MonthlySummary, last: Option<rainfall::Rainfall>) -> impl I
|
|||||||
}}
|
}}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card title="Mois par mois" icon=IconName::CloudRain>
|
<Card title="Mois par mois" icon=IconName::CloudRain action=move || view! { <ViewSwitch show_table /> }>
|
||||||
<ColumnChart series columns />
|
<Show when=move || show_table.get() fallback=move || view! { <ColumnChart series=series.clone() columns=columns.clone() /> }>
|
||||||
<details class="group mt-4 border-t border-slate-100 pt-3 dark:border-slate-800">
|
<MonthTable summary=summary.clone() />
|
||||||
<summary class="muted flex cursor-pointer list-none items-center gap-1 text-sm font-medium hover:text-slate-900 dark:hover:text-white">
|
</Show>
|
||||||
<Icon icon=IconName::ChevronDown class="size-4 transition-transform group-open:rotate-180" />
|
<div class="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-slate-100 pt-3 dark:border-slate-800">
|
||||||
"Voir le tableau"
|
<span class="muted text-xs">
|
||||||
</summary>
|
{first_year.map(|first| format!("Mesures depuis {first}"))}
|
||||||
<MonthTable summary />
|
</span>
|
||||||
</details>
|
<YearsBackStepper years_back current=shown_years_back max=max_years_back />
|
||||||
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Clés localStorage de « Mois par mois » : mode d'affichage et nombre d'années précédentes.
|
||||||
|
const MONTHLY_VIEW_KEY: &str = "bermite.monthly-view";
|
||||||
|
const YEARS_BACK_KEY: &str = "bermite.monthly-years-back";
|
||||||
|
|
||||||
|
fn local_storage() -> Option<web_sys::Storage> {
|
||||||
|
window().local_storage().ok().flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stored(key: &str) -> Option<String> {
|
||||||
|
local_storage()?.get_item(key).ok().flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn store(key: &str, value: &str) {
|
||||||
|
if let Some(storage) = local_storage() {
|
||||||
|
let _ = storage.set_item(key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Boutons − / + pour retirer ou ajouter une année précédente. `current` : nombre
|
||||||
|
/// d'années affichées (celui demandé, borné par le serveur).
|
||||||
|
#[component]
|
||||||
|
fn YearsBackStepper(years_back: RwSignal<u32>, current: u32, max: u32) -> impl IntoView {
|
||||||
|
let step = move |delta: i32| {
|
||||||
|
let n = (current as i32 + delta).clamp(1, max as i32) as u32;
|
||||||
|
years_back.set(n);
|
||||||
|
store(YEARS_BACK_KEY, &n.to_string());
|
||||||
|
};
|
||||||
|
let button = "flex size-7 cursor-pointer items-center justify-center rounded-md border border-slate-200 text-slate-600 transition hover:bg-slate-50 hover:text-slate-900 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white";
|
||||||
|
view! {
|
||||||
|
<div class="flex items-center gap-2 text-sm">
|
||||||
|
<span class="muted">"Années précédentes"</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class=button
|
||||||
|
aria-label="Retirer une année"
|
||||||
|
title="Retirer une année"
|
||||||
|
disabled={current <= 1}
|
||||||
|
on:click=move |_| step(-1)
|
||||||
|
>
|
||||||
|
<Icon icon=IconName::Minus class="size-4" />
|
||||||
|
</button>
|
||||||
|
<span class="w-4 text-center font-semibold tabular-nums" aria-live="polite">
|
||||||
|
{current}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class=button
|
||||||
|
aria-label="Ajouter une année"
|
||||||
|
title="Ajouter une année"
|
||||||
|
disabled={current >= max}
|
||||||
|
on:click=move |_| step(1)
|
||||||
|
>
|
||||||
|
<Icon icon=IconName::Plus class="size-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Contrôle segmenté graphique / tableau ; le choix est mémorisé dans le navigateur.
|
||||||
|
#[component]
|
||||||
|
fn ViewSwitch(show_table: RwSignal<bool>) -> impl IntoView {
|
||||||
|
let segment = |active: bool| {
|
||||||
|
format!(
|
||||||
|
"flex size-7 cursor-pointer items-center justify-center rounded-md transition {}",
|
||||||
|
if active {
|
||||||
|
"bg-white text-slate-900 shadow-sm dark:bg-slate-700 dark:text-white"
|
||||||
|
} else {
|
||||||
|
"text-slate-500 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white"
|
||||||
|
}
|
||||||
|
)
|
||||||
|
};
|
||||||
|
view! {
|
||||||
|
<div class="inline-flex rounded-lg bg-slate-100 p-1 dark:bg-slate-800" role="radiogroup" aria-label="Affichage">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked=move || (!show_table.get()).to_string()
|
||||||
|
aria-label="Graphique"
|
||||||
|
title="Graphique"
|
||||||
|
class=move || segment(!show_table.get())
|
||||||
|
on:click=move |_| {
|
||||||
|
show_table.set(false);
|
||||||
|
store(MONTHLY_VIEW_KEY, "chart");
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Icon icon=IconName::ChartColumn class="size-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked=move || show_table.get().to_string()
|
||||||
|
aria-label="Tableau"
|
||||||
|
title="Tableau"
|
||||||
|
class=move || segment(show_table.get())
|
||||||
|
on:click=move |_| {
|
||||||
|
show_table.set(true);
|
||||||
|
store(MONTHLY_VIEW_KEY, "table");
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Icon icon=IconName::Table class="size-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
fn MonthTable(summary: MonthlySummary) -> impl IntoView {
|
fn MonthTable(summary: MonthlySummary) -> impl IntoView {
|
||||||
let year = summary.current_year;
|
let year = summary.current_year;
|
||||||
|
let years = (1..=summary.total_previous.len() as i32).map(|back| year - back);
|
||||||
view! {
|
view! {
|
||||||
<table class="mt-3 w-full text-sm tabular-nums">
|
<div class="overflow-x-auto">
|
||||||
<thead>
|
<table class="w-full text-sm tabular-nums">
|
||||||
<tr class="muted border-b border-slate-200 text-left dark:border-slate-700">
|
<thead>
|
||||||
<th class="py-2 font-medium">"Mois"</th>
|
<tr class="muted border-b border-slate-200 text-left dark:border-slate-700">
|
||||||
<th class="py-2 text-right font-medium">{year}</th>
|
<th class="py-2 font-medium">"Mois"</th>
|
||||||
<th class="py-2 text-right font-medium">{year - 1}</th>
|
<th class="py-2 pl-3 text-right font-medium">{year}</th>
|
||||||
</tr>
|
{years.map(|y| view! { <th class="py-2 pl-3 text-right font-medium">{y}</th> }).collect_view()}
|
||||||
</thead>
|
</tr>
|
||||||
<tbody class="divide-y divide-slate-100 dark:divide-slate-800">
|
</thead>
|
||||||
{summary
|
<tbody class="divide-y divide-slate-100 dark:divide-slate-800">
|
||||||
.rows
|
{summary
|
||||||
.into_iter()
|
.rows
|
||||||
.map(|row| {
|
.into_iter()
|
||||||
view! {
|
.map(|row| {
|
||||||
<tr>
|
view! {
|
||||||
<td class="py-1.5">{row.label}</td>
|
<tr>
|
||||||
<td class="py-1.5 text-right">{row.current.map(|v| format!("{v} mm"))}</td>
|
<td class="py-1.5">{row.label}</td>
|
||||||
<td class="py-1.5 text-right">{row.previous} " mm"</td>
|
<td class="py-1.5 pl-3 text-right whitespace-nowrap">
|
||||||
</tr>
|
{row.current.map(|v| format!("{v} mm"))}
|
||||||
}
|
</td>
|
||||||
})
|
{row
|
||||||
.collect_view()}
|
.previous
|
||||||
</tbody>
|
.into_iter()
|
||||||
<tfoot>
|
.map(|v| view! { <td class="py-1.5 pl-3 text-right whitespace-nowrap">{v} " mm"</td> })
|
||||||
<tr class="border-t border-slate-200 font-semibold dark:border-slate-700">
|
.collect_view()}
|
||||||
<td class="py-2">"Total"</td>
|
</tr>
|
||||||
<td class="py-2 text-right">{format_number(summary.total_current)} " mm"</td>
|
}
|
||||||
<td class="py-2 text-right">{format_number(summary.total_previous)} " mm"</td>
|
})
|
||||||
</tr>
|
.collect_view()}
|
||||||
</tfoot>
|
</tbody>
|
||||||
</table>
|
<tfoot>
|
||||||
{summary
|
<tr class="border-t border-slate-200 font-semibold dark:border-slate-700">
|
||||||
.first_year
|
<td class="py-2">"Total"</td>
|
||||||
.map(|first| view! { <p class="muted mt-2 text-right text-xs">"Mesures depuis " {first}</p> })}
|
<td class="py-2 pl-3 text-right whitespace-nowrap">{format_number(summary.total_current)} " mm"</td>
|
||||||
|
{summary
|
||||||
|
.total_previous
|
||||||
|
.into_iter()
|
||||||
|
.map(|v| {
|
||||||
|
view! { <td class="py-2 pl-3 text-right whitespace-nowrap">{format_number(v)} " mm"</td> }
|
||||||
|
})
|
||||||
|
.collect_view()}
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ pub enum IconName {
|
|||||||
CloudSun,
|
CloudSun,
|
||||||
User,
|
User,
|
||||||
Plus,
|
Plus,
|
||||||
|
Minus,
|
||||||
Trash,
|
Trash,
|
||||||
Pencil,
|
Pencil,
|
||||||
Check,
|
Check,
|
||||||
@@ -23,6 +24,8 @@ pub enum IconName {
|
|||||||
ArrowRight,
|
ArrowRight,
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
Calendar,
|
Calendar,
|
||||||
|
ChartColumn,
|
||||||
|
Table,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IconName {
|
impl IconName {
|
||||||
@@ -69,10 +72,17 @@ impl IconName {
|
|||||||
r#"<rect width="20" height="14" x="2" y="3" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/>"#
|
r#"<rect width="20" height="14" x="2" y="3" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/>"#
|
||||||
}
|
}
|
||||||
IconName::ArrowRight => r#"<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>"#,
|
IconName::ArrowRight => r#"<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>"#,
|
||||||
|
IconName::Minus => r#"<path d="M5 12h14"/>"#,
|
||||||
IconName::ChevronDown => r#"<path d="m6 9 6 6 6-6"/>"#,
|
IconName::ChevronDown => r#"<path d="m6 9 6 6 6-6"/>"#,
|
||||||
IconName::Calendar => {
|
IconName::Calendar => {
|
||||||
r#"<path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/>"#
|
r#"<path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/>"#
|
||||||
}
|
}
|
||||||
|
IconName::ChartColumn => {
|
||||||
|
r#"<path d="M3 3v16a2 2 0 0 0 2 2h16"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/>"#
|
||||||
|
}
|
||||||
|
IconName::Table => {
|
||||||
|
r#"<path d="M12 3v18"/><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M3 9h18"/><path d="M3 15h18"/>"#
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-13
@@ -189,21 +189,39 @@ pub async fn graph_data(
|
|||||||
Ok(graph::group(start, end, period, &daily))
|
Ok(graph::group(start, end, period, &daily))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cumuls mensuels de l'année en cours et de la précédente (page d'accueil).
|
/// Nombre maximal d'années précédentes affichées sur l'accueil (une couleur de série
|
||||||
|
/// chacune, en plus de l'année en cours).
|
||||||
|
pub const MAX_YEARS_BACK: u32 = 7;
|
||||||
|
|
||||||
|
/// Cumuls mensuels de l'année en cours et des `years_back` précédentes (page d'accueil).
|
||||||
#[server]
|
#[server]
|
||||||
pub async fn last_months() -> Result<MonthlySummary, ServerFnError> {
|
pub async fn last_months(years_back: u32) -> Result<MonthlySummary, ServerFnError> {
|
||||||
use chrono::Datelike;
|
use chrono::Datelike;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
let user_id = server::require_user_id().await?;
|
let user_id = server::require_user_id().await?;
|
||||||
let pool = server::pool()?;
|
let pool = server::pool()?;
|
||||||
let today = today();
|
let today = today();
|
||||||
|
let first_year: Option<i32> = sqlx::query_scalar::<_, Option<String>>(
|
||||||
|
"SELECT MIN(date) FROM rainfalls WHERE user_id = ?1",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.map_err(server::internal_error)?
|
||||||
|
.and_then(|date| date.get(..4)?.parse().ok());
|
||||||
|
// Pas plus loin que la première mesure.
|
||||||
|
let years_back = first_year
|
||||||
|
.map_or(1, |first| (today.year() - first).max(1) as u32)
|
||||||
|
.min(MAX_YEARS_BACK)
|
||||||
|
.min(years_back)
|
||||||
|
.max(1);
|
||||||
let rows = sqlx::query_as::<_, (String, i64)>(
|
let rows = sqlx::query_as::<_, (String, i64)>(
|
||||||
"SELECT substr(date, 1, 7) AS month, SUM(value) FROM rainfalls \
|
"SELECT substr(date, 1, 7) AS month, SUM(value) FROM rainfalls \
|
||||||
WHERE user_id = ?1 AND date >= ?2 GROUP BY month",
|
WHERE user_id = ?1 AND date >= ?2 GROUP BY month",
|
||||||
)
|
)
|
||||||
.bind(user_id)
|
.bind(user_id)
|
||||||
.bind(format!("{}-01-01", today.year() - 1))
|
.bind(format!("{}-01-01", today.year() - years_back as i32))
|
||||||
.fetch_all(&pool)
|
.fetch_all(&pool)
|
||||||
.await
|
.await
|
||||||
.map_err(server::internal_error)?;
|
.map_err(server::internal_error)?;
|
||||||
@@ -215,16 +233,7 @@ pub async fn last_months() -> Result<MonthlySummary, ServerFnError> {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let first_year = sqlx::query_scalar::<_, Option<String>>(
|
Ok(graph::monthly_summary(today, &sums, first_year, years_back))
|
||||||
"SELECT MIN(date) FROM rainfalls WHERE user_id = ?1",
|
|
||||||
)
|
|
||||||
.bind(user_id)
|
|
||||||
.fetch_one(&pool)
|
|
||||||
.await
|
|
||||||
.map_err(server::internal_error)?
|
|
||||||
.and_then(|date| date.get(..4)?.parse().ok());
|
|
||||||
|
|
||||||
Ok(graph::monthly_summary(today, &sums, first_year))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
+34
-11
@@ -149,7 +149,8 @@ pub struct MonthRow {
|
|||||||
pub label: String,
|
pub label: String,
|
||||||
/// Cumul de l'année en cours ; `None` pour les mois pas encore commencés.
|
/// Cumul de l'année en cours ; `None` pour les mois pas encore commencés.
|
||||||
pub current: Option<i64>,
|
pub current: Option<i64>,
|
||||||
pub previous: i64,
|
/// Cumuls des années précédentes, de l'an dernier à la plus ancienne demandée.
|
||||||
|
pub previous: Vec<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
@@ -157,38 +158,45 @@ pub struct MonthlySummary {
|
|||||||
pub current_year: i32,
|
pub current_year: i32,
|
||||||
pub rows: Vec<MonthRow>,
|
pub rows: Vec<MonthRow>,
|
||||||
pub total_current: i64,
|
pub total_current: i64,
|
||||||
pub total_previous: i64,
|
/// Totaux des années précédentes, dans l'ordre de `MonthRow::previous`.
|
||||||
|
pub total_previous: Vec<i64>,
|
||||||
/// Cumul de l'an dernier sur les mêmes mois (janvier au mois en cours inclus).
|
/// Cumul de l'an dernier sur les mêmes mois (janvier au mois en cours inclus).
|
||||||
pub total_previous_to_date: i64,
|
pub total_previous_to_date: i64,
|
||||||
/// Année de la plus ancienne mesure.
|
/// Année de la plus ancienne mesure.
|
||||||
pub first_year: Option<i32>,
|
pub first_year: Option<i32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Port de `RainfallController::lastMonths` : de janvier de l'an dernier au mois en cours.
|
/// Port de `RainfallController::lastMonths`, étendu à `years_back` années précédentes
|
||||||
/// `sums` associe (année, mois) au cumul du mois.
|
/// (au moins une). `sums` associe (année, mois) au cumul du mois.
|
||||||
pub fn monthly_summary(
|
pub fn monthly_summary(
|
||||||
today: NaiveDate,
|
today: NaiveDate,
|
||||||
sums: &HashMap<(i32, u32), i64>,
|
sums: &HashMap<(i32, u32), i64>,
|
||||||
first_year: Option<i32>,
|
first_year: Option<i32>,
|
||||||
|
years_back: u32,
|
||||||
) -> MonthlySummary {
|
) -> MonthlySummary {
|
||||||
let year = today.year();
|
let year = today.year();
|
||||||
|
let years_back = years_back.max(1) as i32;
|
||||||
let rows: Vec<MonthRow> = (1..=12)
|
let rows: Vec<MonthRow> = (1..=12)
|
||||||
.map(|month| MonthRow {
|
.map(|month| MonthRow {
|
||||||
month,
|
month,
|
||||||
label: month_name(month).to_string(),
|
label: month_name(month).to_string(),
|
||||||
current: (month <= today.month())
|
current: (month <= today.month())
|
||||||
.then(|| sums.get(&(year, month)).copied().unwrap_or(0)),
|
.then(|| sums.get(&(year, month)).copied().unwrap_or(0)),
|
||||||
previous: sums.get(&(year - 1, month)).copied().unwrap_or(0),
|
previous: (1..=years_back)
|
||||||
|
.map(|back| sums.get(&(year - back, month)).copied().unwrap_or(0))
|
||||||
|
.collect(),
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
MonthlySummary {
|
MonthlySummary {
|
||||||
current_year: year,
|
current_year: year,
|
||||||
total_current: rows.iter().filter_map(|r| r.current).sum(),
|
total_current: rows.iter().filter_map(|r| r.current).sum(),
|
||||||
total_previous: rows.iter().map(|r| r.previous).sum(),
|
total_previous: (0..years_back as usize)
|
||||||
|
.map(|i| rows.iter().map(|r| r.previous[i]).sum())
|
||||||
|
.collect(),
|
||||||
total_previous_to_date: rows
|
total_previous_to_date: rows
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|r| r.current.is_some())
|
.filter(|r| r.current.is_some())
|
||||||
.map(|r| r.previous)
|
.map(|r| r.previous[0])
|
||||||
.sum(),
|
.sum(),
|
||||||
rows,
|
rows,
|
||||||
first_year,
|
first_year,
|
||||||
@@ -330,7 +338,7 @@ mod tests {
|
|||||||
((2022, 1), 6),
|
((2022, 1), 6),
|
||||||
((2022, 12), 8),
|
((2022, 12), 8),
|
||||||
]);
|
]);
|
||||||
let summary = monthly_summary(d("2023-03-14"), &sums, Some(2021));
|
let summary = monthly_summary(d("2023-03-14"), &sums, Some(2021), 1);
|
||||||
assert_eq!(summary.current_year, 2023);
|
assert_eq!(summary.current_year, 2023);
|
||||||
assert_eq!(summary.rows.len(), 12);
|
assert_eq!(summary.rows.len(), 12);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -339,15 +347,30 @@ mod tests {
|
|||||||
month: 1,
|
month: 1,
|
||||||
label: "Janvier".into(),
|
label: "Janvier".into(),
|
||||||
current: Some(15),
|
current: Some(15),
|
||||||
previous: 6
|
previous: vec![6]
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
assert_eq!(summary.rows[1].current, Some(0));
|
assert_eq!(summary.rows[1].current, Some(0));
|
||||||
assert_eq!(summary.rows[3].current, None, "avril n'a pas commencé");
|
assert_eq!(summary.rows[3].current, None, "avril n'a pas commencé");
|
||||||
assert_eq!(summary.rows[11].previous, 8);
|
assert_eq!(summary.rows[11].previous, vec![8]);
|
||||||
assert_eq!(summary.total_current, 25);
|
assert_eq!(summary.total_current, 25);
|
||||||
assert_eq!(summary.total_previous, 14);
|
assert_eq!(summary.total_previous, vec![14]);
|
||||||
assert_eq!(summary.total_previous_to_date, 6);
|
assert_eq!(summary.total_previous_to_date, 6);
|
||||||
assert_eq!(summary.first_year, Some(2021));
|
assert_eq!(summary.first_year, Some(2021));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn monthly_summary_covers_older_years() {
|
||||||
|
let sums = HashMap::from([
|
||||||
|
((2023, 1), 15),
|
||||||
|
((2022, 1), 6),
|
||||||
|
((2021, 1), 4),
|
||||||
|
((2021, 5), 9),
|
||||||
|
]);
|
||||||
|
let summary = monthly_summary(d("2023-03-14"), &sums, Some(2021), 2);
|
||||||
|
assert_eq!(summary.rows[0].previous, vec![6, 4]);
|
||||||
|
assert_eq!(summary.rows[4].previous, vec![0, 9]);
|
||||||
|
assert_eq!(summary.total_previous, vec![6, 13]);
|
||||||
|
assert_eq!(summary.total_previous_to_date, 6);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -73,11 +73,13 @@ pub fn Page(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Carte : surface blanche arrondie, avec un titre et une icône facultatifs.
|
/// Carte : surface blanche arrondie, avec un titre, une icône et une action (à droite du
|
||||||
|
/// titre) facultatifs.
|
||||||
#[component]
|
#[component]
|
||||||
pub fn Card(
|
pub fn Card(
|
||||||
#[prop(optional)] title: Option<&'static str>,
|
#[prop(optional)] title: Option<&'static str>,
|
||||||
#[prop(optional)] icon: Option<IconName>,
|
#[prop(optional)] icon: Option<IconName>,
|
||||||
|
#[prop(optional, into)] action: Option<ViewFn>,
|
||||||
#[prop(optional, into)] class: String,
|
#[prop(optional, into)] class: String,
|
||||||
children: Children,
|
children: Children,
|
||||||
) -> impl IntoView {
|
) -> impl IntoView {
|
||||||
@@ -86,17 +88,20 @@ pub fn Card(
|
|||||||
{title
|
{title
|
||||||
.map(|title| {
|
.map(|title| {
|
||||||
view! {
|
view! {
|
||||||
<h2 class="mb-4 flex items-center gap-2.5 font-semibold">
|
<div class="mb-4 flex items-center justify-between gap-3">
|
||||||
{icon
|
<h2 class="flex items-center gap-2.5 font-semibold">
|
||||||
.map(|icon| {
|
{icon
|
||||||
view! {
|
.map(|icon| {
|
||||||
<span class="flex size-8 items-center justify-center rounded-lg bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-400">
|
view! {
|
||||||
<Icon icon class="size-4" />
|
<span class="flex size-8 items-center justify-center rounded-lg bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-400">
|
||||||
</span>
|
<Icon icon class="size-4" />
|
||||||
}
|
</span>
|
||||||
})}
|
}
|
||||||
{title}
|
})}
|
||||||
</h2>
|
{title}
|
||||||
|
</h2>
|
||||||
|
{action.map(|action| action.run())}
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
})}
|
})}
|
||||||
{children()}
|
{children()}
|
||||||
|
|||||||
@@ -24,6 +24,12 @@
|
|||||||
/* Séries des graphiques (palette validée en clair et en sombre, daltonisme compris). */
|
/* Séries des graphiques (palette validée en clair et en sombre, daltonisme compris). */
|
||||||
--color-chart-1: #2a78d6;
|
--color-chart-1: #2a78d6;
|
||||||
--color-chart-2: #eb6834;
|
--color-chart-2: #eb6834;
|
||||||
|
--color-chart-3: #1baf7a;
|
||||||
|
--color-chart-4: #eda100;
|
||||||
|
--color-chart-5: #e87ba4;
|
||||||
|
--color-chart-6: #008300;
|
||||||
|
--color-chart-7: #6250d6;
|
||||||
|
--color-chart-8: #e34948;
|
||||||
}
|
}
|
||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
@@ -41,11 +47,23 @@
|
|||||||
:root[data-theme="dark"] {
|
:root[data-theme="dark"] {
|
||||||
--color-chart-1: #3987e5;
|
--color-chart-1: #3987e5;
|
||||||
--color-chart-2: #d95926;
|
--color-chart-2: #d95926;
|
||||||
|
--color-chart-3: #199e70;
|
||||||
|
--color-chart-4: #c98500;
|
||||||
|
--color-chart-5: #d55181;
|
||||||
|
--color-chart-6: #008300;
|
||||||
|
--color-chart-7: #9085e9;
|
||||||
|
--color-chart-8: #e66767;
|
||||||
}
|
}
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
:root:where(:not([data-theme="light"])) {
|
:root:where(:not([data-theme="light"])) {
|
||||||
--color-chart-1: #3987e5;
|
--color-chart-1: #3987e5;
|
||||||
--color-chart-2: #d95926;
|
--color-chart-2: #d95926;
|
||||||
|
--color-chart-3: #199e70;
|
||||||
|
--color-chart-4: #c98500;
|
||||||
|
--color-chart-5: #d55181;
|
||||||
|
--color-chart-6: #008300;
|
||||||
|
--color-chart-7: #9085e9;
|
||||||
|
--color-chart-8: #e66767;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user