feat(properties): CRUD + service/trust/document editors (plan phase 4)

Utilities section becomes create/edit/archive-able, with its child data.

API:
- Property gains archivedAt (soft-delete); list/browser default to
  archivedAt=null with ?includeArchived opt-in.
- PropertiesService: header create/update/archive/restore (customer FK
  validated); PropertyService add/update/remove scoped to the property;
  TrustAccount upsert (1:1) + remove; ServiceDocument pointer delete.
- Controller write routes: create needs STAFF+ (property:create), archive
  MANAGER+ (property:delete), every service/trust/document route
  property:update. Mutations audited. DTOs added.
- Document *upload* deliberately deferred: it needs the object-storage
  client wired into the API (today only the migration writes to MinIO);
  removing an existing pointer row is supported and the UI says so.

Web:
- PropertyForm (header) with CustomerPicker; /servicios/nuevo (accepts
  ?customerId prefill) and /servicios/[id]/editar.
- Property detail: gated action bar (Editar/Archivar) + "Administrar
  propiedad" — services via the shared ChildCollection editor, an inline
  1:1 TrustEditor (create/update/clear), and document-row delete.
- "Nueva propiedad" buttons on the list and customer detail (prefilled).
  api.ts + types for all of it.

Verified against dev: property create (archivedAt null), service
add/update, VIEWER service-add 403, trust upsert (create then update the
same row), trust/service remove, cross-property child guard 404, archive
drops from the default list and includeArchived surfaces it. Both apps
compile clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-23 12:27:53 -07:00
co-authored by Claude Opus 4.8
parent 7a46c30d9b
commit 506f8ce684
12 changed files with 922 additions and 15 deletions
+30 -7
View File
@@ -97,7 +97,11 @@ function Detail({ id }: { id: string }) {
<Hero data={data} hasUtilities={hasUtilities} hasInsurance={hasInsurance} />
<DatosSection data={data} />
<PropiedadesSection properties={data.properties} />
<PropiedadesSection
properties={data.properties}
customerId={data.id}
customerName={data.name}
/>
<PolizasSection
policies={data.policies}
customerId={data.id}
@@ -337,14 +341,33 @@ function KV({
}
/* ----------------------------------------------- Propiedades y servicios */
function PropiedadesSection({ properties }: { properties: Property[] }) {
function PropiedadesSection({
properties,
customerId,
customerName,
}: {
properties: Property[];
customerId: string;
customerName: string;
}) {
const canCreate = useCan("property:create");
return (
<section className="section">
<SectionHead
rule="servicios"
title="Propiedades y servicios"
count={properties.length}
/>
<div className="detail-actionbar">
<SectionHead
rule="servicios"
title="Propiedades y servicios"
count={properties.length}
/>
{canCreate && (
<Link
href={`/servicios/nuevo?customerId=${customerId}&customerName=${encodeURIComponent(customerName)}`}
className="btn btn-outline"
>
+ Nueva propiedad
</Link>
)}
</div>
<div className="card">
{properties.length === 0 ? (
<div className="empty-inline">
@@ -0,0 +1,54 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { PropertyForm } from "@/components/PropertyForm";
import { useCan } from "@/lib/abilities";
import { getProperty } from "@/lib/api";
import type { PropertyDetail } from "@/lib/types";
export default function EditarPropiedadPage({
params,
}: {
params: { id: string };
}) {
return (
<AppShell>
<EditarPropiedad id={params.id} />
</AppShell>
);
}
function EditarPropiedad({ id }: { id: string }) {
const allowed = useCan("property:update");
const [property, setProperty] = useState<PropertyDetail | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!allowed) return;
getProperty(id)
.then(setProperty)
.catch((e) => setError(e?.message ?? "No se pudo cargar la propiedad."));
}, [id, allowed]);
return (
<>
<div className="page-head">
<Link href={`/servicios/${id}`} className="back-link"> Propiedad</Link>
<h1 className="page-title">Editar propiedad</h1>
</div>
{!allowed ? (
<div className="state-box state-error">
No tiene permisos para editar propiedades.
</div>
) : error ? (
<div className="state-box state-error">{error}</div>
) : !property ? (
<div className="empty-inline"><span className="spinner" aria-label="Cargando" /></div>
) : (
<PropertyForm property={property} />
)}
</>
);
}
+257 -3
View File
@@ -3,19 +3,32 @@
import { useEffect, useState } from "react";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { getProperty } from "@/lib/api";
import {
addService,
archiveProperty,
getProperty,
removePropertyDocument,
removeService,
removeTrust,
restoreProperty,
updateService,
upsertTrust,
} from "@/lib/api";
import { useCan } from "@/lib/abilities";
import { ChildCollection, type ChildConfig } from "@/components/ChildCollection";
import {
expiryPhrase,
formatDate,
formatMoney,
formatNumber,
SERVICE_KIND_LABELS,
serviceKindGlyph,
serviceKindLabel,
serviceNoteLabel,
SIN_NOMBRE,
trustStatusLabel,
} from "@/lib/labels";
import type { PropertyDetail, Service, Transaction } from "@/lib/types";
import type { PropertyDetail, Service, Transaction, TrustInput } from "@/lib/types";
export default function PropiedadDetailPage({
params,
@@ -76,9 +89,14 @@ function Detail({ id }: { id: string }) {
if (!data) return null;
const reload = () => getProperty(id).then(setData).catch(() => {});
return (
<div className="rise">
<BackLink />
<div className="detail-actionbar">
<BackLink />
<PropertyActions data={data} onChange={reload} />
</div>
<Hero data={data} />
<ClienteSection data={data} />
<ServiciosSection data={data} />
@@ -86,10 +104,246 @@ function Detail({ id }: { id: string }) {
{data.policy && <PolizaSection data={data} />}
<MovimientosSection data={data} />
<DocumentosSection data={data} />
<PropertyEditor data={data} onChange={reload} />
</div>
);
}
/** Edit / archive controls for the property header. */
function PropertyActions({
data,
onChange,
}: {
data: PropertyDetail;
onChange: () => void;
}) {
const canEdit = useCan("property:update");
const canDelete = useCan("property:delete");
const [busy, setBusy] = useState(false);
const archived = data.archivedAt != null;
async function toggle() {
const verb = archived ? "restaurar" : "archivar";
if (!window.confirm(`¿Seguro que desea ${verb} esta propiedad?`)) return;
setBusy(true);
try {
if (archived) await restoreProperty(data.id);
else await archiveProperty(data.id);
onChange();
} catch (e) {
window.alert((e as Error)?.message ?? "No se pudo completar la acción.");
} finally {
setBusy(false);
}
}
if (!canEdit && !canDelete) return null;
return (
<div className="row-actions">
{archived && <span className="badge badge-negative">Archivada</span>}
{canEdit && (
<Link href={`/servicios/${data.id}/editar`} className="btn btn-outline">
Editar
</Link>
)}
{canDelete && (
<button type="button" className="btn btn-ghost" onClick={toggle} disabled={busy}>
{archived ? "Restaurar" : "Archivar"}
</button>
)}
</div>
);
}
/** Editable services + trust + documents — only for users who can edit. */
function PropertyEditor({
data,
onChange,
}: {
data: PropertyDetail;
onChange: () => void;
}) {
const canEdit = useCan("property:update");
if (!canEdit) return null;
const SERVICES: ChildConfig = {
apiKind: "services",
title: "Servicios",
fields: [
{
key: "kind",
label: "Tipo",
type: "select",
options: Object.entries(SERVICE_KIND_LABELS).map(([value, label]) => ({
value,
label,
})),
},
{ key: "accountNumber", label: "Cuenta" },
{ key: "meterNumber", label: "Medidor" },
{ key: "route", label: "Ruta" },
{ key: "dueDay", label: "Día pago" },
{ key: "notes", label: "Notas" },
{ key: "active", label: "Activo", type: "checkbox" },
],
};
return (
<section className="section">
<div className="section-head">
<span className="section-rule cuenta" aria-hidden />
<h2 className="section-title">Administrar propiedad</h2>
</div>
<ChildCollection
config={SERVICES}
rows={data.services as unknown as Record<string, unknown>[]}
canEdit={canEdit}
onAdd={async (p) => { await addService(data.id, p as never); onChange(); }}
onSave={async (sid, p) => { await updateService(data.id, sid, p as never); onChange(); }}
onRemove={async (sid) => { await removeService(data.id, sid); onChange(); }}
/>
<TrustEditor data={data} onChange={onChange} />
{data.documents.length > 0 && (
<div className="card" style={{ padding: 16 }}>
<h3 className="section-title" style={{ marginTop: 0 }}>Documentos</h3>
<div className="tx-scroll">
<table className="tx-table">
<thead>
<tr><th>Tipo</th><th>Clave</th><th className="num">Acción</th></tr>
</thead>
<tbody>
{data.documents.map((d) => (
<tr key={d.id ?? d.storageKey}>
<td>{d.documentType ?? "—"}</td>
<td className="mono">{d.storageKey ?? "—"}</td>
<td>
<div className="row-actions">
<button
type="button"
className="btn btn-ghost"
onClick={async () => {
if (!d.id) return;
if (!window.confirm("¿Eliminar este documento?")) return;
try {
await removePropertyDocument(data.id, d.id);
onChange();
} catch (e) {
window.alert((e as Error)?.message ?? "No se pudo eliminar.");
}
}}
>
Eliminar
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
<p className="inline-form-note">
La carga de nuevos documentos requiere el almacenamiento de archivos
(pendiente); aquí solo se pueden eliminar los existentes.
</p>
</div>
)}
</section>
);
}
/** Trust is 1:1 — a small inline form that upserts or clears it. */
function TrustEditor({
data,
onChange,
}: {
data: PropertyDetail;
onChange: () => void;
}) {
const t = data.trustAccount;
const [bankName, setBankName] = useState(t?.bankName ?? "");
const [trustNumber, setTrustNumber] = useState(t?.trustNumber ?? "");
const [bankFee, setBankFee] = useState(t?.bankFee != null ? String(t.bankFee) : "");
const [dueDate1, setDueDate1] = useState(toDateInput(t?.dueDate1));
const [dueDate2, setDueDate2] = useState(toDateInput(t?.dueDate2));
const [busy, setBusy] = useState(false);
async function save() {
setBusy(true);
const input: TrustInput = {
bankName: bankName.trim() || undefined,
trustNumber: trustNumber.trim() || undefined,
bankFee: bankFee.trim() === "" ? undefined : Number(bankFee),
dueDate1: dueDate1 || undefined,
dueDate2: dueDate2 || undefined,
};
try {
await upsertTrust(data.id, input);
onChange();
} catch (e) {
window.alert((e as Error)?.message ?? "No se pudo guardar el fideicomiso.");
} finally {
setBusy(false);
}
}
async function clear() {
if (!window.confirm("¿Eliminar el fideicomiso de esta propiedad?")) return;
try {
await removeTrust(data.id);
onChange();
} catch (e) {
window.alert((e as Error)?.message ?? "No se pudo eliminar.");
}
}
return (
<div className="card" style={{ padding: 16, marginBottom: 14 }}>
<h3 className="section-title" style={{ marginTop: 0 }}>Fideicomiso</h3>
<div className="form-grid">
<label className="field">
<span className="field-label">Banco</span>
<input className="input" value={bankName} onChange={(e) => setBankName(e.target.value)} />
</label>
<label className="field">
<span className="field-label">No. fideicomiso</span>
<input className="input" value={trustNumber} onChange={(e) => setTrustNumber(e.target.value)} />
</label>
<label className="field">
<span className="field-label">Cuota banco</span>
<input className="input" type="number" step="0.01" value={bankFee} onChange={(e) => setBankFee(e.target.value)} />
</label>
<label className="field">
<span className="field-label">Vence 1</span>
<input className="input" type="date" value={dueDate1} onChange={(e) => setDueDate1(e.target.value)} />
</label>
<label className="field">
<span className="field-label">Vence 2 (próxima)</span>
<input className="input" type="date" value={dueDate2} onChange={(e) => setDueDate2(e.target.value)} />
</label>
</div>
<div className="form-actions">
<button type="button" className="btn btn-primary" onClick={save} disabled={busy}>
{busy ? "Guardando…" : t ? "Guardar fideicomiso" : "Crear fideicomiso"}
</button>
{t && (
<button type="button" className="btn btn-ghost" onClick={clear}>
Eliminar
</button>
)}
</div>
</div>
);
}
function toDateInput(v: string | null | undefined): string {
if (!v) return "";
const d = new Date(v);
return isNaN(d.getTime()) ? "" : d.toISOString().slice(0, 10);
}
function BackLink() {
return (
<Link href="/servicios" className="back-link">
+41
View File
@@ -0,0 +1,41 @@
"use client";
import { Suspense } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { AppShell } from "@/components/AppShell";
import { PropertyForm } from "@/components/PropertyForm";
import { useCan } from "@/lib/abilities";
export default function NuevaPropiedadPage() {
return (
<AppShell>
<Suspense fallback={null}>
<NuevaPropiedad />
</Suspense>
</AppShell>
);
}
function NuevaPropiedad() {
const allowed = useCan("property:create");
const params = useSearchParams();
const customerId = params.get("customerId") ?? undefined;
const customerName = params.get("customerName") ?? undefined;
return (
<>
<div className="page-head">
<Link href="/servicios" className="back-link"> Propiedades</Link>
<h1 className="page-title">Nueva propiedad</h1>
</div>
{allowed ? (
<PropertyForm fixedCustomerId={customerId} fixedCustomerName={customerName} />
) : (
<div className="state-box state-error">
No tiene permisos para crear propiedades.
</div>
)}
</>
);
}
+9 -1
View File
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { useCan } from "@/lib/abilities";
import {
EXPIRY_WINDOW_DAYS,
getPropertyFacets,
@@ -81,6 +82,7 @@ export default function ServiciosPage() {
}
function ServiciosBrowser() {
const canCreate = useCan("property:create");
const [stats, setStats] = useState<PropertyStats | null>(null);
const [facets, setFacets] = useState<PropertyFacets | null>(null);
@@ -164,7 +166,13 @@ function ServiciosBrowser() {
<>
<div className="page-head rise">
<p className="eyebrow">Administración de servicios</p>
<h1 className="page-title">Propiedades</h1>
<div style={{ display: "flex", alignItems: "center", gap: 16 }}>
<h1 className="page-title" style={{ margin: 0 }}>Propiedades</h1>
<span style={{ flex: 1 }} />
{canCreate && (
<Link href="/servicios/nuevo" className="btn btn-primary">+ Nueva propiedad</Link>
)}
</div>
<StatStrip stats={stats} focus={focus} onPickFocus={pickFocus} />
<ServiceMixStrip
stats={stats}