Skip to content
This repository has been archived by the owner on Nov 28, 2023. It is now read-only.

Commit

Permalink
Working month heatmap
Browse files Browse the repository at this point in the history
  • Loading branch information
AOx0 committed Nov 12, 2023
1 parent d89261b commit 4ab40e5
Show file tree
Hide file tree
Showing 3 changed files with 124 additions and 3 deletions.
49 changes: 48 additions & 1 deletion assets/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,37 @@ function load_years_data(data, cfg) {
});
}

function load_month_data(data, cfg) {
console.log('Fetching months')
console.log(JSON.stringify(data))

for (let i = 0; i <= 7; i++) {
for (let j = 0; j < 12; j++) {
document.getElementById(`anio-${i + 2016}-mes-${j + 1}`).style.opacity = 0.2;
}
}
for (let i = 0; i <= 7; i++) {
const temp_data = {
anio: i + 2016,
categorias: data['categorias']
};

fetch(cfg.endpoint,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(temp_data)
}
)
.then((response) => response.json())
.then((json) => {
update_mes_data(cfg.num, json);
});
}
}

function calculateStandardDeviation(numbers) {
if (numbers.length === 0) {
return 0;
Expand Down Expand Up @@ -301,7 +332,7 @@ function update_years_data(n, data) {
let r = calculateStandardDeviation(vals);
let r2 = calculateMean(vals);

for (let i = 0; i <= 7; i++) {
for (let i = 0; i < 8; i++) {
// There's no map zone for undefined areas and outside the city
let color2 = calculateProbabilityLessThan(vals[i], r2, r);
console.log(`anio-${i + 2016} a ${color2}`)
Expand All @@ -310,4 +341,20 @@ function update_years_data(n, data) {
}
}

function update_mes_data(n, data) {
console.log(`Updating ${n} with ${data.total} y ${data.valores}`)
let vals = data.valores.map((v) => v / data.total);

let r = calculateStandardDeviation(vals);
let r2 = calculateMean(vals);

for (let i = 0; i < 12; i++) {
// There's no map zone for undefined areas and outside the city
let color2 = calculateProbabilityLessThan(vals[i], r2, r);
console.log(`anio-${data.anio}-${i + 1} a ${color2}`)
document.getElementById(`anio-${data.anio}-mes-${i + 1}`).style.backgroundColor = MAIN_COLOR;
document.getElementById(`anio-${data.anio}-mes-${i + 1}`).style.opacity = color2 + 0.1;
}
}


76 changes: 74 additions & 2 deletions src/bin/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,20 @@ struct SolicitudPorcentajePorAnio {
categorias: Vec<u16>,
}

#[derive(Debug, Deserialize)]
struct SolicitudPorcentajePorMesDeAnio {
#[serde(default)]
categorias: Vec<u16>,
anio: u16,
}

#[derive(Serialize, Debug, Default)]
struct MesPorcetajesEnAnio {
total: u64,
anio: u16,
valores: Vec<u64>,
}

#[derive(Serialize, Debug, Default)]
struct AnioPorcetajes {
total: u64,
Expand Down Expand Up @@ -446,12 +460,12 @@ async fn anio_porcentajes(

let resultados: Vec<(i64,)> = if categorias.is_empty() || categorias.len() >= ACTUAL_CATEGORIES
{
sqlx::query_as(&format!("SELECT COUNT(1) FROM delitos WHERE id_anio_hecho BETWEEN {annio_inicio} AND {annio_final} AND delitos.id_alcaldia_hecho IS NOT NULL GROUP BY delitos.id_anio_hecho ORDER BY delitos.id_anio_hecho;"))
sqlx::query_as(&format!("SELECT COUNT(1) FROM delitos WHERE id_anio_hecho BETWEEN {annio_inicio} AND {annio_final} GROUP BY delitos.id_anio_hecho ORDER BY delitos.id_anio_hecho;"))
.fetch_all(&state.db)
.await
.unwrap()
} else {
sqlx::query_as(&format!("SELECT COUNT(1) FROM delitos WHERE delitos.id_categoria IN ({0}) AND id_anio_hecho BETWEEN {annio_inicio} AND {annio_final} AND delitos.id_alcaldia_hecho IS NOT NULL GROUP BY delitos.id_anio_hecho ORDER BY delitos.id_anio_hecho;",
sqlx::query_as(&format!("SELECT COUNT(1) FROM delitos WHERE delitos.id_categoria IN ({0}) AND id_anio_hecho BETWEEN {annio_inicio} AND {annio_final} GROUP BY delitos.id_anio_hecho ORDER BY delitos.id_anio_hecho;",
categorias
.iter()
.map(|id| format!("{id}"))
Expand All @@ -472,6 +486,63 @@ async fn anio_porcentajes(
.into()
}

async fn mes_porcentajes(
State(state): State<Shared>,
Json(sol): Json<SolicitudPorcentajePorMesDeAnio>,
) -> Json<MesPorcetajesEnAnio> {
let SolicitudPorcentajePorMesDeAnio { categorias, anio } = dbg!(sol);

let anio = anio - OFFSET;

let (total,): (i64,) = if categorias.is_empty() || categorias.len() >= ACTUAL_CATEGORIES {
sqlx::query_as(&format!(
"SELECT COUNT(1) FROM delitos WHERE id_anio_hecho = {anio};"
))
.fetch_one(&state.db)
.await
.unwrap()
} else {
sqlx::query_as(&format!("SELECT COUNT(1) FROM delitos WHERE delitos.id_categoria IN ({0}) AND id_anio_hecho = {anio};",
categorias
.iter()
.map(|id| format!("{id}"))
.collect::<Vec<_>>()
.join(",")
))
.fetch_one(&state.db)
.await
.unwrap()
};

let resultados: Vec<(i64,)> = if categorias.is_empty() || categorias.len() >= ACTUAL_CATEGORIES
{
sqlx::query_as(&format!("SELECT COUNT(1) FROM delitos WHERE id_anio_hecho = {anio} GROUP BY delitos.id_mes_hecho ORDER BY delitos.id_mes_hecho;"))
.fetch_all(&state.db)
.await
.unwrap()
} else {
sqlx::query_as(&format!("SELECT COUNT(1) FROM delitos WHERE delitos.id_categoria IN ({0}) AND id_anio_hecho = {anio} GROUP BY delitos.id_mes_hecho ORDER BY delitos.id_mes_hecho;",
categorias
.iter()
.map(|id| format!("{id}"))
.collect::<Vec<_>>()
.join(",")
))
.fetch_all(&state.db)
.await
.unwrap()
};

println!("{resultados:?}");

MesPorcetajesEnAnio {
total: u64::try_from(total).unwrap(),
valores: resultados.into_iter().map(|(n,)| n as u64).collect(),
anio: anio + OFFSET,
}
.into()
}

async fn untilnow(State(state): State<Shared>) -> String {
let utc: DateTime<Utc> = Utc::now();
let year = utc.format("%Y").to_string();
Expand Down Expand Up @@ -532,6 +603,7 @@ async fn main() -> anyhow::Result<()> {
.route("/health", get(|| async { "alive" }))
.route("/date/:date", get(date))
.route("/map_percent", post(mapa_porcentajes))
.route("/mes_percent", post(mes_porcentajes))
.route("/anio_percent", post(anio_porcentajes))
.route("/c_por_mes", post(cantidades_por_mes))
.route("/date/upnow", get(untilnow))
Expand Down
2 changes: 2 additions & 0 deletions templates/hello.html
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,11 @@ <h1 class="text-3xl font-bold pb-3">Zonas Calientes</h1>
<section x-init="
$watch('data', value => {
load_years_data(data, { num: 2, endpoint: '/anio_percent' });
load_month_data(data, { num: 2, endpoint: '/mes_percent' });
}
);
load_years_data(data, { num: 2, endpoint: '/anio_percent' });
load_month_data(data, { num: 2, endpoint: '/mes_percent' });
" x-data="{ data: { categorias: [ 1, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ] } }"
id="incidentes-por-mes" class="flex flex-col p-3">
<div class="flex flex-col md:flex-row md:justify-between">
Expand Down

0 comments on commit 4ab40e5

Please sign in to comment.