import { useState } from "react";
import { Link, useLocation{% if references %}, useSearch{% endif %} } from "wouter";
import type { Esquemas } from "../../../api/cliente";
import { desenvolver{% if targets %}, LIMITE_PAGINA_MAXIMO{% endif %} } from "../../../api/http";
{%- if access.get_roles %}
import { useAuth } from "../../../auth/auth";
{%- endif %}
{%- if targets %}
import { opcionesReferencia } from "../../../compartido/formularios";
{%- endif %}
import { AlertaError, codigoError } from "../../../compartido/ui/alerta-error";
import { useCarga } from "../../../compartido/use-carga";
import { useDependencias } from "../../../dependencias";
import { aProblema } from "../mensajes";
import { aFormulario{{ pascal }}, aPeticion{{ pascal }}, VistaFormulario{{ pascal }} } from "../vistas/formulario-{{ kebab }}";
type {{ pascal }} = Esquemas["Dto{{ pascal }}"];
{%- if targets %}
/** La primera página de cada entidad referenciada: lo que ofrecen sus selects. */
const PRIMERA_PAGINA = { params: { query: { limite: LIMITE_PAGINA_MAXIMO } } };
{%- endif %}
/** Crear, o editar con `id`: el formulario de {{ words_plural }}. */
export function ContenedorFormulario{{ pascal }}({ id }: { id?: string }) {
const { api } = useDependencias();
const existente = useCarga(
() =>
id === undefined
? Promise.resolve(null)
: desenvolver(api.GET("/{{ plural }}/{id}", { params: { path: { id } } })),
[api, id],
);
const titulo = id === undefined ? "Crear {{ words }}" : "Editar {{ words }}";
return (
<section className="space-y-4">
<h1 className="text-2xl font-bold">{titulo}</h1>
{existente.estado === "cargando" && <span className="loading loading-spinner" />}
{existente.estado === "error" && <AlertaError error={existente.error} />}
{existente.estado === "listo" && <Formulario{{ pascal }} existente={existente.datos} />}
<Link href={id === undefined ? "/{{ plural }}" : `/{{ plural }}/${id}`} className="link">
Cancelar
</Link>
</section>
);
}
function Formulario{{ pascal }}({ existente }: { existente: {{ pascal }} | null }) {
const { api } = useDependencias();
{%- if access.get_roles %}
const { puede } = useAuth();
{%- endif %}
{%- for t in targets %}
{%- if t.load_inline %}
const {{ t.plural_ident }} = useCarga(() => desenvolver(api.GET("/{{ t.plural }}", PRIMERA_PAGINA)), [api]);
{%- else %}
const {{ t.plural_ident }} = useCarga(
() => desenvolver(api.GET("/{{ t.plural }}", PRIMERA_PAGINA)),
[api],
);
{%- endif %}
{%- endfor %}
const [, navegar] = useLocation();
{%- if references %}
// 27.19: al crear, la referencia que trae la URL (`?{{ references.0.camel }}=…`) llega elegida.
const desdeUrl = new URLSearchParams(useSearch());
const [valores, setValores] = useState(() => {
const iniciales = aFormulario{{ pascal }}(existente);
if (existente !== null) return iniciales;
return {
...iniciales,
{%- for r in references %}
{%- if r.is_set %}
{{ r.camel }}: desdeUrl.getAll("{{ r.camel }}"),
{%- else %}
{{ r.camel }}: desdeUrl.get("{{ r.camel }}") ?? iniciales.{{ r.camel }},
{%- endif %}
{%- endfor %}
};
});
{%- else %}
const [valores, setValores] = useState(aFormulario{{ pascal }}(existente));
{%- endif %}
const [guardando, setGuardando] = useState(false);
const [fallo, setFallo] = useState<unknown>(null);
const problema = fallo === null ? null : aProblema(codigoError(fallo));
const guardar = async () => {
setGuardando(true);
setFallo(null);
try {
const cuerpo = aPeticion{{ pascal }}(valores);
const guardado = await desenvolver(
existente === null
? api.POST("/{{ plural }}", { body: cuerpo })
{%- if save_inline %}
: api.PUT("/{{ plural }}/{id}", { params: { path: { id: existente.id } }, body: cuerpo }),
{%- else %}
: api.PUT("/{{ plural }}/{id}", {
params: { path: { id: existente.id } },
body: cuerpo,
}),
{%- endif %}
);
{%- if access.get_roles %}
// Lo creado se ve con {% for r in access.get_roles %}`{{ r }}`{% if not loop.last %} y {% endif %}{% endfor %}: sin ese rol, su detalle daría un 403.
if (existente !== null || {% for r in access.get_roles %}puede("{{ r }}"){% if not loop.last %} && {% endif %}{% endfor %}) {
navegar(`/{{ plural }}/${guardado.id}`);
{%- if access.list_roles and access.list_reachable %}
} else if ({% for r in access.list_roles %}puede("{{ r }}"){% if not loop.last %} && {% endif %}{% endfor %}) {
navegar("/{{ plural }}");
} else {
navegar("/?guardado");
}
{%- elif access.list_roles %}
} else {
navegar("/?guardado");
}
{%- else %}
} else {
navegar("/{{ plural }}");
}
{%- endif %}
{%- else %}
navegar(`/{{ plural }}/${guardado.id}`);
{%- endif %}
} catch (error) {
setFallo(error);
setGuardando(false);
}
};
return (
<div className="card bg-base-100">
<div className="card-body">
{problema?.campo === null && <AlertaError error={fallo} mensaje={problema.texto} />}
{%- for t in targets %}
{{ "{" }}{{ t.plural_ident }}.estado === "error" && <AlertaError error={{ "{" }}{{ t.plural_ident }}.error} />}
{%- endfor %}
<VistaFormulario{{ pascal }}
valores={valores}
{%- if targets %}
opciones={{ "{{" }}
{%- for t in targets %}{% for o in t.option_lines %}{% set c = o.camel %}
{%- if t.is_self and t.options_inline %}
{{ c }}: opcionesReferencia({{ t.plural_ident }}, ({{ t.ident }}) => {{ t.ident }}.{{ t.label }}).filter(
(opcion) => opcion.id !== existente?.id,
),
{%- elif t.is_self %}
{{ c }}: opcionesReferencia(
{{ t.plural_ident }},
({{ t.ident }}) => {{ t.ident }}.{{ t.label }},
).filter((opcion) => opcion.id !== existente?.id),
{%- elif o.inline %}
{{ c }}: opcionesReferencia({{ t.plural_ident }}, ({{ t.ident }}) => {{ t.label_of }}),
{%- else %}
{{ c }}: opcionesReferencia(
{{ t.plural_ident }},
({{ t.ident }}) => {{ t.label_of }},
),
{%- endif %}
{%- endfor %}{% endfor %}
}}
{%- endif %}
guardando={guardando}
{%- if defaulted %}
creando={existente === null}
{%- endif %}
problema={problema}
alCambiar={setValores}
alEnviar={guardar}
/>
</div>
</div>
);
}