Initial commit: NutriApp - Rust + Axum + Dioxus - CI/CD con Gitea Runner
This commit is contained in:
@@ -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"
|
||||
}
|
||||
Reference in New Issue
Block a user