puerto 0.34.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-framework.
//! `puerto generar notificaciones` (Fase 41.4, ADR-0037): the runtime's inbox in a project — its
//! flag in `puerto.toml`, its migration, its routes in `bootstrap.rs` and, with `web/`, the bell in
//! the frame's header and the `/notificaciones` page.

use std::path::Path;

use serde::Serialize;

use crate::generators::effective_fields;
use crate::generators::layout;
use crate::generators::naming::{pluralize, to_pascal_case, write_file};
use crate::generators::render::render;
use crate::generators::worker::{
    check_new_consumer, regenerate_registry, write_new_consumer, write_processed_events_migration,
};
use crate::puerto_toml::{Entity, PuertoConfig};

/// Written once, never overwritten: the user's from then on.
const WEB_FILES: [(&str, &str); 5] = [
    (
        "web/src/notificaciones/campana.tsx",
        "web/notificaciones/campana.tsx",
    ),
    (
        "web/src/notificaciones/campana.test.tsx",
        "web/notificaciones/campana.test.tsx",
    ),
    (
        "web/src/notificaciones/pagina-notificaciones.tsx",
        "web/notificaciones/pagina-notificaciones.tsx",
    ),
    (
        "web/src/notificaciones/pagina-notificaciones.test.tsx",
        "web/notificaciones/pagina-notificaciones.test.tsx",
    ),
    (
        "web/src/pruebas/api-notificaciones.ts",
        "web/notificaciones/api-notificaciones.ts",
    ),
];

/// An inbox is someone's, and the worker writes it and it arrives live: a project with auth and
/// events.
fn check_project(config: &PuertoConfig) -> Result<(), String> {
    if !config.project.has_auth() {
        return Err(
            "la bandeja de notificaciones es de cada usuario: necesita un proyecto con auth \
             (`puerto nuevo --auth oidc|local`)"
                .into(),
        );
    }
    if !config.project.has_events() {
        return Err(
            "las notificaciones las escribe el worker y llegan en vivo: necesitan un proyecto \
             con eventos (`puerto nuevo --db --eventos db|kafka`)"
                .into(),
        );
    }
    Ok(())
}

/// Refuses a project without auth or events ([`check_project`]), and one that already has it.
pub fn run_generate_notifications(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = crate::puerto_toml::read(base)?;
    check_project(&config)?;
    if config.project.notificaciones {
        return Err(
            "este proyecto ya tiene la bandeja de notificaciones (`[proyecto] notificaciones` en \
             puerto.toml)"
                .into(),
        );
    }
    config.project.notificaciones = true;
    crate::puerto_toml::write(base, &config)?;

    let sql = render("infrastructure/notifications.sql", &tera::Context::new())?;
    crate::generators::migration::run_migration("crear_notificaciones", base, Some(&sql))?;
    // The spec export test of `bootstrap.rs` builds the inbox over its double.
    crate::generators::bootstrap::add_crate_dependency(
        base,
        layout::API_MANIFEST,
        "dev-dependencies",
        "puerto-nucleo",
        "{ workspace = true, features = [\"pruebas\"] }",
    )?;
    crate::generators::bootstrap::regenerate_bootstrap(base)?;
    if config.project.web {
        for (path, template) in WEB_FILES {
            let path = base.join(path);
            if !path.exists() {
                write_file(&path, &render(template, &tera::Context::new())?)?;
            }
        }
        crate::generators::web::regenerate_web(base, &config)?;
    }

    println!("✓ La bandeja de notificaciones: /api/notificaciones, para cada usuario con sesión");
    println!(
        "  Un consumidor del worker notifica con \
         `puerto_sqlx::notificaciones::NotificacionesPostgres` (presentacion/worker/AGENTS.md)."
    );
    if config.project.web {
        println!(
            "  web/src/notificaciones/ es tuyo: la campana de la cabecera y la página \
             /notificaciones. Siguiente: task web:sync"
        );
    }
    println!("  Aplica la migración: task sqlx:migrate");
    Ok(())
}

/// One event a notification goes out on: an arm of its consumer's `match`.
#[derive(Serialize)]
struct Arm {
    event_type: String,
    constant: String,
    entity_pascal: String,
    entity_snake: String,
    /// The entity's detail page, which the notification links to: with `web/` and its
    /// `obtener_<entity>`.
    plural: Option<String>,
}

/// Whom a snapshot of `entity` can notify: its owner and its required `ref:Usuario` fields.
fn users(entity: &Entity) -> Vec<String> {
    effective_fields(&entity.fields)
        .into_iter()
        .filter(|f| f.field_type == "Uuid")
        .filter(|f| {
            entity.owner.as_deref() == Some(f.name.as_str())
                || f.references.as_deref() == Some("Usuario")
        })
        .map(|f| f.name)
        .collect()
}

/// `puerto generar notificacion <name> --tras <event_type>[,…] --para <field>` (Fase 42.1): the
/// consumer `notificar_<name>`, which leaves a notification in `<field>`'s inbox after each event,
/// once per event. Installs the inbox first if the project lacks it. Everything is checked before
/// anything is written.
pub fn run_generate_notification(
    name: &str,
    on: &[String],
    to: &str,
    base: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;
    check_project(&config)?;
    let consumer_name = format!("notificar_{name}");
    let (consumer, events) = check_new_consumer(&config, &consumer_name, on, base)?;

    let mut arms = vec![];
    let mut imports: std::collections::BTreeMap<String, Vec<String>> = Default::default();
    for event in &events {
        let entity = config
            .entity
            .iter()
            .find(|e| e.name == event.entity_pascal)
            .ok_or_else(|| format!("la entidad {} no está en puerto.toml", event.entity_pascal))?;
        let users = users(entity);
        if !users.iter().any(|u| u == to) {
            return Err(format!(
                "--para {to}: el snapshot de {} no lleva ese usuario. Una notificación va al \
                 propietario de la entidad o a un `ref:Usuario` obligatorio: {}",
                event.event_type,
                if users.is_empty() {
                    format!("{} no tiene ninguno", entity.name)
                } else {
                    format!("aquí, {}", users.join(", "))
                }
            )
            .into());
        }
        let shows = config.project.web
            && entity
                .use_cases
                .contains(&format!("obtener_{}", event.entity_snake));
        arms.push(Arm {
            event_type: event.event_type.clone(),
            constant: event.constant.clone(),
            entity_pascal: event.entity_pascal.clone(),
            entity_snake: event.entity_snake.clone(),
            plural: shows.then(|| pluralize(&event.entity_snake)),
        });
        let names = imports
            .entry(event.entity_snake.clone())
            .or_insert_with(|| vec![format!("Snapshot{}", event.entity_pascal)]);
        names.push(event.constant.clone());
    }
    let imports: Vec<String> = imports
        .into_iter()
        .map(|(snake, mut names)| {
            names.sort();
            format!("dominio_{snake}::eventos::{{{}}}", names.join(", "))
        })
        .collect();

    let mut ctx = tera::Context::new();
    ctx.insert("name", name);
    ctx.insert("pascal", &to_pascal_case(name));
    ctx.insert("to", to);
    ctx.insert("message", &crate::generators::mail::humanize(name));
    ctx.insert("arms", &arms);
    ctx.insert("first", &events[0]);
    ctx.insert("imports", &imports);
    let content = render("worker/notification_consumer.tera", &ctx)?;

    if !config.project.notificaciones {
        run_generate_notifications(base)?;
    }
    write_new_consumer(base, consumer, &content)?;
    // `MockNotificaciones` and `EventosProcesadosEnMemoria`, in its tests.
    crate::generators::bootstrap::add_crate_dependency(
        base,
        layout::WORKER_MANIFEST,
        "dev-dependencies",
        "puerto-nucleo",
        "{ workspace = true, features = [\"pruebas\"] }",
    )?;
    write_processed_events_migration(base)?;
    regenerate_registry(base, &crate::puerto_toml::read(base)?)?;

    println!("✓ Notificación '{name}': a `{to}`, tras {}", on.join(", "));
    println!(
        "  {} es tuyo: cambia el mensaje, el enlace o a quién va.",
        layout::consumer(&consumer_name)
    );
    println!("  Aplica la migración: task sqlx:migrate. Arranca el worker con `task worker`.");
    Ok(())
}