diff --git a/apps/web/public/placeholder.webp b/apps/web/public/placeholder.webp new file mode 100644 index 0000000..4fe0d62 Binary files /dev/null and b/apps/web/public/placeholder.webp differ diff --git a/apps/web/src/components/customers/branches/branch-form-dialog.tsx b/apps/web/src/components/customers/branches/branch-form-dialog.tsx new file mode 100644 index 0000000..247b608 --- /dev/null +++ b/apps/web/src/components/customers/branches/branch-form-dialog.tsx @@ -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, + "branch" | "customerId" +> { + open: boolean; + onOpenChange: (open: boolean) => void; +} + +export function BranchFormDialog({ + branch, + customerId, + open, + onOpenChange, +}: BranchFormDialogProps) { + return ( + + + + + {branch ? "Editar sucursal" : "Nueva sucursal"} + + + {branch + ? "Actualiza los datos de la sucursal." + : "Captura los datos de la nueva sucursal."} + + + onOpenChange(false)} + onSuccess={() => onOpenChange(false)} + /> + + + ); +} diff --git a/apps/web/src/components/customers/branches/branch-form.tsx b/apps/web/src/components/customers/branches/branch-form.tsx new file mode 100644 index 0000000..9b8523f --- /dev/null +++ b/apps/web/src/components/customers/branches/branch-form.tsx @@ -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; + +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, + 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 ( +
{ + event.preventDefault(); + form.handleSubmit(); + }} + > +
+ + Datos generales + +
+ + {(field) => ( + + )} + + + {(field) => ( + + )} + +
+
+ +
+ + Dirección + +
+ fillAddress(value) }} + name="postalCode" + > + {(field) => ( + + )} + + + {(field) => ( + + )} + + + {(field) => ( + + )} + + + {(field) => ( + + )} + + + {(field) => ( + + )} + + + {(field) => } + + + {(field) => } + +
+
+ +
+ + +
+
+ ); +} diff --git a/apps/web/src/components/customers/branches/branch-header.tsx b/apps/web/src/components/customers/branches/branch-header.tsx new file mode 100644 index 0000000..2605152 --- /dev/null +++ b/apps/web/src/components/customers/branches/branch-header.tsx @@ -0,0 +1,104 @@ +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 { Archive, ArchiveRestore, Building2, Pencil } from "lucide-react"; +import { useState } from "react"; + +import { ChangeBranchStatusDialog } from "./change-branch-status-dialog"; + +type Branch = AppRouterOutputs["branches"]["get"]; + +interface BranchHeaderProps { + branch: Pick; + customerName: string; + onEdit?: () => void; +} + +export function BranchHeader({ + branch, + customerName, + onEdit, +}: BranchHeaderProps) { + const isArchived = !!branch.archived; + const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false); + + return ( + <> +
+
+
+
+ +
+
+

+ {branch.name} +

+ {isArchived ? ( + + + Archivada + + ) : null} +
+
+

+ Sucursal de {customerName} +

+
+ + {onEdit ? ( +
+ {isArchived ? null : ( + + )} + +
+ ) : null} +
+ + + + ); +} diff --git a/apps/web/src/components/customers/branches/branch-info.tsx b/apps/web/src/components/customers/branches/branch-info.tsx new file mode 100644 index 0000000..2569104 --- /dev/null +++ b/apps/web/src/components/customers/branches/branch-info.tsx @@ -0,0 +1,85 @@ +import { cn } from "@suni/ui/lib/utils"; +import { Camera, MapPin, Phone, ZoomIn } from "lucide-react"; + +import type { Branch } from "./util/branch-address"; +import { formatAddress } from "./util/branch-address"; + +const overlayButton = + "flex size-10 items-center justify-center rounded-full bg-black/50 text-white transition-colors hover:bg-black/70"; + +interface BranchInfoContentProps { + branch: Branch; + branchImage: string; + onImagePreview: () => void; + onImageUpload?: () => void; +} + +export function BranchInfoContent({ + branch, + branchImage, + onImagePreview, + onImageUpload, +}: BranchInfoContentProps) { + const isArchived = !!branch.archived; + const address = formatAddress(branch); + + return ( +
+
+

Dirección

+
+
+ +
+ {address.streetLine} + {address.locationLine} +
+
+ + {branch.phone ? ( +
+ + {branch.phone} +
+ ) : null} +
+
+ +
+

+ Imagen de fachada +

+
+ {branch.name} +
+ + {!isArchived && onImageUpload ? ( + + ) : null} +
+
+
+
+ ); +} diff --git a/apps/web/src/components/customers/branches/card.tsx b/apps/web/src/components/customers/branches/card.tsx new file mode 100644 index 0000000..c790aea --- /dev/null +++ b/apps/web/src/components/customers/branches/card.tsx @@ -0,0 +1,261 @@ +import type { AppRouterOutputs } from "@suni/api/routers/index"; +import { Badge } from "@suni/ui/components/badge"; +import { Button } from "@suni/ui/components/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuTrigger, +} from "@suni/ui/components/dropdown-menu"; +import { cn } from "@suni/ui/lib/utils"; +import { Link } from "@tanstack/react-router"; +import { + Archive, + ArchiveRestore, + Building2, + Camera, + ChevronRight, + MapPin, + MoreVertical, + Pencil, + Phone, + ZoomIn, +} from "lucide-react"; +import { useState } from "react"; + +import { BranchFormDialog } from "./branch-form-dialog"; +import { ChangeBranchStatusDialog } from "./change-branch-status-dialog"; +import { formatAddress } from "./util/branch-address"; + +type Branch = AppRouterOutputs["branches"]["list"][number]; + +interface BranchCardProps { + branch: Branch; + customer?: { id: string; name: string }; +} + +interface BranchImageProps { + name: string; + src: string; + hasImage: boolean; + isArchived: boolean; + onUploadClick?: () => void; + onExpandClick?: () => void; +} + +function BranchImage({ + name, + src, + hasImage, + isArchived, + onUploadClick, + onExpandClick, +}: BranchImageProps) { + const overlayButton = + "flex size-8 items-center justify-center rounded-full bg-black/50 text-white transition-opacity hover:bg-black/70 pointer-fine:opacity-0 pointer-fine:group-hover/image:opacity-100 pointer-fine:focus-visible:opacity-100"; + + return ( +
+ {name} +
+ + {hasImage && onExpandClick && ( + + )} + + {!isArchived && onUploadClick && ( + + )} +
+ ); +} + +export default function BranchCard({ branch, customer }: BranchCardProps) { + const isOwnArchived = !!branch.archived; + const isCustomerArchived = !!branch.customer?.archived; + const isArchived = isOwnArchived || isCustomerArchived; + + const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false); + const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false); + const placeholder = "/placeholder.webp"; + const address = formatAddress(branch); + + const branchImage = branch.frontImageUrl + ? `${branch.frontImageUrl}` + : placeholder; + + return ( + <> +
+ + + {/* Header */} +
+
+
+ +

+ {branch.name} +

+ + + {customer && ( +
+ + + {customer.name} + +
+ )} +
+ + + + } + > + Abrir menú + + + + + Acciones + {!isArchived && ( + setIsUpdateFormOpen(true)} + > + + Editar + + )} + {/* Si el cliente es quien la archiva, desarchivarla no tendría efecto */} + {!isCustomerArchived && ( + setIsStatusDialogOpen(true)} + > + {isOwnArchived ? ( + + ) : ( + + )} + {isOwnArchived ? "Desarchivar" : "Archivar"} + + )} + + + + +
+
+ + {/* Body */} +
+ {/* Address */} +
+ +
+ {address.streetLine} + {address.locationLine} +
+
+ + {/* Phone */} + {branch.phone && ( +
+ + {branch.phone} +
+ )} + + {/* Archived badge */} + {isArchived && ( +
+ + + {isCustomerArchived ? "Cliente archivado" : "Archivada"} + +
+ )} +
+ + {/* View details footer */} + +
+ + Ver detalles + + +
+ +
+ + + + + ); +} diff --git a/apps/web/src/components/customers/branches/change-branch-status-dialog.tsx b/apps/web/src/components/customers/branches/change-branch-status-dialog.tsx new file mode 100644 index 0000000..12882e7 --- /dev/null +++ b/apps/web/src/components/customers/branches/change-branch-status-dialog.tsx @@ -0,0 +1,93 @@ +import type { AppRouterOutputs } from "@suni/api/routers/index"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@suni/ui/components/alert-dialog"; +import { Archive, ArchiveRestore } from "lucide-react"; + +import { useArchiveBranch } from "@/hooks/use-branches"; + +type BranchRow = AppRouterOutputs["branches"]["list"][number]; + +const ACTIONS = { + archive: { + label: "Archivar", + Icon: Archive, + confirmVariant: "destructive", + nameClassName: "text-destructive", + description: "Esto archivará", + }, + unarchive: { + label: "Desarchivar", + Icon: ArchiveRestore, + confirmVariant: "default", + nameClassName: "text-success", + description: "Esto restaurará", + }, +} as const; + +interface ChangeBranchStatusDialogProps { + branch: Pick; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +export function ChangeBranchStatusDialog({ + branch, + open, + onOpenChange, +}: ChangeBranchStatusDialogProps) { + const action = branch.archived ? ACTIONS.unarchive : ACTIONS.archive; + const mutation = useArchiveBranch(); + + return ( + !mutation.isPending && onOpenChange(next)} + open={open} + > + + + + ¿Quieres {action.label.toLowerCase()} la sucursal {branch.name}? + + + {action.description} la sucursal{" "} + + {branch.name} + + . + + + + + Cancelar + + + mutation.mutate( + { + id: branch.id, + name: branch.name, + archived: !branch.archived, + }, + { + onSuccess: () => onOpenChange(false), + } + ) + } + variant={action.confirmVariant} + > + {mutation.isPending ? "Guardando..." : action.label} + + + + + ); +} diff --git a/apps/web/src/components/customers/branches/filters.tsx b/apps/web/src/components/customers/branches/filters.tsx new file mode 100644 index 0000000..b16ee4a --- /dev/null +++ b/apps/web/src/components/customers/branches/filters.tsx @@ -0,0 +1,161 @@ +import { Button } from "@suni/ui/components/button"; +import { Input } from "@suni/ui/components/input"; +import { ReactSelect } from "@suni/ui/components/react-select"; +import { X } from "lucide-react"; + +export type BranchStatusFilter = "all" | "active" | "archived"; + +export interface BranchFilters { + name: string; + status: BranchStatusFilter; + customerId: string; +} + +const DEFAULT_BRANCH_FILTERS: BranchFilters = { + name: "", + status: "all", + customerId: "all", +}; + +interface Option { + value: T; + label: string; +} + +const STATUS_OPTIONS: Option[] = [ + { value: "all", label: "Todas" }, + { value: "active", label: "Activas" }, + { value: "archived", label: "Archivadas" }, +]; + +const MAX_CUSTOMER_BADGE_LENGTH = 20; + +interface BranchesFiltersProps { + filters: BranchFilters; + onFiltersChange: (filters: BranchFilters) => void; + customers?: { id: string; name: string }[]; +} + +function FilterBadge({ + children, + onClear, +}: { + children: React.ReactNode; + onClear: () => void; +}) { + return ( + + ); +} + +export function BranchesFilters({ + filters, + onFiltersChange, + customers, +}: BranchesFiltersProps) { + const showCustomerFilter = !!customers; + + const customerOptions: Option[] = [ + { value: "all", label: "Todos los clientes" }, + ...(customers ?? []).map((c) => ({ value: c.id, label: c.name })), + ]; + + const selectedCustomerName = + filters.customerId === "all" + ? null + : (customers?.find((c) => c.id === filters.customerId)?.name ?? null); + + const hasActiveFilters = + filters.name.trim() !== "" || + filters.status !== "all" || + (showCustomerFilter && filters.customerId !== "all"); + + const update = (patch: Partial) => + onFiltersChange({ ...filters, ...patch }); + + return ( +
+
+ update({ name: event.target.value })} + placeholder="Buscar por nombre de sucursal..." + type="text" + value={filters.name} + /> + | null) => + update({ status: option?.value ?? "all" }) + } + options={STATUS_OPTIONS} + placeholder="Estatus" + value={STATUS_OPTIONS.find((opt) => opt.value === filters.status)} + /> +
+ + {showCustomerFilter && ( +
+ + update({ customerId: option?.value ?? "all" }) + } + options={customerOptions} + placeholder="Cliente" + value={customerOptions.find( + (opt) => opt.value === filters.customerId + )} + /> +
+ )} + + {hasActiveFilters && ( +
+ + Filtros activos: + + + {filters.name.trim() && ( + update({ name: "" })}> + Nombre: “{filters.name.trim()}” + + )} + + {filters.status !== "all" && ( + update({ status: "all" })}> + Estatus: {filters.status === "active" ? "Activas" : "Archivadas"} + + )} + + {showCustomerFilter && selectedCustomerName && ( + update({ customerId: "all" })}> + Cliente:{" "} + {selectedCustomerName.length > MAX_CUSTOMER_BADGE_LENGTH + ? `${selectedCustomerName.slice(0, MAX_CUSTOMER_BADGE_LENGTH)}...` + : selectedCustomerName} + + )} + + +
+ )} +
+ ); +} diff --git a/apps/web/src/components/customers/branches/grid.tsx b/apps/web/src/components/customers/branches/grid.tsx new file mode 100644 index 0000000..f23cf09 --- /dev/null +++ b/apps/web/src/components/customers/branches/grid.tsx @@ -0,0 +1,123 @@ +import { Button } from "@suni/ui/components/button"; +import { useQuery } from "@tanstack/react-query"; +import { Building2, Plus, SearchX } from "lucide-react"; +import { useMemo, useState } from "react"; + +import { orpc } from "@/utils/orpc"; + +import { BranchFormDialog } from "./branch-form-dialog"; +import BranchCard from "./card"; +import { BranchesFilters } from "./filters"; +import type { BranchFilters } from "./filters"; + +interface BranchesGridProps { + customerId: string; +} + +const DEFAULT_BRANCH_FILTERS: BranchFilters = { + name: "", + status: "all", + customerId: "all", +}; + +export function BranchesGrid({ customerId }: BranchesGridProps) { + const [filters, setFilters] = useState(DEFAULT_BRANCH_FILTERS); + const [isFormOpen, setIsFormOpen] = useState(false); + + const { + data: branches = [], + isPending, + isError, + } = useQuery(orpc.branches.list.queryOptions({ input: { customerId } })); + + const filtered = useMemo(() => { + const term = filters.name.trim().toLowerCase(); + + return branches.filter((branch) => { + if (term && !branch.name.toLowerCase().includes(term)) { + return false; + } + + if (filters.status === "active") { + return !branch.archived; + } + + if (filters.status === "archived") { + return !!branch.archived; + } + + return true; + }); + }, [branches, filters]); + + const hasActiveFilters = + filters.name.trim() !== "" || filters.status !== "all"; + + return ( + <> +
+
+

Sucursales

+ +
+ + + + {isPending ? ( +

+ Cargando sucursales… +

+ ) : null} + + {isError ? ( +

+ No se pudieron cargar las sucursales. +

+ ) : null} + + {!(isPending || isError) && filtered.length === 0 ? ( +
+ {hasActiveFilters ? ( + + ) : ( + + )} +

+ {hasActiveFilters + ? "No se encontraron sucursales" + : "No hay sucursales para mostrar"} +

+

+ {hasActiveFilters + ? "Intenta con otros filtros de búsqueda" + : "Las sucursales del cliente aparecerán aquí"} +

+
+ ) : null} + + {filtered.length > 0 ? ( +
+ {filtered.map((branch) => ( + + ))} +
+ ) : null} +
+ + + + ); +} diff --git a/apps/web/src/components/customers/branches/util/branch-address.ts b/apps/web/src/components/customers/branches/util/branch-address.ts new file mode 100644 index 0000000..87b86c3 --- /dev/null +++ b/apps/web/src/components/customers/branches/util/branch-address.ts @@ -0,0 +1,17 @@ +import type { AppRouterOutputs } from "@suni/api/routers/index"; + +export type Branch = AppRouterOutputs["branches"]["list"][number]; + +export function formatAddress(branch: Branch) { + const streetParts = [ + branch.street, + branch.extNumber && `No. Ext. ${branch.extNumber}`, + branch.intNumber && `No. Int. ${branch.intNumber}`, + `Col. ${branch.suburb}`, + ].filter(Boolean); + + return { + streetLine: streetParts.join(", "), + locationLine: `${branch.city}, ${branch.state}, CP ${branch.postalCode}`, + }; +} diff --git a/apps/web/src/components/customers/contacts/change-contact-status-dialog.tsx b/apps/web/src/components/customers/contacts/change-contact-status-dialog.tsx new file mode 100644 index 0000000..c0184e7 --- /dev/null +++ b/apps/web/src/components/customers/contacts/change-contact-status-dialog.tsx @@ -0,0 +1,90 @@ +import type { AppRouterOutputs } from "@suni/api/routers/index"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@suni/ui/components/alert-dialog"; + +import { useArchiveContact } from "@/hooks/use-contacts"; + +type ContactRow = AppRouterOutputs["contacts"]["list"][number]; + +const ACTIONS = { + archive: { + label: "Archivar", + confirmVariant: "destructive", + nameClassName: "text-destructive", + description: "Esto archivará", + }, + unarchive: { + label: "Desarchivar", + confirmVariant: "default", + nameClassName: "text-success", + description: "Esto restaurará", + }, +} as const; + +interface ChangeContactStatusDialogProps { + contact: Pick; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +export function ChangeContactStatusDialog({ + contact, + open, + onOpenChange, +}: ChangeContactStatusDialogProps) { + const action = contact.archived ? ACTIONS.unarchive : ACTIONS.archive; + const mutation = useArchiveContact(); + + return ( + !mutation.isPending && onOpenChange(next)} + open={open} + > + + + + ¿Quieres {action.label.toLowerCase()} al contacto {contact.name}? + + + {action.description} al contacto{" "} + + {contact.name} + + . + + + + + Cancelar + + + mutation.mutate( + { + id: contact.id, + name: contact.name, + archived: !contact.archived, + }, + { + onSuccess: () => onOpenChange(false), + } + ) + } + variant={action.confirmVariant} + > + {mutation.isPending ? "Guardando..." : action.label} + + + + + ); +} diff --git a/apps/web/src/components/customers/contacts/contact-card.tsx b/apps/web/src/components/customers/contacts/contact-card.tsx new file mode 100644 index 0000000..270380e --- /dev/null +++ b/apps/web/src/components/customers/contacts/contact-card.tsx @@ -0,0 +1,272 @@ +import type { AppRouterOutputs } from "@suni/api/routers/index"; +import { Badge } from "@suni/ui/components/badge"; +import { Button } from "@suni/ui/components/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuTrigger, +} from "@suni/ui/components/dropdown-menu"; +import { cn } from "@suni/ui/lib/utils"; +import { Link } from "@tanstack/react-router"; +import { + Archive, + ArchiveRestore, + Building2, + Mail, + MapPin, + MoreVertical, + Pencil, + Phone, +} from "lucide-react"; +import { useState } from "react"; + +import { ChangeContactStatusDialog } from "./change-contact-status-dialog"; +import { ContactFormDialog } from "./contact-form-dialog"; + +type Contact = AppRouterOutputs["contacts"]["list"][number]; + +interface ContactCardProps { + contact: Contact; + /** Si viene definido, muestra el cliente (útil en listados de varios clientes). */ + customer?: { id: string; name: string }; + readOnly?: boolean; +} + +function getArchiveState(contact: Contact) { + const isOwn = !!contact.archived; + const isCustomer = !!contact.customer?.archived; + const isBranch = !!contact.branch?.archived; + const isParent = isCustomer || isBranch; + + let label = "Archivado"; + + if (isCustomer) { + label = "Cliente archivado"; + } else if (isBranch) { + label = "Sucursal archivada"; + } + + return { isOwn, isParent, isArchived: isOwn || isParent, label }; +} + +interface ContactMenuProps { + isArchived: boolean; + isOwnArchived: boolean; + isParentArchived: boolean; + onEdit: () => void; + onToggleStatus: () => void; +} + +function ContactMenu({ + isArchived, + isOwnArchived, + isParentArchived, + onEdit, + onToggleStatus, +}: ContactMenuProps) { + return ( + + + }> + Abrir menú + + + + + Acciones + {!isArchived && ( + + + Editar + + )} + + {/* Si un padre lo archiva, desarchivarlo no tendría efecto */} + {!isParentArchived && ( + + {isOwnArchived ? ( + + ) : ( + + )} + {isOwnArchived ? "Desarchivar" : "Archivar"} + + )} + + + + + ); +} + +interface ContactParentsProps { + contact: Contact; + customer?: { id: string; name: string }; +} + +function ContactParents({ contact, customer }: ContactParentsProps) { + return ( + <> + {customer && ( +
+ + + {customer.name} + +
+ )} + + {contact.branch && ( +
+ + + {contact.branch.name} + +
+ )} + + ); +} + +function ContactPhone({ contact }: { contact: Contact }) { + if (!contact.phone) { + return null; + } + + return ( +
+ + + {contact.phone} + {contact.phoneExtension && ` ext. ${contact.phoneExtension}`} + +
+ ); +} + +export default function ContactCard({ + contact, + customer, + readOnly = false, +}: ContactCardProps) { + const { isOwn, isParent, isArchived, label } = getArchiveState(contact); + + const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false); + const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false); + + return ( + <> +
+ {/* Header */} +
+
+
+

+ {contact.name} +

+ + {contact.position && ( +

+ {contact.position} +

+ )} + + +
+ + {!readOnly && ( + setIsUpdateFormOpen(true)} + onToggleStatus={() => setIsStatusDialogOpen(true)} + /> + )} +
+
+ + {/* Body */} + + + {/* Archived badge */} + {isArchived && ( +
+ + + {label} + +
+ )} +
+ + {!readOnly && ( + <> + + + + )} + + ); +} diff --git a/apps/web/src/components/customers/contacts/contact-filters.tsx b/apps/web/src/components/customers/contacts/contact-filters.tsx new file mode 100644 index 0000000..1b36983 --- /dev/null +++ b/apps/web/src/components/customers/contacts/contact-filters.tsx @@ -0,0 +1,120 @@ +import { Button } from "@suni/ui/components/button"; +import { Input } from "@suni/ui/components/input"; +import { ReactSelect } from "@suni/ui/components/react-select"; +import { X } from "lucide-react"; + +export type ContactStatusFilter = "all" | "active" | "archived"; + +export interface ContactFilters { + name: string; + status: ContactStatusFilter; +} + +const DEFAULT_CONTACT_FILTERS: ContactFilters = { + name: "", + status: "all", +}; + +interface Option { + value: T; + label: string; +} + +const STATUS_OPTIONS: Option[] = [ + { value: "all", label: "Todos" }, + { value: "active", label: "Activos" }, + { value: "archived", label: "Archivados" }, +]; + +interface ContactsFiltersProps { + filters: ContactFilters; + onFiltersChange: (filters: ContactFilters) => void; +} + +function FilterBadge({ + children, + onClear, +}: { + children: React.ReactNode; + onClear: () => void; +}) { + return ( + + ); +} + +export function ContactsFilters({ + filters, + onFiltersChange, +}: ContactsFiltersProps) { + const hasName = filters.name.trim() !== ""; + const hasStatus = filters.status !== "all"; + const hasActiveFilters = hasName || hasStatus; + + const statusLabel = STATUS_OPTIONS.find( + (option) => option.value === filters.status + )?.label; + + const update = (patch: Partial) => + onFiltersChange({ ...filters, ...patch }); + + return ( +
+
+ update({ name: event.target.value })} + placeholder="Buscar por nombre..." + type="text" + value={filters.name} + /> + | null) => + update({ status: option?.value ?? "all" }) + } + options={STATUS_OPTIONS} + placeholder="Estatus" + value={STATUS_OPTIONS.find((opt) => opt.value === filters.status)} + /> +
+ + {hasActiveFilters && ( +
+ + Filtros activos: + + + {hasName && ( + update({ name: "" })}> + Nombre: “{filters.name.trim()}” + + )} + + {hasStatus && ( + update({ status: "all" })}> + Estatus: {statusLabel} + + )} + + +
+ )} +
+ ); +} diff --git a/apps/web/src/components/customers/contacts/contact-form-dialog.tsx b/apps/web/src/components/customers/contacts/contact-form-dialog.tsx new file mode 100644 index 0000000..a89e1fe --- /dev/null +++ b/apps/web/src/components/customers/contacts/contact-form-dialog.tsx @@ -0,0 +1,50 @@ +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@suni/ui/components/dialog"; +import type { ComponentProps } from "react"; + +import { ContactForm } from "./contact-form"; + +interface ContactFormDialogProps extends Pick< + ComponentProps, + "contact" | "customerId" | "branchId" +> { + open: boolean; + onOpenChange: (open: boolean) => void; +} + +export function ContactFormDialog({ + contact, + customerId, + branchId, + open, + onOpenChange, +}: ContactFormDialogProps) { + return ( + + + + + {contact ? "Editar contacto" : "Nuevo contacto"} + + + {contact + ? "Actualiza los datos del contacto." + : "Captura los datos del nuevo contacto."} + + + onOpenChange(false)} + onSuccess={() => onOpenChange(false)} + /> + + + ); +} diff --git a/apps/web/src/components/customers/contacts/contact-form.tsx b/apps/web/src/components/customers/contacts/contact-form.tsx new file mode 100644 index 0000000..728e419 --- /dev/null +++ b/apps/web/src/components/customers/contacts/contact-form.tsx @@ -0,0 +1,182 @@ +import type { AppRouterOutputs } from "@suni/api/routers/index"; +import { + contactFormSchema, + contactInputSchema, +} from "@suni/db/validation/contacts"; +import { Button } from "@suni/ui/components/button"; +import { revalidateLogic } from "@tanstack/react-form"; +import { Loader2 } from "lucide-react"; +import type { z } from "zod"; + +import { useAppForm } from "@/components/form/use-app-form"; +import { useCreateContact, useUpdateContact } from "@/hooks/use-contacts"; + +type Contact = AppRouterOutputs["contacts"]["list"][number]; + +type FormValues = z.input; + +interface ContactFormProps { + customerId?: string | null; + branchId?: string | null; + contact?: Contact; + onSuccess?: () => void; + onCancel: () => void; +} + +const PHONE_LENGTH = 10; + +const EXTENSION_LENGTH = 10; + +const EMPTY_VALUES: FormValues = { + name: "", + email: "", + phone: "", + phoneExtension: "", + position: "", +}; + +function toFormValues(contact?: Contact): FormValues { + if (!contact) { + return EMPTY_VALUES; + } + + return { + name: contact.name, + email: contact.email, + phone: contact.phone, + phoneExtension: contact.phoneExtension ?? "", + position: contact.position ?? "", + }; +} + +export function ContactForm({ + customerId, + branchId, + contact, + onSuccess, + onCancel, +}: ContactFormProps) { + const createContact = useCreateContact(); + const updateContact = useUpdateContact(); + + const submitting = createContact.isPending || updateContact.isPending; + + const form = useAppForm({ + defaultValues: toFormValues(contact), + validationLogic: revalidateLogic(), + validators: { onDynamic: contactFormSchema }, + onSubmit: ({ value }) => { + const parsed = contactInputSchema.parse(value); + + if (contact) { + updateContact.mutate( + { id: contact.id, ...parsed }, + { onSuccess: () => onSuccess?.() } + ); + } else if (customerId && branchId) { + createContact.mutate( + { customerId, branchId, ...parsed }, + { onSuccess: () => onSuccess?.() } + ); + } + }, + }); + + return ( +
{ + event.preventDefault(); + form.handleSubmit(); + }} + > +
+ + Datos generales + +
+ + {(field) => ( + + )} + + + {(field) => ( + + )} + +
+
+ +
+ + Contacto + +
+ + {(field) => ( + + )} + +
+ + {(field) => ( + + )} + + + {(field) => ( + + )} + +
+
+
+ +
+ + +
+
+ ); +} diff --git a/apps/web/src/components/customers/contacts/contact-grid.tsx b/apps/web/src/components/customers/contacts/contact-grid.tsx new file mode 100644 index 0000000..b53a3e0 --- /dev/null +++ b/apps/web/src/components/customers/contacts/contact-grid.tsx @@ -0,0 +1,118 @@ +import { useQuery } from "@tanstack/react-query"; +import { SearchX, Users } from "lucide-react"; +import { useMemo, useState } from "react"; + +import { NewEntityButton } from "@/components/customers/select-entity-button"; +import { orpc } from "@/utils/orpc"; + +import ContactCard from "./contact-card"; +import { ContactsFilters } from "./contact-filters"; +import type { ContactFilters } from "./contact-filters"; + +interface ContactsGridProps { + customerId: string; + branchId?: string; +} + +const DEFAULT_CONTACT_FILTERS: ContactFilters = { + name: "", + status: "all", +}; + +export function ContactsGrid({ customerId, branchId }: ContactsGridProps) { + const [filters, setFilters] = useState( + DEFAULT_CONTACT_FILTERS + ); + + const { + data: contacts = [], + isPending, + isError, + } = useQuery( + orpc.contacts.list.queryOptions({ input: { customerId, branchId } }) + ); + + const filtered = useMemo(() => { + const term = filters.name.trim().toLowerCase(); + + return contacts.filter((contact) => { + if (term && !contact.name.toLowerCase().includes(term)) { + return false; + } + + if (filters.status === "active") { + return !contact.archived; + } + + if (filters.status === "archived") { + return !!contact.archived; + } + + return true; + }); + }, [contacts, filters]); + + const hasActiveFilters = + filters.name.trim() !== "" || filters.status !== "all"; + + return ( +
+
+

Contactos

+ +
+ + + + {isPending ? ( +

+ Cargando contactos… +

+ ) : null} + + {isError ? ( +

+ No se pudieron cargar los contactos. +

+ ) : null} + + {!(isPending || isError) && filtered.length === 0 ? ( +
+ {hasActiveFilters ? ( + + ) : ( + + )} +

+ {hasActiveFilters + ? "No se encontraron contactos" + : "No hay contactos para mostrar"} +

+

+ {hasActiveFilters + ? "Intenta con otros filtros de búsqueda" + : "Los contactos aparecerán aquí"} +

+
+ ) : null} + + {filtered.length > 0 ? ( +
+ {filtered.map((contact) => ( + + ))} +
+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/customers/select-entity-button.tsx b/apps/web/src/components/customers/select-entity-button.tsx new file mode 100644 index 0000000..6a06152 --- /dev/null +++ b/apps/web/src/components/customers/select-entity-button.tsx @@ -0,0 +1,257 @@ +import { Button } from "@suni/ui/components/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@suni/ui/components/dialog"; +import { ReactSelect } from "@suni/ui/components/react-select"; +import { Plus } from "lucide-react"; +import { useMemo, useState } from "react"; + +import { BranchFormDialog } from "@/components/customers/branches/branch-form-dialog"; +import { ContactFormDialog } from "@/components/customers/contacts/contact-form-dialog"; +import { useListBranches } from "@/hooks/use-branches"; +import { useListCustomers } from "@/hooks/use-customers"; + +interface PickerProps { + value: string | null; + onValueChange: (value: string) => void; +} + +function CustomerPicker({ value, onValueChange }: PickerProps) { + const { data: customers = [], isPending } = useListCustomers({ + status: "active", + }); + + const options = useMemo( + () => + customers + .toSorted((a, b) => a.name.localeCompare(b.name, "es")) + .map((customer) => ({ value: customer.id, label: customer.name })), + [customers] + ); + + return ( + "Cargando…"} + noOptionsMessage={() => "Sin resultados"} + onChange={(option) => { + if (option) { + onValueChange(option.value); + } + }} + options={options} + placeholder="Selecciona un cliente" + value={options.find((option) => option.value === value) ?? null} + /> + ); +} + +function BranchPicker({ + customerId, + value, + onValueChange, +}: PickerProps & { customerId: string | null }) { + const { data: branches = [], isPending } = useListBranches( + customerId ? { customerId } : {}, + !!customerId + ); + + const options = useMemo( + () => + branches + .filter((branch) => !branch.archived) + .toSorted((a, b) => a.name.localeCompare(b.name, "es")) + .map((branch) => ({ value: branch.id, label: branch.name })), + [branches] + ); + + return ( + "Cargando…"} + noOptionsMessage={() => "Sin resultados"} + onChange={(option) => { + if (option) { + onValueChange(option.value); + } + }} + options={options} + placeholder="Selecciona una sucursal" + value={options.find((option) => option.value === value) ?? null} + /> + ); +} + +interface EntityFormProps { + entity: "branch" | "contact"; + customerId: string; + branchId: string | null; + onOpenChange: (open: boolean) => void; +} + +function EntityForm({ + entity, + customerId, + branchId, + onOpenChange, +}: EntityFormProps) { + if (entity === "branch") { + return ( + + ); + } + + if (!branchId) { + return null; + } + + return ( + + ); +} + +const COPY = { + branch: { + label: "Nueva Sucursal", + title: "Nueva sucursal", + description: "Selecciona el cliente al que pertenecerá la sucursal.", + }, + contact: { + label: "Nuevo Contacto", + title: "Nuevo contacto", + description: "Selecciona a dónde pertenecerá el contacto.", + }, +} as const; + +interface NewEntityButtonProps { + entity: "branch" | "contact"; + customerId?: string; + branchId?: string; + label?: string; + className?: string; +} + +type Step = "closed" | "select" | "form"; + +export function NewEntityButton({ + entity, + customerId, + branchId, + label, + className, +}: NewEntityButtonProps) { + const [step, setStep] = useState("closed"); + const [pickedCustomerId, setPickedCustomerId] = useState(null); + const [pickedBranchId, setPickedBranchId] = useState(null); + + const copy = COPY[entity]; + const isContact = entity === "contact"; + + const effectiveCustomerId = customerId ?? pickedCustomerId; + const effectiveBranchId = branchId ?? pickedBranchId; + + const needsCustomer = !customerId; + const needsBranch = isContact && !branchId; + + const canContinue = + !!effectiveCustomerId && (!isContact || !!effectiveBranchId); + + const close = () => { + setStep("closed"); + setPickedCustomerId(null); + setPickedBranchId(null); + }; + + const handleFormOpenChange = (open: boolean) => { + if (!open) { + close(); + } + }; + + return ( + <> + + + { + if (!open && step === "select") { + close(); + } + }} + open={step === "select"} + > + + + {copy.title} + {copy.description} + + +
+ {needsCustomer ? ( + { + setPickedCustomerId(value); + setPickedBranchId(null); + }} + value={pickedCustomerId} + /> + ) : null} + + {needsBranch ? ( + + ) : null} +
+ + + + + +
+
+ + {step === "form" && effectiveCustomerId ? ( + + ) : null} + + ); +} diff --git a/apps/web/src/components/dynamic-breadcrumb.tsx b/apps/web/src/components/dynamic-breadcrumb.tsx index 70cd813..5f0cd82 100644 --- a/apps/web/src/components/dynamic-breadcrumb.tsx +++ b/apps/web/src/components/dynamic-breadcrumb.tsx @@ -16,6 +16,7 @@ const SEGMENT_LABELS = { new: "Nuevo", edit: "Editar", customers: "Clientes", + branches: "Sucursales", } satisfies Record; type KnownSegment = keyof typeof SEGMENT_LABELS; diff --git a/apps/web/src/components/nav-bar.tsx b/apps/web/src/components/nav-bar.tsx index e080579..cb1f414 100644 --- a/apps/web/src/components/nav-bar.tsx +++ b/apps/web/src/components/nav-bar.tsx @@ -1,28 +1,31 @@ import { SidebarMenu, SidebarMenuItem } from "@suni/ui/components/sidebar"; import { cn } from "@suni/ui/lib/utils"; import { Link, useRouterState } from "@tanstack/react-router"; +import type { LinkProps } from "@tanstack/react-router"; import type { LucideIcon } from "lucide-react"; -import { Home, Users } from "lucide-react"; +import { Building2, Contact, ContactRound, Home, Users } from "lucide-react"; import { useIsAdmin } from "@/hooks/use-is-admin"; interface NavItem { - to: "/dashboard" | "/users" | "/customers"; + to: NonNullable; label: string; icon: LucideIcon; adminOnly?: true; } -const NAV_ITEMS: NavItem[] = [ +const NAV_ITEMS = [ { to: "/dashboard", label: "Inicio", icon: Home }, { to: "/users", label: "Usuarios", icon: Users, adminOnly: true }, - { to: "/customers", label: "Clientes", icon: Users }, -]; + { to: "/customers", label: "Clientes", icon: ContactRound }, + { to: "/branches", label: "Sucursales", icon: Building2 }, + { to: "/contacts", label: "Contactos", icon: Contact }, +] satisfies NavItem[]; export function NavMain() { const pathname = useRouterState({ select: (s) => s.location.pathname }); const isAdmin = useIsAdmin(); - const items = NAV_ITEMS.filter((item) => isAdmin || !item.adminOnly); + const items = NAV_ITEMS.filter((item) => isAdmin || !("adminOnly" in item)); return ( @@ -32,12 +35,12 @@ export function NavMain() { return ( {label} diff --git a/apps/web/src/hooks/use-branches.ts b/apps/web/src/hooks/use-branches.ts new file mode 100644 index 0000000..a4ee52e --- /dev/null +++ b/apps/web/src/hooks/use-branches.ts @@ -0,0 +1,80 @@ +import type { + AppRouterInputs, + AppRouterOutputs, +} from "@suni/api/routers/index"; +import { + keepPreviousData, + useMutation, + useQuery, + useQueryClient, +} from "@tanstack/react-query"; +import { toast } from "sonner"; + +import { client, orpc } from "@/utils/orpc"; + +type BranchRow = AppRouterOutputs["branches"]["list"][number]; + +export function useListBranches( + params: AppRouterInputs["branches"]["list"], + enabled = true +) { + return useQuery({ + ...orpc.branches.list.queryOptions({ input: params }), + placeholderData: keepPreviousData, + enabled, + }); +} + +export function useCreateBranch() { + const queryClient = useQueryClient(); + + return useMutation( + orpc.branches.create.mutationOptions({ + onSuccess: async () => { + toast.success("Sucursal creada"); + await queryClient.invalidateQueries({ queryKey: orpc.branches.key() }); + }, + onError: (error) => toast.error(error.message), + }) + ); +} + +export function useUpdateBranch() { + const queryClient = useQueryClient(); + + return useMutation( + orpc.branches.update.mutationOptions({ + onSuccess: async () => { + toast.success("Sucursal actualizada"); + await queryClient.invalidateQueries({ queryKey: orpc.branches.key() }); + await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }); + }, + onError: (error) => toast.error(error.message), + }) + ); +} + +export function useArchiveBranch() { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: ({ + id, + archived, + }: Pick & { archived: boolean }) => + client.branches.setArchived({ id, archived }), + onSuccess: async (_data, { archived, name }) => { + await queryClient.invalidateQueries({ queryKey: orpc.branches.key() }); + toast.success(archived ? "Sucursal archivada" : "Sucursal desarchivada", { + description: `Se ${archived ? "archivó" : "desarchivó"} ${name} con éxito.`, + }); + }, + onError: (error) => { + console.error("Error al archivar la sucursal:", error); + toast.error("Algo salió mal...", { + description: + "Hubo un error al cambiar el estado de la sucursal. Intenta de nuevo.", + }); + }, + }); +} diff --git a/apps/web/src/hooks/use-contacts.ts b/apps/web/src/hooks/use-contacts.ts new file mode 100644 index 0000000..6e26b93 --- /dev/null +++ b/apps/web/src/hooks/use-contacts.ts @@ -0,0 +1,75 @@ +import type { + AppRouterInputs, + AppRouterOutputs, +} from "@suni/api/routers/index"; +import { + keepPreviousData, + useMutation, + useQuery, + useQueryClient, +} from "@tanstack/react-query"; +import { toast } from "sonner"; + +import { client, orpc } from "@/utils/orpc"; + +type ContactRow = AppRouterOutputs["contacts"]["list"][number]; + +export function useListContacts(params: AppRouterInputs["contacts"]["list"]) { + return useQuery({ + ...orpc.contacts.list.queryOptions({ input: params }), + placeholderData: keepPreviousData, + }); +} + +export function useCreateContact() { + const queryClient = useQueryClient(); + + return useMutation( + orpc.contacts.create.mutationOptions({ + onSuccess: async () => { + toast.success("Contacto creado"); + await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }); + }, + onError: (error) => toast.error(error.message), + }) + ); +} + +export function useUpdateContact() { + const queryClient = useQueryClient(); + + return useMutation( + orpc.contacts.update.mutationOptions({ + onSuccess: async () => { + toast.success("Contacto actualizado"); + await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }); + }, + onError: (error) => toast.error(error.message), + }) + ); +} + +export function useArchiveContact() { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: ({ + id, + archived, + }: Pick & { archived: boolean }) => + client.contacts.setArchived({ id, archived }), + onSuccess: async (_data, { archived, name }) => { + await queryClient.invalidateQueries({ queryKey: orpc.contacts.key() }); + toast.success(archived ? "Contacto archivado" : "Contacto desarchivado", { + description: `Se ${archived ? "archivó" : "desarchivó"} a ${name} con éxito.`, + }); + }, + onError: (error) => { + console.error("Error al archivar el contacto:", error); + toast.error("Algo salió mal...", { + description: + "Hubo un error al cambiar el estado del contacto. Intenta de nuevo.", + }); + }, + }); +} diff --git a/apps/web/src/routes/_auth/branches/index.tsx b/apps/web/src/routes/_auth/branches/index.tsx new file mode 100644 index 0000000..c93f1d9 --- /dev/null +++ b/apps/web/src/routes/_auth/branches/index.tsx @@ -0,0 +1,146 @@ +import { cn } from "@suni/ui/lib/utils"; +import { createFileRoute, stripSearchParams } from "@tanstack/react-router"; +import { Building2, SearchX } from "lucide-react"; +import { useMemo } from "react"; +import { z } from "zod"; + +import BranchCard from "@/components/customers/branches/card"; +import { BranchesFilters } from "@/components/customers/branches/filters"; +import type { BranchFilters } from "@/components/customers/branches/filters"; +import { NewEntityButton } from "@/components/customers/select-entity-button"; +import { useListBranches } from "@/hooks/use-branches"; +import { useListCustomers } from "@/hooks/use-customers"; +import { stripAccents } from "@/lib/string-utils"; + +/* oxlint-disable promise/prefer-await-to-then, github/no-then -- zod `.catch()` is not Promise.catch */ +const searchSchema = z.object({ + name: z.string().default("").catch(""), + status: z.enum(["all", "active", "archived"]).default("all").catch("all"), + customerId: z.string().default("all").catch("all"), +}); +/* oxlint-enable promise/prefer-await-to-then, github/no-then */ + +const defaultFilters = searchSchema.parse({}); + +export const Route = createFileRoute("/_auth/branches/")({ + validateSearch: searchSchema, + search: { middlewares: [stripSearchParams(defaultFilters)] }, + component: RouteComponent, +}); + +function RouteComponent() { + const filters = Route.useSearch(); + const navigate = Route.useNavigate(); + + const { + data: branches = [], + isError, + isPending, + isPlaceholderData, + } = useListBranches({ + status: filters.status, + ...(filters.customerId === "all" + ? undefined + : { customerId: filters.customerId }), + }); + + const visibleBranches = useMemo(() => { + const term = stripAccents(filters.name.trim()).toLowerCase(); + + return branches + .filter( + (branch) => + !term || stripAccents(branch.name).toLowerCase().includes(term) + ) + .toSorted((a, b) => a.name.localeCompare(b.name, "es")); + }, [branches, filters.name]); + + const { data: customers } = useListCustomers({}); + + const hasFilters = + filters.name.trim() !== "" || + filters.status !== defaultFilters.status || + filters.customerId !== defaultFilters.customerId; + + const handleFiltersChange = (next: BranchFilters) => + navigate({ search: next, replace: true }); + + return ( +
+
+
+
+
+ +
+

Sucursales

+
+

+ Gestiona las sucursales de los clientes +

+
+
+ +
+
+ + + + {isPending ? ( +

+ Cargando sucursales… +

+ ) : null} + + {isError ? ( +

+ No se pudieron cargar las sucursales. +

+ ) : null} + + {!(isPending || isError) && visibleBranches.length === 0 ? ( +
+ {hasFilters ? ( + + ) : ( + + )} +

+ {hasFilters + ? "No se encontraron sucursales" + : "No hay sucursales para mostrar"} +

+

+ {hasFilters + ? "Intenta con otros filtros de búsqueda" + : "Las sucursales aparecerán aquí"} +

+
+ ) : null} + + {visibleBranches.length > 0 ? ( +
+ {visibleBranches.map((branch) => ( + + ))} +
+ ) : null} +
+ ); +} diff --git a/apps/web/src/routes/_auth/contacts/index.tsx b/apps/web/src/routes/_auth/contacts/index.tsx new file mode 100644 index 0000000..691eaaa --- /dev/null +++ b/apps/web/src/routes/_auth/contacts/index.tsx @@ -0,0 +1,134 @@ +import { cn } from "@suni/ui/lib/utils"; +import { createFileRoute, stripSearchParams } from "@tanstack/react-router"; +import { SearchX, Users } from "lucide-react"; +import { useMemo } from "react"; +import { z } from "zod"; + +import ContactCard from "@/components/customers/contacts/contact-card"; +import { ContactsFilters } from "@/components/customers/contacts/contact-filters"; +import type { ContactFilters } from "@/components/customers/contacts/contact-filters"; +import { NewEntityButton } from "@/components/customers/select-entity-button"; +import { useListContacts } from "@/hooks/use-contacts"; +import { stripAccents } from "@/lib/string-utils"; + +/* oxlint-disable promise/prefer-await-to-then, github/no-then -- zod `.catch()` is not Promise.catch */ +const searchSchema = z.object({ + name: z.string().default("").catch(""), + status: z.enum(["all", "active", "archived"]).default("all").catch("all"), +}); +/* oxlint-enable promise/prefer-await-to-then, github/no-then */ + +const defaultFilters = searchSchema.parse({}); + +export const Route = createFileRoute("/_auth/contacts/")({ + validateSearch: searchSchema, + search: { middlewares: [stripSearchParams(defaultFilters)] }, + component: RouteComponent, +}); + +function RouteComponent() { + const filters = Route.useSearch(); + const navigate = Route.useNavigate(); + + const { + data: contacts = [], + isError, + isPending, + isPlaceholderData, + } = useListContacts({ status: filters.status }); + + const visibleContacts = useMemo(() => { + const term = stripAccents(filters.name.trim()).toLowerCase(); + + return contacts + .filter( + (contact) => + !term || stripAccents(contact.name).toLowerCase().includes(term) + ) + .toSorted((a, b) => a.name.localeCompare(b.name, "es")); + }, [contacts, filters.name]); + + const hasFilters = + filters.name.trim() !== "" || filters.status !== defaultFilters.status; + + const handleFiltersChange = (next: ContactFilters) => + navigate({ search: next, replace: true }); + + return ( +
+
+
+
+
+ +
+

Contactos

+
+

+ Gestiona los contactos de las sucursales +

+
+
+ +
+
+ + + + {isPending ? ( +

+ Cargando contactos… +

+ ) : null} + + {isError ? ( +

+ No se pudieron cargar los contactos. +

+ ) : null} + + {!(isPending || isError) && visibleContacts.length === 0 ? ( +
+ {hasFilters ? ( + + ) : ( + + )} +

+ {hasFilters + ? "No se encontraron contactos" + : "No hay contactos para mostrar"} +

+

+ {hasFilters + ? "Intenta con otros filtros de búsqueda" + : "Los contactos aparecerán aquí"} +

+
+ ) : null} + + {visibleContacts.length > 0 ? ( +
+ {visibleContacts.map((contact) => ( + + ))} +
+ ) : null} +
+ ); +} diff --git a/apps/web/src/routes/_auth/customers/$customerId/branches/$branchId/index.tsx b/apps/web/src/routes/_auth/customers/$customerId/branches/$branchId/index.tsx new file mode 100644 index 0000000..8998c0c --- /dev/null +++ b/apps/web/src/routes/_auth/customers/$customerId/branches/$branchId/index.tsx @@ -0,0 +1,117 @@ +import { + Tabs, + TabsContent, + TabsList, + TabsTrigger, +} from "@suni/ui/components/tabs"; +import { useSuspenseQuery } from "@tanstack/react-query"; +import { createFileRoute } from "@tanstack/react-router"; +import { FileText, FolderOpen, HardHat, Info, Users } from "lucide-react"; +import type { ReactNode } from "react"; +import { useState } from "react"; + +import { BranchFormDialog } from "@/components/customers/branches/branch-form-dialog"; +import { BranchHeader } from "@/components/customers/branches/branch-header"; +import { BranchInfoContent } from "@/components/customers/branches/branch-info"; +import { ContactsGrid } from "@/components/customers/contacts/contact-grid"; +import { orpc } from "@/utils/orpc"; + +export const Route = createFileRoute( + "/_auth/customers/$customerId/branches/$branchId/" +)({ + loader: ({ context: { queryClient }, params: { customerId, branchId } }) => + Promise.all([ + queryClient.query( + orpc.branches.get.queryOptions({ input: { id: branchId } }) + ), + queryClient.query( + orpc.customers.get.queryOptions({ input: { id: customerId } }) + ), + ]), + component: RouteComponent, + errorComponent: () => ( +

+ No se pudo cargar la sucursal. +

+ ), +}); + +const TABS = [ + { value: "info", label: "Información general", icon: Info }, + { value: "quotations", label: "Cotizaciones", icon: FileText }, + { value: "files", label: "Archivos", icon: FolderOpen }, + { value: "contacts", label: "Contactos", icon: Users }, + { + value: "technical-requirements", + label: "Requerimientos Técnicos", + icon: HardHat, + }, +] as const; + +function RouteComponent() { + const { customerId, branchId } = Route.useParams(); + const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false); + + // Lee el caché de queries (no el loader) para que ediciones y archivados se reflejen. + const { data: branch } = useSuspenseQuery( + orpc.branches.get.queryOptions({ input: { id: branchId } }) + ); + + const { data: customer } = useSuspenseQuery( + orpc.customers.get.queryOptions({ input: { id: customerId } }) + ); + + const placeholder = "/placeholder.webp"; + const branchImage = branch.frontImageUrl ?? placeholder; + + const content: Record<(typeof TABS)[number]["value"], ReactNode> = { + info: ( + {}} + // eslint-disable-next-line no-empty-function -- pendiente de implementar + onImageUpload={() => {}} + /> + ), + contacts: , + quotations: null, + files: null, + "technical-requirements": null, + }; + + return ( +
+ setIsUpdateFormOpen(true)} + /> + + + + {TABS.map(({ value, label, icon: Icon }) => ( + + + {label} + + ))} + + + {TABS.map(({ value }) => ( + + {content[value]} + + ))} + + + +
+ ); +} diff --git a/apps/web/src/routes/_auth/customers/$customerId/index.tsx b/apps/web/src/routes/_auth/customers/$customerId/index.tsx index 7b2f8e7..9958bc4 100644 --- a/apps/web/src/routes/_auth/customers/$customerId/index.tsx +++ b/apps/web/src/routes/_auth/customers/$customerId/index.tsx @@ -1,5 +1,10 @@ import { buttonVariants } from "@suni/ui/components/button"; -import { Tabs, TabsList, TabsTrigger } from "@suni/ui/components/tabs"; +import { + Tabs, + TabsList, + TabsTrigger, + TabsContent, +} from "@suni/ui/components/tabs"; import { cn } from "@suni/ui/lib/utils"; import { useSuspenseQuery } from "@tanstack/react-query"; import { createFileRoute, Link } from "@tanstack/react-router"; @@ -13,6 +18,8 @@ import { Users, } from "lucide-react"; +import { BranchesGrid } from "@/components/customers/branches/grid"; +import { ContactsGrid } from "@/components/customers/contacts/contact-grid"; import { CustomerData } from "@/components/customers/data"; import { orpc } from "@/utils/orpc"; @@ -92,6 +99,12 @@ function RouteComponent() { ))} + + + + + +
); diff --git a/packages/api/src/routers/branches/create.ts b/packages/api/src/routers/branches/create.ts new file mode 100644 index 0000000..1a586ee --- /dev/null +++ b/packages/api/src/routers/branches/create.ts @@ -0,0 +1,18 @@ +import { branch } from "@suni/db/schema/branches"; +import { createBranchSchema } from "@suni/db/validation/branches"; + +import { protectedProcedure } from "../../index"; + +export const create = protectedProcedure + .route({ method: "POST", path: "/" }) + .input(createBranchSchema) + .handler(async ({ input, context }) => { + const userId = context.session.user.id; + + const [created] = await context.db + .insert(branch) + .values({ ...input, sellerId: userId, modifiedBy: userId }) + .returning({ id: branch.id }); + + return created; + }); diff --git a/packages/api/src/routers/branches/get.ts b/packages/api/src/routers/branches/get.ts new file mode 100644 index 0000000..c72e0f9 --- /dev/null +++ b/packages/api/src/routers/branches/get.ts @@ -0,0 +1,29 @@ +import { ORPCError } from "@orpc/server"; +import { z } from "zod"; + +import { isAdmin, protectedProcedure } from "../../index"; + +export const get = protectedProcedure + .route({ method: "GET", path: "/{id}" }) + .input(z.object({ id: z.string() })) + .handler(async ({ input, context }) => { + const admin = await isAdmin(context, context.session.user.id); + + const found = await context.db.query.branch.findFirst({ + where: admin + ? { id: input.id } + : { id: input.id, sellerId: context.session.user.id }, + columns: admin ? undefined : { sellerId: false, modifiedBy: false }, + with: { + customer: { columns: { id: true, name: true, archived: true } }, + contacts: true, + ...(admin && { seller: { columns: { id: true, name: true } } }), + }, + }); + + if (!found) { + throw new ORPCError("NOT_FOUND", { message: "Branch not found" }); + } + + return admin ? found : { ...found, seller: null }; + }); diff --git a/packages/api/src/routers/branches/index.ts b/packages/api/src/routers/branches/index.ts new file mode 100644 index 0000000..708dd61 --- /dev/null +++ b/packages/api/src/routers/branches/index.ts @@ -0,0 +1,11 @@ +import { o } from "../../index"; +import { create } from "./create"; +import { get } from "./get"; +import { list } from "./list"; +import { setArchived } from "./set-archived"; +import { update } from "./update"; + +export const branchesRouter = o + .prefix("/branches") + .tag("Branches") + .router({ list, get, create, update, setArchived }); diff --git a/packages/api/src/routers/branches/list.ts b/packages/api/src/routers/branches/list.ts new file mode 100644 index 0000000..cf4990c --- /dev/null +++ b/packages/api/src/routers/branches/list.ts @@ -0,0 +1,47 @@ +import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; +import { z } from "zod"; + +import { isAdmin, protectedProcedure } from "../../index"; +import { statusWhere } from "../../util/status"; + +export const list = protectedProcedure + .route({ method: "GET", path: "/" }) + .input( + z.object({ + customerId: z.string().optional(), + status: z.enum(CUSTOMER_STATUSES).default("active"), + }) + ) + .handler(async ({ input, context }) => { + const userId = context.session.user.id; + + const where = { + AND: [ + statusWhere("branch", input.status), + ...(input.customerId ? [{ customerId: input.customerId }] : []), + ], + }; + + if (await isAdmin(context, userId)) { + return context.db.query.branch.findMany({ + where, + with: { + customer: { columns: { id: true, name: true, archived: true } }, + seller: { columns: { id: true, name: true } }, + contacts: true, + }, + }); + } + + // Seller identity is admin-only. + const rows = await context.db.query.branch.findMany({ + where: { AND: [where, { sellerId: userId }] }, + columns: { sellerId: false, modifiedBy: false }, + with: { + customer: { columns: { id: true, name: true, archived: true } }, + contacts: true, + }, + }); + + return rows.map((row) => ({ ...row, seller: null })); + }); diff --git a/packages/api/src/routers/branches/set-archived.ts b/packages/api/src/routers/branches/set-archived.ts new file mode 100644 index 0000000..0339bee --- /dev/null +++ b/packages/api/src/routers/branches/set-archived.ts @@ -0,0 +1,35 @@ +import { ORPCError } from "@orpc/server"; +import { branch } from "@suni/db/schema/branches"; +import { and, eq, sql } from "drizzle-orm"; +import { z } from "zod"; + +import { isAdmin, protectedProcedure } from "../../index"; + +export const setArchived = protectedProcedure + .route({ method: "POST", path: "/{id}/archived" }) + .input(z.object({ id: z.string(), archived: z.boolean() })) + .handler(async ({ input, context }) => { + const userId = context.session.user.id; + const admin = await isAdmin(context, userId); + + const [updated] = await context.db + .update(branch) + .set({ + archived: input.archived + ? sql`COALESCE(${branch.archived}, now())` + : null, + modifiedBy: userId, + }) + .where( + admin + ? eq(branch.id, input.id) + : and(eq(branch.id, input.id), eq(branch.sellerId, userId)) + ) + .returning({ id: branch.id }); + + if (!updated) { + throw new ORPCError("NOT_FOUND", { message: "Branch not found" }); + } + + return updated; + }); diff --git a/packages/api/src/routers/branches/update.ts b/packages/api/src/routers/branches/update.ts new file mode 100644 index 0000000..43c8152 --- /dev/null +++ b/packages/api/src/routers/branches/update.ts @@ -0,0 +1,44 @@ +import { ORPCError } from "@orpc/server"; +import { branch } from "@suni/db/schema/branches"; +import { updateBranchSchema } from "@suni/db/validation/branches"; +import { and, eq, isNull } from "drizzle-orm"; +import { z } from "zod"; + +import { isAdmin, protectedProcedure } from "../../index"; + +export const update = protectedProcedure + .route({ method: "PATCH", path: "/{id}" }) + .input(updateBranchSchema.omit({ archived: true }).extend({ id: z.string() })) + .handler(async ({ input, context }) => { + const { id, ...fields } = input; + + const userId = context.session.user.id; + + if (Object.values(fields).every((v) => v === undefined)) { + throw new ORPCError("BAD_REQUEST", { + message: "No hay campos para actualizar", + }); + } + + const admin = await isAdmin(context, userId); + + const [updated] = await context.db + .update(branch) + .set({ ...fields, modifiedBy: userId }) + .where( + and( + eq(branch.id, id), + isNull(branch.archived), + admin ? undefined : eq(branch.sellerId, userId) + ) + ) + .returning({ id: branch.id }); + + if (!updated) { + throw new ORPCError("NOT_FOUND", { + message: "La sucursal no existe o está archivada", + }); + } + + return updated; + }); diff --git a/packages/api/src/routers/contacts/create.ts b/packages/api/src/routers/contacts/create.ts new file mode 100644 index 0000000..9f3e56f --- /dev/null +++ b/packages/api/src/routers/contacts/create.ts @@ -0,0 +1,37 @@ +import { ORPCError } from "@orpc/server"; +import { contact } from "@suni/db/schema/contacts"; +import { createContactSchema } from "@suni/db/validation/contacts"; + +import { isAdmin, protectedProcedure } from "../../index"; + +export const create = protectedProcedure + .route({ method: "POST", path: "/" }) + .input(createContactSchema) + .handler(async ({ input, context }) => { + const userId = context.session.user.id; + const admin = await isAdmin(context, userId); + + const parent = await context.db.query.branch.findFirst({ + where: { + id: input.branchId, + customerId: input.customerId, + archived: { isNull: true }, + sellerId: admin ? undefined : userId, + }, + columns: { id: true }, + }); + + if (!parent) { + throw new ORPCError("NOT_FOUND", { + message: + "La sucursal no existe, está archivada o no pertenece al cliente", + }); + } + + const [created] = await context.db + .insert(contact) + .values({ ...input, modifiedBy: userId }) + .returning({ id: contact.id }); + + return created; + }); diff --git a/packages/api/src/routers/contacts/get.ts b/packages/api/src/routers/contacts/get.ts new file mode 100644 index 0000000..4a2cc90 --- /dev/null +++ b/packages/api/src/routers/contacts/get.ts @@ -0,0 +1,30 @@ +import { ORPCError } from "@orpc/server"; +import { z } from "zod"; + +import { isAdmin, protectedProcedure } from "../../index"; + +export const get = protectedProcedure + .route({ method: "GET", path: "/{id}" }) + .input(z.object({ id: z.string() })) + .handler(async ({ input, context }) => { + const userId = context.session.user.id; + const admin = await isAdmin(context, userId); + + const found = await context.db.query.contact.findFirst({ + where: { + id: input.id, + branch: admin ? undefined : { sellerId: userId }, + }, + columns: admin ? undefined : { modifiedBy: false }, + with: { + branch: { columns: { id: true, name: true, archived: true } }, + customer: { columns: { id: true, name: true, archived: true } }, + }, + }); + + if (!found) { + throw new ORPCError("NOT_FOUND", { message: "Contact not found" }); + } + + return found; + }); diff --git a/packages/api/src/routers/contacts/index.ts b/packages/api/src/routers/contacts/index.ts new file mode 100644 index 0000000..7d49128 --- /dev/null +++ b/packages/api/src/routers/contacts/index.ts @@ -0,0 +1,11 @@ +import { o } from "../../index"; +import { create } from "./create"; +import { get } from "./get"; +import { list } from "./list"; +import { setArchived } from "./set-archived"; +import { update } from "./update"; + +export const contactsRouter = o + .prefix("/contacts") + .tag("Contacts") + .router({ list, get, create, update, setArchived }); diff --git a/packages/api/src/routers/contacts/list.ts b/packages/api/src/routers/contacts/list.ts new file mode 100644 index 0000000..a81448d --- /dev/null +++ b/packages/api/src/routers/contacts/list.ts @@ -0,0 +1,34 @@ +import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; +import { z } from "zod"; + +import { isAdmin, protectedProcedure } from "../../index"; +import { statusWhere } from "../../util/status"; + +export const list = protectedProcedure + .route({ method: "GET", path: "/" }) + .input( + z.object({ + customerId: z.string().optional(), + branchId: z.string().optional(), + status: z.enum(CUSTOMER_STATUSES).default("active"), + }) + ) + .handler(async ({ input, context }) => { + const userId = context.session.user.id; + const admin = await isAdmin(context, userId); + + return context.db.query.contact.findMany({ + where: { + AND: [ + statusWhere("contact", input.status), + { customerId: input.customerId, branchId: input.branchId }, + ...(admin ? [] : [{ branch: { sellerId: userId } }]), + ], + }, + columns: admin ? undefined : { modifiedBy: false }, + with: { + branch: { columns: { id: true, name: true, archived: true } }, + customer: { columns: { id: true, name: true, archived: true } }, + }, + }); + }); diff --git a/packages/api/src/routers/contacts/set-archived.ts b/packages/api/src/routers/contacts/set-archived.ts new file mode 100644 index 0000000..29fc631 --- /dev/null +++ b/packages/api/src/routers/contacts/set-archived.ts @@ -0,0 +1,45 @@ +import { ORPCError } from "@orpc/server"; +import { branch } from "@suni/db/schema/branches"; +import { contact } from "@suni/db/schema/contacts"; +import { and, eq, inArray, sql } from "drizzle-orm"; +import { z } from "zod"; + +import { isAdmin, protectedProcedure } from "../../index"; + +export const setArchived = protectedProcedure + .route({ method: "POST", path: "/{id}/archived" }) + .input(z.object({ id: z.string(), archived: z.boolean() })) + .handler(async ({ input, context }) => { + const userId = context.session.user.id; + const admin = await isAdmin(context, userId); + + const [updated] = await context.db + .update(contact) + .set({ + archived: input.archived + ? sql`COALESCE(${contact.archived}, now())` + : null, + modifiedBy: userId, + }) + .where( + and( + eq(contact.id, input.id), + admin + ? undefined + : inArray( + contact.branchId, + context.db + .select({ id: branch.id }) + .from(branch) + .where(eq(branch.sellerId, userId)) + ) + ) + ) + .returning({ id: contact.id }); + + if (!updated) { + throw new ORPCError("NOT_FOUND", { message: "Contact not found" }); + } + + return updated; + }); diff --git a/packages/api/src/routers/contacts/update.ts b/packages/api/src/routers/contacts/update.ts new file mode 100644 index 0000000..74e1a2f --- /dev/null +++ b/packages/api/src/routers/contacts/update.ts @@ -0,0 +1,56 @@ +import { ORPCError } from "@orpc/server"; +import { branch } from "@suni/db/schema/branches"; +import { contact } from "@suni/db/schema/contacts"; +import { updateContactSchema } from "@suni/db/validation/contacts"; +import { and, eq, inArray, isNull } from "drizzle-orm"; +import { z } from "zod"; + +import { isAdmin, protectedProcedure } from "../../index"; + +export const update = protectedProcedure + .route({ method: "PATCH", path: "/{id}" }) + .input( + updateContactSchema + .omit({ archived: true, customerId: true }) + .extend({ id: z.string() }) + ) + .handler(async ({ input, context }) => { + const { id, ...fields } = input; + const userId = context.session.user.id; + + if (Object.values(fields).every((v) => v === undefined)) { + throw new ORPCError("BAD_REQUEST", { + message: "No hay campos para actualizar", + }); + } + + const admin = await isAdmin(context, userId); + + const [updated] = await context.db + .update(contact) + .set({ ...fields, modifiedBy: userId }) + .where( + and( + eq(contact.id, id), + isNull(contact.archived), + admin + ? undefined + : inArray( + contact.branchId, + context.db + .select({ id: branch.id }) + .from(branch) + .where(eq(branch.sellerId, userId)) + ) + ) + ) + .returning({ id: contact.id }); + + if (!updated) { + throw new ORPCError("NOT_FOUND", { + message: "El contacto no existe o está archivado", + }); + } + + return updated; + }); diff --git a/packages/api/src/routers/index.ts b/packages/api/src/routers/index.ts index c3c34c1..7dbffa0 100644 --- a/packages/api/src/routers/index.ts +++ b/packages/api/src/routers/index.ts @@ -5,6 +5,8 @@ import type { } from "@orpc/server"; import { protectedProcedure, publicProcedure } from "../index"; +import { branchesRouter } from "./branches"; +import { contactsRouter } from "./contacts"; import { customersRouter } from "./customers"; import { usersRouter } from "./users"; @@ -16,6 +18,8 @@ export const appRouter = { })), users: usersRouter, customers: customersRouter, + branches: branchesRouter, + contacts: contactsRouter, }; export type AppRouter = typeof appRouter; diff --git a/packages/api/src/util/status.ts b/packages/api/src/util/status.ts new file mode 100644 index 0000000..45b3245 --- /dev/null +++ b/packages/api/src/util/status.ts @@ -0,0 +1,43 @@ +const isNull = { isNull: true } as const; + +const isNotNull = { isNotNull: true } as const; + +const visible = { + customer: { archived: isNull }, + branch: { archived: isNull, customer: { archived: isNull } }, + contact: { + archived: isNull, + branch: { archived: isNull }, + customer: { archived: isNull }, + }, +} as const; + +const archived = { + customer: { archived: isNotNull }, + branch: { + OR: [{ archived: isNotNull }, { customer: { archived: isNotNull } }], + }, + contact: { + OR: [ + { archived: isNotNull }, + { branch: { archived: isNotNull } }, + { customer: { archived: isNotNull } }, + ], + }, +} as const; + +type Entity = keyof typeof visible; + +type Status = "active" | "archived" | "all"; + +export function statusWhere(entity: Entity, status: Status) { + if (status === "all") { + return {}; + } + + if (status === "active") { + return visible[entity]; + } + + return archived[entity]; +} diff --git a/packages/db/src/migrations/20261106201415_organic_tomorrow_man/migration.sql b/packages/db/src/migrations/20261106201415_organic_tomorrow_man/migration.sql new file mode 100644 index 0000000..7c814c3 --- /dev/null +++ b/packages/db/src/migrations/20261106201415_organic_tomorrow_man/migration.sql @@ -0,0 +1,41 @@ +CREATE TABLE "customer_branches" ( + "id" text PRIMARY KEY, + "name" text NOT NULL, + "street" text NOT NULL, + "int_number" text, + "ext_number" text NOT NULL, + "city" text NOT NULL, + "suburb" text NOT NULL, + "state" text NOT NULL, + "postal_code" text NOT NULL, + "phone" text, + "front_image_url" text, + "customer_id" text NOT NULL, + "seller_id" text NOT NULL, + "modified_by" text NOT NULL, + "archived" timestamp, + "created_at" timestamp DEFAULT now() NOT NULL, + "updated_at" timestamp DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "contact" ( + "id" text PRIMARY KEY, + "name" text NOT NULL, + "email" text NOT NULL, + "phone" text NOT NULL, + "phone_extension" text, + "position" text, + "customer_id" text NOT NULL, + "branch_id" text, + "archived" timestamp, + "modified_by" text NOT NULL, + "created_at" timestamp DEFAULT now() NOT NULL, + "updated_at" timestamp DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "customer_branches" ADD CONSTRAINT "customer_branches_customer_id_customer_id_fkey" FOREIGN KEY ("customer_id") REFERENCES "customer"("id");--> statement-breakpoint +ALTER TABLE "customer_branches" ADD CONSTRAINT "customer_branches_seller_id_user_id_fkey" FOREIGN KEY ("seller_id") REFERENCES "user"("id");--> statement-breakpoint +ALTER TABLE "customer_branches" ADD CONSTRAINT "customer_branches_modified_by_user_id_fkey" FOREIGN KEY ("modified_by") REFERENCES "user"("id");--> statement-breakpoint +ALTER TABLE "contact" ADD CONSTRAINT "contact_customer_id_customer_id_fkey" FOREIGN KEY ("customer_id") REFERENCES "customer"("id");--> statement-breakpoint +ALTER TABLE "contact" ADD CONSTRAINT "contact_branch_id_customer_branches_id_fkey" FOREIGN KEY ("branch_id") REFERENCES "customer_branches"("id");--> statement-breakpoint +ALTER TABLE "contact" ADD CONSTRAINT "contact_modified_by_user_id_fkey" FOREIGN KEY ("modified_by") REFERENCES "user"("id"); \ No newline at end of file diff --git a/packages/db/src/migrations/20261106201415_organic_tomorrow_man/snapshot.json b/packages/db/src/migrations/20261106201415_organic_tomorrow_man/snapshot.json new file mode 100644 index 0000000..9848217 --- /dev/null +++ b/packages/db/src/migrations/20261106201415_organic_tomorrow_man/snapshot.json @@ -0,0 +1,1532 @@ +{ + "version": "8", + "dialect": "postgres", + "id": "31829c0c-39bb-4545-ada1-2829bb29f26d", + "prevIds": [ + "4f627249-c9fb-46cb-8f36-c4fa0305c360" + ], + "ddl": [ + { + "values": [ + "Redes sociales", + "Recomendación", + "Prospección", + "Teléfono", + "Correo", + "Página web", + "Díptico" + ], + "name": "acquisition", + "entityType": "enums", + "schema": "public" + }, + { + "values": [ + "Cliente", + "Asesor" + ], + "name": "customer_type", + "entityType": "enums", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "account", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "session", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "user", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "verification", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "customer_branches", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "contact", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "customer", + "entityType": "tables", + "schema": "public" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "account_id", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "provider_id", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "access_token", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "refresh_token", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id_token", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "access_token_expires_at", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "refresh_token_expires_at", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "scope", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "password", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "account" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "session" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires_at", + "entityType": "columns", + "schema": "public", + "table": "session" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "token", + "entityType": "columns", + "schema": "public", + "table": "session" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "session" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "session" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ip_address", + "entityType": "columns", + "schema": "public", + "table": "session" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_agent", + "entityType": "columns", + "schema": "public", + "table": "session" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "session" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "impersonated_by", + "entityType": "columns", + "schema": "public", + "table": "session" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "name", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "email", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "email_verified", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "image", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "role", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "banned", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ban_reason", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ban_expires", + "entityType": "columns", + "schema": "public", + "table": "user" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "verification" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "identifier", + "entityType": "columns", + "schema": "public", + "table": "verification" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "value", + "entityType": "columns", + "schema": "public", + "table": "verification" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires_at", + "entityType": "columns", + "schema": "public", + "table": "verification" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "verification" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "verification" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "name", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "street", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "int_number", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ext_number", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "city", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "suburb", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "state", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "postal_code", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "phone", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "front_image_url", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "customer_id", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "seller_id", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "modified_by", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "archived", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "customer_branches" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "name", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "email", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "phone", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "phone_extension", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "position", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "customer_id", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "branch_id", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "archived", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "modified_by", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "contact" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "name", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "rfc", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "street", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "int_number", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ext_number", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "city", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "suburb", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "state", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "postal_code", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "phone", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "phone_extension", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "acquisition", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "acquisition", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "customer_type", + "typeSchema": "public", + "notNull": true, + "dimensions": 0, + "default": "'Cliente'", + "generated": null, + "identity": null, + "name": "type", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "seller_id", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "modified_by", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "type": "timestamp", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "archived", + "entityType": "columns", + "schema": "public", + "table": "customer" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "account_userId_idx", + "entityType": "indexes", + "schema": "public", + "table": "account" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "session_userId_idx", + "entityType": "indexes", + "schema": "public", + "table": "session" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "identifier", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "verification_identifier_idx", + "entityType": "indexes", + "schema": "public", + "table": "verification" + }, + { + "nameExplicit": false, + "columns": [ + "user_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "account_user_id_user_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "account" + }, + { + "nameExplicit": false, + "columns": [ + "user_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "name": "session_user_id_user_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "session" + }, + { + "nameExplicit": false, + "columns": [ + "customer_id" + ], + "schemaTo": "public", + "tableTo": "customer", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "customer_branches_customer_id_customer_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "customer_branches" + }, + { + "nameExplicit": false, + "columns": [ + "seller_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "customer_branches_seller_id_user_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "customer_branches" + }, + { + "nameExplicit": false, + "columns": [ + "modified_by" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "customer_branches_modified_by_user_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "customer_branches" + }, + { + "nameExplicit": false, + "columns": [ + "customer_id" + ], + "schemaTo": "public", + "tableTo": "customer", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "contact_customer_id_customer_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "contact" + }, + { + "nameExplicit": false, + "columns": [ + "branch_id" + ], + "schemaTo": "public", + "tableTo": "customer_branches", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "contact_branch_id_customer_branches_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "contact" + }, + { + "nameExplicit": false, + "columns": [ + "modified_by" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "contact_modified_by_user_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "contact" + }, + { + "nameExplicit": false, + "columns": [ + "seller_id" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "customer_seller_id_user_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "customer" + }, + { + "nameExplicit": false, + "columns": [ + "modified_by" + ], + "schemaTo": "public", + "tableTo": "user", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "NO ACTION", + "name": "customer_modified_by_user_id_fkey", + "entityType": "fks", + "schema": "public", + "table": "customer" + }, + { + "columns": [ + "id" + ], + "nameExplicit": false, + "name": "account_pkey", + "schema": "public", + "table": "account", + "entityType": "pks" + }, + { + "columns": [ + "id" + ], + "nameExplicit": false, + "name": "session_pkey", + "schema": "public", + "table": "session", + "entityType": "pks" + }, + { + "columns": [ + "id" + ], + "nameExplicit": false, + "name": "user_pkey", + "schema": "public", + "table": "user", + "entityType": "pks" + }, + { + "columns": [ + "id" + ], + "nameExplicit": false, + "name": "verification_pkey", + "schema": "public", + "table": "verification", + "entityType": "pks" + }, + { + "columns": [ + "id" + ], + "nameExplicit": false, + "name": "customer_branches_pkey", + "schema": "public", + "table": "customer_branches", + "entityType": "pks" + }, + { + "columns": [ + "id" + ], + "nameExplicit": false, + "name": "contact_pkey", + "schema": "public", + "table": "contact", + "entityType": "pks" + }, + { + "columns": [ + "id" + ], + "nameExplicit": false, + "name": "customer_pkey", + "schema": "public", + "table": "customer", + "entityType": "pks" + }, + { + "nameExplicit": false, + "columns": [ + "token" + ], + "nullsNotDistinct": false, + "name": "session_token_key", + "schema": "public", + "table": "session", + "entityType": "uniques" + }, + { + "nameExplicit": false, + "columns": [ + "email" + ], + "nullsNotDistinct": false, + "name": "user_email_key", + "schema": "public", + "table": "user", + "entityType": "uniques" + } + ], + "renames": [] +} \ No newline at end of file diff --git a/packages/db/src/relations.ts b/packages/db/src/relations.ts index 46cf597..ee5736b 100644 --- a/packages/db/src/relations.ts +++ b/packages/db/src/relations.ts @@ -7,6 +7,8 @@ import { user, verification, } from "./schema/auth"; +import { branch } from "./schema/branches"; +import { contact } from "./schema/contacts"; import { customer } from "./schema/customers"; const customerRelations = defineRelationsPart({ customer, user }, (r) => ({ @@ -19,8 +21,57 @@ const customerRelations = defineRelationsPart({ customer, user }, (r) => ({ }, })); +const branchRelations = defineRelationsPart( + { branch, contact, customer, user }, + (r) => ({ + branch: { + customer: r.one.customer({ + from: r.branch.customerId, + to: r.customer.id, + optional: false, + }), + seller: r.one.user({ + from: r.branch.sellerId, + to: r.user.id, + optional: false, + }), + contacts: r.many.contact({ + from: r.branch.id, + to: r.contact.branchId, + }), + }, + }) +); + +const contactRelations = defineRelationsPart( + { branch, contact, customer }, + (r) => ({ + contact: { + customer: r.one.customer({ + from: r.contact.customerId, + to: r.customer.id, + optional: false, + }), + branch: r.one.branch({ + from: r.contact.branchId, + to: r.branch.id, + }), + }, + }) +); + export const relations = { - ...defineRelations({ account, session, user, verification, customer }), + ...defineRelations({ + account, + session, + user, + verification, + customer, + branch, + contact, + }), ...authRelations, ...customerRelations, + ...branchRelations, + ...contactRelations, }; diff --git a/packages/db/src/schema/branches.ts b/packages/db/src/schema/branches.ts new file mode 100644 index 0000000..376ab14 --- /dev/null +++ b/packages/db/src/schema/branches.ts @@ -0,0 +1,35 @@ +import { pgTable, text, timestamp } from "drizzle-orm/pg-core"; + +import { user } from "./auth"; +import { customer } from "./customers"; + +export const branch = pgTable("customer_branches", { + id: text("id") + .primaryKey() + .$defaultFn(() => crypto.randomUUID()), + name: text("name").notNull(), + street: text("street").notNull(), + intNumber: text("int_number"), + extNumber: text("ext_number").notNull(), + city: text("city").notNull(), + suburb: text("suburb").notNull(), + state: text("state").notNull(), + postalCode: text("postal_code").notNull(), + phone: text("phone"), + frontImageUrl: text("front_image_url"), + customerId: text("customer_id") + .notNull() + .references(() => customer.id), + sellerId: text("seller_id") + .notNull() + .references(() => user.id), + modifiedBy: text("modified_by") + .notNull() + .references(() => user.id), + archived: timestamp("archived"), + createdAt: timestamp("created_at").defaultNow().notNull(), + updatedAt: timestamp("updated_at") + .defaultNow() + .$onUpdate(() => new Date()) + .notNull(), +}); diff --git a/packages/db/src/schema/contacts.ts b/packages/db/src/schema/contacts.ts new file mode 100644 index 0000000..b745449 --- /dev/null +++ b/packages/db/src/schema/contacts.ts @@ -0,0 +1,29 @@ +import { pgTable, text, timestamp } from "drizzle-orm/pg-core"; + +import { user } from "./auth"; +import { branch } from "./branches"; +import { customer } from "./customers"; + +export const contact = pgTable("contact", { + id: text("id") + .primaryKey() + .$defaultFn(() => crypto.randomUUID()), + name: text("name").notNull(), + email: text("email").notNull(), + phone: text("phone").notNull(), + phoneExtension: text("phone_extension"), + position: text("position"), + customerId: text("customer_id") + .notNull() + .references(() => customer.id), + branchId: text("branch_id").references(() => branch.id), + archived: timestamp("archived"), + modifiedBy: text("modified_by") + .notNull() + .references(() => user.id), + createdAt: timestamp("created_at").defaultNow().notNull(), + updatedAt: timestamp("updated_at") + .defaultNow() + .$onUpdate(() => new Date()) + .notNull(), +}); diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 7f5f1ec..4cbb2bd 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -1,3 +1,7 @@ export * from "./auth"; +export * from "./branches"; + +export * from "./contacts"; + export * from "./customers"; diff --git a/packages/db/src/validation/branches.ts b/packages/db/src/validation/branches.ts new file mode 100644 index 0000000..639ced6 --- /dev/null +++ b/packages/db/src/validation/branches.ts @@ -0,0 +1,30 @@ +import { z } from "zod"; + +import { emptyToNull, required } from "./shared"; + +export const branchFormSchema = z.object({ + name: required("El nombre de la sucursal es requerido"), + street: required("La calle es requerida"), + intNumber: z.string().trim().max(20, "Máximo 20 caracteres"), + extNumber: required("El número exterior es requerido"), + city: required("El municipio es requerido"), + suburb: required("La colonia es requerida"), + state: required("El estado es requerido"), + postalCode: z.string().regex(/^\d{5}$/u, "Debe tener 5 dígitos"), + phone: z.string().regex(/^(?:\d{10})?$/u, "Debe tener 10 dígitos"), + frontImageUrl: z.string().trim().max(2048, "URL demasiado larga"), +}); + +export const branchInputSchema = branchFormSchema.extend({ + intNumber: emptyToNull(branchFormSchema.shape.intNumber), + phone: emptyToNull(branchFormSchema.shape.phone), + frontImageUrl: emptyToNull(branchFormSchema.shape.frontImageUrl), +}); + +export const createBranchSchema = branchInputSchema.extend({ + customerId: required("El cliente es requerido"), +}); + +export const updateBranchSchema = branchInputSchema.partial().extend({ + archived: z.coerce.date().nullable().optional(), +}); diff --git a/packages/db/src/validation/contacts.ts b/packages/db/src/validation/contacts.ts new file mode 100644 index 0000000..4008fc5 --- /dev/null +++ b/packages/db/src/validation/contacts.ts @@ -0,0 +1,26 @@ +import { z } from "zod"; + +import { emptyToNull, required } from "./shared"; + +export const contactFormSchema = z.object({ + name: required("El nombre es requerido"), + email: z.email("Correo inválido"), + phone: z.string().regex(/^(?:\d{10})?$/u, "Debe tener 10 dígitos"), + phoneExtension: z.string().regex(/^\d{0,10}$/u, "Solo dígitos"), + position: z.string().trim().max(255, "Máximo 255 caracteres"), +}); + +export const contactInputSchema = contactFormSchema.extend({ + phoneExtension: emptyToNull(contactFormSchema.shape.phoneExtension), + position: emptyToNull(contactFormSchema.shape.position), +}); + +export const createContactSchema = contactInputSchema.extend({ + customerId: required("El cliente es requerido"), + branchId: required("La sucursal es requerida"), +}); + +export const updateContactSchema = contactInputSchema.partial().extend({ + customerId: required("El cliente es requerido").optional(), + archived: z.coerce.date().nullable().optional(), +}); diff --git a/packages/db/src/validation/customers.ts b/packages/db/src/validation/customers.ts index deb281e..4d1b9b4 100644 --- a/packages/db/src/validation/customers.ts +++ b/packages/db/src/validation/customers.ts @@ -1,10 +1,7 @@ import { z } from "zod"; import { ACQUISITION_CHANNELS, CUSTOMER_TYPES } from "../schema/customer-enums"; - -function required(message = "Campo requerido") { - return z.string().trim().min(1, message).max(255, "Máximo 255 caracteres"); -} +import { emptyToNull, required } from "./shared"; // Shared by the web form and the API, so it must stay free of drizzle imports. export const customerFormSchema = z.object({ @@ -25,10 +22,6 @@ export const customerFormSchema = z.object({ type: z.enum(CUSTOMER_TYPES), }); -function emptyToNull(schema: z.ZodString) { - return schema.nullable().transform((value) => value || null); -} - // The form keeps "" for empty optional fields; the database stores null. export const customerInputSchema = customerFormSchema.extend({ intNumber: emptyToNull(customerFormSchema.shape.intNumber), diff --git a/packages/db/src/validation/shared.ts b/packages/db/src/validation/shared.ts new file mode 100644 index 0000000..2fe833a --- /dev/null +++ b/packages/db/src/validation/shared.ts @@ -0,0 +1,9 @@ +import { z } from "zod"; + +export function required(message = "Campo requerido") { + return z.string().trim().min(1, message).max(255, "Máximo 255 caracteres"); +} + +export function emptyToNull(schema: z.ZodString) { + return schema.nullable().transform((value) => value || null); +} diff --git a/packages/ui/src/components/dialog.tsx b/packages/ui/src/components/dialog.tsx new file mode 100644 index 0000000..4b22437 --- /dev/null +++ b/packages/ui/src/components/dialog.tsx @@ -0,0 +1,139 @@ +import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; +import { X } from "lucide-react"; +import * as React from "react"; + +import { cn } from "../lib/utils"; + +function Dialog(props: DialogPrimitive.Root.Props) { + return ; +} + +function DialogTrigger(props: DialogPrimitive.Trigger.Props) { + return ; +} + +function DialogPortal(props: DialogPrimitive.Portal.Props) { + return ; +} + +function DialogClose(props: DialogPrimitive.Close.Props) { + return ; +} + +function DialogOverlay({ + className, + ...props +}: DialogPrimitive.Backdrop.Props) { + return ( + + ); +} + +interface DialogContentProps extends DialogPrimitive.Popup.Props { + /** Muestra el botón "X" en la esquina superior derecha. */ + showCloseButton?: boolean; +} + +function DialogContent({ + className, + children, + showCloseButton = true, + ...props +}: DialogContentProps) { + return ( + + + + {children} + {showCloseButton && ( + + + Cerrar + + )} + + + ); +} + +function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) { + return ( + + ); +} + +function DialogDescription({ + className, + ...props +}: DialogPrimitive.Description.Props) { + return ( + + ); +} + +export { + Dialog, + DialogPortal, + DialogOverlay, + DialogTrigger, + DialogClose, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +}; \ No newline at end of file