diff --git a/apps/web/public/suni-logo.png b/apps/web/public/suni-logo.png new file mode 100644 index 0000000..3c5c27d Binary files /dev/null and b/apps/web/public/suni-logo.png differ diff --git a/apps/web/public/suni-mark.png b/apps/web/public/suni-mark.png new file mode 100644 index 0000000..95608fd Binary files /dev/null and b/apps/web/public/suni-mark.png differ diff --git a/apps/web/src/components/app-sidebar.tsx b/apps/web/src/components/app-sidebar.tsx index 1026c98..f879966 100644 --- a/apps/web/src/components/app-sidebar.tsx +++ b/apps/web/src/components/app-sidebar.tsx @@ -3,25 +3,69 @@ import { SidebarContent, SidebarFooter, SidebarHeader, + SidebarMenu, + SidebarMenuButton, + SidebarMenuItem, + SidebarRail, + useSidebar, } from "@suni/ui/components/sidebar"; +import { Link, useRouter } from "@tanstack/react-router"; +import { useEffect } from "react"; import type { ComponentProps } from "react"; import { NavMain } from "@/components/nav-bar"; +import { NavUser } from "@/components/nav-user"; export function AppSidebar(props: ComponentProps) { + const router = useRouter(); + const { setOpenMobile } = useSidebar(); + + // On mobile the menu is a sheet over the page; close it once a link navigates. + useEffect( + () => router.subscribe("onBeforeNavigate", () => setOpenMobile(false)), + [router, setOpenMobile] + ); + return ( - + -
Suni
+ + + } + > + + + } + tooltip="Suni" + > + + + +
-
- -
+
-
Footer
+
+
); } diff --git a/apps/web/src/components/customers/branches/branch-form.tsx b/apps/web/src/components/customers/branches/branch-form.tsx index b9a1f61..f58a1cf 100644 --- a/apps/web/src/components/customers/branches/branch-form.tsx +++ b/apps/web/src/components/customers/branches/branch-form.tsx @@ -97,7 +97,7 @@ export function BranchForm({ }} >
- + Datos generales
@@ -119,7 +119,7 @@ export function BranchForm({
- + Dirección
@@ -206,7 +206,7 @@ export function BranchForm({ disabled={submitting} onClick={onCancel} type="button" - variant="outline-destructive" + variant="outline" > Cancelar @@ -214,7 +214,6 @@ export function BranchForm({ className="w-full sm:w-auto" disabled={submitting} type="submit" - variant="green" > {submitting ? : null} {branch ? "Guardar" : "Crear"} diff --git a/apps/web/src/components/customers/branches/branch-header.tsx b/apps/web/src/components/customers/branches/branch-header.tsx index 794085e..4e3df8c 100644 --- a/apps/web/src/components/customers/branches/branch-header.tsx +++ b/apps/web/src/components/customers/branches/branch-header.tsx @@ -6,7 +6,7 @@ import { Link } from "@tanstack/react-router"; import { Archive, ArchiveRestore, Building2, Pencil } from "lucide-react"; import { useState } from "react"; -import { archiveState } from "../shared/archive-state"; +import { archiveState, archivedLabel } from "../shared/archive-state"; import { ChangeBranchStatusDialog } from "./change-branch-status-dialog"; type Branch = AppRouterOutputs["branches"]["get"]; @@ -17,8 +17,9 @@ interface BranchHeaderProps { } export function BranchHeader({ branch, onEdit }: BranchHeaderProps) { - const { isOwnArchived, isCustomerArchived, isArchived } = - archiveState(branch); + const archive = archiveState(branch); + + const { isOwnArchived, isCustomerArchived, isArchived } = archive; const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false); @@ -37,13 +38,13 @@ export function BranchHeader({ branch, onEdit }: BranchHeaderProps) {
@@ -51,7 +52,7 @@ export function BranchHeader({ branch, onEdit }: BranchHeaderProps) {

{branch.name} @@ -59,7 +60,7 @@ export function BranchHeader({ branch, onEdit }: BranchHeaderProps) { {isArchived ? ( - {isCustomerArchived ? "Cliente archivado" : "Archivada"} + {archivedLabel(archive, "Archivada")} ) : null}

@@ -80,7 +81,7 @@ export function BranchHeader({ branch, onEdit }: BranchHeaderProps) { {onEdit && !isCustomerArchived ? (
{isArchived ? null : ( - diff --git a/apps/web/src/components/customers/branches/branch-info.tsx b/apps/web/src/components/customers/branches/branch-info.tsx index 29af8ad..dbde801 100644 --- a/apps/web/src/components/customers/branches/branch-info.tsx +++ b/apps/web/src/components/customers/branches/branch-info.tsx @@ -27,7 +27,9 @@ export function BranchInfoContent({ return (
-

Dirección

+

+ Dirección +

@@ -47,7 +49,7 @@ export function BranchInfoContent({
-

+

Imagen de fachada

diff --git a/apps/web/src/components/customers/branches/card.tsx b/apps/web/src/components/customers/branches/card.tsx index a0e559d..47b0ea7 100644 --- a/apps/web/src/components/customers/branches/card.tsx +++ b/apps/web/src/components/customers/branches/card.tsx @@ -1,4 +1,3 @@ -import { Badge } from "@suni/ui/components/badge"; import { Button } from "@suni/ui/components/button"; import { DropdownMenu, @@ -19,10 +18,12 @@ import { Pencil, Phone, } from "lucide-react"; -import { useState } from "react"; +import { useRef, useState } from "react"; + +import { ArchivedFooter } from "@/components/customers/shared/archived-footer"; import { ArchiveMenuItem } from "../shared/archive-menu-item"; -import { archiveState } from "../shared/archive-state"; +import { archiveState, archivedLabel } from "../shared/archive-state"; import { BranchFormDialog } from "./branch-form-dialog"; import { ChangeBranchStatusDialog } from "./change-branch-status-dialog"; import { branchImageSrc, formatAddress } from "./util/branch-address"; @@ -53,32 +54,29 @@ function BranchImage({ name, src, isArchived }: BranchImageProps) { src={src} />
- {isArchived && ( - - - Archivada - - )}
); } export default function BranchCard({ branch, customer }: BranchCardProps) { - const { isOwnArchived, isCustomerArchived, isArchived, parentHint } = - archiveState(branch); + const archive = archiveState(branch); + const { isOwnArchived, isCustomerArchived, isArchived, parentHint } = archive; + const archivedText = archivedLabel(archive, "Archivada"); const [isUpdateFormOpen, setIsUpdateFormOpen] = useState(false); const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false); + const cardRef = useRef(null); const address = formatAddress(branch); return ( <>
{branch.name} + {archivedText ? ( + , {archivedText} + ) : null} @@ -117,7 +120,7 @@ export default function BranchCard({ branch, customer }: BranchCardProps) { "line-clamp-1 text-sm font-medium hover:underline", isCustomerArchived ? "text-muted-foreground" - : "text-success" + : "text-primary" )} params={{ customerId: customer.id }} title={customer.name} @@ -181,17 +184,29 @@ export default function BranchCard({ branch, customer }: BranchCardProps) { )}
- -
- - Ver detalles - - -
- + {archivedText ? ( + setIsStatusDialogOpen(true) + : undefined + } + /> + ) : ( + +
+ + Ver detalles + + +
+ + )}
; open: boolean; onOpenChange: (open: boolean) => void; + finalFocus?: RefObject; } export function ChangeBranchStatusDialog({ branch, open, onOpenChange, + finalFocus, }: ChangeBranchStatusDialogProps) { const mutation = useArchiveBranch(); return ( { - value: T; +interface Option { + value: string; 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 { + action?: ReactNode; + /** The status control, when the page has no status tabs. */ + children?: ReactNode; filters: BranchFilters; - hasFilters: boolean; onFiltersChange: (filters: BranchFilters) => void; customers?: { id: string; name: string }[]; } export function BranchesFilters({ filters, - hasFilters, onFiltersChange, customers, + action, + children, }: 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 customerOptions: Option[] = (customers ?? []).map((c) => ({ + value: c.id, + label: c.name, + })); const update = (patch: Partial) => onFiltersChange({ ...filters, ...patch }); return ( -
-
- update({ name: event.target.value })} - placeholder="Buscar por nombre de sucursal..." - type="text" - value={filters.name} - /> + update({ name })} + search={filters.name} + searchLabel="Buscar sucursal" + > + {customers ? ( | null) => - update({ status: option?.value ?? "all" }) + aria-label="Filtrar por cliente" + className="w-full sm:w-64" + isClearable + onChange={(option: Option | null) => + update({ customerId: option?.value ?? "all" }) + } + options={customerOptions} + // "all" is the empty state, so it shows as the placeholder and offers nothing to clear. + placeholder="Todos los clientes" + value={ + filters.customerId === "all" + ? null + : (customerOptions.find( + (opt) => opt.value === filters.customerId + ) ?? { + value: filters.customerId, + label: "Cliente seleccionado", + }) } - 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 - )} - /> -
- )} - - {hasFilters && ( -
- - Filtros activos: - - - {filters.name.trim() && ( - update({ name: "" })}> - Nombre: “{filters.name.trim()}” - - )} - - {filters.status !== "all" && ( - update({ status: "all" })}> - Estatus:{" "} - { - STATUS_OPTIONS.find((opt) => opt.value === filters.status) - ?.label - } - - )} - - {showCustomerFilter && selectedCustomerName && ( - update({ customerId: "all" })}> - Cliente:{" "} - {selectedCustomerName.length > MAX_CUSTOMER_BADGE_LENGTH - ? `${selectedCustomerName.slice(0, MAX_CUSTOMER_BADGE_LENGTH)}...` - : selectedCustomerName} - - )} - - -
- )} -
+ ) : null} + {children} + ); } diff --git a/apps/web/src/components/customers/branches/grid.tsx b/apps/web/src/components/customers/branches/grid.tsx index d9d1852..7b6d707 100644 --- a/apps/web/src/components/customers/branches/grid.tsx +++ b/apps/web/src/components/customers/branches/grid.tsx @@ -1,14 +1,24 @@ import { skipToken } from "@tanstack/react-query"; import { Building2 } from "lucide-react"; +import type { ReactNode } from "react"; import { useMemo, useState } from "react"; import { NewEntityButton } from "@/components/customers/new-entity-button"; import { EntityGrid } from "@/components/customers/shared/entity-grid"; import { DEFAULT_BRANCH_FILTERS, + byStatus, + countByStatus, matchingName, } from "@/components/customers/shared/filters"; -import type { BranchFilters } from "@/components/customers/shared/filters"; +import type { + BranchFilters, + StatusFilter, +} from "@/components/customers/shared/filters"; +import { + StatusSegmented, + StatusTabs, +} from "@/components/customers/shared/status-tabs"; import { useListBranches } from "@/hooks/use-branches"; import { useListCustomers } from "@/hooks/use-customers"; @@ -16,6 +26,7 @@ import BranchCard from "./card"; import { BranchesFilters } from "./filters"; interface BranchesListProps { + action?: ReactNode; filters: BranchFilters; onFiltersChange: (filters: BranchFilters) => void; /** Scopes the list to one customer and hides the customer filter. */ @@ -25,13 +36,14 @@ interface BranchesListProps { export function BranchesList({ filters, onFiltersChange, + action, customerId, }: BranchesListProps) { const pickedCustomerId = filters.customerId === "all" ? undefined : filters.customerId; const query = useListBranches({ - status: filters.status, + status: "all", customerId: customerId ?? pickedCustomerId, }); @@ -40,24 +52,38 @@ export function BranchesList({ customerId ? skipToken : { status: "all" } ); - const visibleBranches = useMemo( - () => matchingName(query.data ?? [], filters.name), + const rowsByStatus = useMemo( + () => byStatus(matchingName(query.data ?? [], filters.name)), [query.data, filters.name] ); + const visibleBranches = rowsByStatus[filters.status]; + const hasFilters = filters.name.trim() !== "" || - filters.status !== DEFAULT_BRANCH_FILTERS.status || (!customerId && filters.customerId !== DEFAULT_BRANCH_FILTERS.customerId); - return ( + const statusProps = { + counts: query.data ? countByStatus(rowsByStatus) : undefined, + gender: "feminine" as const, + onValueChange: (status: StatusFilter) => + onFiltersChange({ ...filters, status }), + value: filters.status, + }; + + // Inside the customer or branch detail the page already has tabs, so the status is a segmented control. + const isNested = customerId !== undefined; + + const list = ( <> + > + {isNested ? : null} + ); + + if (isNested) { + return list; + } + + return {list}; } interface BranchesGridProps { @@ -90,18 +122,20 @@ interface BranchesGridProps { } export function BranchesGrid({ customerId, canCreate }: BranchesGridProps) { - const [filters, setFilters] = useState(DEFAULT_BRANCH_FILTERS); + // An archived customer archives all its branches, so "Activas" would always be empty. + const [filters, setFilters] = useState({ + ...DEFAULT_BRANCH_FILTERS, + status: canCreate ? "active" : "all", + }); return (
-
-

Sucursales

- {canCreate ? ( - - ) : null} -
- + ) : null + } customerId={customerId} filters={filters} onFiltersChange={setFilters} diff --git a/apps/web/src/components/customers/change-customer-status-dialog.tsx b/apps/web/src/components/customers/change-customer-status-dialog.tsx index ae268a4..d278b15 100644 --- a/apps/web/src/components/customers/change-customer-status-dialog.tsx +++ b/apps/web/src/components/customers/change-customer-status-dialog.tsx @@ -1,4 +1,5 @@ import type { AppRouterOutputs } from "@suni/api/routers/index"; +import type { RefObject } from "react"; import { ChangeStatusDialog } from "@/components/customers/shared/change-status-dialog"; import { useArchiveCustomer } from "@/hooks/use-customers"; @@ -9,18 +10,21 @@ interface ChangeCustomerStatusDialogProps { customer: Pick; open: boolean; onOpenChange: (open: boolean) => void; + finalFocus?: RefObject; } export function ChangeCustomerStatusDialog({ customer, open, onOpenChange, + finalFocus, }: ChangeCustomerStatusDialogProps) { const mutation = useArchiveCustomer(); return ( ; open: boolean; onOpenChange: (open: boolean) => void; + finalFocus?: RefObject; } export function ChangeContactStatusDialog({ contact, open, onOpenChange, + finalFocus, }: ChangeContactStatusDialogProps) { const mutation = useArchiveContact(); return ( (null); return ( <>
@@ -188,6 +195,9 @@ export default function ContactCard({ contact, customer }: ContactCardProps) { )} > {contact.name} + {archivedText ? ( + , {archivedText} + ) : null} {contact.position && ( @@ -223,24 +233,27 @@ export default function ContactCard({ contact, customer }: ContactCardProps) { - {isArchived && ( -
- - - Archivado - -
- )} + {archivedText ? ( + setIsStatusDialogOpen(true) + : undefined + } + /> + ) : null}
{ - value: T; - label: string; -} - -const STATUS_OPTIONS: Option[] = [ - { value: "all", label: "Todos" }, - { value: "active", label: "Activos" }, - { value: "archived", label: "Archivados" }, -]; +import { FilterBar } from "@/components/customers/shared/filter-bar"; +import type { ContactFilters } from "@/components/customers/shared/filters"; interface ContactsFiltersProps { + action?: ReactNode; + /** The status control, when the page has no status tabs. */ + children?: ReactNode; filters: ContactFilters; - hasFilters: boolean; onFiltersChange: (filters: ContactFilters) => void; } export function ContactsFilters({ filters, - hasFilters, onFiltersChange, + action, + children, }: ContactsFiltersProps) { - const hasName = filters.name.trim() !== ""; - const hasStatus = filters.status !== "all"; - - 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)} - /> -
- - {hasFilters && ( -
- - Filtros activos: - - - {hasName && ( - update({ name: "" })}> - Nombre: “{filters.name.trim()}” - - )} - - {hasStatus && ( - update({ status: "all" })}> - Estatus: {statusLabel} - - )} - - -
- )} -
+ onFiltersChange({ ...filters, name })} + search={filters.name} + searchLabel="Buscar contacto" + > + {children} + ); } diff --git a/apps/web/src/components/customers/contacts/contact-form.tsx b/apps/web/src/components/customers/contacts/contact-form.tsx index 398ea9f..7d54aba 100644 --- a/apps/web/src/components/customers/contacts/contact-form.tsx +++ b/apps/web/src/components/customers/contacts/contact-form.tsx @@ -90,7 +90,7 @@ export function ContactForm({ }} >
- + Datos generales
@@ -118,7 +118,7 @@ export function ContactForm({
- + Contacto
@@ -162,7 +162,7 @@ export function ContactForm({ disabled={submitting} onClick={onCancel} type="button" - variant="outline-destructive" + variant="outline" > Cancelar @@ -170,7 +170,6 @@ export function ContactForm({ className="w-full sm:w-auto" disabled={submitting} type="submit" - variant="green" > {submitting ? : null} {contact ? "Guardar" : "Crear"} diff --git a/apps/web/src/components/customers/contacts/contact-grid.tsx b/apps/web/src/components/customers/contacts/contact-grid.tsx index 66f60fd..f0d9e63 100644 --- a/apps/web/src/components/customers/contacts/contact-grid.tsx +++ b/apps/web/src/components/customers/contacts/contact-grid.tsx @@ -1,19 +1,30 @@ import { Users } from "lucide-react"; +import type { ReactNode } from "react"; import { useMemo, useState } from "react"; import { NewEntityButton } from "@/components/customers/new-entity-button"; import { EntityGrid } from "@/components/customers/shared/entity-grid"; import { DEFAULT_CONTACT_FILTERS, + byStatus, + countByStatus, matchingName, } from "@/components/customers/shared/filters"; -import type { ContactFilters } from "@/components/customers/shared/filters"; +import type { + ContactFilters, + StatusFilter, +} from "@/components/customers/shared/filters"; +import { + StatusSegmented, + StatusTabs, +} from "@/components/customers/shared/status-tabs"; import { useListContacts } from "@/hooks/use-contacts"; import ContactCard from "./contact-card"; import { ContactsFilters } from "./contact-filters"; interface ContactsListProps { + action?: ReactNode; filters: ContactFilters; onFiltersChange: (filters: ContactFilters) => void; /** Scopes the list to one customer and hides the customer on each card. */ @@ -24,31 +35,44 @@ interface ContactsListProps { export function ContactsList({ filters, onFiltersChange, + action, customerId, branchId, }: ContactsListProps) { const query = useListContacts({ - status: filters.status, + status: "all", customerId, branchId, }); - const visibleContacts = useMemo( - () => matchingName(query.data ?? [], filters.name), + const rowsByStatus = useMemo( + () => byStatus(matchingName(query.data ?? [], filters.name)), [query.data, filters.name] ); - const hasFilters = - filters.name.trim() !== "" || - filters.status !== DEFAULT_CONTACT_FILTERS.status; + const visibleContacts = rowsByStatus[filters.status]; - return ( + const hasFilters = filters.name.trim() !== ""; + + const statusProps = { + counts: query.data ? countByStatus(rowsByStatus) : undefined, + onValueChange: (status: StatusFilter) => + onFiltersChange({ ...filters, status }), + value: filters.status, + }; + + // Inside the customer or branch detail the page already has tabs, so the status is a segmented control. + const isNested = customerId !== undefined; + + const list = ( <> + > + {isNested ? : null} + ); + + if (isNested) { + return list; + } + + return {list}; } interface ContactsGridProps { @@ -86,22 +116,24 @@ export function ContactsGrid({ branchId, canCreate, }: ContactsGridProps) { - const [filters, setFilters] = useState(DEFAULT_CONTACT_FILTERS); + // An archived parent archives everything under it, so "Activos" would always be empty. + const [filters, setFilters] = useState({ + ...DEFAULT_CONTACT_FILTERS, + status: canCreate ? "active" : "all", + }); return (
-
-

Contactos

- {canCreate ? ( - - ) : null} -
- + ) : null + } branchId={branchId} customerId={customerId} filters={filters} diff --git a/apps/web/src/components/customers/customer-card.tsx b/apps/web/src/components/customers/customer-card.tsx index 5db172f..1361635 100644 --- a/apps/web/src/components/customers/customer-card.tsx +++ b/apps/web/src/components/customers/customer-card.tsx @@ -1,5 +1,4 @@ import type { AppRouterOutputs } from "@suni/api/routers/index"; -import { Badge } from "@suni/ui/components/badge"; import { Button } from "@suni/ui/components/button"; import { DropdownMenu, @@ -20,7 +19,9 @@ import { Pencil, UserRound, } from "lucide-react"; -import { useState } from "react"; +import { useRef, useState } from "react"; + +import { ArchivedFooter } from "@/components/customers/shared/archived-footer"; import { ChangeCustomerStatusDialog } from "./change-customer-status-dialog"; @@ -31,15 +32,17 @@ interface CustomerCardProps { export default function CustomerCard({ customer }: CustomerCardProps) { const isArchived = !!customer.archived; const [isStatusDialogOpen, setIsStatusDialogOpen] = useState(false); + const cardRef = useRef(null); return ( <>
@@ -52,10 +55,15 @@ export default function CustomerCard({ customer }: CustomerCardProps) {

{customer.name} + {isArchived ? ( + , Archivado + ) : null}

@@ -134,30 +142,31 @@ export default function CustomerCard({ customer }: CustomerCardProps) {
- - {/* Archived badge */} - {isArchived && ( -
- - - Archivado - -
- )}
- {/* View details footer */} - -
- - Ver detalles - - -
- + {isArchived ? ( + setIsStatusDialogOpen(true)} + /> + ) : ( + +
+ + Ver detalles + + +
+ + )}
; -const statusOptions: { value: Search["status"]; label: string }[] = [ - { value: "active", label: "Clientes activos" }, - { value: "archived", label: "Clientes archivados" }, - { value: "all", label: "Todos los clientes" }, +const TYPE_OPTIONS: { value: Search["type"]; label: string }[] = [ + { value: "all", label: "Todos" }, + ...CUSTOMER_TYPES.map((value) => ({ value, label: value })), ]; interface CustomerFiltersProps { + /** Customers in the current tab and search, before the type filter, for the counts. */ customers: AppRouterOutputs["customers"]["list"][number][]; - hasFilters: boolean; } -export default function CustomerFilters({ - customers, - hasFilters, -}: CustomerFiltersProps) { - const { name, type, status } = routeApi.useSearch(); +export default function CustomerFilters({ customers }: CustomerFiltersProps) { + const { name, type } = routeApi.useSearch(); const navigate = routeApi.useNavigate(); const setFilters = (filters: Partial) => navigate({ search: (prev) => ({ ...prev, ...filters }), replace: true }); - const typeOptions = useMemo(() => { - const count = (value: string) => - customers.filter((customer) => customer.type === value).length; - - return [ - { - value: "all" as const, - label: `Todos los tipos (${customers.length})`, - }, - ...CUSTOMER_TYPES.map((value) => ({ - value, - label: `${value} (${count(value)})`, - })), - ]; - }, [customers]); + const countOf = (value: Search["type"]) => + value === "all" + ? customers.length + : customers.filter((customer) => customer.type === value).length; return ( -
-
- setFilters({ name: event.target.value })} - placeholder="Buscar por nombre..." - type="search" - value={name} - /> -
- setFilters({ type: option?.value ?? "all" })} - options={typeOptions} - placeholder="Filtrar por tipo..." - value={typeOptions.find((option) => option.value === type)} - /> - setFilters({ status: option?.value ?? "active" })} - options={statusOptions} - value={statusOptions.find((option) => option.value === status)} + setFilters({ name: value })} + search={name} + searchLabel="Buscar por nombre" + > + setFilters({ type: value })} + options={TYPE_OPTIONS.map((option) => ({ + ...option, + count: countOf(option.value), + }))} + value={type} /> - {hasFilters && ( - // Empty search falls back to the schema defaults. - - )} -
+ ); } diff --git a/apps/web/src/components/customers/customer-form.tsx b/apps/web/src/components/customers/customer-form.tsx index a1121b8..8c60df6 100644 --- a/apps/web/src/components/customers/customer-form.tsx +++ b/apps/web/src/components/customers/customer-form.tsx @@ -119,7 +119,7 @@ export function CustomerForm({ customer }: CustomerFormProps) { }} >
- + Datos generales
@@ -181,7 +181,7 @@ export function CustomerForm({ customer }: CustomerFormProps) {
- + Dirección
@@ -278,16 +278,11 @@ export function CustomerForm({ customer }: CustomerFormProps) { ) } - variant="outline-destructive" + variant="outline" > Cancelar - diff --git a/apps/web/src/components/customers/data.tsx b/apps/web/src/components/customers/data.tsx index 396f50c..c000ff8 100644 --- a/apps/web/src/components/customers/data.tsx +++ b/apps/web/src/components/customers/data.tsx @@ -1,62 +1,67 @@ import type { AppRouterOutputs } from "@suni/api/routers/index"; +import { cn } from "@suni/ui/lib/utils"; import { Link } from "@tanstack/react-router"; - -import { formatDate } from "@/lib/date-utils"; +import type { ReactNode } from "react"; interface CustomerDataProps { customer: AppRouterOutputs["customers"]["get"]; } -export function CustomerData({ customer }: CustomerDataProps) { +function Field({ + label, + className, + children, +}: { + label: string; + className?: string; + children: ReactNode; +}) { return ( -
-
-
-
Medio de adquisición:
-
{customer.acquisition}
-
- - {customer.seller && ( -
-
Vendedor:
-
- - {customer.seller.name} - -
-
- )} -
+
+
{label}
+
{children}
+
+ ); +} -
-

Dirección Fiscal

-
- +export function CustomerData({ customer }: CustomerDataProps) { + return ( +
+
+ +
{customer.street}, No. Ext. {customer.extNumber} {customer.intNumber && `, No. Int. ${customer.intNumber}`}, Colonia{" "} {customer.suburb} - - +
{`${customer.city}, ${customer.state}, CP ${customer.postalCode}`} +
+
+ + + + {customer.phone} + {customer.phoneExtension && ` ext. ${customer.phoneExtension}`} -
-
+ -
-
Teléfono:
-
- {customer.phone} - {customer.phoneExtension && ` ext. ${customer.phoneExtension}`} -
-
+ {customer.acquisition} - - Última actualización: {formatDate(customer.updatedAt)} - -
+ {customer.seller ? ( + + + {customer.seller.name} + + + ) : null} + +
); } diff --git a/apps/web/src/components/customers/new-entity-button.tsx b/apps/web/src/components/customers/new-entity-button.tsx index 02225c1..906cfaf 100644 --- a/apps/web/src/components/customers/new-entity-button.tsx +++ b/apps/web/src/components/customers/new-entity-button.tsx @@ -188,7 +188,6 @@ export function NewEntityButton({ - diff --git a/apps/web/src/components/customers/shared/archive-state.ts b/apps/web/src/components/customers/shared/archive-state.ts index e0cc6aa..cd25112 100644 --- a/apps/web/src/components/customers/shared/archive-state.ts +++ b/apps/web/src/components/customers/shared/archive-state.ts @@ -4,6 +4,12 @@ interface Archivable { branch?: { archived: unknown } | null; } +const INHERITED_FROM = { + customer: " con el cliente", + branch: " con la sucursal", + self: "", +} as const; + // Mirrors the API rule: an archived customer or branch archives everything under it. export function archiveState(entity: Archivable) { const isOwnArchived = !!entity.archived; @@ -18,7 +24,19 @@ export function archiveState(entity: Archivable) { parentHint = "Desarchiva primero la sucursal"; } + // Parent first, like parentHint: the parent is what has to be unarchived first. + let archivedBy: keyof typeof INHERITED_FROM | null = null; + + if (isCustomerArchived) { + archivedBy = "customer"; + } else if (isBranchArchived) { + archivedBy = "branch"; + } else if (isOwnArchived) { + archivedBy = "self"; + } + return { + archivedBy, isOwnArchived, isCustomerArchived, isBranchArchived, @@ -26,3 +44,11 @@ export function archiveState(entity: Archivable) { parentHint, }; } + +/** "Archivado", "Archivada con el cliente"…, shared by cards and detail headers. */ +export function archivedLabel( + { archivedBy }: ReturnType, + base: "Archivado" | "Archivada" +) { + return archivedBy ? `${base}${INHERITED_FROM[archivedBy]}` : null; +} diff --git a/apps/web/src/components/customers/shared/archived-footer.tsx b/apps/web/src/components/customers/shared/archived-footer.tsx new file mode 100644 index 0000000..4657728 --- /dev/null +++ b/apps/web/src/components/customers/shared/archived-footer.tsx @@ -0,0 +1,35 @@ +import { Button } from "@suni/ui/components/button"; +import { Archive } from "lucide-react"; + +interface ArchivedFooterProps { + label: string; + /** Names the card for screen readers, since every archived card has its own "Desarchivar". */ + name: string; + /** Absent when a parent is archived: that parent has to be unarchived first. */ + onUnarchive?: () => void; +} + +/** Closes an archived card with its state and, when possible, the way back. The title carries the state for screen readers. */ +export function ArchivedFooter({ + label, + name, + onUnarchive, +}: ArchivedFooterProps) { + return ( +
+ + + {label} + + {onUnarchive ? ( + + ) : null} +
+ ); +} diff --git a/apps/web/src/components/customers/shared/change-status-dialog.tsx b/apps/web/src/components/customers/shared/change-status-dialog.tsx index 356401a..8d85354 100644 --- a/apps/web/src/components/customers/shared/change-status-dialog.tsx +++ b/apps/web/src/components/customers/shared/change-status-dialog.tsx @@ -9,6 +9,7 @@ import { AlertDialogTitle, } from "@suni/ui/components/alert-dialog"; import { useState } from "react"; +import type { RefObject } from "react"; const ACTIONS = { archive: { @@ -40,6 +41,8 @@ interface ChangeStatusDialogProps { mutation: ArchiveMutation; open: boolean; onOpenChange: (open: boolean) => void; + /** Where focus lands on close; the button that opened the dialog may be gone once the status flips. */ + finalFocus?: RefObject; } export function ChangeStatusDialog({ @@ -48,6 +51,7 @@ export function ChangeStatusDialog({ mutation, open, onOpenChange, + finalFocus, }: ChangeStatusDialogProps) { // Freeze the status seen on open: the refetch after saving lands before the close animation ends. const [archivedOnOpen, setArchivedOnOpen] = useState(!!entity.archived); @@ -68,7 +72,7 @@ export function ChangeStatusDialog({ onOpenChange={(next) => !mutation.isPending && onOpenChange(next)} open={open} > - + ¿Quieres {action.label.toLowerCase()} {noun} {entity.name}? diff --git a/apps/web/src/components/customers/shared/filter-badge.tsx b/apps/web/src/components/customers/shared/filter-badge.tsx deleted file mode 100644 index f06b74e..0000000 --- a/apps/web/src/components/customers/shared/filter-badge.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { X } from "lucide-react"; -import type { ReactNode } from "react"; - -interface FilterBadgeProps { - children: ReactNode; - onClear: () => void; -} - -export function FilterBadge({ children, onClear }: FilterBadgeProps) { - return ( - - ); -} diff --git a/apps/web/src/components/customers/shared/filter-bar.tsx b/apps/web/src/components/customers/shared/filter-bar.tsx new file mode 100644 index 0000000..fec2175 --- /dev/null +++ b/apps/web/src/components/customers/shared/filter-bar.tsx @@ -0,0 +1,67 @@ +import { + InputGroup, + InputGroupAddon, + InputGroupButton, + InputGroupInput, +} from "@suni/ui/components/input-group"; +import { Search, X } from "lucide-react"; +import { useRef } from "react"; +import type { ReactNode } from "react"; + +interface FilterBarProps { + search: string; + searchLabel: string; + onSearchChange: (search: string) => void; + /** The filters, each sized by its caller, at the end of the row. */ + children?: ReactNode; + action?: ReactNode; +} + +export function FilterBar({ + search, + searchLabel, + onSearchChange, + children, + action, +}: FilterBarProps) { + const searchRef = useRef(null); + + // The clear button unmounts with the text, so focus goes back to the search instead of the page. + const clear = () => { + onSearchChange(""); + searchRef.current?.focus(); + }; + + return ( +
+ + + + + onSearchChange(event.target.value)} + placeholder={`${searchLabel}...`} + ref={searchRef} + type="search" + value={search} + /> + {search ? ( + + + + + + ) : null} + + {children} + {action} +
+ ); +} diff --git a/apps/web/src/components/customers/shared/filters.ts b/apps/web/src/components/customers/shared/filters.ts index 8ee4b3e..329dec7 100644 --- a/apps/web/src/components/customers/shared/filters.ts +++ b/apps/web/src/components/customers/shared/filters.ts @@ -2,6 +2,8 @@ import type { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; import { stripAccents } from "@/lib/string-utils"; +import { archiveState } from "./archive-state"; + export type StatusFilter = (typeof CUSTOMER_STATUSES)[number]; export interface BranchFilters { @@ -12,7 +14,7 @@ export interface BranchFilters { export const DEFAULT_BRANCH_FILTERS: BranchFilters = { name: "", - status: "all", + status: "active", customerId: "all", }; @@ -23,9 +25,27 @@ export interface ContactFilters { export const DEFAULT_CONTACT_FILTERS: ContactFilters = { name: "", - status: "all", + status: "active", }; +/** Rows per status tab, using the same archive rule as the API. */ +export function byStatus[0]>( + rows: readonly T[] +): Record { + const archived = rows.filter((row) => archiveState(row).isArchived); + const active = rows.filter((row) => !archiveState(row).isArchived); + + return { active, archived, all: [...rows] }; +} + +export function countByStatus(byStatusRows: Record) { + return { + active: byStatusRows.active.length, + archived: byStatusRows.archived.length, + all: byStatusRows.all.length, + }; +} + export function byName(a: { name: string }, b: { name: string }) { return a.name.localeCompare(b.name, "es"); } diff --git a/apps/web/src/components/customers/shared/segmented-control.tsx b/apps/web/src/components/customers/shared/segmented-control.tsx new file mode 100644 index 0000000..211c525 --- /dev/null +++ b/apps/web/src/components/customers/shared/segmented-control.tsx @@ -0,0 +1,45 @@ +import { useId } from "react"; + +interface SegmentedControlProps { + legend: string; + value: T; + onValueChange: (value: T) => void; + /** `count` is omitted while loading, so no option shows a false zero. */ + options: readonly { value: T; label: string; count?: number }[]; +} + +/** Radios styled as segments: for a few options that should stay visible instead of hiding in a select. */ +export function SegmentedControl({ + legend, + value, + onValueChange, + options, +}: SegmentedControlProps) { + const name = useId(); + + return ( +
+ {legend} + {options.map((option) => ( + + ))} +
+ ); +} diff --git a/apps/web/src/components/customers/shared/status-tabs.tsx b/apps/web/src/components/customers/shared/status-tabs.tsx new file mode 100644 index 0000000..7454d32 --- /dev/null +++ b/apps/web/src/components/customers/shared/status-tabs.tsx @@ -0,0 +1,77 @@ +import { CUSTOMER_STATUSES } from "@suni/db/schema/customer-enums"; +import { + Tabs, + TabsContent, + TabsList, + TabsTrigger, +} from "@suni/ui/components/tabs"; +import type { ReactNode } from "react"; + +import type { StatusFilter } from "./filters"; +import { SegmentedControl } from "./segmented-control"; + +const LABELS = { + masculine: { active: "Activos", archived: "Archivados", all: "Todos" }, + feminine: { active: "Activas", archived: "Archivadas", all: "Todas" }, +} as const; + +interface StatusControlProps { + value: StatusFilter; + onValueChange: (status: StatusFilter) => void; + /** Omitted while loading, so no option shows a false zero. */ + counts?: Record; + gender?: keyof typeof LABELS; +} + +/** The status is the list's view, so it is a tab with its count, not one more filter. */ +export function StatusTabs({ + value, + onValueChange, + counts, + gender = "masculine", + children, +}: StatusControlProps & { children: ReactNode }) { + return ( + onValueChange(next)} + value={value} + > + + {CUSTOMER_STATUSES.map((status) => ( + + {LABELS[gender][status]} + {counts ? ( + + {counts[status]} + + ) : null} + + ))} + + +
{children}
+
+
+ ); +} + +/** The status inside a page that already has tabs, so it does not read as a second row of sections. */ +export function StatusSegmented({ + value, + onValueChange, + counts, + gender = "masculine", +}: StatusControlProps) { + return ( + ({ + value: status, + label: LABELS[gender][status], + count: counts?.[status], + }))} + value={value} + /> + ); +} diff --git a/apps/web/src/components/dynamic-breadcrumb.tsx b/apps/web/src/components/dynamic-breadcrumb.tsx index 5f0cd82..c95cbe3 100644 --- a/apps/web/src/components/dynamic-breadcrumb.tsx +++ b/apps/web/src/components/dynamic-breadcrumb.tsx @@ -10,6 +10,8 @@ import type { LinkProps } from "@tanstack/react-router"; import { Link, useRouterState } from "@tanstack/react-router"; import { Fragment } from "react"; +import { NAV_ENTRIES, isSection } from "@/components/nav-items"; + const SEGMENT_LABELS = { dashboard: "Inicio", users: "Usuarios", @@ -17,16 +19,31 @@ const SEGMENT_LABELS = { edit: "Editar", customers: "Clientes", branches: "Sucursales", + contacts: "Contactos", } satisfies Record; type KnownSegment = keyof typeof SEGMENT_LABELS; +// Only these segments name a page when nested; others (like a customer's branches) have no route of their own. +const NESTED_SEGMENTS = new Set(["new", "edit"]); + +const SECTION_BY_PATH = new Map(); + +for (const entry of NAV_ENTRIES) { + if (isSection(entry)) { + for (const item of entry.items) { + SECTION_BY_PATH.set(item.to, entry.label); + } + } +} + function isKnownSegment(segment: string): segment is KnownSegment { return Object.hasOwn(SEGMENT_LABELS, segment); } interface Crumb { - path: LinkProps["to"]; + // A section like "Ventas" groups pages in the sidebar but has no page itself. + path?: LinkProps["to"]; label: string; } @@ -37,12 +54,17 @@ function getCrumbs(pathname: string): Crumb[] { { path: "/dashboard", label: SEGMENT_LABELS.dashboard }, ]; + const section = SECTION_BY_PATH.get(`/${segments[0]}`); + + if (section) { + crumbs.push({ label: section }); + } + for (const [index, segment] of segments.entries()) { - if (segment === "dashboard" && index === 0) { - continue; - } + const named = + index === 0 ? segment !== "dashboard" : NESTED_SEGMENTS.has(segment); - if (isKnownSegment(segment)) { + if (named && isKnownSegment(segment)) { crumbs.push({ // SAFETY: solo los segmentos listados en SEGMENT_LABELS llegan aquí path: `/${segments.slice(0, index + 1).join("/")}` as LinkProps["to"], @@ -54,6 +76,28 @@ function getCrumbs(pathname: string): Crumb[] { return crumbs; } +function CrumbLabel({ + crumb, + isCurrent, +}: { + crumb: Crumb; + isCurrent: boolean; +}) { + if (isCurrent) { + return {crumb.label}; + } + + if (!crumb.path) { + return {crumb.label}; + } + + return ( + }> + {crumb.label} + + ); +} + export function DynamicBreadcrumb() { const pathname = useRouterState({ select: (s) => s.location.pathname }); const crumbs = getCrumbs(pathname); @@ -62,16 +106,10 @@ export function DynamicBreadcrumb() { {crumbs.map((crumb, index) => ( - + {index > 0 && } - {index === crumbs.length - 1 ? ( - {crumb.label} - ) : ( - }> - {crumb.label} - - )} + ))} diff --git a/apps/web/src/components/nav-bar.tsx b/apps/web/src/components/nav-bar.tsx index cb1f414..837b0b1 100644 --- a/apps/web/src/components/nav-bar.tsx +++ b/apps/web/src/components/nav-bar.tsx @@ -1,53 +1,156 @@ -import { SidebarMenu, SidebarMenuItem } from "@suni/ui/components/sidebar"; -import { cn } from "@suni/ui/lib/utils"; +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from "@suni/ui/components/collapsible"; +import { + SidebarGroup, + SidebarMenu, + SidebarMenuButton, + SidebarMenuItem, + SidebarMenuSub, + SidebarMenuSubButton, + SidebarMenuSubItem, + SidebarSeparator, + useSidebar, +} from "@suni/ui/components/sidebar"; import { Link, useRouterState } from "@tanstack/react-router"; -import type { LinkProps } from "@tanstack/react-router"; -import type { LucideIcon } from "lucide-react"; -import { Building2, Contact, ContactRound, Home, Users } from "lucide-react"; +import { ChevronRight } from "lucide-react"; +import { useState } from "react"; +import { HOME_LINK, NAV_ENTRIES, isSection } from "@/components/nav-items"; +import type { NavLink, NavSection } from "@/components/nav-items"; import { useIsAdmin } from "@/hooks/use-is-admin"; -interface NavItem { - to: NonNullable; - label: string; - icon: LucideIcon; - adminOnly?: true; +function isActive(pathname: string, to: string) { + return pathname === to || pathname.startsWith(`${to}/`); } -const NAV_ITEMS = [ - { to: "/dashboard", label: "Inicio", icon: Home }, - { to: "/users", label: "Usuarios", icon: Users, adminOnly: true }, - { to: "/customers", label: "Clientes", icon: ContactRound }, - { to: "/branches", label: "Sucursales", icon: Building2 }, - { to: "/contacts", label: "Contactos", icon: Contact }, -] satisfies NavItem[]; +interface NavSectionItemProps { + section: NavSection; + items: NavLink[]; + pathname: string; +} + +function NavSectionItem({ section, items, pathname }: NavSectionItemProps) { + const { isMobile, state, setOpen: setSidebarOpen } = useSidebar(); + const active = items.some((item) => isActive(pathname, item.to)); + const [open, setOpen] = useState(active); + const [wasActive, setWasActive] = useState(active); + + // Entering one of its pages opens the section; leaving keeps whatever the user chose. + if (active !== wasActive) { + setWasActive(active); + + if (active) { + setOpen(true); + } + } + + function handleOpenChange(next: boolean) { + // Sub-items are hidden while collapsed to icons, so expand the sidebar and the section together. + if (!isMobile && state === "collapsed") { + setSidebarOpen(true); + setOpen(true); + + return; + } + + setOpen(next); + } + + const { label, icon: Icon } = section; + + return ( + } + > + + } + > + + {label} + + + + + {items.map((item) => ( + + } + > + {item.label} + + + ))} + + + + ); +} + +function NavLinkItem({ link, pathname }: { link: NavLink; pathname: string }) { + const { to, label, icon: Icon } = link; + + return ( + + } + tooltip={label} + > + + {label} + + + ); +} export function NavMain() { const pathname = useRouterState({ select: (s) => s.location.pathname }); const isAdmin = useIsAdmin(); - const items = NAV_ITEMS.filter((item) => isAdmin || !("adminOnly" in item)); + const canSee = (link: NavLink) => isAdmin || !link.adminOnly; return ( - - {items.map(({ to, label, icon: Icon }) => { - const active = pathname.startsWith(to); - - return ( - - - - {label} - - - ); - })} - + <> + + + + + + + + + {NAV_ENTRIES.map((entry) => { + if (!isSection(entry)) { + return canSee(entry) ? ( + + ) : null; + } + + const items = entry.items.filter(canSee); + + return items.length > 0 ? ( + + ) : null; + })} + + + ); } diff --git a/apps/web/src/components/nav-items.ts b/apps/web/src/components/nav-items.ts new file mode 100644 index 0000000..810f2ff --- /dev/null +++ b/apps/web/src/components/nav-items.ts @@ -0,0 +1,49 @@ +import type { LinkProps } from "@tanstack/react-router"; +import type { LucideIcon } from "lucide-react"; +import { + Building2, + Contact, + ContactRound, + DollarSign, + Home, + Users, +} from "lucide-react"; + +export interface NavLink { + to: NonNullable; + label: string; + icon: LucideIcon; + adminOnly?: true; +} + +export interface NavSection { + label: string; + icon: LucideIcon; + items: NavLink[]; +} + +type NavEntry = NavLink | NavSection; + +export const HOME_LINK: NavLink = { + to: "/dashboard", + label: "Inicio", + icon: Home, +}; + +/** The modules, listed below Inicio in the sidebar. */ +export const NAV_ENTRIES: NavEntry[] = [ + { to: "/users", label: "Usuarios", icon: Users, adminOnly: true }, + { + label: "Ventas", + icon: DollarSign, + items: [ + { to: "/customers", label: "Clientes", icon: ContactRound }, + { to: "/branches", label: "Sucursales", icon: Building2 }, + { to: "/contacts", label: "Contactos", icon: Contact }, + ], + }, +]; + +export function isSection(entry: NavEntry): entry is NavSection { + return "items" in entry; +} diff --git a/apps/web/src/components/nav-user.tsx b/apps/web/src/components/nav-user.tsx new file mode 100644 index 0000000..cb6955e --- /dev/null +++ b/apps/web/src/components/nav-user.tsx @@ -0,0 +1,115 @@ +import { + Avatar, + AvatarFallback, + AvatarImage, +} from "@suni/ui/components/avatar"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@suni/ui/components/dropdown-menu"; +import { + SidebarMenu, + SidebarMenuButton, + SidebarMenuItem, + useSidebar, +} from "@suni/ui/components/sidebar"; +import { useQueryClient } from "@tanstack/react-query"; +import { useNavigate, useRouteContext } from "@tanstack/react-router"; +import { ChevronsUpDown, LogOut } from "lucide-react"; +import { toast } from "sonner"; + +import { authClient } from "@/lib/auth-client"; + +function initials(name: string) { + return name + .split(/\s+/u) + .filter(Boolean) + .slice(0, 2) + .map((word) => word[0]?.toUpperCase()) + .join(""); +} + +function UserIdentity({ + name, + email, + image, +}: { + name: string; + email: string; + image?: string | null; +}) { + return ( + <> + + {image ? : null} + {initials(name)} + +
+ {name} + {email} +
+ + ); +} + +export function NavUser() { + const user = useRouteContext({ + from: "/_auth", + select: (ctx) => ctx.session.user, + }); + + const { isMobile } = useSidebar(); + const navigate = useNavigate(); + const queryClient = useQueryClient(); + + async function signOut() { + const { error } = await authClient.signOut(); + + if (error) { + toast.error("No se pudo cerrar la sesión."); + + return; + } + + // Leave the page first so its queries don't refetch without a session. + await navigate({ to: "/" }); + queryClient.clear(); + } + + return ( + + + + }> + + + + + + +
+ +
+
+
+ + + + Cerrar sesión + +
+
+
+
+ ); +} diff --git a/apps/web/src/components/page-header.tsx b/apps/web/src/components/page-header.tsx new file mode 100644 index 0000000..49f6ccf --- /dev/null +++ b/apps/web/src/components/page-header.tsx @@ -0,0 +1,33 @@ +import type { LucideIcon } from "lucide-react"; +import type { ReactNode } from "react"; + +interface PageHeaderProps { + icon: LucideIcon; + title: string; + description: ReactNode; + actions?: ReactNode; +} + +export function PageHeader({ + icon: Icon, + title, + description, + actions, +}: PageHeaderProps) { + return ( +
+
+
+
+ +
+

{title}

+
+
{description}
+
+ {actions ? ( +
{actions}
+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/users/action-tooltip.tsx b/apps/web/src/components/users/action-tooltip.tsx new file mode 100644 index 0000000..ad1bf94 --- /dev/null +++ b/apps/web/src/components/users/action-tooltip.tsx @@ -0,0 +1,23 @@ +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@suni/ui/components/tooltip"; +import type { ReactNode } from "react"; + +interface ActionTooltipProps { + label: string; + children: ReactNode; +} + +// The span takes the hover because disabled buttons have pointer-events: none. +export function ActionTooltip({ label, children }: ActionTooltipProps) { + return ( + + }> + {children} + + {label} + + ); +} diff --git a/apps/web/src/components/users/change-user-status-dialog.tsx b/apps/web/src/components/users/change-user-status-dialog.tsx index 96d222b..8849145 100644 --- a/apps/web/src/components/users/change-user-status-dialog.tsx +++ b/apps/web/src/components/users/change-user-status-dialog.tsx @@ -14,24 +14,29 @@ import { Button } from "@suni/ui/components/button"; import { Ban, CircleCheckBig } from "lucide-react"; import { useState } from "react"; +import { ActionTooltip } from "@/components/users/action-tooltip"; import { useChangeUserStatus } from "@/hooks/use-users"; type UserRow = AppRouterOutputs["users"]["list"]["items"][number]; +const BLOCKED_REASON = "No puedes cambiar tu propio estado"; + // What the dialog shows when suspending an active user vs. activating a suspended one. const ACTIONS = { suspend: { label: "Suspender", + hint: "Suspender el acceso de este usuario", Icon: Ban, - triggerVariant: "outline-destructive", + triggerVariant: "ghost-destructive", confirmVariant: "destructive", emailClassName: "text-destructive", description: "Esto suspenderá", }, activate: { label: "Activar", + hint: "Reactivar el acceso de este usuario", Icon: CircleCheckBig, - triggerVariant: "outline-green", + triggerVariant: "ghost-success", confirmVariant: "default", emailClassName: "text-success", description: "Esto reactivará", @@ -57,21 +62,24 @@ export function ChangeUserStatusDialog({ onOpenChange={(next) => !mutation.isPending && setOpen(next)} open={open} > - - } - > - - {action.label} - + + + } + > + + + {disabled ? BLOCKED_REASON : action.label} + + + diff --git a/apps/web/src/components/users/create-user-dialog.tsx b/apps/web/src/components/users/create-user-dialog.tsx new file mode 100644 index 0000000..ab4965e --- /dev/null +++ b/apps/web/src/components/users/create-user-dialog.tsx @@ -0,0 +1,36 @@ +import { Button } from "@suni/ui/components/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@suni/ui/components/dialog"; +import { Plus } from "lucide-react"; +import { useState } from "react"; + +import { UserForm } from "@/components/users/user-form"; + +export function CreateUserDialog() { + const [open, setOpen] = useState(false); + const close = () => setOpen(false); + + return ( + + }> + + Nuevo Usuario + + + + Nuevo usuario + + Captura los datos del nuevo usuario. + + + + + + ); +} diff --git a/apps/web/src/components/users/user-form.tsx b/apps/web/src/components/users/user-form.tsx index ed547d3..0ae11fa 100644 --- a/apps/web/src/components/users/user-form.tsx +++ b/apps/web/src/components/users/user-form.tsx @@ -2,7 +2,6 @@ import type { AppRouterOutputs } from "@suni/api/routers/index"; import { userSchema } from "@suni/db/validation/users"; import { Button } from "@suni/ui/components/button"; import { revalidateLogic } from "@tanstack/react-form"; -import { Link, useNavigate } from "@tanstack/react-router"; import { Loader2 } from "lucide-react"; import type { z } from "zod"; @@ -16,17 +15,16 @@ const ROLE_OPTIONS = [ interface UserFormProps { user?: AppRouterOutputs["users"]["get"]; + onSuccess: () => void; + onCancel: () => void; } -export function UserForm({ user }: UserFormProps) { - const navigate = useNavigate(); +export function UserForm({ user, onSuccess, onCancel }: UserFormProps) { const createUser = useCreateUser(); const updateUser = useUpdateUser(); const submitting = createUser.isPending || updateUser.isPending; - const goToUsers = () => navigate({ to: "/users" }); - const defaultValues: z.input = { name: user?.name ?? "", email: user?.email ?? "", @@ -40,22 +38,22 @@ export function UserForm({ user }: UserFormProps) { validators: { onDynamic: userSchema }, onSubmit: ({ value }) => { if (user) { - updateUser.mutate({ id: user.id, ...value }, { onSuccess: goToUsers }); + updateUser.mutate({ id: user.id, ...value }, { onSuccess }); } else { - createUser.mutate(value, { onSuccess: goToUsers }); + createUser.mutate(value, { onSuccess }); } }, }); return (
{ event.preventDefault(); form.handleSubmit(); }} > -
+
{(field) => ( @@ -74,7 +72,7 @@ export function UserForm({ user }: UserFormProps) {
-
+
{(field) => (
-
-
- - -
+
+ +
); diff --git a/apps/web/src/components/users/users-table.tsx b/apps/web/src/components/users/users-table.tsx index e276f62..9b98e04 100644 --- a/apps/web/src/components/users/users-table.tsx +++ b/apps/web/src/components/users/users-table.tsx @@ -18,11 +18,12 @@ import { useReactTable, } from "@tanstack/react-table"; import type { PaginationState } from "@tanstack/react-table"; -import { MonitorCheck, MonitorX, Pencil, Shield, User } from "lucide-react"; +import { LogIn, Pencil, Shield, User } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; +import { ActionTooltip } from "@/components/users/action-tooltip"; import { ChangeUserStatusDialog } from "@/components/users/change-user-status-dialog"; -import { useListUsers } from "@/hooks/use-users"; +import { useImpersonateUser, useListUsers } from "@/hooks/use-users"; type UserRow = AppRouterOutputs["users"]["list"]["items"][number]; @@ -33,35 +34,73 @@ const columnHelper = createColumnHelper(); function RoleBadge({ role }: { role: string | null }) { if (role === "admin") { return ( - - Admin + + Admin ); } return ( - Usuario + Usuario ); } +function StatusDot() { + return ; +} + function StatusBadge({ banned }: { banned: boolean }) { if (banned) { return ( - Suspendido + Suspendido ); } return ( - Activo + Activo ); } +function ImpersonateUserButton({ + user, + currentUserId, +}: { + user: UserRow; + currentUserId: string; +}) { + const impersonate = useImpersonateUser(); + // Better Auth rejects impersonating admins by default. + let blockedReason: string | undefined; + + if (user.id === currentUserId) { + blockedReason = "No puedes suplantarte a ti mismo"; + } else if (user.role === "admin") { + blockedReason = "No puedes suplantar a un administrador"; + } + + return ( + + + + ); +} + function createColumns(currentUserId: string) { return [ columnHelper.accessor("name", { @@ -70,7 +109,7 @@ function createColumns(currentUserId: string) { {info.getValue()} {info.row.original.id === currentUserId && ( - + Tú )} @@ -99,19 +138,21 @@ function createColumns(currentUserId: string) { return (
- + + + + +
-

Usuarios

- - {total} - -
-
{ @@ -257,9 +292,10 @@ export function UsersDataTable({ currentUserId }: UsersDataTableProps) {
-
+
- Página {pagination.pageIndex + 1} de {pageCount} + Página {pagination.pageIndex + 1} de {pageCount} ·{" "} + {total === 1 ? "1 usuario" : `${total} usuarios`}
+ )} +
-
-
-

{customer.rfc}

- + ) : ( + )} - > + {isArchived ? "Desarchivar" : "Archivar"} + + + } + description={ +
+ {customer.rfc} + {customer.type} - +
-
-
- {isArchived ? null : ( - - Editar - - )} - -
-
+ } + icon={ContactRound} + title={customer.name} + /> + {isArchived ? ( +

+ + Este cliente está archivado. Desarchívalo para editarlo o agregarle + sucursales y contactos. +

+ ) : null} + - - - {TABS.map(({ value, label, icon: Icon }) => ( - - - {label} - - ))} - - - - - - - + + {/* Six tabs don't fit a phone; scroll them instead of widening the page. */} +
+ + {TABS.map(({ value, label }) => ( + // Tabs without content yet stay visible but disabled, so the roadmap shows without dead ends. + + {label} + {content[value] === null ? ( + Pronto + ) : null} + + ))} + +
+ {TABS.map(({ value }) => ( + + {content[value]} + + ))}
); diff --git a/apps/web/src/routes/_auth/customers/index.tsx b/apps/web/src/routes/_auth/customers/index.tsx index 98bef13..a2b477a 100644 --- a/apps/web/src/routes/_auth/customers/index.tsx +++ b/apps/web/src/routes/_auth/customers/index.tsx @@ -3,7 +3,6 @@ import { CUSTOMER_TYPES, } from "@suni/db/schema/customer-enums"; import { Button } from "@suni/ui/components/button"; -import { cn } from "@suni/ui/lib/utils"; import { Link, createFileRoute, @@ -15,8 +14,14 @@ import { z } from "zod"; import CustomerFilters from "@/components/customers/customer-filters"; import CustomerList from "@/components/customers/customer-list"; +import { + byStatus, + countByStatus, + matchingName, +} from "@/components/customers/shared/filters"; +import { StatusTabs } from "@/components/customers/shared/status-tabs"; +import { PageHeader } from "@/components/page-header"; 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({ @@ -39,76 +44,63 @@ export const Route = createFileRoute("/_auth/customers/")({ function RouteComponent() { const { name, type, status } = Route.useSearch(); + const navigate = Route.useNavigate(); + // Fetch every status once so each tab shows its count and switching is instant. const { - data: customers = [], + data: customers, isError, isPending, - isPlaceholderData, - } = useListCustomers({ status }); + } = useListCustomers({ status: "all" }); - const matchingName = useMemo(() => { - const term = stripAccents(name.trim()).toLowerCase(); + const rowsByStatus = useMemo( + () => byStatus(matchingName(customers ?? [], name)), + [customers, name] + ); - return customers - .filter((customer) => - stripAccents(customer.name).toLowerCase().includes(term) - ) - .toSorted((a, b) => a.name.localeCompare(b.name, "es")); - }, [customers, name]); + const inTab = rowsByStatus[status]; const visibleCustomers = - type === "all" - ? matchingName - : matchingName.filter((customer) => customer.type === type); + type === "all" ? inTab : inTab.filter((customer) => customer.type === type); - const hasFilters = - name.trim() !== "" || type !== "all" || status !== defaultFilters.status; + const hasFilters = name.trim() !== "" || type !== "all"; return ( -
-
-
-
-
- -
-

Clientes

-
-

- Gestiona los clientes del sistema -

-
-
+
+ } - variant="green" > Nuevo Cliente -
-
- - + } + /> - {/* Placeholder data is the previous filter's list; dim it until the new one arrives. */} -
+ navigate({ + search: (prev) => ({ ...prev, status: next }), + replace: true, + }) + } + value={status} > + -
+
); } diff --git a/apps/web/src/routes/_auth/customers/new.tsx b/apps/web/src/routes/_auth/customers/new.tsx index bcfe83d..55375bd 100644 --- a/apps/web/src/routes/_auth/customers/new.tsx +++ b/apps/web/src/routes/_auth/customers/new.tsx @@ -2,6 +2,7 @@ import { createFileRoute } from "@tanstack/react-router"; import { ContactRound } from "lucide-react"; import { CustomerForm } from "@/components/customers/customer-form"; +import { PageHeader } from "@/components/page-header"; export const Route = createFileRoute("/_auth/customers/new")({ component: RouteComponent, @@ -9,20 +10,12 @@ export const Route = createFileRoute("/_auth/customers/new")({ function RouteComponent() { return ( -
-
-
-
-
- -
-

Nuevo Cliente

-
-

- Crea un nuevo cliente para el sistema -

-
-
+
+
); diff --git a/apps/web/src/routes/_auth/dashboard.tsx b/apps/web/src/routes/_auth/dashboard.tsx index b0a2f15..361c580 100644 --- a/apps/web/src/routes/_auth/dashboard.tsx +++ b/apps/web/src/routes/_auth/dashboard.tsx @@ -1,22 +1,72 @@ -import { useQuery } from "@tanstack/react-query"; -import { createFileRoute } from "@tanstack/react-router"; +import { Link, createFileRoute } from "@tanstack/react-router"; +import { ChevronRight, Home } from "lucide-react"; -import { orpc } from "@/utils/orpc"; +import { NAV_ENTRIES, isSection } from "@/components/nav-items"; +import type { NavLink } from "@/components/nav-items"; +import { PageHeader } from "@/components/page-header"; +import { useIsAdmin } from "@/hooks/use-is-admin"; export const Route = createFileRoute("/_auth/dashboard")({ component: RouteComponent, }); function RouteComponent() { - const { session } = Route.useRouteContext(); + const firstName = Route.useRouteContext({ + select: (ctx) => ctx.session.user.name.split(" ")[0], + }); - const privateData = useQuery(orpc.privateData.queryOptions()); + const isAdmin = useIsAdmin(); + + const shortcuts: (NavLink & { section?: string })[] = []; + + for (const entry of NAV_ENTRIES) { + const links = isSection(entry) + ? entry.items.map((item) => ({ ...item, section: entry.label })) + : [entry]; + + for (const link of links) { + if (isAdmin || !link.adminOnly) { + shortcuts.push(link); + } + } + } return ( -
-

Dashboard

-

Welcome {session.user.name}

-

API: {privateData.data?.message}

+
+ + +
); } diff --git a/apps/web/src/routes/_auth/route.tsx b/apps/web/src/routes/_auth/route.tsx index 4ed1b32..e96c82a 100644 --- a/apps/web/src/routes/_auth/route.tsx +++ b/apps/web/src/routes/_auth/route.tsx @@ -1,12 +1,16 @@ +import { Button } from "@suni/ui/components/button"; +import { Separator } from "@suni/ui/components/separator"; import { SidebarInset, SidebarProvider, SidebarTrigger, } from "@suni/ui/components/sidebar"; +import { TooltipProvider } from "@suni/ui/components/tooltip"; import { Outlet, createFileRoute, redirect } from "@tanstack/react-router"; import { AppSidebar } from "@/components/app-sidebar"; import { DynamicBreadcrumb } from "@/components/dynamic-breadcrumb"; +import { useStopImpersonating } from "@/hooks/use-users"; import { authClient } from "@/lib/auth-client"; export const Route = createFileRoute("/_auth")({ @@ -24,19 +28,54 @@ export const Route = createFileRoute("/_auth")({ }, }); +function ImpersonationBanner() { + const { session } = Route.useRouteContext(); + const stop = useStopImpersonating(); + + if (!session.session.impersonatedBy) { + return null; + } + + return ( +
+ + Estás viendo la aplicación como {session.user.name}. + + +
+ ); +} + function AuthLayout() { return ( - - - -
- - -
-
- -
-
-
+ + {/* The sidebar saves its collapsed state in this cookie; read it back so a reload keeps it. */} + + + +
+ + + +
+ +
+ +
+
+
+
); } diff --git a/apps/web/src/routes/_auth/users/$userId/edit.tsx b/apps/web/src/routes/_auth/users/$userId/edit.tsx index 5ecb1cc..dd01936 100644 --- a/apps/web/src/routes/_auth/users/$userId/edit.tsx +++ b/apps/web/src/routes/_auth/users/$userId/edit.tsx @@ -1,6 +1,7 @@ -import { createFileRoute } from "@tanstack/react-router"; +import { createFileRoute, useNavigate } from "@tanstack/react-router"; import { UserPen } from "lucide-react"; +import { PageHeader } from "@/components/page-header"; import { UserForm } from "@/components/users/user-form"; export const Route = createFileRoute("/_auth/users/$userId/edit")({ @@ -8,32 +9,24 @@ export const Route = createFileRoute("/_auth/users/$userId/edit")({ queryClient.query(orpc.users.get.queryOptions({ input: { id: userId } })), component: RouteComponent, errorComponent: () => ( -

- No se pudo cargar el usuario. -

+

No se pudo cargar el usuario.

), }); function RouteComponent() { const user = Route.useLoaderData(); + const navigate = useNavigate(); + const goToUsers = () => navigate({ to: "/users" }); return ( -
-
-
-
-
- -
-

Editar Usuario

-
-

- Modifica la información del usuario -

-
-
+
+ - +
); } diff --git a/apps/web/src/routes/_auth/users/index.tsx b/apps/web/src/routes/_auth/users/index.tsx index 51111d8..c9a6708 100644 --- a/apps/web/src/routes/_auth/users/index.tsx +++ b/apps/web/src/routes/_auth/users/index.tsx @@ -1,7 +1,8 @@ -import { Button } from "@suni/ui/components/button"; -import { Link, createFileRoute } from "@tanstack/react-router"; -import { Plus, Users } from "lucide-react"; +import { createFileRoute } from "@tanstack/react-router"; +import { Users } from "lucide-react"; +import { PageHeader } from "@/components/page-header"; +import { CreateUserDialog } from "@/components/users/create-user-dialog"; import { UsersDataTable } from "@/components/users/users-table"; export const Route = createFileRoute("/_auth/users/")({ @@ -12,31 +13,13 @@ function RouteComponent() { const { session } = Route.useRouteContext(); return ( -
-
-
-
-
- -
-

Usuarios

-
-

- Administra los usuarios del sistema -

-
-
- -
-
+
+ } + />
); diff --git a/apps/web/src/routes/_auth/users/new.tsx b/apps/web/src/routes/_auth/users/new.tsx deleted file mode 100644 index f9f1f70..0000000 --- a/apps/web/src/routes/_auth/users/new.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { createFileRoute } from "@tanstack/react-router"; -import { User } from "lucide-react"; - -import { UserForm } from "@/components/users/user-form"; - -export const Route = createFileRoute("/_auth/users/new")({ - component: RouteComponent, -}); - -function RouteComponent() { - return ( -
-
-
-
-
- -
-

Nuevo Usuario

-
-

- Crea un nuevo usuario para el sistema -

-
-
- -
- ); -} diff --git a/packages/ui/src/components/avatar.tsx b/packages/ui/src/components/avatar.tsx new file mode 100644 index 0000000..3afe8a9 --- /dev/null +++ b/packages/ui/src/components/avatar.tsx @@ -0,0 +1,108 @@ +"use client" + +import * as React from "react" +import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar" +import { cn } from "cn" + +function Avatar({ + className, + size = "default", + ...props +}: AvatarPrimitive.Root.Props & { + size?: "default" | "sm" | "lg" +}) { + return ( + + ) +} + +function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) { + return ( + + ) +} + +function AvatarFallback({ + className, + ...props +}: AvatarPrimitive.Fallback.Props) { + return ( + + ) +} + +function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) { + return ( + svg]:hidden", + "group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2", + "group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2", + className + )} + {...props} + /> + ) +} + +function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function AvatarGroupCount({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3", + className + )} + {...props} + /> + ) +} + +export { + Avatar, + AvatarImage, + AvatarFallback, + AvatarGroup, + AvatarGroupCount, + AvatarBadge, +} diff --git a/packages/ui/src/components/badge.tsx b/packages/ui/src/components/badge.tsx index bbc701b..eaefaac 100644 --- a/packages/ui/src/components/badge.tsx +++ b/packages/ui/src/components/badge.tsx @@ -4,22 +4,19 @@ import * as React from "react"; import { cn } from "cn"; const badgeVariants = cva( - "inline-flex items-center rounded-md border px-2.5 py-0.5 font-semibold text-xs transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 gap-1", + "inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 font-medium text-xs [&_svg]:size-3 [&_svg]:shrink-0", { variants: { variant: { default: - "border-success/30 bg-success/10 text-success hover:bg-success/20", + "bg-primary/10 text-primary", secondary: - "border-secondary-foreground/20 bg-secondary text-secondary-foreground hover:bg-secondary/80", + "bg-muted text-muted-foreground", destructive: - "border-destructive/30 bg-destructive/10 text-destructive hover:bg-destructive/20", + "bg-destructive/10 text-destructive", success: - "border-green-500/30 bg-green-500/10 text-green-700 hover:bg-green-500/20 dark:text-green-400 gap-1", - blue: "border-brand/30 bg-brand/10 text-brand hover:bg-brand/20", - warning: - "border-amber-500/30 bg-amber-500/10 text-amber-700 hover:bg-amber-500/20 dark:text-amber-400", - outline: "text-foreground", + "bg-success/10 text-success", + outline: "text-muted-foreground ring-1 ring-border ring-inset", }, }, defaultVariants: { diff --git a/packages/ui/src/components/breadcrumb.tsx b/packages/ui/src/components/breadcrumb.tsx index f75efed..9cb34ca 100644 --- a/packages/ui/src/components/breadcrumb.tsx +++ b/packages/ui/src/components/breadcrumb.tsx @@ -39,7 +39,7 @@ function BreadcrumbLink({ return useRender({ defaultTagName: 'a', props: mergeProps<'a'>( - { className: cn('transition-colors hover:text-foreground text-brand', className) }, + { className: cn('transition-colors hover:text-foreground text-primary', className) }, props ), render, @@ -55,7 +55,7 @@ function BreadcrumbPage({ - {children ?? } + {children ?? } ); } diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsx index 39318b1..53b7866 100644 --- a/packages/ui/src/components/button.tsx +++ b/packages/ui/src/components/button.tsx @@ -3,27 +3,25 @@ import { cva, type VariantProps } from "class-variance-authority" import { cn } from "cn" const buttonVariants = cva( - "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md font-medium text-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md font-medium text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", { variants: { variant: { default: - "bg-primary text-primary-foreground shadow hover:bg-primary/90", + "bg-primary text-primary-foreground shadow hover:bg-primary-hover", destructive: - "bg-destructive text-white shadow-sm hover:bg-destructive/90", + "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive-pressed", outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", + // Quiet row actions whose hover color previews the outcome. + "ghost-destructive": + "text-muted-foreground hover:bg-destructive/10 hover:text-destructive", + "ghost-success": + "text-muted-foreground hover:bg-success/10 hover:text-success", link: "text-primary underline-offset-4 hover:underline", - green: - "bg-success text-white shadow transition-colors duration-400 hover:bg-success/80 active:bg-success-pressed", - "outline-green": - "border border-success text-success hover:bg-success/10 duration-500 active:bg-success-pressed active:text-white", - "outline-destructive": - "border border-danger text-danger hover:bg-danger/10 duration-500 active:bg-danger-dark active:text-white", - blue: "bg-brand text-white shadow transition-colors duration-400 hover:bg-brand/80 active:bg-brand-dark", }, size: { default: "h-9 px-4 py-2", diff --git a/packages/ui/src/components/collapsible.tsx b/packages/ui/src/components/collapsible.tsx new file mode 100644 index 0000000..4b242f7 --- /dev/null +++ b/packages/ui/src/components/collapsible.tsx @@ -0,0 +1,19 @@ +import { Collapsible as CollapsiblePrimitive } from "@base-ui/react/collapsible" + +function Collapsible({ ...props }: CollapsiblePrimitive.Root.Props) { + return +} + +function CollapsibleTrigger({ ...props }: CollapsiblePrimitive.Trigger.Props) { + return ( + + ) +} + +function CollapsibleContent({ ...props }: CollapsiblePrimitive.Panel.Props) { + return ( + + ) +} + +export { Collapsible, CollapsibleTrigger, CollapsibleContent } diff --git a/packages/ui/src/components/input-group.tsx b/packages/ui/src/components/input-group.tsx index f8faf77..dfad241 100644 --- a/packages/ui/src/components/input-group.tsx +++ b/packages/ui/src/components/input-group.tsx @@ -12,7 +12,7 @@ function InputGroup({ className, ...props }: React.ComponentProps<"div">) { data-slot="input-group" role="group" className={cn( - "group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5", + "group/input-group relative flex h-9 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5", className )} {...props} diff --git a/packages/ui/src/components/input.tsx b/packages/ui/src/components/input.tsx index 32d1520..6ed6e4d 100644 --- a/packages/ui/src/components/input.tsx +++ b/packages/ui/src/components/input.tsx @@ -8,7 +8,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) { type={type} data-slot="input" className={cn( - "h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 read-only:cursor-default read-only:bg-muted/60 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40", + "h-9 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 read-only:cursor-default read-only:bg-muted/60 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40", className )} {...props} diff --git a/packages/ui/src/components/react-select.tsx b/packages/ui/src/components/react-select.tsx index 61cf740..b69c2e9 100644 --- a/packages/ui/src/components/react-select.tsx +++ b/packages/ui/src/components/react-select.tsx @@ -13,7 +13,7 @@ export const selectClassNames = { control: (state) => cn( // Mirrors Input so selects line up with text fields; min-h needs ! to beat react-select's base minHeight of 38px. - "min-h-8! rounded-lg border border-input bg-transparent px-2.5 text-base transition-colors md:text-sm dark:bg-input/30", + "min-h-9! rounded-lg border border-input bg-transparent px-2.5 text-base transition-colors md:text-sm dark:bg-input/30", state.isFocused && "border-ring ring-3 ring-ring/50", // aria-invalid sits on the inner input, so Input's aria-invalid: variants can't reach this box. isInvalid(state.selectProps["aria-invalid"]) && diff --git a/packages/ui/src/components/separator.tsx b/packages/ui/src/components/separator.tsx new file mode 100644 index 0000000..7d8337e --- /dev/null +++ b/packages/ui/src/components/separator.tsx @@ -0,0 +1,22 @@ +import { Separator as SeparatorPrimitive } from "@base-ui/react/separator" +import { cn } from "cn" + +function Separator({ + className, + orientation = "horizontal", + ...props +}: SeparatorPrimitive.Props) { + return ( + + ) +} + +export { Separator } diff --git a/packages/ui/src/components/sheet.tsx b/packages/ui/src/components/sheet.tsx new file mode 100644 index 0000000..c9c3357 --- /dev/null +++ b/packages/ui/src/components/sheet.tsx @@ -0,0 +1,136 @@ +import * as React from "react" +import { Dialog as SheetPrimitive } from "@base-ui/react/dialog" +import { cn } from "cn" + +import { Button } from "@suni/ui/components/button" +import { XIcon } from "lucide-react" + +function Sheet({ ...props }: SheetPrimitive.Root.Props) { + return +} + +function SheetTrigger({ ...props }: SheetPrimitive.Trigger.Props) { + return +} + +function SheetClose({ ...props }: SheetPrimitive.Close.Props) { + return +} + +function SheetPortal({ ...props }: SheetPrimitive.Portal.Props) { + return +} + +function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) { + return ( + + ) +} + +function SheetContent({ + className, + children, + side = "right", + showCloseButton = true, + ...props +}: SheetPrimitive.Popup.Props & { + side?: "top" | "right" | "bottom" | "left" + showCloseButton?: boolean +}) { + return ( + + + + {children} + {showCloseButton && ( + + } + > + + Close + + )} + + + ) +} + +function SheetHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function SheetFooter({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) { + return ( + + ) +} + +function SheetDescription({ + className, + ...props +}: SheetPrimitive.Description.Props) { + return ( + + ) +} + +export { + Sheet, + SheetTrigger, + SheetClose, + SheetContent, + SheetHeader, + SheetFooter, + SheetTitle, + SheetDescription, +} diff --git a/packages/ui/src/components/sidebar.tsx b/packages/ui/src/components/sidebar.tsx index 82861d7..d0dc0c9 100644 --- a/packages/ui/src/components/sidebar.tsx +++ b/packages/ui/src/components/sidebar.tsx @@ -1,155 +1,254 @@ -import { PanelLeft } from 'lucide-react'; -import * as React from 'react'; +"use client" + +import * as React from "react" +import { mergeProps } from "@base-ui/react/merge-props" +import { useRender } from "@base-ui/react/use-render" +import { cva, type VariantProps } from "class-variance-authority" +import { cn } from "cn" + +import { useIsMobile } from "@suni/ui/hooks/use-mobile" import { Button } from "@suni/ui/components/button" -import { cn } from 'cn'; +import { Input } from "@suni/ui/components/input" +import { Separator } from "@suni/ui/components/separator" +import { + Sheet, + SheetContent, + SheetDescription, + SheetHeader, + SheetTitle, +} from "@suni/ui/components/sheet" +import { Skeleton } from "@suni/ui/components/skeleton" +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@suni/ui/components/tooltip" +import { PanelLeftIcon } from "lucide-react" -const SIDEBAR_WIDTH = '16rem'; -const SIDEBAR_KEYBOARD_SHORTCUT = 'b'; +const SIDEBAR_COOKIE_NAME = "sidebar_state" +const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7 +const SIDEBAR_WIDTH = "16rem" +const SIDEBAR_WIDTH_MOBILE = "18rem" +const SIDEBAR_WIDTH_ICON = "3rem" +const SIDEBAR_KEYBOARD_SHORTCUT = "b" type SidebarContextProps = { - state: 'expanded' | 'collapsed'; - open: boolean; - setOpen: React.Dispatch>; - openMobile: boolean; - setOpenMobile: React.Dispatch>; - toggleSidebar: () => void; -}; + state: "expanded" | "collapsed" + open: boolean + setOpen: (open: boolean) => void + openMobile: boolean + setOpenMobile: (open: boolean) => void + isMobile: boolean + toggleSidebar: () => void +} -const SidebarContext = React.createContext(null); +const SidebarContext = React.createContext(null) function useSidebar() { - const context = React.useContext(SidebarContext); + const context = React.useContext(SidebarContext) if (!context) { - throw new Error('useSidebar must be used within a SidebarProvider.'); + throw new Error("useSidebar must be used within a SidebarProvider.") } - return context; -} - -/* ---------------------------------- Provider --------------------------------- */ -type SidebarProviderProps = React.ComponentProps<'div'> & { - /** Estado inicial en escritorio. En móvil siempre inicia cerrada. */ - defaultOpen?: boolean; -}; + return context +} function SidebarProvider({ defaultOpen = true, + open: openProp, + onOpenChange: setOpenProp, className, style, children, ...props -}: SidebarProviderProps) { - const [open, setOpen] = React.useState(defaultOpen); - const [openMobile, setOpenMobile] = React.useState(false); +}: React.ComponentProps<"div"> & { + defaultOpen?: boolean + open?: boolean + onOpenChange?: (open: boolean) => void +}) { + const isMobile = useIsMobile() + const [openMobile, setOpenMobile] = React.useState(false) + + // This is the internal state of the sidebar. + // We use openProp and setOpenProp for control from outside the component. + const [_open, _setOpen] = React.useState(defaultOpen) + const open = openProp ?? _open + const setOpen = React.useCallback( + (value: boolean | ((value: boolean) => boolean)) => { + const openState = typeof value === "function" ? value(open) : value + if (setOpenProp) { + setOpenProp(openState) + } else { + _setOpen(openState) + } - // Alterna ambos estados: el CSS (breakpoint md) decide cuál se ve. + // This sets the cookie to keep the sidebar state. + document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}` + }, + [setOpenProp, open] + ) + + // Helper to toggle the sidebar. const toggleSidebar = React.useCallback(() => { - setOpen((value) => !value); - setOpenMobile((value) => !value); - }, []); + return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open) + }, [isMobile, setOpen, setOpenMobile]) + // Adds a keyboard shortcut to toggle the sidebar. React.useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { - // Ctrl/Cmd + B if ( event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey) ) { - event.preventDefault(); - toggleSidebar(); - } - // Escape cierra el panel en móvil - if (event.key === 'Escape') { - setOpenMobile(false); + event.preventDefault() + toggleSidebar() } - }; - window.addEventListener('keydown', handleKeyDown); - return () => window.removeEventListener('keydown', handleKeyDown); - }, [toggleSidebar]); + } - const value = React.useMemo( + window.addEventListener("keydown", handleKeyDown) + return () => window.removeEventListener("keydown", handleKeyDown) + }, [toggleSidebar]) + + // We add a state so that we can do data-state="expanded" or "collapsed". + // This makes it easier to style the sidebar with Tailwind classes. + const state = open ? "expanded" : "collapsed" + + const contextValue = React.useMemo( () => ({ - state: open ? 'expanded' : 'collapsed', + state, open, setOpen, + isMobile, openMobile, setOpenMobile, toggleSidebar, }), - [open, openMobile, toggleSidebar] - ); + [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar] + ) return ( - +
{children}
- ); + ) } -/* ---------------------------------- Sidebar ---------------------------------- */ - -/** - * Mobile first: - * - Base (móvil): panel fuera de pantalla que se desliza sobre el contenido con un fondo oscuro. - * - md y superior: panel fijo al costado que ocupa espacio y se puede colapsar. - */ function Sidebar({ + side = "left", + variant = "sidebar", + collapsible = "offcanvas", className, children, + dir, ...props -}: React.ComponentProps<'aside'>) { - const { state, openMobile, setOpenMobile } = useSidebar(); +}: React.ComponentProps<"div"> & { + side?: "left" | "right" + variant?: "sidebar" | "floating" | "inset" + collapsible?: "offcanvas" | "icon" | "none" +}) { + const { isMobile, state, openMobile, setOpenMobile } = useSidebar() + + if (collapsible === "none") { + return ( +
+ {children} +
+ ) + } + + if (isMobile) { + return ( + + + + Menú + Navegación principal de Suni. + +
{children}
+
+
+ ) + } return (
- {/* Fondo oscuro (solo móvil) */} + {/* This is what handles the sidebar gap on desktop */} - ); + ) } function SidebarTrigger({ @@ -157,99 +256,468 @@ function SidebarTrigger({ onClick, ...props }: React.ComponentProps) { - const { toggleSidebar } = useSidebar(); + const { toggleSidebar } = useSidebar() return ( - - ); + + ) } -function SidebarInset({ +function SidebarRail({ className, ...props }: React.ComponentProps<"button">) { + const { toggleSidebar } = useSidebar() + + return ( +