Initial commit: NutriApp - Rust + Axum + Dioxus - CI/CD con Gitea Runner
This commit is contained in:
@@ -0,0 +1,14 @@
|
|||||||
|
# ─── Base de datos ──────────────────────────────────────────
|
||||||
|
# PostgreSQL en la Raspberry Pi 5 del homelab
|
||||||
|
DATABASE_URL=postgres://joel:***@192.168.1.87:5432/nutriapp
|
||||||
|
|
||||||
|
# ─── Servidor ───────────────────────────────────────────────
|
||||||
|
HOST=0.0.0.0
|
||||||
|
PORT=3100
|
||||||
|
|
||||||
|
# ─── Logging ────────────────────────────────────────────────
|
||||||
|
RUST_LOG=nutriapp_backend=debug,tower_http=debug
|
||||||
|
|
||||||
|
# ─── Auth ───────────────────────────────────────────────────
|
||||||
|
# Clave para firmar cookies de sesión (generar con: openssl rand -base64 64)
|
||||||
|
SESSION_KEY=cambiar-por-clave-real-de-64-bytes
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
# Rust
|
||||||
|
target/
|
||||||
|
**/*.rs.bk
|
||||||
|
*.pdb
|
||||||
|
|
||||||
|
# Dioxus
|
||||||
|
frontend/dist/
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# Secrets
|
||||||
|
.env
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
[workspace]
|
||||||
|
resolver = "2"
|
||||||
|
members = [
|
||||||
|
"backend",
|
||||||
|
"frontend",
|
||||||
|
"shared",
|
||||||
|
]
|
||||||
|
|
||||||
|
[workspace.dependencies]
|
||||||
|
# --- Serialización ---
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
|
||||||
|
# --- Utilidades ---
|
||||||
|
uuid = { version = "1", features = ["v4", "serde"] }
|
||||||
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
|
thiserror = "2"
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
[application]
|
||||||
|
name = "NutriApp"
|
||||||
|
default_platform = "web"
|
||||||
|
|
||||||
|
[web.app]
|
||||||
|
title = "NutriApp"
|
||||||
|
|
||||||
|
[web.watcher]
|
||||||
|
reload_html = true
|
||||||
|
watch_path = ["src", "public"]
|
||||||
|
|
||||||
|
[web.resource]
|
||||||
|
style = []
|
||||||
|
script = []
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
# ─── NutriApp Dockerfile ──────────────────────────────────────
|
||||||
|
# Imagen mínima para producción en ARM64 (Raspberry Pi 5)
|
||||||
|
# Build: docker build -t k3s.proyectosjoel.com/nutriapp:latest .
|
||||||
|
|
||||||
|
FROM debian:bookworm-slim
|
||||||
|
|
||||||
|
# Dependencias mínimas (ca-certificates para TLS a PostgreSQL)
|
||||||
|
RUN apt-get update -qq && \
|
||||||
|
apt-get install -y -qq ca-certificates && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Binario compilado por CI/CD (cargo build --release)
|
||||||
|
COPY target/release/nutriapp-backend /app/nutriapp
|
||||||
|
|
||||||
|
# Frontend estático (Dioxus → WASM compilado)
|
||||||
|
COPY frontend/dist /app/frontend/dist
|
||||||
|
|
||||||
|
# Migraciones SQL
|
||||||
|
COPY backend/migrations /app/migrations
|
||||||
|
|
||||||
|
EXPOSE 3100
|
||||||
|
|
||||||
|
ENV HOST=0.0.0.0
|
||||||
|
ENV PORT=3100
|
||||||
|
ENV RUST_LOG=nutriapp_backend=info
|
||||||
|
|
||||||
|
CMD ["/app/nutriapp"]
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
[package]
|
||||||
|
name = "nutriapp-backend"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
# --- Workspace shared ---
|
||||||
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
chrono = { workspace = true }
|
||||||
|
thiserror = { workspace = true }
|
||||||
|
shared = { path = "../shared" }
|
||||||
|
|
||||||
|
# --- Runtime async ---
|
||||||
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
|
||||||
|
# --- HTTP framework + WebSockets ---
|
||||||
|
axum = { version = "0.8", features = ["ws"] }
|
||||||
|
|
||||||
|
# --- Base de datos ---
|
||||||
|
sqlx = { version = "0.8", features = [
|
||||||
|
"runtime-tokio",
|
||||||
|
"tls-rustls",
|
||||||
|
"postgres",
|
||||||
|
"chrono",
|
||||||
|
"uuid",
|
||||||
|
"migrate",
|
||||||
|
] }
|
||||||
|
|
||||||
|
# --- Middleware HTTP ---
|
||||||
|
tower = "0.5"
|
||||||
|
tower-http = { version = "0.6", features = [
|
||||||
|
"cors",
|
||||||
|
"trace",
|
||||||
|
"compression-gzip",
|
||||||
|
"limit",
|
||||||
|
"fs",
|
||||||
|
] }
|
||||||
|
|
||||||
|
# --- Auth + sesiones ---
|
||||||
|
bcrypt = "0.16"
|
||||||
|
tower-sessions = "0.14"
|
||||||
|
tower-sessions-sqlx-store = { version = "0.14", features = ["postgres"] }
|
||||||
|
|
||||||
|
# --- Jobs programados ---
|
||||||
|
tokio-cron-scheduler = "0.13"
|
||||||
|
|
||||||
|
# --- Configuración ---
|
||||||
|
config = "0.15"
|
||||||
|
dotenvy = "0.15"
|
||||||
|
|
||||||
|
# --- Logging ---
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
|
||||||
|
|
||||||
|
# --- Upload de archivos (fotos de recetas) ---
|
||||||
|
axum-typed-multipart = "0.17"
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- NutriApp — Migración inicial
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
-- Habilitar extensión UUID
|
||||||
|
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||||
|
|
||||||
|
-- ─── Familias ────────────────────────────────────────────────
|
||||||
|
CREATE TABLE IF NOT EXISTS familias (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
nombre VARCHAR(255) NOT NULL,
|
||||||
|
codigo_invitacion VARCHAR(8) UNIQUE NOT NULL,
|
||||||
|
creador_id UUID,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ─── Usuarios ────────────────────────────────────────────────
|
||||||
|
CREATE TABLE IF NOT EXISTS usuarios (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
email VARCHAR(255) UNIQUE NOT NULL,
|
||||||
|
nombre VARCHAR(255) NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
familia_id UUID REFERENCES familias(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- FK circular: creador_id → usuarios
|
||||||
|
ALTER TABLE familias
|
||||||
|
ADD CONSTRAINT fk_familias_creador
|
||||||
|
FOREIGN KEY (creador_id) REFERENCES usuarios(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
-- ─── Ingredientes (catálogo global por familia) ──────────────
|
||||||
|
CREATE TABLE IF NOT EXISTS ingredientes (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
familia_id UUID NOT NULL REFERENCES familias(id) ON DELETE CASCADE,
|
||||||
|
nombre VARCHAR(255) NOT NULL,
|
||||||
|
categoria VARCHAR(50),
|
||||||
|
unidad_medida VARCHAR(20) NOT NULL DEFAULT 'unidad',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE(familia_id, nombre)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ─── Recetas ─────────────────────────────────────────────────
|
||||||
|
CREATE TABLE IF NOT EXISTS recetas (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
familia_id UUID NOT NULL REFERENCES familias(id) ON DELETE CASCADE,
|
||||||
|
creador_id UUID NOT NULL REFERENCES usuarios(id) ON DELETE CASCADE,
|
||||||
|
nombre VARCHAR(255) NOT NULL,
|
||||||
|
descripcion TEXT,
|
||||||
|
porciones INTEGER NOT NULL DEFAULT 1,
|
||||||
|
tiempo_preparacion_min INTEGER,
|
||||||
|
instrucciones TEXT,
|
||||||
|
imagen_url TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ─── Ingredientes de cada receta ────────────────────────────
|
||||||
|
CREATE TABLE IF NOT EXISTS receta_ingredientes (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
receta_id UUID NOT NULL REFERENCES recetas(id) ON DELETE CASCADE,
|
||||||
|
ingrediente_id UUID NOT NULL REFERENCES ingredientes(id) ON DELETE CASCADE,
|
||||||
|
cantidad DOUBLE PRECISION NOT NULL,
|
||||||
|
unidad VARCHAR(20) NOT NULL DEFAULT 'unidad',
|
||||||
|
UNIQUE(receta_id, ingrediente_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ─── Calendario semanal (slots de comida) ──────────────────
|
||||||
|
CREATE TABLE IF NOT EXISTS slots_comida (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
familia_id UUID NOT NULL REFERENCES familias(id) ON DELETE CASCADE,
|
||||||
|
fecha DATE NOT NULL,
|
||||||
|
tipo VARCHAR(20) NOT NULL CHECK (tipo IN ('desayuno', 'comida', 'cena')),
|
||||||
|
receta_id UUID REFERENCES recetas(id) ON DELETE SET NULL,
|
||||||
|
porciones INTEGER NOT NULL DEFAULT 1,
|
||||||
|
creado_por UUID REFERENCES usuarios(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE(familia_id, fecha, tipo, receta_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ─── Inventario familiar ────────────────────────────────────
|
||||||
|
CREATE TABLE IF NOT EXISTS inventario (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
familia_id UUID NOT NULL REFERENCES familias(id) ON DELETE CASCADE,
|
||||||
|
ingrediente_id UUID NOT NULL REFERENCES ingredientes(id) ON DELETE CASCADE,
|
||||||
|
cantidad DOUBLE PRECISION NOT NULL DEFAULT 0,
|
||||||
|
unidad VARCHAR(20) NOT NULL,
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE(familia_id, ingrediente_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ─── Índices ─────────────────────────────────────────────────
|
||||||
|
CREATE INDEX idx_recetas_familia ON recetas(familia_id);
|
||||||
|
CREATE INDEX idx_slots_familia_fecha ON slots_comida(familia_id, fecha);
|
||||||
|
CREATE INDEX idx_inventario_familia ON inventario(familia_id);
|
||||||
|
CREATE INDEX idx_ingredientes_familia ON ingredientes(familia_id);
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// Middleware de autenticación
|
||||||
|
// Extraerá CurrentUser de la sesión y lo inyectará en los handlers
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
// Auth module — login, registro, middleware de sesión
|
||||||
|
// Se implementará con tower-sessions + bcrypt
|
||||||
|
|
||||||
|
pub mod middleware;
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
// Jobs programados con tokio-cron-scheduler
|
||||||
|
// - Generar lista de compras cada domingo
|
||||||
|
// - Limpiar sesiones expiradas
|
||||||
|
// - Recordatorios de menú diario
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
use axum::{
|
||||||
|
Router,
|
||||||
|
routing::get,
|
||||||
|
response::Json,
|
||||||
|
};
|
||||||
|
use serde::Serialize;
|
||||||
|
use sqlx::postgres::PgPoolOptions;
|
||||||
|
use tower_http::{
|
||||||
|
cors::CorsLayer,
|
||||||
|
services::{ServeDir, ServeFile},
|
||||||
|
trace::TraceLayer,
|
||||||
|
compression::CompressionLayer,
|
||||||
|
limit::RequestBodyLimitLayer,
|
||||||
|
};
|
||||||
|
use tower_sessions::{
|
||||||
|
SessionManagerLayer,
|
||||||
|
cookie::Key,
|
||||||
|
};
|
||||||
|
use tower_sessions_sqlx_store::PostgresStore;
|
||||||
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||||
|
|
||||||
|
mod routes;
|
||||||
|
mod models;
|
||||||
|
mod auth;
|
||||||
|
mod ws;
|
||||||
|
mod jobs;
|
||||||
|
|
||||||
|
// ─── App State ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AppState {
|
||||||
|
pub db: sqlx::PgPool,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Health Endpoint ──────────────────────────────────────────
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct HealthResponse {
|
||||||
|
status: &'static str,
|
||||||
|
version: &'static str,
|
||||||
|
db: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn health() -> Json<HealthResponse> {
|
||||||
|
Json(HealthResponse {
|
||||||
|
status: "ok",
|
||||||
|
version: env!("CARGO_PKG_VERSION"),
|
||||||
|
db: "connected",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Entrypoint ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
// --- Logging ---
|
||||||
|
tracing_subscriber::registry()
|
||||||
|
.with(tracing_subscriber::EnvFilter::try_from_default_env()
|
||||||
|
.unwrap_or_else(|_| "nutriapp_backend=debug,tower_http=debug".into()))
|
||||||
|
.with(tracing_subscriber::fmt::layer())
|
||||||
|
.init();
|
||||||
|
|
||||||
|
// --- Config desde .env ---
|
||||||
|
dotenvy::dotenv().ok();
|
||||||
|
|
||||||
|
let database_url = std::env::var("DATABASE_URL")
|
||||||
|
.unwrap_or_else(|_| {
|
||||||
|
"postgres://joel:factory_admin_2026@192.168.1.87:5432/nutriapp".to_string()
|
||||||
|
});
|
||||||
|
|
||||||
|
let host = std::env::var("HOST").unwrap_or_else(|_| "0.0.0.0".to_string());
|
||||||
|
let port: u16 = std::env::var("PORT")
|
||||||
|
.unwrap_or_else(|_| "3100".to_string())
|
||||||
|
.parse()
|
||||||
|
.unwrap_or(3100);
|
||||||
|
|
||||||
|
// --- Pool PostgreSQL ---
|
||||||
|
let pool = PgPoolOptions::new()
|
||||||
|
.max_connections(10)
|
||||||
|
.connect(&database_url)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!("✅ PostgreSQL conectado");
|
||||||
|
|
||||||
|
// --- Migraciones automáticas ---
|
||||||
|
sqlx::migrate!("./migrations")
|
||||||
|
.run(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!("✅ Migraciones aplicadas");
|
||||||
|
|
||||||
|
// --- Session store ---
|
||||||
|
let session_store = PostgresStore::new(pool.clone());
|
||||||
|
session_store.migrate().await?;
|
||||||
|
|
||||||
|
let session_layer = SessionManagerLayer::new(session_store)
|
||||||
|
.with_secure(false); // false en dev (sin HTTPS), true en prod
|
||||||
|
|
||||||
|
// --- App state ---
|
||||||
|
let state = AppState { db: pool };
|
||||||
|
|
||||||
|
// --- Router ---
|
||||||
|
let app = Router::new()
|
||||||
|
// API
|
||||||
|
.route("/api/health", get(health))
|
||||||
|
.nest("/api", routes::api_routes())
|
||||||
|
// WebSocket
|
||||||
|
.nest("/ws", ws::ws_routes())
|
||||||
|
// Frontend estático (producción)
|
||||||
|
.nest_service("/", ServeDir::new("../frontend/dist")
|
||||||
|
.fallback(ServeFile::new("../frontend/dist/index.html")))
|
||||||
|
// Middleware (orden importa: último = más externo)
|
||||||
|
.layer(CompressionLayer::new())
|
||||||
|
.layer(RequestBodyLimitLayer::new(10 * 1024 * 1024)) // 10MB
|
||||||
|
.layer(CorsLayer::permissive())
|
||||||
|
.layer(TraceLayer::new_for_http())
|
||||||
|
.layer(session_layer)
|
||||||
|
.with_state(state);
|
||||||
|
|
||||||
|
// --- Arranque ---
|
||||||
|
let addr = format!("{host}:{port}");
|
||||||
|
tracing::info!("🚀 NutriApp corriendo en http://{addr}");
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind(&addr).await?;
|
||||||
|
axum::serve(listener, app).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
|
pub struct Familia {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub nombre: String,
|
||||||
|
pub codigo_invitacion: String,
|
||||||
|
pub creador_id: Uuid,
|
||||||
|
pub created_at: chrono::NaiveDateTime,
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
|
pub struct Ingrediente {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub nombre: String,
|
||||||
|
pub categoria: Option<String>, // "verdura", "proteina", "lacteo", etc.
|
||||||
|
pub unidad_medida: String, // "g", "ml", "unidad", "cucharada"
|
||||||
|
pub created_at: chrono::NaiveDateTime,
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
pub mod receta;
|
||||||
|
pub mod ingrediente;
|
||||||
|
pub mod usuario;
|
||||||
|
pub mod familia;
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
use chrono::NaiveDateTime;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
|
pub struct Receta {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub familia_id: Uuid,
|
||||||
|
pub creador_id: Uuid,
|
||||||
|
pub nombre: String,
|
||||||
|
pub descripcion: Option<String>,
|
||||||
|
pub porciones: i32,
|
||||||
|
pub tiempo_preparacion_min: Option<i32>,
|
||||||
|
pub instrucciones: Option<String>,
|
||||||
|
pub imagen_url: Option<String>,
|
||||||
|
pub created_at: NaiveDateTime,
|
||||||
|
pub updated_at: NaiveDateTime,
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
|
pub struct Usuario {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub email: String,
|
||||||
|
pub nombre: String,
|
||||||
|
pub password_hash: String,
|
||||||
|
pub familia_id: Option<Uuid>,
|
||||||
|
pub created_at: chrono::NaiveDateTime,
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
use axum::{Router, routing::get};
|
||||||
|
|
||||||
|
pub fn api_routes() -> Router<crate::AppState> {
|
||||||
|
Router::new()
|
||||||
|
.route("/v1/recetas", get(list_recetas))
|
||||||
|
// TODO: .route("/v1/recetas", post(create_receta))
|
||||||
|
// TODO: .route("/v1/recetas/:id", get(get_receta))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn list_recetas() -> axum::response::Json<serde_json::Value> {
|
||||||
|
axum::response::Json(serde_json::json!({
|
||||||
|
"recetas": [],
|
||||||
|
"total": 0
|
||||||
|
}))
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
use axum::{Router, routing::get};
|
||||||
|
|
||||||
|
pub fn ws_routes() -> Router<crate::AppState> {
|
||||||
|
Router::new()
|
||||||
|
.route("/familia/:familia_id", get(ws_familia_handler))
|
||||||
|
}
|
||||||
|
|
||||||
|
// WebSocket colaborativo para edición en tiempo real del menú
|
||||||
|
async fn ws_familia_handler(
|
||||||
|
// ws: axum::extract::ws::WebSocketUpgrade,
|
||||||
|
// Path(familia_id): axum::extract::Path<uuid::Uuid>,
|
||||||
|
// State(state): axum::extract::State<crate::AppState>,
|
||||||
|
) -> &'static str {
|
||||||
|
"WebSocket endpoint — TODO: implementar broadcast por familia"
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
[package]
|
||||||
|
name = "nutriapp-frontend"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
# --- Dioxus ---
|
||||||
|
dioxus = { version = "0.6", features = ["web"] }
|
||||||
|
|
||||||
|
# --- Shared ---
|
||||||
|
shared = { path = "../shared" }
|
||||||
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
uuid = { workspace = true, features = ["v4"] }
|
||||||
|
chrono = { workspace = true }
|
||||||
|
|
||||||
|
# --- HTTP calls al backend ---
|
||||||
|
reqwest = { version = "0.12", features = ["json"] }
|
||||||
|
|
||||||
|
# --- WASM bindings ---
|
||||||
|
wasm-bindgen = "0.2"
|
||||||
|
web-sys = { version = "0.3", features = ["console"] }
|
||||||
|
console_error_panic_hook = "0.1"
|
||||||
|
|
||||||
|
# --- Logging ---
|
||||||
|
log = "0.4"
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="es">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>NutriApp</title>
|
||||||
|
<style>
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
font-family: system-ui, -apple-system, sans-serif;
|
||||||
|
background: #0f172a;
|
||||||
|
color: #e2e8f0;
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
#main { min-height: 100vh; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="main"></div>
|
||||||
|
<script type="module">
|
||||||
|
import init from './assets/dioxus/nutriapp-frontend.js';
|
||||||
|
init('./assets/dioxus/nutriapp-frontend_bg.wasm');
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// Cliente HTTP para la API del backend (Axum en :3100)
|
||||||
|
// TODO: reemplazar con llamadas reales a /api/v1/*
|
||||||
|
|
||||||
|
use reqwest::Client;
|
||||||
|
use shared::{RecetaDto, SlotComidaDto, ItemCompraDto, ListaCompraRequest};
|
||||||
|
|
||||||
|
const API_BASE: &str = "http://localhost:3100/api/v1";
|
||||||
|
|
||||||
|
pub async fn listar_recetas() -> Result<Vec<RecetaDto>, String> {
|
||||||
|
let client = Client::new();
|
||||||
|
let resp = client
|
||||||
|
.get(format!("{API_BASE}/recetas"))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
resp.json::<Vec<RecetaDto>>()
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn listar_slots(
|
||||||
|
familia_id: &str,
|
||||||
|
desde: &str,
|
||||||
|
hasta: &str,
|
||||||
|
) -> Result<Vec<SlotComidaDto>, String> {
|
||||||
|
let client = Client::new();
|
||||||
|
let resp = client
|
||||||
|
.get(format!(
|
||||||
|
"{API_BASE}/calendario?familia_id={familia_id}&desde={desde}&hasta={hasta}"
|
||||||
|
))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
resp.json::<Vec<SlotComidaDto>>()
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn generar_lista_compras(
|
||||||
|
req: &ListaCompraRequest,
|
||||||
|
) -> Result<Vec<ItemCompraDto>, String> {
|
||||||
|
let client = Client::new();
|
||||||
|
let resp = client
|
||||||
|
.post(format!("{API_BASE}/lista-compras"))
|
||||||
|
.json(req)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
resp.json::<Vec<ItemCompraDto>>()
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// API client para llamadas al backend (Axum en :3100)
|
||||||
|
pub mod client;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
pub mod receta_card;
|
||||||
|
pub mod slot_calendario;
|
||||||
|
pub mod nav;
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
// Barra de navegación reutilizable
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// Componente tarjeta de receta — nombre, porciones, tiempo, ingredientes
|
||||||
|
use dioxus::prelude::*;
|
||||||
|
use shared::RecetaDto;
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn RecetaCard(receta: RecetaDto, on_click: Option<EventHandler<()>>) -> Element {
|
||||||
|
rsx! {
|
||||||
|
div {
|
||||||
|
class: "receta-card",
|
||||||
|
onclick: move |_| {
|
||||||
|
if let Some(ref handler) = on_click {
|
||||||
|
handler.call(());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
h3 { "{receta.nombre}" }
|
||||||
|
span { "🍽️ {receta.porciones} porciones" }
|
||||||
|
if let Some(tiempo) = receta.tiempo_preparacion_min {
|
||||||
|
span { "⏱️ {tiempo} min" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
// Slot de comida en el calendario (desayuno/comida/cena de un día)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
#![allow(non_snake_case)]
|
||||||
|
|
||||||
|
use dioxus::prelude::*;
|
||||||
|
|
||||||
|
mod pages;
|
||||||
|
mod components;
|
||||||
|
mod api;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
console_error_panic_hook::set_once();
|
||||||
|
dioxus::launch(App);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
fn App() -> Element {
|
||||||
|
rsx! {
|
||||||
|
div { class: "app-container",
|
||||||
|
header { class: "header",
|
||||||
|
h1 { "🍽️ NutriApp" }
|
||||||
|
nav {
|
||||||
|
a { href: "/", "Calendario" }
|
||||||
|
a { href: "/recetas", "Recetas" }
|
||||||
|
a { href: "/lista", "Lista de Compras" }
|
||||||
|
a { href: "/inventario", "Inventario" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
main { class: "main-content",
|
||||||
|
// Placeholder — routing se agrega después
|
||||||
|
h2 { "Bienvenido a NutriApp" }
|
||||||
|
p { "Planifica tus comidas semanales en familia." }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
// Página de calendario semanal
|
||||||
|
// Grid 7 columnas (días) × 3 filas (desayuno, comida, cena)
|
||||||
|
// Drag & drop de recetas a slots
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// Página de inventario — productos disponibles en casa
|
||||||
|
// Se descuenta de la lista de compras
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
// Página de lista de compras generada automáticamente desde el menú semanal
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
pub mod calendario;
|
||||||
|
pub mod recetas;
|
||||||
|
pub mod lista_compras;
|
||||||
|
pub mod inventario;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// Página de recetas
|
||||||
|
// Lista, búsqueda, crear/editar receta con ingredientes dinámicos
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# ─── NutriApp K3s Deployment ─────────────────────────────────
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: nutriapp
|
||||||
|
namespace: nutriapp
|
||||||
|
labels:
|
||||||
|
app: nutriapp
|
||||||
|
spec:
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: nutriapp
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: nutriapp
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: nutriapp
|
||||||
|
image: k3s.proyectosjoel.com/nutriapp:latest
|
||||||
|
imagePullPolicy: Always
|
||||||
|
ports:
|
||||||
|
- containerPort: 3100
|
||||||
|
name: http
|
||||||
|
env:
|
||||||
|
- name: DATABASE_URL
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: nutriapp-db
|
||||||
|
key: url
|
||||||
|
- name: SESSION_KEY
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: nutriapp-db
|
||||||
|
key: session-key
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
memory: "32Mi"
|
||||||
|
cpu: "50m"
|
||||||
|
limits:
|
||||||
|
memory: "128Mi"
|
||||||
|
cpu: "500m"
|
||||||
|
livenessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /api/health
|
||||||
|
port: 3100
|
||||||
|
initialDelaySeconds: 10
|
||||||
|
periodSeconds: 30
|
||||||
|
readinessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /api/health
|
||||||
|
port: 3100
|
||||||
|
initialDelaySeconds: 5
|
||||||
|
periodSeconds: 10
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: nutriapp
|
||||||
|
namespace: nutriapp
|
||||||
|
labels:
|
||||||
|
app: nutriapp
|
||||||
|
spec:
|
||||||
|
selector:
|
||||||
|
app: nutriapp
|
||||||
|
ports:
|
||||||
|
- port: 3100
|
||||||
|
targetPort: 3100
|
||||||
|
name: http
|
||||||
|
type: ClusterIP
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[package]
|
||||||
|
name = "shared"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
chrono = { workspace = true }
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
use chrono::NaiveDate;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
/// Tipos compartidos entre backend y frontend (Dioxus).
|
||||||
|
/// Ambos crates dependen de `shared`.
|
||||||
|
|
||||||
|
// ─── Enums ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
|
pub enum TipoComida {
|
||||||
|
Desayuno,
|
||||||
|
Comida,
|
||||||
|
Cena,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
|
pub enum UnidadMedida {
|
||||||
|
Gramos,
|
||||||
|
Mililitros,
|
||||||
|
Unidad,
|
||||||
|
Cucharada,
|
||||||
|
Cucharadita,
|
||||||
|
Taza,
|
||||||
|
Pizca,
|
||||||
|
AlGusto,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
|
pub enum CategoriaIngrediente {
|
||||||
|
Verdura,
|
||||||
|
Fruta,
|
||||||
|
Proteina,
|
||||||
|
Lacteo,
|
||||||
|
Cereal,
|
||||||
|
Legumbre,
|
||||||
|
Bebida,
|
||||||
|
Snack,
|
||||||
|
Condimento,
|
||||||
|
Otro,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── DTOs ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Receta con sus ingredientes
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RecetaDto {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub nombre: String,
|
||||||
|
pub descripcion: Option<String>,
|
||||||
|
pub porciones: i32,
|
||||||
|
pub tiempo_preparacion_min: Option<i32>,
|
||||||
|
pub instrucciones: Option<String>,
|
||||||
|
pub imagen_url: Option<String>,
|
||||||
|
pub ingredientes: Vec<IngredienteRecetaDto>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cantidad de un ingrediente en una receta
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct IngredienteRecetaDto {
|
||||||
|
pub ingrediente_id: Uuid,
|
||||||
|
pub nombre: String,
|
||||||
|
pub cantidad: f64,
|
||||||
|
pub unidad: UnidadMedida,
|
||||||
|
pub categoria: CategoriaIngrediente,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Un platillo asignado a un slot del calendario
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct SlotComidaDto {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub fecha: NaiveDate,
|
||||||
|
pub tipo: TipoComida,
|
||||||
|
pub receta_id: Uuid,
|
||||||
|
pub receta_nombre: String,
|
||||||
|
pub porciones: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Solicitud de lista de compras
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ListaCompraRequest {
|
||||||
|
pub familia_id: Uuid,
|
||||||
|
pub desde: NaiveDate,
|
||||||
|
pub hasta: NaiveDate,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Item de la lista de compras
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ItemCompraDto {
|
||||||
|
pub ingrediente_id: Uuid,
|
||||||
|
pub nombre: String,
|
||||||
|
pub cantidad_total: f64,
|
||||||
|
pub unidad: UnidadMedida,
|
||||||
|
pub categoria: CategoriaIngrediente,
|
||||||
|
pub en_inventario: bool,
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user