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.
// Fase 42.1: `puerto generar notificacion <nombre> --tras <evento>,… --para <campo>` — the worker
// leaves a notification in someone's inbox after an event, like `generar correo --tras --para`.
use super::*;
use crate::commands::new::{NewOptions, new_project};

fn read(dir: &Path, path: &str) -> String {
    fs::read_to_string(dir.join(path)).unwrap_or_else(|e| panic!("{path}: {e}"))
}

fn strings(args: &[&str]) -> Vec<String> {
    args.iter().map(|a| a.to_string()).collect()
}

fn auth_events() -> NewOptions {
    NewOptions {
        db: true,
        events: Some("db".into()),
        auth: Some("oidc".into()),
        ..Default::default()
    }
}

/// A fresh project with `options` and an `Encargo` owned by `titular_id`, with a reviewer and an
/// optional one.
fn project_with_encargo(name: &str, options: NewOptions) -> (PathBuf, PathBuf) {
    let dir = temp_dir(name);
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();
    let output = new_project(
        Some(name.replace('_', "-")),
        NewOptions {
            no_portada: true,
            ..options
        },
        Some(dir.clone()),
    )
    .unwrap();
    let mut args = vec!["referencia:String", "titular_id:Uuid"];
    if puerto_toml::read(&output).unwrap().project.has_auth() {
        args.extend(["revisor_id:ref:Usuario", "suplente_id:ref:opt:Usuario"]);
    }
    let fields: Vec<puerto_toml::Field> = args
        .iter()
        .map(|arg| puerto_toml::parse_field_arg(arg).unwrap())
        .collect();
    let owned = puerto_toml::read(&output).unwrap().project.has_auth();
    let shape = scaffold::EntityShape::default().with_owner(owned.then(|| "titular_id".into()));
    scaffold::run_scaffold_with_options(
        "Encargo",
        &output,
        &fields,
        OverwritePolicy::Force,
        &scaffold::ScaffoldAccess::default(),
        &shape,
    )
    .unwrap();
    (dir, output)
}

const HANDLER: &str = "presentacion/worker/src/consumidores/notificar_encargo_recibido.rs";

#[test]
fn should_write_a_consumer_that_notifies_the_owner_after_the_event() {
    let (dir, output) = project_with_encargo("notificacion_alta", auth_events());

    scaffold::run_generate_notification(
        "encargo_recibido",
        &strings(&["encargo_creado"]),
        "titular_id",
        &output,
    )
    .unwrap();

    let manifest = read(&output, "puerto.toml");
    assert!(
        manifest.contains(
            "[[consumidor]]\nnombre = \"notificar_encargo_recibido\"\neventos = [\"encargo_creado\"]"
        ),
        "{manifest}"
    );
    let handler = read(&output, HANDLER);
    assert!(
        handler.contains("pub struct NotificarEncargoRecibido {"),
        "{handler}"
    );
    assert!(
        handler.contains("const TIPO: &str = \"encargo_recibido\";"),
        "{handler}"
    );
    assert!(
        handler.contains("NotificacionNueva::new(encargo.titular_id, TIPO, \"Encargo recibido\")"),
        "{handler}"
    );
    assert!(
        handler.contains(".con_enlace(format!(\"/encargos/{}\", encargo.id))"),
        "{handler}"
    );
    assert!(
        handler.contains("procesar_una_vez(&*self.procesados, \"notificar_encargo_recibido\""),
        "{handler}"
    );
    assert!(
        read(&output, "presentacion/worker/src/consumidores.rs")
            .contains("pub mod notificar_encargo_recibido;")
    );
    let registry = read(&output, "presentacion/worker/src/generado/registro.rs");
    assert!(
        registry.contains("NotificarEncargoRecibido::construir(&pool)"),
        "{registry}"
    );
    assert!(
        read(&output, "presentacion/worker/Cargo.toml")
            .contains("puerto-nucleo = { workspace = true, features = [\"pruebas\"] }")
    );
    let migrations: Vec<String> = fs::read_dir(output.join("migraciones"))
        .unwrap()
        .flatten()
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .collect();
    assert!(
        migrations
            .iter()
            .any(|m| m.ends_with("_eventos_procesados.sql")),
        "{migrations:?}"
    );
    cleanup(&dir);
}

#[test]
fn should_install_the_inbox_with_the_first_notification_only() {
    let (dir, output) = project_with_encargo("notificacion_bandeja", auth_events());

    scaffold::run_generate_notification(
        "encargo_recibido",
        &strings(&["encargo_creado"]),
        "titular_id",
        &output,
    )
    .unwrap();
    scaffold::run_generate_notification(
        "encargo_para_revisar",
        &strings(&["encargo_creado", "encargo_actualizado"]),
        "revisor_id",
        &output,
    )
    .unwrap();

    assert!(read(&output, "puerto.toml").contains("notificaciones = true"));
    let inboxes = fs::read_dir(output.join("migraciones"))
        .unwrap()
        .flatten()
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_crear_notificaciones.sql")
        })
        .count();
    assert_eq!(inboxes, 1);
    let handler = read(
        &output,
        "presentacion/worker/src/consumidores/notificar_encargo_para_revisar.rs",
    );
    assert!(handler.contains("ENCARGO_ACTUALIZADO =>"), "{handler}");
    assert!(
        handler.contains("NotificacionNueva::new(encargo.revisor_id, TIPO,"),
        "{handler}"
    );
    cleanup(&dir);
}

#[test]
fn should_leave_the_link_out_without_web() {
    let (dir, output) = project_with_encargo(
        "notificacion_sin_web",
        NewOptions {
            no_web: true,
            ..auth_events()
        },
    );

    scaffold::run_generate_notification(
        "encargo_recibido",
        &strings(&["encargo_creado"]),
        "titular_id",
        &output,
    )
    .unwrap();

    assert!(!read(&output, HANDLER).contains("con_enlace"));
    cleanup(&dir);
}

#[test]
fn should_refuse_a_notification_to_someone_who_is_not_a_user() {
    let (dir, output) = project_with_encargo("notificacion_para", auth_events());
    let error = |to: &str| {
        scaffold::run_generate_notification(
            "encargo_recibido",
            &strings(&["encargo_creado"]),
            to,
            &output,
        )
        .unwrap_err()
        .to_string()
    };

    for to in ["referencia", "suplente_id", "no_existe"] {
        let message = error(to);
        assert!(
            message.contains("titular_id") && message.contains("revisor_id"),
            "{to}: {message}"
        );
    }
    let unknown = scaffold::run_generate_notification(
        "encargo_recibido",
        &strings(&["encargo_enviado"]),
        "titular_id",
        &output,
    )
    .unwrap_err()
    .to_string();
    assert!(unknown.contains("encargo_enviado"), "{unknown}");
    // Nothing was written: the inbox is not half installed.
    assert!(!read(&output, "puerto.toml").contains("notificaciones = true"));
    cleanup(&dir);
}

#[test]
fn should_refuse_a_notification_twice_and_without_auth_or_events() {
    let (dir, output) = project_with_encargo("notificacion_dos_veces", auth_events());
    let notify = |output: &Path| {
        scaffold::run_generate_notification(
            "encargo_recibido",
            &strings(&["encargo_creado"]),
            "titular_id",
            output,
        )
        .err()
        .map(|e| e.to_string())
        .unwrap_or_default()
    };
    assert_eq!(notify(&output), "");
    assert!(notify(&output).contains("ya está declarado"));
    cleanup(&dir);

    let (dir, output) = project_with_encargo(
        "notificacion_sin_auth",
        NewOptions {
            auth: None,
            ..auth_events()
        },
    );
    assert!(notify(&output).contains("auth"));
    cleanup(&dir);

    let (dir, output) = project_with_encargo(
        "notificacion_sin_eventos",
        NewOptions {
            events: None,
            ..auth_events()
        },
    );
    assert!(notify(&output).contains("eventos"));
    cleanup(&dir);
}