Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
d2d1ebd
Guarda campos opcionales vacíos como "" en lugar de NULL
adrrian17 Nov 9, 2026
7afa36e
Agrega migración para guardar campos opcionales vacíos como ""
adrrian17 Nov 9, 2026
cbf60d6
Resuelve el rol una vez por request con scopedProcedure
adrrian17 Nov 9, 2026
d9f2c68
Centraliza el filtro de dueño de sucursales y contactos
adrrian17 Nov 9, 2026
6082fe3
Aplica la regla de dueño a clientes
adrrian17 Nov 9, 2026
35bdd07
Declara NOT_FOUND como error tipado con mensajes en español
adrrian17 Nov 9, 2026
043f25a
Valida los updates con el schema completo del formulario
adrrian17 Nov 9, 2026
fb889ec
Comparte el schema de usuarios entre el formulario y la API
adrrian17 Nov 9, 2026
95cae8e
Genera los IDs con cuid2 en vez de UUID
adrrian17 Nov 10, 2026
86640d1
Unifica el uso de los hooks de consultas
adrrian17 Nov 10, 2026
dcf6985
Refresca sucursales y contactos al archivar su padre
adrrian17 Nov 10, 2026
70a5691
Muestra el cliente y el estado archivado en las tarjetas de sucursales
adrrian17 Nov 10, 2026
0213b5e
Bloquea cambios en sucursales y contactos bajo un padre archivado
adrrian17 Nov 11, 2026
1dd6116
Oculta acciones bajo padres archivados y comparte componentes de clie…
adrrian17 Nov 11, 2026
738350a
Agrega la migración de contact.branch_id NOT NULL
adrrian17 Nov 11, 2026
a0abeef
Muestra Desarchivar deshabilitado en contactos con un padre archivado
adrrian17 Nov 11, 2026
87f3ac1
Alinea la tarjeta de contacto con la de sucursal
adrrian17 Nov 11, 2026
8e66b1d
Muestra el estado archivado y permite desarchivar en el detalle del c…
adrrian17 Nov 11, 2026
78606b0
Evita que el diálogo de archivo muestre la acción contraria al guardar
adrrian17 Nov 11, 2026
bce8650
Centraliza la regla de que solo un admin ve al vendedor
adrrian17 Nov 11, 2026
07f981a
Usa las reglas de archivado de util/status.ts en create y setArchived
adrrian17 Nov 11, 2026
696a881
Quita el alias createCustomerSchema
adrrian17 Nov 11, 2026
1b15ddc
Renombra select-entity-button.tsx a new-entity-button.tsx
adrrian17 Nov 11, 2026
c96d12d
Quita props sin uso y comentarios que repiten el código
adrrian17 Nov 11, 2026
23c966f
Centraliza el estado de archivado heredado del padre
adrrian17 Nov 11, 2026
bd3dd75
Calcula los filtros activos y la búsqueda por nombre en un solo lugar
adrrian17 Nov 11, 2026
474ffb0
Extrae el autollenado por código postal a useAddressLookup
adrrian17 Nov 11, 2026
24754e7
Marca ADMIN_EMAIL y ADMIN_NAME como públicas en el schema de entorno
adrrian17 Nov 11, 2026
c1579fe
Agrega la regla de lint suni/require-seller-scope
adrrian17 Nov 11, 2026
d291ffa
Bloquea el teclado en las tarjetas obsoletas mientras carga el filtro
adrrian17 Nov 11, 2026
4a35587
Restaura el límite de 255 caracteres del puesto del contacto
adrrian17 Nov 11, 2026
348eb25
Rechaza claves computadas en la lista de columnas de require-seller-s…
adrrian17 Nov 11, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .env.schema
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ SMTP_PASS=
# @public @optional @type=url
LOGO_URL=

# @required @type=email
# @required @public @type=email
ADMIN_EMAIL=if(forEnv(development), "suni@localhost.com")

# @required
# @required @public
ADMIN_NAME=if(forEnv(development), "Suni")

# @public @type=url
Expand Down
29 changes: 28 additions & 1 deletion apps/server/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { OpenAPIHandler } from "@orpc/openapi/fetch";
import { OpenAPIReferencePlugin } from "@orpc/openapi/plugins";
import { onError } from "@orpc/server";
import { ORPCError, onError, ValidationError } from "@orpc/server";
import { RPCHandler } from "@orpc/server/fetch";
import { ZodToJsonSchemaConverter } from "@orpc/zod/zod4";
import { appRouter } from "@suni/api/routers/index";
Expand All @@ -12,6 +12,7 @@ import { evlog } from "evlog/hono";
import type { EvlogVariables } from "evlog/hono";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { z } from "zod";

import { createContext } from "./context";
import { ENV } from "./env.server";
Expand All @@ -33,6 +34,30 @@ function handleError<T>(error: T) {
console.error(error);
}

// Default Zod messages (e.g. a missing field) in Spanish; schemas keep their own messages.
z.config(z.locales.es());

// oRPC answers failed input validation with a generic English message; send the schema's own message instead.
async function schemaErrorMessage<T>({ next }: { next: () => Promise<T> }) {
try {
return await next();
} catch (error) {
if (
error instanceof ORPCError &&
error.code === "BAD_REQUEST" &&
error.cause instanceof ValidationError
) {
throw new ORPCError("BAD_REQUEST", {
message: error.cause.issues[0]?.message ?? error.message,
data: error.data,
cause: error.cause,
});
}

throw error;
}
}

app.use(
evlog(process.env.NODE_ENV === "production" ? {} : { drain: createFsDrain() })
);
Expand Down Expand Up @@ -62,10 +87,12 @@ export const apiHandler = new OpenAPIHandler(appRouter, {
}),
],
interceptors: [onError(handleError)],
clientInterceptors: [schemaErrorMessage],
});

export const rpcHandler = new RPCHandler(appRouter, {
interceptors: [onError(handleError)],
clientInterceptors: [schemaErrorMessage],
});

app.use("/*", async (c, next) => {
Expand Down
129 changes: 27 additions & 102 deletions apps/web/src/components/customers/branches/branch-form.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,16 @@
import type { AppRouterOutputs } from "@suni/api/routers/index";
import {
branchFormSchema,
branchInputSchema,
} from "@suni/db/validation/branches";
import { branchSchema } from "@suni/db/validation/branches";
import { Button } from "@suni/ui/components/button";
import { revalidateLogic, useSelector } from "@tanstack/react-form";
import { useQueryClient } from "@tanstack/react-query";
import type { UseQueryResult } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import type { z } from "zod";

import { useAppForm } from "@/components/form/use-app-form";
import { useCreateBranch, useUpdateBranch } from "@/hooks/use-branches";
import { postalCodeQueryOptions, usePostalCode } from "@/hooks/use-postal-code";
import type { Settlement } from "@/hooks/use-postal-code";
import { POSTAL_CODE_LENGTH, useAddressLookup } from "@/hooks/use-postal-code";

type Branch = AppRouterOutputs["branches"]["list"][number];
import type { Branch } from "./util/branch-address";

type FormValues = z.input<typeof branchFormSchema>;
type FormValues = z.input<typeof branchSchema>;

interface BranchFormProps {
customerId: string;
Expand All @@ -26,8 +19,6 @@ interface BranchFormProps {
onCancel: () => void;
}

const POSTAL_CODE_LENGTH = 5;

const PHONE_LENGTH = 10;

const FILLED_BY_POSTAL_CODE = "Se llena con el código postal";
Expand All @@ -54,42 +45,22 @@ function toFormValues(branch?: Branch): FormValues {
name: branch.name,
street: branch.street,
extNumber: branch.extNumber,
intNumber: branch.intNumber ?? "",
intNumber: branch.intNumber,
postalCode: branch.postalCode,
suburb: branch.suburb,
city: branch.city,
state: branch.state,
phone: branch.phone ?? "",
frontImageUrl: branch.frontImageUrl ?? "",
phone: branch.phone,
frontImageUrl: branch.frontImageUrl,
};
}

function postalCodeStatus(
query: UseQueryResult<Settlement[]>,
settlements: Settlement[]
): string | null {
if (query.isFetching) {
return "Buscando código postal…";
}

if (query.isError) {
return "No se pudo consultar el código postal. Captura la dirección a mano.";
}

if (query.isSuccess && settlements.length === 0) {
return "No encontramos ese código postal. Captura la dirección a mano.";
}

return null;
}

export function BranchForm({
customerId,
branch,
onSuccess,
onCancel,
}: BranchFormProps) {
const queryClient = useQueryClient();
const createBranch = useCreateBranch();
const updateBranch = useUpdateBranch();

Expand All @@ -98,77 +69,24 @@ export function BranchForm({
const form = useAppForm({
defaultValues: toFormValues(branch),
validationLogic: revalidateLogic(),
validators: { onDynamic: branchFormSchema },
validators: { onDynamic: branchSchema },
onSubmit: ({ value }) => {
const parsed = branchInputSchema.parse(value);

if (branch) {
updateBranch.mutate(
{ id: branch.id, ...parsed },
{ id: branch.id, ...value },
{ onSuccess: () => onSuccess?.() }
);
} else {
createBranch.mutate(
{ customerId, ...parsed },
{ customerId, ...value },
{ onSuccess: () => onSuccess?.() }
);
}
},
});

const zip = useSelector(form.store, (state) => state.values.postalCode);
const postalCode = usePostalCode(zip);
const settlements = postalCode.data ?? [];

// SEPOMEX define municipio y estado; solo un fallo o un código inexistente los desbloquea.
const regionLocked = !(
postalCode.isError ||
(postalCode.isSuccess && settlements.length === 0)
);

// La colonia solo espera a la consulta; después queda abierta por si SEPOMEX no la tiene.
const suburbLocked = !(postalCode.isSuccess || postalCode.isError);

const suburbOptions = [...new Set(settlements.map((s) => s.d_asenta))].map(
(value) => ({ value, label: value })
);

const fillAddress = async (value: string) => {
form.setFieldValue("suburb", "");
form.setFieldValue("city", "");
form.setFieldValue("state", "");

if (value.length !== POSTAL_CODE_LENGTH) {
return;
}

let found: Settlement[];

try {
found = await queryClient.query(postalCodeQueryOptions(value));
} catch {
// usePostalCode muestra el error bajo el campo.
return;
}

// El usuario siguió escribiendo mientras corría la petición.
if (form.getFieldValue("postalCode") !== value) {
return;
}

const [first] = found;

if (!first) {
return;
}

form.setFieldValue("city", first.d_mnpio);
form.setFieldValue("state", first.d_estado);

if (found.length === 1) {
form.setFieldValue("suburb", first.d_asenta);
}
};
const address = useAddressLookup(zip);

return (
<form
Expand Down Expand Up @@ -206,13 +124,20 @@ export function BranchForm({
</legend>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<form.AppField
listeners={{ onChange: ({ value }) => fillAddress(value) }}
listeners={{
onChange: ({ value }) =>
address.fill(value, {
getPostalCode: () => form.getFieldValue("postalCode"),
set: (field, fieldValue) =>
form.setFieldValue(field, fieldValue),
}),
}}
name="postalCode"
>
{(field) => (
<field.DigitsField
autoComplete="postal-code"
hint={postalCodeStatus(postalCode, settlements)}
hint={address.hint}
label="Código postal"
maxLength={POSTAL_CODE_LENGTH}
required
Expand All @@ -224,13 +149,13 @@ export function BranchForm({
<field.SelectField
creatable
label="Colonia"
options={suburbOptions}
options={address.suburbOptions}
placeholder={
suburbLocked
address.suburbLocked
? FILLED_BY_POSTAL_CODE
: "Selecciona o escribe la colonia..."
}
readOnly={suburbLocked}
readOnly={address.suburbLocked}
required
/>
)}
Expand All @@ -240,8 +165,8 @@ export function BranchForm({
<field.TextField
autoComplete="address-level2"
label="Municipio"
placeholder={regionLocked ? FILLED_BY_POSTAL_CODE : ""}
readOnly={regionLocked}
placeholder={address.regionLocked ? FILLED_BY_POSTAL_CODE : ""}
readOnly={address.regionLocked}
required
/>
)}
Expand All @@ -251,8 +176,8 @@ export function BranchForm({
<field.TextField
autoComplete="address-level1"
label="Estado"
placeholder={regionLocked ? FILLED_BY_POSTAL_CODE : ""}
readOnly={regionLocked}
placeholder={address.regionLocked ? FILLED_BY_POSTAL_CODE : ""}
readOnly={address.regionLocked}
required
/>
)}
Expand Down
33 changes: 20 additions & 13 deletions apps/web/src/components/customers/branches/branch-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,24 @@ import type { AppRouterOutputs } from "@suni/api/routers/index";
import { Badge } from "@suni/ui/components/badge";
import { Button } from "@suni/ui/components/button";
import { cn } from "@suni/ui/lib/utils";
import { Link } from "@tanstack/react-router";
import { Archive, ArchiveRestore, Building2, Pencil } from "lucide-react";
import { useState } from "react";

import { archiveState } from "../shared/archive-state";
import { ChangeBranchStatusDialog } from "./change-branch-status-dialog";

type Branch = AppRouterOutputs["branches"]["get"];

interface BranchHeaderProps {
branch: Pick<Branch, "id" | "customerId" | "name" | "archived">;
customerName: string;
branch: Pick<Branch, "id" | "customerId" | "name" | "archived" | "customer">;
onEdit?: () => void;
}

export function BranchHeader({
branch,
customerName,
onEdit,
}: BranchHeaderProps) {
const isArchived = !!branch.archived;
export function BranchHeader({ branch, onEdit }: BranchHeaderProps) {
const { isOwnArchived, isCustomerArchived, isArchived } =
archiveState(branch);

const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false);

return (
Expand Down Expand Up @@ -60,17 +59,25 @@ export function BranchHeader({
{isArchived ? (
<Badge className="shrink-0" variant="secondary">
<Archive className="size-3" />
Archivada
{isCustomerArchived ? "Cliente archivado" : "Archivada"}
</Badge>
) : null}
</div>
</div>
<p className="text-muted-foreground text-sm">
Sucursal de {customerName}
Sucursal de{" "}
<Link
className="hover:underline"
params={{ customerId: branch.customerId }}
to="/customers/$customerId"
>
{branch.customer.name}
</Link>
</p>
</div>

{onEdit ? (
{/* An archived customer wins: unarchive it first, from its own page */}
{onEdit && !isCustomerArchived ? (
<div className="flex shrink-0 items-center gap-2">
{isArchived ? null : (
<Button onClick={onEdit} size="sm" variant="green">
Expand All @@ -83,12 +90,12 @@ export function BranchHeader({
size="sm"
variant="outline"
>
{isArchived ? (
{isOwnArchived ? (
<ArchiveRestore className="size-3.5" />
) : (
<Archive className="size-3.5" />
)}
{isArchived ? "Desarchivar" : "Archivar"}
{isOwnArchived ? "Desarchivar" : "Archivar"}
</Button>
</div>
) : null}
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/components/customers/branches/branch-info.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { cn } from "@suni/ui/lib/utils";
import { Camera, MapPin, Phone, ZoomIn } from "lucide-react";

import { archiveState } from "../shared/archive-state";
import type { Branch } from "./util/branch-address";
import { formatAddress } from "./util/branch-address";

Expand All @@ -20,7 +21,7 @@ export function BranchInfoContent({
onImagePreview,
onImageUpload,
}: BranchInfoContentProps) {
const isArchived = !!branch.archived;
const { isArchived } = archiveState(branch);
const address = formatAddress(branch);

return (
Expand Down
Loading