Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
415d523
Crea contact y branch table, define relations y agrega enum de contact
YAHIRE-1 Nov 4, 2026
6fc5304
Crea validations de bran ches y contacts, crea shred para validacione…
YAHIRE-1 Nov 4, 2026
c33e835
Borrra enum types contact
YAHIRE-1 Nov 5, 2026
9b4a766
Crea CRUD de branches
YAHIRE-1 Nov 5, 2026
eededcf
Crea CRUD de contacts
YAHIRE-1 Nov 5, 2026
d59f967
Crea hook para branches
YAHIRE-1 Nov 5, 2026
b48c8ef
Crea hook para contacts
YAHIRE-1 Nov 5, 2026
68aae54
Agrega export db
YAHIRE-1 Nov 6, 2026
a5ecbad
Crea component dialog
YAHIRE-1 Nov 6, 2026
59b6c10
Agrega imagen placeholder
YAHIRE-1 Nov 6, 2026
7df64e0
Agrega contacts en list
YAHIRE-1 Nov 6, 2026
d93f096
Crea branch Form
YAHIRE-1 Nov 6, 2026
2fa3bb9
Agrega branch components
YAHIRE-1 Nov 6, 2026
d6754e6
Agrega sucursales a breacrumb
YAHIRE-1 Nov 6, 2026
7fe00a1
Crea contact form
YAHIRE-1 Nov 6, 2026
09fc8e5
Crea contact form y dialogs
YAHIRE-1 Nov 6, 2026
0100bf7
Crea grid y agrega a index
YAHIRE-1 Nov 6, 2026
2ea5c3d
Agrega grid contacts a customers index
YAHIRE-1 Nov 6, 2026
c088e53
Invalidar consultas de contacto tras una actualización de la sucursal.
YAHIRE-1 Nov 6, 2026
71733dc
Limita los paneles provisionales a pestañas sin contenido.
YAHIRE-1 Nov 6, 2026
a972c4a
Agrega migraciones
YAHIRE-1 Nov 6, 2026
22b67b6
Crea branches page index y component select
YAHIRE-1 Nov 6, 2026
3aba253
Integra select component a grid contacts
YAHIRE-1 Nov 6, 2026
1589a5c
Crea contacts index
YAHIRE-1 Nov 6, 2026
192c68f
Agrega sucursales y contactos a nav-bar
YAHIRE-1 Nov 6, 2026
1f39a84
Agrega hook ppara listar clientes en filtro branches
YAHIRE-1 Nov 8, 2026
3fc6ca3
Omite la consulta de la sucursal hasta que se seleccione un cliente.
YAHIRE-1 Nov 8, 2026
651c308
Agrega filtro de estado compartido (cliente > sucursal > contacto)
YAHIRE-1 Nov 9, 2026
3ae47a5
Implementa helper statusWhere
YAHIRE-1 Nov 9, 2026
a887b2b
Implementa helper statusWhere en frontend agrega reglas para mostrar …
YAHIRE-1 Nov 9, 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
Binary file added apps/web/public/placeholder.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 48 additions & 0 deletions apps/web/src/components/customers/branches/branch-form-dialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@suni/ui/components/dialog";
import type { ComponentProps } from "react";

import { BranchForm } from "./branch-form";

interface BranchFormDialogProps extends Pick<
ComponentProps<typeof BranchForm>,
"branch" | "customerId"
> {
open: boolean;
onOpenChange: (open: boolean) => void;
}

export function BranchFormDialog({
branch,
customerId,
open,
onOpenChange,
}: BranchFormDialogProps) {
return (
<Dialog onOpenChange={onOpenChange} open={open}>
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-3xl">
<DialogHeader>
<DialogTitle>
{branch ? "Editar sucursal" : "Nueva sucursal"}
</DialogTitle>
<DialogDescription>
{branch
? "Actualiza los datos de la sucursal."
: "Captura los datos de la nueva sucursal."}
</DialogDescription>
</DialogHeader>
<BranchForm
branch={branch}
customerId={customerId}
onCancel={() => onOpenChange(false)}
onSuccess={() => onOpenChange(false)}
/>
</DialogContent>
</Dialog>
);
}
300 changes: 300 additions & 0 deletions apps/web/src/components/customers/branches/branch-form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,300 @@
import type { AppRouterOutputs } from "@suni/api/routers/index";
import {
branchFormSchema,
branchInputSchema,
} 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";

type Branch = AppRouterOutputs["branches"]["list"][number];

type FormValues = z.input<typeof branchFormSchema>;

interface BranchFormProps {
customerId: string;
branch?: Branch;
onSuccess?: () => void;
onCancel: () => void;
}

const POSTAL_CODE_LENGTH = 5;

const PHONE_LENGTH = 10;

const FILLED_BY_POSTAL_CODE = "Se llena con el código postal";

const EMPTY_VALUES: FormValues = {
name: "",
street: "",
extNumber: "",
intNumber: "",
postalCode: "",
suburb: "",
city: "",
state: "",
phone: "",
frontImageUrl: "",
};

function toFormValues(branch?: Branch): FormValues {
if (!branch) {
return EMPTY_VALUES;
}

return {
name: branch.name,
street: branch.street,
extNumber: branch.extNumber,
intNumber: branch.intNumber ?? "",
postalCode: branch.postalCode,
suburb: branch.suburb,
city: branch.city,
state: branch.state,
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();

const submitting = createBranch.isPending || updateBranch.isPending;

const form = useAppForm({
defaultValues: toFormValues(branch),
validationLogic: revalidateLogic(),
validators: { onDynamic: branchFormSchema },
onSubmit: ({ value }) => {
const parsed = branchInputSchema.parse(value);

if (branch) {
updateBranch.mutate(
{ id: branch.id, ...parsed },
{ onSuccess: () => onSuccess?.() }
);
} else {
createBranch.mutate(
{ customerId, ...parsed },
{ 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);
}
};
Comment thread
YAHIRE-1 marked this conversation as resolved.
Resolved

return (
<form
className="space-y-6"
onSubmit={(event) => {
event.preventDefault();
form.handleSubmit();
}}
>
<fieldset className="space-y-4">
<legend className="text-brand mb-4 text-lg font-semibold">
Datos generales
</legend>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<form.AppField name="name">
{(field) => (
<field.TextField label="Nombre de la sucursal" required />
)}
</form.AppField>
<form.AppField name="phone">
{(field) => (
<field.DigitsField
autoComplete="tel-national"
label="Teléfono"
maxLength={PHONE_LENGTH}
/>
)}
</form.AppField>
</div>
</fieldset>

<fieldset className="space-y-4">
<legend className="text-brand mb-4 text-lg font-semibold">
Dirección
</legend>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<form.AppField
listeners={{ onChange: ({ value }) => fillAddress(value) }}
name="postalCode"
>
{(field) => (
<field.DigitsField
autoComplete="postal-code"
hint={postalCodeStatus(postalCode, settlements)}
label="Código postal"
maxLength={POSTAL_CODE_LENGTH}
required
/>
)}
</form.AppField>
<form.AppField name="suburb">
{(field) => (
<field.SelectField
creatable
label="Colonia"
options={suburbOptions}
placeholder={
suburbLocked
? FILLED_BY_POSTAL_CODE
: "Selecciona o escribe la colonia..."
}
readOnly={suburbLocked}
required
/>
)}
</form.AppField>
<form.AppField name="city">
{(field) => (
<field.TextField
autoComplete="address-level2"
label="Municipio"
placeholder={regionLocked ? FILLED_BY_POSTAL_CODE : ""}
readOnly={regionLocked}
required
/>
)}
</form.AppField>
<form.AppField name="state">
{(field) => (
<field.TextField
autoComplete="address-level1"
label="Estado"
placeholder={regionLocked ? FILLED_BY_POSTAL_CODE : ""}
readOnly={regionLocked}
required
/>
)}
</form.AppField>
<form.AppField name="street">
{(field) => (
<field.TextField
autoComplete="address-line1"
label="Calle"
required
/>
)}
</form.AppField>
<form.AppField name="extNumber">
{(field) => <field.TextField label="Número exterior" required />}
</form.AppField>
<form.AppField name="intNumber">
{(field) => <field.TextField label="Número interior" />}
</form.AppField>
</div>
</fieldset>

<div className="flex justify-end gap-4 pt-4">
<Button
className="w-full sm:w-auto"
disabled={submitting}
onClick={onCancel}
type="button"
variant="outline-destructive"
>
Cancelar
</Button>
<Button
className="w-full sm:w-auto"
disabled={submitting}
type="submit"
variant="green"
>
{submitting ? <Loader2 className="animate-spin" /> : null}
{branch ? "Guardar" : "Crear"}
</Button>
</div>
</form>
);
}
Loading
Loading