Application de suivi de la pluviométrie et de la météo, portée depuis Laravel + React vers Leptos 0.8 (SSR + hydratation) sur Axum, avec Tailwind CSS v4 et SQLite. - Pages : accueil (chiffres clés, comparaison mois par mois avec l'an dernier), pluviométrie (graphique par jour/semaine/mois/année), liste des mesures (édition en place), météo OpenWeatherMap, profil (emplacement, thème clair/sombre), authentification et réinitialisation du mot de passe par e-mail. - Sessions tower-sessions en SQLite ; mots de passe Argon2, les hash bcrypt de Laravel restent valides et sont convertis à la connexion. - Import unique des données MySQL de lara-bermite (bin import_mysql). - PWA : manifest et service worker « réseau d'abord ». - Makefile de cross-compilation aarch64 et service systemd pour le Pi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
326 lines
13 KiB
Rust
326 lines
13 KiB
Rust
//! Blocs de la pluviométrie partagés entre l'accueil et la page Pluviométrie.
|
|
|
|
use chrono::Datelike;
|
|
use leptos::{html, prelude::*};
|
|
use leptos_router::components::A;
|
|
|
|
use crate::{
|
|
chart::{Column, ColumnChart, Series},
|
|
errors::error_message,
|
|
icons::{Icon, IconName},
|
|
rainfall::{
|
|
self, AddRainfall, MonthlySummary,
|
|
graph::{month_name, month_short},
|
|
},
|
|
ui::{
|
|
Card, ErrorBanner, Field, Loading, StatTile, SubmitButton, SuccessBanner, field_error_of,
|
|
general_error_of, succeeded,
|
|
},
|
|
weather::weekday_fr,
|
|
};
|
|
|
|
/// Nombre avec séparateur de milliers à la française (espace fine insécable).
|
|
pub fn format_number(value: i64) -> String {
|
|
let digits = value.unsigned_abs().to_string();
|
|
let mut out = String::new();
|
|
for (i, c) in digits.chars().enumerate() {
|
|
if i > 0 && (digits.len() - i).is_multiple_of(3) {
|
|
out.push('\u{202f}');
|
|
}
|
|
out.push(c);
|
|
}
|
|
if value < 0 { format!("-{out}") } else { out }
|
|
}
|
|
|
|
/// « mardi 14 octobre » à partir d'une date AAAA-MM-JJ.
|
|
pub fn format_long_date(date: &str) -> String {
|
|
chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
|
|
.map(|d| {
|
|
format!(
|
|
"{} {} {}",
|
|
weekday_fr(d.weekday()),
|
|
d.day(),
|
|
month_name(d.month()).to_lowercase()
|
|
)
|
|
})
|
|
.unwrap_or_else(|_| date.to_string())
|
|
}
|
|
|
|
/// Formulaire « Nouvelle mesure ».
|
|
#[component]
|
|
pub fn AddRainfallForm(add: ServerAction<AddRainfall>) -> impl IntoView {
|
|
let value = add.value();
|
|
let form = NodeRef::<html::Form>::new();
|
|
let today = rainfall::today().format("%Y-%m-%d").to_string();
|
|
|
|
// Vide le formulaire après un ajout réussi (`ActionForm` ne le fait pas) ; la date
|
|
// revient à sa valeur par défaut, aujourd'hui.
|
|
Effect::new(move |_| {
|
|
if succeeded(value).get()
|
|
&& let Some(form) = form.get()
|
|
{
|
|
form.reset();
|
|
}
|
|
});
|
|
|
|
view! {
|
|
<Card title="Nouvelle mesure" icon=IconName::Plus>
|
|
<ActionForm action=add node_ref=form attr:class="flex flex-col gap-4">
|
|
<Show when=move || succeeded(value).get()>
|
|
<SuccessBanner>"Mesure enregistrée."</SuccessBanner>
|
|
</Show>
|
|
<ErrorBanner message=general_error_of(value) />
|
|
<div class="grid grid-cols-2 gap-3">
|
|
<Field label="Date" name="date" kind="date" value=today error=field_error_of(value, "date") />
|
|
<Field
|
|
label="Pluie (mm)"
|
|
name="value"
|
|
kind="number"
|
|
min="1"
|
|
max="1000"
|
|
step="1"
|
|
inputmode="numeric"
|
|
placeholder="0"
|
|
error=field_error_of(value, "value")
|
|
/>
|
|
</div>
|
|
<SubmitButton pending=add.pending() class="w-full">
|
|
<Icon icon=IconName::Check class="size-4" />
|
|
"Enregistrer"
|
|
</SubmitButton>
|
|
</ActionForm>
|
|
</Card>
|
|
}
|
|
}
|
|
|
|
/// Les 5 dernières mesures. `reload` : signal qui change après chaque ajout.
|
|
#[component]
|
|
pub fn LastRainfalls(#[prop(into)] reload: Signal<usize>) -> impl IntoView {
|
|
let last = Resource::new(move || reload.get(), |_| rainfall::list_rainfalls(5));
|
|
view! {
|
|
<Card title="Dernières mesures" icon=IconName::List>
|
|
<Transition fallback=|| view! { <Loading height="h-40" /> }>
|
|
{move || {
|
|
last.get()
|
|
.map(|result| match result {
|
|
Ok(page) if page.items.is_empty() => {
|
|
view! { <p class="muted py-4 text-center text-sm">"Aucune mesure pour l'instant."</p> }
|
|
.into_any()
|
|
}
|
|
Ok(page) => {
|
|
view! {
|
|
<ul class="-my-2 divide-y divide-slate-100 dark:divide-slate-800">
|
|
{page
|
|
.items
|
|
.into_iter()
|
|
.map(|r| {
|
|
view! {
|
|
<li class="flex items-center justify-between gap-3 py-2.5">
|
|
<span class="first-letter:uppercase">{format_long_date(&r.date)}</span>
|
|
<span class="rounded-full bg-blue-50 px-2.5 py-0.5 text-sm font-semibold text-blue-700 tabular-nums dark:bg-blue-500/10 dark:text-blue-300">
|
|
{r.value} " mm"
|
|
</span>
|
|
</li>
|
|
}
|
|
})
|
|
.collect_view()}
|
|
</ul>
|
|
}
|
|
.into_any()
|
|
}
|
|
Err(e) => view! { <ErrorBanner message=Some(error_message(&e)) /> }.into_any(),
|
|
})
|
|
}}
|
|
</Transition>
|
|
<A
|
|
href="/pluviometrie/mesures"
|
|
attr:class="mt-4 flex items-center justify-center gap-1.5 rounded-lg border border-slate-200 py-2 text-sm font-medium text-slate-600 transition hover:bg-slate-50 hover:text-slate-900 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white"
|
|
>
|
|
"Toutes les mesures"
|
|
<Icon icon=IconName::ArrowRight class="size-4" />
|
|
</A>
|
|
</Card>
|
|
}
|
|
}
|
|
|
|
/// Chiffres clés et comparaison mois par mois avec l'an dernier (page d'accueil).
|
|
#[component]
|
|
pub fn YearOverview(#[prop(into)] reload: Signal<usize>) -> impl IntoView {
|
|
let summary = Resource::new(move || reload.get(), |_| rainfall::last_months());
|
|
let last = Resource::new(move || reload.get(), |_| rainfall::list_rainfalls(1));
|
|
view! {
|
|
<Transition fallback=|| {
|
|
view! {
|
|
<div class="grid gap-4 sm:grid-cols-3">
|
|
<Loading height="h-28" />
|
|
<Loading height="h-28" />
|
|
<Loading height="h-28" />
|
|
</div>
|
|
<Loading height="h-80" />
|
|
}
|
|
}>
|
|
{move || {
|
|
let last = last.get().and_then(Result::ok).and_then(|page| page.items.into_iter().next());
|
|
summary
|
|
.get()
|
|
.map(|result| match result {
|
|
Ok(summary) => view! { <Overview summary last /> }.into_any(),
|
|
Err(e) => view! { <ErrorBanner message=Some(error_message(&e)) /> }.into_any(),
|
|
})
|
|
}}
|
|
</Transition>
|
|
}
|
|
}
|
|
|
|
#[component]
|
|
fn Overview(summary: MonthlySummary, last: Option<rainfall::Rainfall>) -> impl IntoView {
|
|
let year = summary.current_year;
|
|
let month = rainfall::today().month();
|
|
let this_month = summary.rows.iter().find(|r| r.month == month).cloned();
|
|
|
|
let difference = summary.total_current - summary.total_previous_to_date;
|
|
let year_detail = format!(
|
|
"{} mm à la même date en {} ({}{})",
|
|
format_number(summary.total_previous_to_date),
|
|
year - 1,
|
|
if difference >= 0 { "+" } else { "" },
|
|
format_number(difference),
|
|
);
|
|
|
|
let series = vec![
|
|
Series {
|
|
name: year.to_string(),
|
|
color: "bg-chart-1",
|
|
},
|
|
Series {
|
|
name: (year - 1).to_string(),
|
|
color: "bg-chart-2",
|
|
},
|
|
];
|
|
let columns = summary
|
|
.rows
|
|
.iter()
|
|
.map(|row| Column {
|
|
label: month_short(row.month).to_string(),
|
|
title: Some(row.label.clone()),
|
|
values: vec![row.current, Some(row.previous)],
|
|
})
|
|
.collect::<Vec<_>>();
|
|
|
|
view! {
|
|
<div class="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4">
|
|
<div class="col-span-2 sm:col-span-1">
|
|
<StatTile
|
|
label=format!("Cumul {year}")
|
|
value=format_number(summary.total_current)
|
|
unit="mm"
|
|
detail=year_detail
|
|
icon=IconName::Droplet
|
|
/>
|
|
</div>
|
|
<StatTile
|
|
label=format!("{} {year}", month_name(month))
|
|
value=format_number(this_month.as_ref().and_then(|r| r.current).unwrap_or(0))
|
|
unit="mm"
|
|
detail=format!(
|
|
"{} mm en {} {}",
|
|
format_number(this_month.map(|r| r.previous).unwrap_or(0)),
|
|
month_name(month).to_lowercase(),
|
|
year - 1,
|
|
)
|
|
icon=IconName::Calendar
|
|
/>
|
|
{match last {
|
|
Some(last) => {
|
|
view! {
|
|
<StatTile
|
|
label="Dernière mesure"
|
|
value=last.value.to_string()
|
|
unit="mm"
|
|
detail=format_long_date(&last.date)
|
|
icon=IconName::CloudRain
|
|
/>
|
|
}
|
|
.into_any()
|
|
}
|
|
None => {
|
|
view! {
|
|
<StatTile label="Dernière mesure" value="—" detail="Aucune mesure" icon=IconName::CloudRain />
|
|
}
|
|
.into_any()
|
|
}
|
|
}}
|
|
</div>
|
|
|
|
<Card title="Mois par mois" icon=IconName::CloudRain>
|
|
<ColumnChart series columns />
|
|
<details class="group mt-4 border-t border-slate-100 pt-3 dark:border-slate-800">
|
|
<summary class="muted flex cursor-pointer list-none items-center gap-1 text-sm font-medium hover:text-slate-900 dark:hover:text-white">
|
|
<Icon icon=IconName::ChevronDown class="size-4 transition-transform group-open:rotate-180" />
|
|
"Voir le tableau"
|
|
</summary>
|
|
<MonthTable summary />
|
|
</details>
|
|
</Card>
|
|
}
|
|
}
|
|
|
|
#[component]
|
|
fn MonthTable(summary: MonthlySummary) -> impl IntoView {
|
|
let year = summary.current_year;
|
|
view! {
|
|
<table class="mt-3 w-full text-sm tabular-nums">
|
|
<thead>
|
|
<tr class="muted border-b border-slate-200 text-left dark:border-slate-700">
|
|
<th class="py-2 font-medium">"Mois"</th>
|
|
<th class="py-2 text-right font-medium">{year}</th>
|
|
<th class="py-2 text-right font-medium">{year - 1}</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody class="divide-y divide-slate-100 dark:divide-slate-800">
|
|
{summary
|
|
.rows
|
|
.into_iter()
|
|
.map(|row| {
|
|
view! {
|
|
<tr>
|
|
<td class="py-1.5">{row.label}</td>
|
|
<td class="py-1.5 text-right">{row.current.map(|v| format!("{v} mm"))}</td>
|
|
<td class="py-1.5 text-right">{row.previous} " mm"</td>
|
|
</tr>
|
|
}
|
|
})
|
|
.collect_view()}
|
|
</tbody>
|
|
<tfoot>
|
|
<tr class="border-t border-slate-200 font-semibold dark:border-slate-700">
|
|
<td class="py-2">"Total"</td>
|
|
<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>
|
|
</tfoot>
|
|
</table>
|
|
{summary
|
|
.first_year
|
|
.map(|first| view! { <p class="muted mt-2 text-right text-xs">"Mesures depuis " {first}</p> })}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn numbers_are_grouped_by_thousands() {
|
|
assert_eq!(format_number(0), "0");
|
|
assert_eq!(format_number(999), "999");
|
|
assert_eq!(format_number(1281), "1\u{202f}281");
|
|
assert_eq!(format_number(-1234567), "-1\u{202f}234\u{202f}567");
|
|
}
|
|
|
|
#[test]
|
|
fn long_dates_are_french() {
|
|
assert_eq!(format_long_date("2026-10-14"), "mercredi 14 octobre");
|
|
}
|
|
}
|