Repository navigation
Agrega sucursales y contactos de clientes #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
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 6fc5304
Crea validations de bran ches y contacts, crea shred para validacione…
YAHIRE-1 c33e835
Borrra enum types contact
YAHIRE-1 9b4a766
Crea CRUD de branches
YAHIRE-1 eededcf
Crea CRUD de contacts
YAHIRE-1 d59f967
Crea hook para branches
YAHIRE-1 b48c8ef
Crea hook para contacts
YAHIRE-1 68aae54
Agrega export db
YAHIRE-1 a5ecbad
Crea component dialog
YAHIRE-1 59b6c10
Agrega imagen placeholder
YAHIRE-1 7df64e0
Agrega contacts en list
YAHIRE-1 d93f096
Crea branch Form
YAHIRE-1 2fa3bb9
Agrega branch components
YAHIRE-1 d6754e6
Agrega sucursales a breacrumb
YAHIRE-1 7fe00a1
Crea contact form
YAHIRE-1 09fc8e5
Crea contact form y dialogs
YAHIRE-1 0100bf7
Crea grid y agrega a index
YAHIRE-1 2ea5c3d
Agrega grid contacts a customers index
YAHIRE-1 c088e53
Invalidar consultas de contacto tras una actualización de la sucursal.
YAHIRE-1 71733dc
Limita los paneles provisionales a pestañas sin contenido.
YAHIRE-1 a972c4a
Agrega migraciones
YAHIRE-1 22b67b6
Crea branches page index y component select
YAHIRE-1 3aba253
Integra select component a grid contacts
YAHIRE-1 1589a5c
Crea contacts index
YAHIRE-1 192c68f
Agrega sucursales y contactos a nav-bar
YAHIRE-1 1f39a84
Agrega hook ppara listar clientes en filtro branches
YAHIRE-1 3fc6ca3
Omite la consulta de la sucursal hasta que se seleccione un cliente.
YAHIRE-1 651c308
Agrega filtro de estado compartido (cliente > sucursal > contacto)
YAHIRE-1 3ae47a5
Implementa helper statusWhere
YAHIRE-1 a887b2b
Implementa helper statusWhere en frontend agrega reglas para mostrar …
YAHIRE-1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
48
apps/web/src/components/customers/branches/branch-form-dialog.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
300
apps/web/src/components/customers/branches/branch-form.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| }; | ||
|
|
||
| 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> | ||
| ); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.